def plot_raster(self, spikeTimestamps, eventOnsetTimes, plotTitle, sortArray=[], replace=0, timeRange=[-0.5, 1]): ''' Plot a raster given spike timestamps and event onset times This method will take the spike timestamps directly, convert them so that they are relative to the event onset times, and then call the appropriate plotting code. This method should ideally be able to handle making both sortArrayed and unsortArrayed rasters. sortArray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter ''' if len(sortArray) > 0: trialsEachCond = behavioranalysis.find_trials_each_type( sortArray, np.unique(sortArray)) else: trialsEachCond = [] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) #pdb.set_trace() extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond) show()
def raster_sound_block_switching(): correct = bdata['outcome']==bdata.labels['outcome']['correct'] possibleFreq = np.unique(bdata['targetFrequency']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq correctOneFreq = oneFreq & correct trialsEachBlock = bdata.blocks['trialsEachBlock'] correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis] correctBlockSizes = sum(correctTrialsEachBlock) if (correctBlockSizes[-1] < minBlockSize): #Just a check to see if last block is too small to plot blockSizes = sum(trialsEachBlock) numBlocks = len(trialsEachBlock[0]) sumBlocks = sum(blockSizes) newTrialsLastBlock = np.zeros((blockSizes[-1],numBlocks), dtype=np.bool) correctTrialsEachBlock[(sumBlocks-blockSizes[-1]):] = newTrialsLastBlock #if the last block is too small, make the condition for the last trial all false #correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis] trialsEachCond = correctTrialsEachBlock; if bdata['currentBlock'][0]==bdata.labels['currentBlock']['low_boundary']: colorEachBlock = 4*['g','r'] else: colorEachBlock = 4*['r','g'] extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachBlock,fillWidth=None,labels=None) plt.ylabel('Trials') plt.title('Blocks')
def plot_reward_change_raster(cellObj, evlockDir, behavClass=loadbehavior.FlexCategBehaviorData, alignment='sound', timeRange=[-0.3,0.4], freqToPlot='low', byBlock=False, colorCondDict=colorDictRC): ''' Function to plot reward change raster. ''' spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = load_intermediate_data_for_raster_psth(cellObj, evlockDir, alignment, timeRange, behavClass) #spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = calculate_intermediate_data_for_raster_psth(cellObj, alignment, timeRange, behavClass) if np.any(spikeTimesFromEventOnset): if freqToPlot == 'low' or freqToPlot=='high': trialsEachCond, colorEachCond, labelEachCond = get_trials_each_cond_reward_change(cellObj, freqToPlot, byBlock, colorCondDict, behavClass) elif freqToPlot == 'both': trialsEachCondList = [] colorEachCond = [] labelEachCond = [] for freq in ['low','high']: trialsEachCondThisFreq, colorEachCondThisFreq, labelEachCondThisFreq = get_trials_each_cond_reward_change(cellObj, freqToPlot, byBlock, colorCondDict, behavClass) trialsEachCondList.append(trialsEachCondThisFreq) colorEachCond.extend(colorEachCondThisFreq) labelEachCond.extend(labelEachCondThisFreq) trialsEachCond = np.concatenate(trialsEachCondList, axis=1) # -- Plot raster -- # extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None) plt.axvline(x=0,linewidth=1, color='darkgrey') plt.ylabel('Trials') plt.xlim(timeRange[0]+0.1,timeRange[-1]) plt.title('{0}_{1}freq'.format(alignment,freqToPlot),fontsize=10) else: pass
def plot_noisebursts_response_raster(animal, ephysSession, tetrode, cluster, alignment='sound', timeRange=[-0.1, 0.3]): ''' Function to plot noisebursts along with waveforms for each cluster to distinguish cell responses and noise. ''' eventData = load_event_data(animal, ephysSession) spikeData = load_spike_data(animal, ephysSession, tetrode, cluster) spikeTimestamps = spikeData.timestamps eventOnsetTimes = np.array(eventData.timestamps) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) # -- Plot raster -- # plt.subplot(2, 1, 1) extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=[], fillWidth=None, labels=None) plt.ylabel('Trials') plt.subplot(2, 1, 2) wavesThisCluster = spikeData.samples spikesorting.plot_waveforms(wavesThisCluster) plt.title('{0} T{1}C{2} noisebursts'.format(ephysSession, tetrode, cluster, alignment), fontsize=10) plt.show()
def plot_noisebursts_response_raster(animal, ephysSession, tetrode, cluster, timeRange=[-0.1, 0.3]): ''' Function to plot noisebursts along with waveforms for each cluster to distinguish cell responses and noise. ''' eventData = load_event_data(animal, ephysSession) spikeData = load_spike_data(animal, ephysSession, tetrode, cluster) spikeTimestamps = spikeData.timestamps eventOnsetTimes = np.array(eventData.timestamps) soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel == soundTriggerChannel) eventOnsetTimes = eventOnsetTimes[soundOnsetEvents] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) # -- Plot raster -- # extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=[], fillWidth=None, labels=None) plt.ylabel('Trials') plt.xlabel('Time from sound onset (s)')
def raster_sound_allFreq_switching(): 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']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq trialsToUseRight = rightward & oneFreq trialsToUseLeft = leftward & oneFreq lowFreq = ((bdata['targetFrequency'] == possibleFreq[0]) & correct) highFreq = ((bdata['targetFrequency'] == possibleFreq[2]) & correct) trialsEachCond = np.c_[highFreq,trialsToUseLeft,trialsToUseRight,lowFreq]; colorEachCond = ['b','r','g','y'] extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None) plt.ylabel('Trials') plt.title('All Frequencies')
def plot_movement_response_raster(cellObj, evlockDir, behavClass=loadbehavior.FlexCategBehaviorData, alignment='center-out', timeRange=[-0.3,0.5], colorCondDict=colorDictMovement): ''' Function to plot activity during movement as raster. ''' spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = load_intermediate_data_for_raster_psth(cellObj, evlockDir, alignment, timeRange, behavClass) spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = calculate_intermediate_data_for_raster_psth(cellObj, alignment, timeRange, behavClass) bdata = load_n_remove_missing_trials_2afc_behav(cellObj, behavClass) if np.any(spikeTimesFromEventOnset): # -- Select trials to plot from behavior file -- # rightward = bdata['choice']==bdata.labels['choice']['right'] leftward = bdata['choice']==bdata.labels['choice']['left'] condLabels = ['go left', 'go right'] trialsEachCond = np.c_[leftward,rightward] colorEachCond = [colorCondDict['left'],colorCondDict['right']] # -- Plot raster -- # #plt.subplot2grid((3,1), (0, 0), rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None) plt.axvline(x=0,linewidth=1, color='darkgrey') plt.ylabel('Trials') plt.xlim(timeRange[0]+0.1,timeRange[-1]) plt.title('{}_movement_response'.format(alignment),fontsize=10) else: pass
def raster_sound_switching(): 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']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq trialsToUseRight = rightward & oneFreq trialsToUseLeft = leftward & oneFreq trialsEachCond = np.c_[trialsToUseLeft, trialsToUseRight] colorEachCond = ['r', 'g'] extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, fillWidth=None, labels=None) #plt.ylabel('Trials') plt.title('Frequency: ' + str(Freq))
def raster_movement_allFreq_switching(): 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']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq trialsToUseRight = rightward & oneFreq trialsToUseLeft = leftward & oneFreq lowFreq = ((bdata['targetFrequency'] == possibleFreq[0]) & correct) highFreq = ((bdata['targetFrequency'] == possibleFreq[2]) & correct) trialsEachCond = np.c_[lowFreq, trialsToUseRight, trialsToUseLeft, highFreq] colorEachCond = ['y', 'g', 'r', 'b'] extraplots.raster_plot(spikeTimesFromMovementOnset, indexLimitsEachMovementTrial, timeRange, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, fillWidth=None, labels=None)
def raster_sound_block_switching(): correct = bdata['outcome']==bdata.labels['outcome']['correct'] possibleFreq = np.unique(bdata['targetFrequency']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq correctOneFreq = oneFreq & correct trialsEachBlock = bdata.blocks['trialsEachBlock'] correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis] correctBlockSizes = sum(correctTrialsEachBlock) if (correctBlockSizes[-1] < minBlockSize): #Just a check to see if last block is too small to plot blockSizes = sum(trialsEachBlock) numBlocks = len(trialsEachBlock[0]) sumBlocks = sum(blockSizes) newTrialsLastBlock = np.zeros((blockSizes[-1],numBlocks), dtype=np.bool) correctTrialsEachBlock[(sumBlocks-blockSizes[-1]):] = newTrialsLastBlock #if the last block is too small, make the condition for the last trial all false #correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis] trialsEachCond = correctTrialsEachBlock; if bdata['currentBlock'][0]==bdata.labels['currentBlock']['low_boundary']: colorEachBlock = 4*['g','r'] else: colorEachBlock = 4*['r','g'] extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachBlock,fillWidth=None,labels=None) #plt.ylabel('Trials') plt.title('Sound Aligned (Top) and Movement Aligned (Bottom)')
def plot_rew_change_per_cell_raster(oneCell, alignment='sound', freqToPlot='left', byBlock=False, timeRange=[-0.4, 1.2], binWidth=0.010): ''' Function to plot raster for reward_change_freq_dis task. Args: oneCell: a CellInfo object; alignment: a string indicating the event to align the spike times to, can be 'sound', 'center-out', or 'side-in'. freqToPlot: a string indicating the frequency to plot, can be 'left', 'right', or 'both', since only used two frequencies during recording. byBlock: boolean value indicating whether to split the plot by behavior blocks or just group all blocks of the same condition together. ''' bdata, trialsEachCond, colorEachCond = get_trials_each_cond_reward_change( oneCell, freqToPlot=freqToPlot, byBlock=byBlock) (spikeTimestamps, waveforms, eventOnsetTimes, eventData) = load_ephys_per_cell(oneCell) # -- determine spike time based on event to align spikes to -- # if alignment == 'sound': soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel == soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] elif alignment == 'center-out': soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel == soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] diffTimes = bdata['timeCenterOut'] - bdata['timeTarget'] EventOnsetTimes += diffTimes elif alignment == 'side-in': soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel == soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] diffTimes = bdata['timeSideIn'] - bdata['timeTarget'] EventOnsetTimes += diffTimes (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spikeTimestamps,EventOnsetTimes,timeRange) # -- Plot raster -- # #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') plt.xlim(timeRange[0] + 0.1, timeRange[-1]) plt.title('{0}_{1}_TT{2}_c{3}_{4}'.format(oneCell.animalName, oneCell.behavSession, oneCell.tetrode, oneCell.cluster, alignment))
def raster_movement_psycurve(Frequency): 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']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq trialsToUseRight = rightward & oneFreq trialsToUseLeft = leftward & oneFreq trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['r','g'] extraplots.raster_plot(spikeTimesFromMovementOnset,indexLimitsEachMovementTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None)
def raster_movement_psycurve(Frequency): 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']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq trialsToUseRight = rightward & oneFreq trialsToUseLeft = leftward & oneFreq trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['r','g'] extraplots.raster_plot(spikeTimesFromMovementOnset,indexLimitsEachMovementTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None)
def plot_raster(self, spikeTimestamps, eventOnsetTimes, sortArray = [], replace = 0, timeRange = [-0.5, 1], ms = 4): ''' Plot a raster given spike timestamps and event onset times This method will take the spike timestamps directly, convert them so that they are relative to the event onset times, and then call the appropriate plotting code. This method should ideally be able to handle making both sortArrayed and unsortArrayed rasters. sortArray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter ''' if len(sortArray)>0: trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray)) else: trialsEachCond = [] spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange) #pdb.set_trace() if replace: #Now using cla() so that it will work with subplots cla() #else: # figure() pRaster,hcond,zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond = trialsEachCond) setp(pRaster,ms=ms)
def noise_raster(ephysData, gs): plt.subplot(gs[7:11, 0]) eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] baseTimeRange = [-0.15, -0.05] trialsEachCond = [] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange) base_avg = np.mean(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) base_sem = stats.sem(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond) title = "Noise Bursts (Base FR: {} +/- {} spikes/s)".format( round(base_avg, 2), round(base_sem, 2)) #title = "Noise Bursts (Base FR: {} spikes/s)".format(round(base_avg, 2)) #title = "Noise Bursts" xlabel = 'Time from sound onset (s)' ylabel = 'Trial' plt.title(title, fontsize='medium') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def raster_allfreq_sound_psycurve(): rightward = bdata['choice'] == bdata.labels['choice']['right'] leftward = bdata['choice'] == bdata.labels['choice']['left'] correct = bdata['outcome'] == bdata.labels['outcome']['correct'] invalid = bdata['outcome'] == bdata.labels['outcome']['invalid'] possibleFreq = np.unique(bdata['targetFrequency']) trialsToUseEachCond = None for indFreq in range(len(possibleFreq)): Freq = possibleFreq[indFreq] oneFreq = bdata['targetFrequency'] == Freq trialsToUse = correct & oneFreq if (trialsToUseEachCond == None): trialsToUseEachCond = trialsToUse else: trialsToUseEachCond = np.c_[trialsToUseEachCond, trialsToUse] trialsEachCond = trialsToUseEachCond colorEachCond = [[0.5, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.3, 0.7], [0.1, 1.0, 0.1], [0.1, 0.6, 0.1], [0.0, 0.3, 0.0]] (pRaster, hcond, zline) = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, fillWidth=None, labels=None) for indRaster in range(len(pRaster)): pRaster[indRaster].set_ms(point_size)
def plot_separated_rasters(gridspec, xcoords, ycoord, firstSort, secondSort, spikeTimestamps, eventOnsetTimes, timeRange=[-0.2,1.5], ylabel='bandwidth (octaves)', xlabel='Time from sound onset (sec)', titles=None, duplicate=False, colours=None, plotHeight=1): firstSortLabels = ['{}'.format(first) for first in np.unique(firstSort)] numFirst = np.unique(firstSort) numSec = np.unique(secondSort) trialsEachCond = behavioranalysis.find_trials_each_combination(firstSort, numFirst, secondSort, numSec) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) if colours is None: colours = [np.tile(['0.25','0.6'],len(numFirst)/2+1), np.tile(['#4e9a06','#8ae234'],len(numFirst)/2+1)] for ind, secondArrayVal in enumerate(numSec): plt.subplot(gridspec[ycoord+ind*plotHeight:ycoord+ind*plotHeight+plotHeight, xcoords[0]:xcoords[1]]) trialsThisSecondVal = trialsEachCond[:, :, ind] # a dumb workaround specifically for plotting harmonic sessions if duplicate: for ind2, first in enumerate(numFirst): if not any(trialsThisSecondVal[:,ind2]): trialsThisSecondVal[:,ind2]=trialsEachCond[:,ind2,ind+1] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsThisSecondVal, labels=firstSortLabels, colorEachCond = colours[ind]) plt.setp(pRaster, ms=4) plt.ylabel(ylabel) if ind == len(numSec) - 1: plt.xlabel(xlabel) if titles is not None: plt.title(titles[ind])
def noise_raster(ephysData, gs): plt.subplot(gs[0, 1]) eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] baseTimeRange = [-0.15, -0.05] trialsEachCond = [] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange) base_avg = np.mean(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) base_sem = stats.sem(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond) title = "Noise Bursts (Base FR: {} +/- {} spikes/s)".format(round(base_avg, 2), round(base_sem, 2)) #title = "Noise Bursts (Base FR: {} spikes/s)".format(round(base_avg, 2)) #title = "Noise Bursts" xlabel = 'Time from sound onset (s)' ylabel = 'Trial' plt.title(title, fontsize = 'medium') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def plot_example(subplotSpec, exampleName): # lowFreq = 4 # highFreq = 128 # nFreqLabels = 3 # freqs = np.logspace(np.log10(lowFreq),np.log10(highFreq),nFreqLabels) # freqs = np.round(freqs, decimals=1) spikeTimes = exampleSpikeTimes[exampleName] indexLimitsEachTrial = exampleIndexLimitsEachTrial[exampleName] timeRange = [-0.2, 0.7] freqEachTrial = exampleFreqEachTrial[exampleName] possibleFreq = np.unique(freqEachTrial) freqLabels = ['{0:.1f}'.format(freq) for freq in possibleFreq] trialsEachCondition = behavioranalysis.find_trials_each_type( freqEachTrial, possibleFreq) pRaster, hCond, zline = extraplots.raster_plot(spikeTimes, indexLimitsEachTrial, timeRange, trialsEachCondition, labels=freqLabels) ax = plt.gca() ax.set_xticks([0, 0.5]) ax.set_xlabel('Time from sound onset (s)') ax.set_ylabel('AM Rate (Hz)') # ax.set_yticks(freqs) # ax.set_yticklabels(freqs) plt.setp(pRaster, ms=2)
def plot_sorted_raster(spikeTimeStamps, eventOnsetTimes, sortArray, timeRange=[-0.5, 1], xlabel='Time from sound onset (sec)', ylabel='Frequency (kHz)', ms=4, labels=None, *args, **kwargs): ''' Function to accept spike timestamps, event onset times, and a sorting array and plot a raster plot sorted by the array passed Args: sortarray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter. Must be the same length as the event onset times array ''' trialsEachCond = behavioranalysis.find_trials_each_type( sortArray, np.unique(sortArray)) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, labels=labels, *args, **kwargs) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.setp(pRaster, ms=ms)
def tuning_raster(bdata, ephysdata, gs): plt.subplot(gs[0, 1]) freqEachTrial = bdata['currentFreq'] eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] possiblefreqs = np.unique(freqEachTrial) freqLabels = [round(x / 1000, 1) for x in possiblefreqs] trialsEachCond = behavioranalysis.find_trials_each_type( freqEachTrial, possiblefreqs) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) #print len(freqEachTrial), len(eventOnsetTimes) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, labels=freqLabels) xlabel = 'time (s)' ylabel = 'Frequency (kHz)' plt.title('Tuning Curve') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def tuning_raster(bdata, ephysdata, gs): plt.subplot(gs[0, 1]) freqEachTrial = bdata['currentFreq'] eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] possiblefreqs = np.unique(freqEachTrial) freqLabels = [round(x/1000, 1) for x in possiblefreqs] trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) #print len(freqEachTrial), len(eventOnsetTimes) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond, labels=freqLabels) xlabel = 'time (s)' ylabel = 'Frequency (kHz)' plt.title('Tuning Curve') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def noise_raster(ephysData, gs): plt.subplot(gs[0, 0]) eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] trialsEachCond = [] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond) xlabel = 'time (s)' ylabel = 'Trial' plt.title('Noise Bursts') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def plot_noisebursts_response_raster(cellObj, timeRange=[-0.1, 0.3]): ''' Function to plot noisebursts along with waveforms for each cluster to distinguish cell responses and noise. ''' sessionType = 'nb' sessionInd = cellObj.get_session_inds(sessionType)[0] ephysData, bdata = cellObj.load_by_index(sessionInd, behavClass=behavClass) eventsDict = ephysData['events'] spikeTimestamps = ephysData['spikeTimes'] soundOnsetTimes = eventsDict['{}On'.format(soundChannelType)] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps, soundOnsetTimes, timeRange) # -- Plot raster -- # extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=[],fillWidth=None,labels=None) plt.ylabel('Trials') plt.xlabel('Time from sound onset (s)')
def tuning_test_raster(bdata, ephysData, gs): plt.subplot(gs[11:15, 0]) freqEachTrial = bdata['currentFreq'] eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] baseTimeRange = [-0.15, -0.05] possiblefreqs = np.unique(freqEachTrial) freqLabels = [round(x / 1000, 1) for x in possiblefreqs] trialsEachCond = behavioranalysis.find_trials_each_type( freqEachTrial, possiblefreqs) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) #print len(freqEachTrial), len(eventOnsetTimes) baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange) base_avg = np.mean(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) base_sem = stats.sem(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) # for freqInd, freq in enumerate(possiblefreqs): # freq_spikecounts = spikeMat[trialsEachCond[:,freqInd]==True] # freq_avg = np.mean(freq_spikecounts) / (soundTimeRange[1] - soundTimeRange[0]) # freq_avgs.append(freq_avg) ''' try: base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, baseIndexLimitsEachTrial) except: behavBaseIndexLimitsEachTrial = baseIndexLimitsEachTrial[0:2,:-1] base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavBaseIndexLimitsEachTrial) base_avg = np.mean(base_avgs) base_frs = np.divide(base_avg, baseTimeRange[1] - baseTimeRange[0]) #print(base_avg) ''' title = "Tuning Test (Base FR: {} +/- {} spikes/s)".format( round(base_avg, 2), round(base_sem, 2)) #title = "Tuning Curve (Base FR: {} spikes/s)".format(round(base_avg, 2)) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, labels=freqLabels) xlabel = 'Time from sound onset (s)' ylabel = 'Frequency (kHz)' plt.title(title, fontsize='medium') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def plot_tuning_raster(cellObj, sessionType='tc', intensity=50, timeRange = [-0.5,1]): ''' Function to plot a tuning raster sorted by frequency. :param arg1: Cell object from ephyscore. :param arg2: A string for the session type, for tuning it should be 'tc'. :param arg3: An int for the intensity in (dB) to plot, default is 50(dB), which is the stimulus intensity used in 2afc task. :param arg4: A list of floats for the start and the end of the time period around sound-onset to plot raster. ''' sessionInd = cellObj.get_session_inds(sessionType)[0] bdata = cellObj.load_behavior_by_index(sessionInd) ephysData = cellObj.load_ephys_by_index(sessionInd) eventsDict = ephysData['events'] spikeTimestamps = ephysData['spikeTimes'] soundOnsetTimes = eventsDict['{}On'.format(soundChannelType)] freqEachTrial = bdata['currentFreq'] intensityEachTrial = bdata['currentIntensity'] possibleFreq = np.unique(freqEachTrial) possibleIntensity = np.unique(intensityEachTrial) if len(possibleIntensity) != 1: intensity = intensity ###Just select the trials with a given intensity### trialsThisIntensity = [intensityEachTrial==intensity] freqEachTrial = freqEachTrial[trialsThisIntensity] intensityEachTrial = intensityEachTrial[trialsThisIntensity] soundOnsetTimes = soundOnsetTimes[trialsThisIntensity] #print len(intensityEachTrial),len(eventOnsetTimes),len(spikeTimestamps) freqLabels = ['{0:.1f}'.format(freq/1000.0) for freq in possibleFreq] #intensityLabels = ['{:.0f} dB'.format(intensity) for intensity in possibleIntensity] ### FIXME: this is a bad hack for when ephys is one trial more than behavior file ### if len(soundOnsetTimes)==len(freqEachTrial)+1: soundOnsetTimes=soundOnsetTimes[:-1] print('Tuning behavior is one trial less than ephys!') ### FIXME: this is a bad hack for when behavior is one trial more than ephys file ### if len(soundOnsetTimes)==len(freqEachTrial)-1: freqEachTrial=freqEachTrial[:-1] print('Tuning behavior is one trial more than ephys!') #print len(freqEachTrial),len(eventOnsetTimes),len(spikeTimestamps) trialsEachFreq = behavioranalysis.find_trials_each_type(freqEachTrial,possibleFreq) (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spikeTimestamps,soundOnsetTimes,timeRange) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachFreq, labels=freqLabels) plt.xlabel('Time from sound onset') plt.xlim(timeRange[0]+0.1,timeRange[1]) plotTitle = 'tuning with 50dB chords' plt.title(plotTitle,fontsize=10)
def raster_sidein_block_switching(): correct = bdata['outcome'] == bdata.labels['outcome']['correct'] #invalid = bdata['outcome']==bdata.labels['outcome']['invalid'] #nochoice = bdata['outcome']==bdata.labels['outcome']['nochoice'] #aborted = bdata['outcome']==bdata.labels['outcome']['aborted'] possibleFreq = np.unique(bdata['targetFrequency']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq correctOneFreq = oneFreq & correct trialsEachBlock = bdata.blocks['trialsEachBlock'] correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:, np.newaxis] correctBlockSizes = sum(correctTrialsEachBlock) if (correctBlockSizes[-1] < minBlockSize ): #Just a check to see if last block is too small to plot blockSizes = sum(trialsEachBlock) numBlocks = len(trialsEachBlock[0]) sumBlocks = sum(blockSizes) newTrialsLastBlock = np.zeros((blockSizes[-1], numBlocks), dtype=np.bool) correctTrialsEachBlock[( sumBlocks - blockSizes[-1] ):] = newTrialsLastBlock #if the last block is too small, make the condition for the last trial all false #correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis] trialsEachCond = correctTrialsEachBlock if bdata['currentBlock'][0] == bdata.labels['currentBlock'][ 'low_boundary']: colorEachBlock = 4 * ['g', 'r'] else: colorEachBlock = 4 * ['r', 'g'] extraplots.raster_plot(spikeTimesFromSideinOnset, indexLimitsEachSideinTrial, sideinTimeRange, trialsEachCond=trialsEachCond, colorEachCond=colorEachBlock, fillWidth=None, labels=None)
def plot_movement_response_raster(animal, behavSession, ephysSession, tetrode, cluster, alignment='center-out', timeRange=[-0.3, 0.5], colorCondDict=colorDictMovement): ''' Function to plot activity during movement as raster. ''' spikeTimesFromEventOnset, indexLimitsEachTrial = get_intermediate_data_for_raster_psth( animal, behavSession, ephysSession, tetrode, cluster, alignment, timeRange) bdata = load_n_remove_missing_trials_2afc_behav(animal, behavSession, ephysSession, tetrode, cluster) # -- Select trials to plot from behavior file -- # rightward = bdata['choice'] == bdata.labels['choice']['right'] leftward = bdata['choice'] == bdata.labels['choice']['left'] condLabels = ['go left', 'go right'] trialsEachCond = np.c_[leftward, rightward] colorEachCond = [colorCondDict['left'], colorCondDict['right']] # -- Plot raster -- # #plt.subplot2grid((3,1), (0, 0), rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, fillWidth=None, labels=None) plt.axvline(x=0, linewidth=1, color='darkgrey') plt.ylabel('Trials') plt.xlim(timeRange[0] + 0.1, timeRange[-1]) plt.title('{0}_T{1}c{2}_{3}_movement_response'.format( behavSession, tetrode, cluster, alignment), fontsize=10)
def raster_movement_switching(): 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']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == Freq trialsToUseRight = rightward & oneFreq trialsToUseLeft = leftward & oneFreq trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['r','g'] extraplots.raster_plot(spikeTimesFromMovementOnset,indexLimitsEachMovementTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None) plt.ylabel('Trials') plt.title('Movement Aligned')
def plot_laser_bandwidth_summary(cell, bandIndex): cellInfo = get_cell_info(cell) loader = dataloader.DataLoader(cell['subject']) plt.clf() gs = gridspec.GridSpec(2, 4) eventData = loader.get_session_events(cellInfo['ephysDirs'][bandIndex]) spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][bandIndex], cellInfo['tetrode'], cluster=cellInfo['cluster']) eventOnsetTimes = loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps timeRange = [-0.2, 1.5] bandBData = loader.get_session_behavior(cellInfo['behavDirs'][bandIndex]) bandEachTrial = bandBData['currentBand'] laserTrial = bandBData['laserTrial'] numBands = np.unique(bandEachTrial) numLas = np.unique(laserTrial) firstSortLabels = ['{}'.format(band) for band in np.unique(bandEachTrial)] secondSortLabels = ['no laser','laser'] trialsEachCond = behavioranalysis.find_trials_each_combination(bandEachTrial, numBands, laserTrial, numLas) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) colours = [np.tile(['0.25','0.6'],len(numBands)/2+1), np.tile(['#4e9a06','#8ae234'],len(numBands)/2+1)] for ind, secondArrayVal in enumerate(numLas): plt.subplot(gs[ind, 0:2]) trialsThisSecondVal = trialsEachCond[:, :, ind] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsThisSecondVal, labels=firstSortLabels, colorEachCond = colours[ind]) plt.setp(pRaster, ms=4) #plt.title(secondSortLabels[ind]) plt.ylabel('bandwidth (octaves)') if ind == len(numLas) - 1: plt.xlabel("Time from sound onset (sec)") # -- plot Yashar plots for bandwidth data -- plt.subplot(gs[0:, 2:]) spikeArray, errorArray, baseSpikeRate = band_select(spikeTimestamps, eventOnsetTimes, laserTrial, bandEachTrial, timeRange = [0.0, 1.0]) band_select_plot(spikeArray, errorArray, baseSpikeRate, numBands, legend=True, labels=secondSortLabels, linecolours=['0.25','#4e9a06'], errorcolours=['0.6','#8ae234']) fig_path = '/home/jarauser/Pictures/cell reports' fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}.svg'.format(cellInfo['subject'], cellInfo['date'], cellInfo['depth'], cellInfo['tetrode'], cellInfo['cluster']) full_fig_path = os.path.join(fig_path, fig_name) fig = plt.gcf() fig.set_size_inches(16, 8) fig.savefig(full_fig_path, format = 'svg', bbox_inches='tight')
def am_raster(bdata, ephysData, gs): plt.subplot(gs[1, 1]) freqEachTrial = bdata['currentFreq'] eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] baseTimeRange = [-0.15, -0.05] possiblefreqs = np.unique(freqEachTrial) freqLabels = [round(x/1000, 1) for x in possiblefreqs] trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) #print len(freqEachTrial), len(eventOnsetTimes) baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange) base_avg = np.mean(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) base_sem = stats.sem(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0]) # for freqInd, freq in enumerate(possiblefreqs): # freq_spikecounts = spikeMat[trialsEachCond[:,freqInd]==True] # freq_avg = np.mean(freq_spikecounts) / (soundTimeRange[1] - soundTimeRange[0]) # freq_avgs.append(freq_avg) ''' try: base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, baseIndexLimitsEachTrial) except: behavBaseIndexLimitsEachTrial = baseIndexLimitsEachTrial[0:2,:-1] base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavBaseIndexLimitsEachTrial) base_avg = np.mean(base_avgs) base_frs = np.divide(base_avg, baseTimeRange[1] - baseTimeRange[0]) #print(base_avg) ''' title = "Tuning Curve (Base FR: {} +/- {} spikes/s)".format(round(base_avg, 2), round(base_sem, 2)) #title = "Tuning Curve (Base FR: {} spikes/s)".format(round(base_avg, 2)) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond, labels=freqLabels) xlabel = 'Time from sound onset (s)' ylabel = 'Frequency (kHz)' plt.title(title, fontsize = 'medium') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def plot_separated_rasters(gridspec, xcoords, ycoord, firstSort, secondSort, spikeTimestamps, eventOnsetTimes, timeRange=[-0.2, 1.5], ylabel='bandwidth (octaves)', xlabel='Time from sound onset (sec)', titles=None, duplicate=False, colours=None, plotHeight=1): firstSortLabels = ['{}'.format(first) for first in np.unique(firstSort)] numFirst = np.unique(firstSort) numSec = np.unique(secondSort) trialsEachCond = behavioranalysis.find_trials_each_combination( firstSort, numFirst, secondSort, numSec) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) if colours is None: colours = [ np.tile(['0.25', '0.6'], len(numFirst) / 2 + 1), np.tile(['#4e9a06', '#8ae234'], len(numFirst) / 2 + 1) ] for ind, secondArrayVal in enumerate(numSec): plt.subplot(gridspec[ycoord + ind * plotHeight:ycoord + ind * plotHeight + plotHeight, xcoords[0]:xcoords[1]]) trialsThisSecondVal = trialsEachCond[:, :, ind] # a dumb workaround specifically for plotting harmonic sessions if duplicate: for ind2, first in enumerate(numFirst): if not any(trialsThisSecondVal[:, ind2]): trialsThisSecondVal[:, ind2] = trialsEachCond[:, ind2, ind + 1] pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsThisSecondVal, labels=firstSortLabels, colorEachCond=colours[ind]) plt.setp(pRaster, ms=4) plt.ylabel(ylabel) if ind == len(numSec) - 1: plt.xlabel(xlabel) if titles is not None: plt.title(titles[ind])
def laser_tuning_raster(bdata, ephysData, gs): freqEachTrial = bdata['currentFreq'] laserEachTrial = bdata['laserOn'] intEachTrial = bdata['currentIntensity'] eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] possiblefreqs = np.unique(freqEachTrial) freqLabels = [round(x / 1000, 1) for x in possiblefreqs] possiblelaser = np.unique(laserEachTrial) possibleInts = np.unique(intEachTrial) #trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs) laserTrialsEachCond = behavioranalysis.find_trials_each_combination( freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser) intTrialsEachCond = behavioranalysis.find_trials_each_combination( freqEachTrial, possiblefreqs, intEachTrial, possibleInts) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) #plt.figure() for intInd, inten in enumerate(possibleInts): for indLaser in possiblelaser: #plt.subplot(2, 1, indLaser) plt.subplot(gs[intInd + 1, indLaser]) if indLaser == 0: title = "No Laser " + str(inten) + " dB" else: title = "Laser " + str(inten) + " dB" trialsEachCond = laserTrialsEachCond[:, :, indLaser] & intTrialsEachCond[:, :, intInd] pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, labels=freqLabels) xlabel = 'time (s)' ylabel = 'Frequency (kHz)' plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def plot_raster(spikeTimestamps, eventOnsetTimes, sortArray = [], timeRange = [-0.5, 1], ms = 4, labels=None): ''' Args: sortarray (array): an array of parameter values for each trial. output will be sorted by the possible values of the parameter. Must be the same length as the event onset times array ''' if len(sortArray)>0: trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray)) if not labels: labels=['%.1f' % f for f in np.unique(sortArray)] else: trialsEachCond = [] spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange) pRaster,hcond,zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond = trialsEachCond, labels=labels) plt.setp(pRaster,ms=ms)
def plot_sorted_tuning_raster(self, session, tetrode, behavFileIdentifier, cluster = None, replace=0, timeRange = [-0.5, 1], ms = 1): ''' ''' bdata = self.get_session_behav_data(session,behavFileIdentifier) freqEachTrial = bdata['currentFreq'] possibleFreq = np.unique(freqEachTrial) intensityEachTrial = bdata['currentIntensity'] possibleIntensity = np.unique(intensityEachTrial) trialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possibleFreq, intensityEachTrial, possibleIntensity) spikeData = self.get_session_spike_data_one_tetrode(session, tetrode) eventData = self.get_session_event_data(session) eventOnsetTimes = self.get_event_onset_times(eventData) spikeTimestamps=spikeData.timestamps spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange) freqLabels = ['{0:.1f}'.format(freq/1000.0) for freq in possibleFreq] plotTitle = self.get_session_plot_title(session) fig = plt.figure() for indIntensity, intensity in enumerate(possibleIntensity[::-1]): if indIntensity == 0: fig.add_subplot(len(possibleIntensity), 1, indIntensity+1) plt.title(plotTitle) else: fig.add_subplot(len(possibleIntensity), 1, indIntensity+1, sharex=fig.axes[0], sharey=fig.axes[0]) trialsThisIntensity = trialsEachCond[:, :, len(possibleIntensity)-indIntensity-1] #FIXME: There must be a better way to flip so high intensity is on top pRaster,hcond,zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond = trialsThisIntensity, labels = freqLabels) plt.setp(pRaster,ms=ms) plt.ylabel('{:.0f} dB'.format(intensity)) if indIntensity == len(possibleIntensity)-1: plt.xlabel("time (sec)") fig.show()
def laser_tuning_raster(bdata, ephysData, gs): freqEachTrial = bdata['currentFreq'] laserEachTrial = bdata['laserOn'] intEachTrial = bdata['currentIntensity'] eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] possiblefreqs = np.unique(freqEachTrial) freqLabels = [round(x/1000, 1) for x in possiblefreqs] possiblelaser = np.unique(laserEachTrial) possibleInts = np.unique(intEachTrial) #trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs) laserTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser) intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) #plt.figure() for intInd, inten in enumerate(possibleInts): for indLaser in possiblelaser: #plt.subplot(2, 1, indLaser) plt.subplot(gs[intInd+1, indLaser]) if indLaser == 0: title = "No Laser " + str(inten) + " dB" else: title = "Laser " + str(inten) + " dB" trialsEachCond = laserTrialsEachCond[:,:,indLaser] & intTrialsEachCond[:,:,intInd] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond, labels=freqLabels) xlabel = 'time (s)' ylabel = 'Frequency (kHz)' plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=[], timeRange=[-0.5, 1], ms=4, labels=None, *args, **kwargs): ''' Function to accept spike timestamps, event onset times, and an optional sorting array and plot a raster plot (sorted if the sorting array is passed) This function does not replicate functionality. It allows you to pass spike timestamps and event onset times, which are simple to get, as well as an array of any values that can be used to sort the raster. This function wraps three other good functions and provides a way to use them easily Args: sortarray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter. Must be the same length as the event onset times array ''' # If a sort array is supplied, find the trials that correspond to each value of the array if len(sortArray) > 0: trialsEachCond = behavioranalysis.find_trials_each_type( sortArray, np.unique(sortArray)) if not labels: labels = ['%.1f' % f for f in np.unique(sortArray)] else: trialsEachCond = [] # Align spiketimestamps to the event onset times for plotting spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) #Plot the raster, which will sort if trialsEachCond is supplied pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, labels=labels, *args, **kwargs) #Set the marker size for better viewing plt.setp(pRaster, ms=ms)
def am_example(cell, timeRange=[-0.2, 0.7]): #Plot histograms of spikes relative to stimulus period? plotCycleHists = False spikeData, eventData = celldatabase.get_session_ephys(cell, 'am') eventOnsetTimes = eventData.get_event_onset_times(eventID=1, eventChannel=0) eventOnsetTimes = spikesanalysis.minimum_event_onset_diff(eventOnsetTimes, minEventOnsetDiff=0.7) bdata = celldatabase.get_session_bdata(cell, 'am') colors = get_colors(len(np.unique(bdata['currentFreq']))) #Raster plt.clf() if plotCycleHists: plt.subplot2grid((11, 3), (0, 0), rowspan=11, colspan=2) else: plt.subplot(111) ms=6 #4 sortArray = bdata['currentFreq'] trialsEachCond = behavioranalysis.find_trials_each_type( sortArray, np.unique(sortArray)) labels = ['%.1f' % f for f in np.unique(sortArray)] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeData.timestamps, eventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, labels=labels, colorEachCond=colors) plt.setp(pRaster, ms=ms) fontsize = 20 plt.ylabel('AM rate', fontsize=fontsize) plt.xlabel('Time from stimulus onset (s)', fontsize=fontsize) if plotCycleHists: #Want to plot a hist of spike times from 0 to 2pi # ax3 = plt.subplot(313) plt.hold(True) for indFreq, (freq, spikeTimesThisFreq, trialIndicesThisFreq) in enumerate(spiketimes_each_frequency(spikeTimesFromEventOnset, trialIndexForEachSpike, sortArray)): radsPerSec=freq*2*np.pi spikeRads = (spikeTimesThisFreq*radsPerSec)%(2*np.pi) ax = plt.subplot2grid((11, 3), (10-indFreq, 2)) ax.hist(spikeRads, bins=50, color=colors[indFreq], histtype='step')
def plot_sorted_raster(spikeTimeStamps, eventOnsetTimes, sortArray, timeRange=[-0.5, 1],xlabel='Time from sound onset (sec)',ylabel='Frequency (kHz)',ms=4,labels=None,*args,**kwargs): ''' Function to accept spike timestamps, event onset times, and a sorting array and plot a raster plot sorted by the array passed Args: sortarray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter. Must be the same length as the event onset times array ''' trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray)) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond,labels=labels, *args, **kwargs) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.setp(pRaster, ms=ms)
def plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=[], timeRange=[-0.5, 1], ms=4, labels=None, *args, **kwargs): ''' Function to accept spike timestamps, event onset times, and an optional sorting array and plot a raster plot (sorted if the sorting array is passed) This function does not replicate functionality. It allows you to pass spike timestamps and event onset times, which are simple to get, as well as an array of any values that can be used to sort the raster. This function wraps three other good functions and provides a way to use them easily Args: sortarray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter. Must be the same length as the event onset times array ''' # If a sort array is supplied, find the trials that correspond to each value of the array if len(sortArray) > 0: trialsEachCond = behavioranalysis.find_trials_each_type( sortArray, np.unique(sortArray)) if not labels: labels = ['%.1f' % f for f in np.unique(sortArray)] else: trialsEachCond = [] # Align spiketimestamps to the event onset times for plotting spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) #Plot the raster, which will sort if trialsEachCond is supplied pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, labels=labels, *args, **kwargs) #Set the marker size for better viewing plt.setp(pRaster, ms=ms)
def noise_raster(ephysData, gs): plt.subplot(gs[0, 0]) eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] trialsEachCond = [] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond) xlabel = 'time (s)' ylabel = 'Trial' plt.title('Noise Bursts') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def histPlot(subject,behavSession,tetrodeID,cluster): allCellsName = 'allcells_'+subject allcells = __import__(allCellsName) cellIndex = allcells.cellDB.findcell(subject,behavSession,tetrodeID,cluster) ephysSession = allcells.cellDB[cellIndex].ephysSession ephysRoot = ephysRootDir+subject+'/' # -- Load Behavior Data -- behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession) bdata = loadbehavior.BehaviorData(behaviorFilename) numberOfTrials = len(bdata['choice']) targetFreqs = 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 ############################################################################################################################################################################### trialsToUse1 = correctLeftward #This is an array of 1's and 0's to decide which trials to count spikes in and compare to the other trials trialsToUse2 = correctRightward #This is an array of 1's and 0's to decide which trials to count spikes in and compare to the other trials ################################################################################################################################################################################## # -- 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 multipleEventOnset=np.array(events.eventID) #loads the onset times of all events (matches up with eventID to say if event 1 went on (1) or off (0) eventChannel = np.array(events.eventChannel) #loads the ID of the channel of the event. For example, 0 is sound event, 1 is trial event, 2 ... # -- Load Spike Data From Certain Cluster -- spkData = ephyscore.CellData(allcells.cellDB[cellIndex]) spkTimeStamps = spkData.spikes.timestamps # -- Only use event onset times of one event -- oneEvent = eventChannel==eventID #This picks out which channel you care about if there is more that one event eventOnset = multipleEventOnset*oneEvent #This keeps the correct size of the array to match eventTimes and picks out the onset of the channel you want while (numberOfTrials < np.sum(eventOnset)): eventOnset = eventOnset[:-1] eventOnsetTimes = eventTimes[eventOnset == 1] #This gives only the times of the onset of the channel you want # -- This is for one Frequency -- trialsOfFreq = targetFreqs==possibleFreq[Frequency] #array of booleans that is true if the frequency chosen was played in that trial trialsToUseWithFreq1 = trialsToUse1*trialsOfFreq #array with 1 is this is a trial to use and of the frequency chosen and 0 if not trialsToUseWithFreq2 = trialsToUse2*trialsOfFreq #array with 1 is this is a trial to use and of the frequency chosen and 0 if not eventOnsetTimesTrials1 = eventOnsetTimes[trialsToUseWithFreq1==1] eventOnsetTimesTrials2 = eventOnsetTimes[trialsToUseWithFreq2==1] # -- Convert spike data into np.array's -- (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) (spikeTimesFromEventOnsetTrials1,trialIndexForEachSpikeTrials1,indexLimitsEachTrialTrials1) = spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesTrials1,timeRange) (spikeTimesFromEventOnsetTrials2,trialIndexForEachSpikeTrials2,indexLimitsEachTrialTrials2) = spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesTrials2,timeRange) ''' spikesanalysis.eventlocked_spiketimes Create a vector with the spike timestamps w.r.t. events onset. (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = eventlocked_spiketimes(timeStamps,eventOnsetTimes,timeRange) timeStamps: (np.array) the time of each spike. eventOnsetTimes: (np.array) the time of each instance of the event to lock to. timeRange: (list or np.array) two-element array specifying time-range to extract around event. spikeTimesFromEventOnset: 1D array with time of spikes locked to event. trialIndexForEachSpike: 1D array with the trial corresponding to each spike. The first spike index is 0. indexLimitsEachTrial: [2,nTrials] range of spikes for each trial. Note that the range is from firstSpike to lastSpike+1 (like in python slices) spikeIndices ''' # -- Find the number of spikes in each bin -- spikeNumberInBinPerTrial = np.empty([numberOfBins,numberOfTrials]) for i,binRange in enumerate(binTimeRanges): spikeNumberInBinPerTrial[i] = spikesanalysis.count_spikes_in_range(spikeTimesFromEventOnset,indexLimitsEachTrial,binRange) #array of the number of spikes in range for each trial ''' spikesanalysis.count_spikes_in_range Count number of spikes on each trial in a given time range. spikeTimesFromEventOnset: vector of spikes timestamps with respect to the onset of the event. indexLimitsEachTrial: each column contains [firstInd,lastInd+1] of the spikes on a trial. timeRange: time range to evaluate. Spike times exactly at the limits are not counted. returns nSpikes ''' ''' ###################################################################################################################### #THIS IS FOR ALL FREQUENCIES # -- Pick which trials you care about in counting spikes -- spikeMeanInBin1 = np.empty(numberOfBins) #This will hold the mean number of spikes in each bin or time range for the trialsToUse1 spikeMeanInBin2 = np.empty(numberOfBins) #This will hold the mean number of spikes in each bin or time range for the trialsToUse2 for indBin, spikeCounts in enumerate(spikeNumberInBinPerTrial): spikeMeanInBin1[indBin] = np.mean(np.append(spikeCounts[trialsToUse1==1],0)) #The append 0 is just for the edge case that there are no trials to use so np.mean does not give a nan. spikeMeanInBin2[indBin] = np.mean(np.append(spikeCounts[trialsToUse2==1],0)) ###################################################################################################################### ''' ###################################################################################################################### #THIS IS FOR ALL ONE FREQUENCY # -- Pick which trials you care about in counting spikes -- spikeMeanInBin1 = np.empty(numberOfBins) #This will hold the mean number of spikes in each bin or time range for the trialsToUse1 for the frequency chosen spikeMeanInBin2 = np.empty(numberOfBins) #This will hold the mean number of spikes in each bin or time range for the trialsToUse2 for the frequency chosen for indBin, spikeCounts in enumerate(spikeNumberInBinPerTrial): spikeMeanInBin1[indBin] = np.mean(np.append(spikeCounts[trialsToUseWithFreq1==1],0)) #The append 0 is just for the edge case that there are no trials to use with this frequency so np.mean does not give a nan. spikeMeanInBin2[indBin] = np.mean(np.append(spikeCounts[trialsToUseWithFreq2==1],0)) ###################################################################################################################### ################################################################################################################################################################################### #####################################################THIS IS FOR THE RASTOR PLOT################################################################################################### ################################################################################################################################################################################### targetFreqsTrials1 = targetFreqs[trialsToUseWithFreq1==1] targetFreqsTrials2 = targetFreqs[trialsToUseWithFreq2==1] sortedTrials1 = [] #array that sorts trials for different frequencies for indf1,oneFreq1 in enumerate(possibleFreq): #indf is index of this freq and oneFreq is the frequency indsThisFreq1 = np.flatnonzero(targetFreqsTrials1==oneFreq1) #this gives indices of this frequency sortedTrials1.append(indsThisFreq1) #adds all indices to a list called sortedTrials sortedTrials2 = [] #array that sorts trials for different frequencies for indf2,oneFreq2 in enumerate(possibleFreq): #indf is index of this freq and oneFreq is the frequency indsThisFreq2 = np.flatnonzero(targetFreqsTrials2==oneFreq2) #this gives indices of this frequency sortedTrials2.append(indsThisFreq2) #adds all indices to a list called sortedTrials colorEachFreq = [] strPossibleFreq = [] for indFreq, Freq in enumerate(possibleFreq): colorEachFreq.append('b') colorEachFreq.append('g') strPossibleFreq.append(str(Freq)) clf() rastorFreq1 = plt.subplot2grid((3,4), (0, 0), colspan=2, rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnsetTrials1, indexLimitsEachTrialTrials1, timeRange, sortedTrials1, labels=strPossibleFreq,colorEachCond = colorEachFreq) rastorFreq2 = plt.subplot2grid((3,4), (0, 2), colspan=2, rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnsetTrials2, indexLimitsEachTrialTrials2, timeRange, sortedTrials2, labels=strPossibleFreq,colorEachCond = colorEachFreq) ################################################################################################################################################################################### #####################################################THIS IS FOR THE HISTOGRAM##################################################################################################### ################################################################################################################################################################################### histogram3 = plt.subplot2grid((3,4), (2, 0), colspan=2) bar(xCoordinatesPlot,spikeMeanInBin1, width=binTime) ylabel('trialsToUse1, Average number of spikes in bin size {} sec'.format(binTime)) xlabel(timeLabeling) histogram4 = plt.subplot2grid((3,4), (2, 2), colspan=2) bar(xCoordinatesPlot,spikeMeanInBin2, width=binTime) ylabel('trialsToUse2, Average number of spikes in bin size {} sec'.format(binTime)) xlabel(timeLabeling) show() #clusterName = 'cluster'+str(oneCell.cluster) #tetrodeName = 'TT'+str(tetrodeID) tetrodeClusterName = 'T'+str(tetrodeID)+'c'+str(cluster) plt.gcf().set_size_inches((8.5,11)) figformat = 'png' #'png' #'pdf' #'svg' filename = 'psy_%s_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,nametrialsToUse,figformat) fulloutputDir = outputDir+subject+'/'+'cluster_oneFreq'+'/' fullFileName = os.path.join(fulloutputDir,filename)
def plot_bandwidth_report(mouse, date, site, siteName): sessions = site.get_session_ephys_filenames() behavFilename = site.get_session_behav_filenames() ei = ephysinterface.EphysInterface(mouse, date, '', 'bandwidth_am') bdata = ei.loader.get_session_behavior(behavFilename[3][-4:-3]) charfreq = str(np.unique(bdata['charFreq'])[0]/1000) modrate = str(np.unique(bdata['modRate'])[0]) ei2 = ephysinterface.EphysInterface(mouse, date, '', 'am_tuning_curve') bdata2 = ei2.loader.get_session_behavior(behavFilename[1][-4:-3]) bdata3 = ei2.loader.get_session_behavior(behavFilename[2][-4:-3]) currentFreq = bdata2['currentFreq'] currentBand = bdata['currentBand'] currentAmp = bdata['currentAmp'] currentInt = bdata2['currentIntensity'] currentRate = bdata3['currentFreq'] #for tetrode in site.tetrodes: for tetrode in [2]: oneTT = sitefuncs.cluster_site(site, siteName, tetrode) dataSpikes = ei.loader.get_session_spikes(sessions[3], tetrode) dataSpikes2 = ei2.loader.get_session_spikes(sessions[1], tetrode) #clusters = np.unique(dataSpikes.clusters) clusters = [8] for cluster in clusters: plt.clf() # -- plot bandwidth rasters -- eventData = ei.loader.get_session_events(sessions[3]) spikeData = ei.loader.get_session_spikes(sessions[3], tetrode, cluster=cluster) eventOnsetTimes = ei.loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps timeRange = [-0.2, 1.5] numBands = np.unique(currentBand) numAmps = np.unique(currentAmp) firstSortLabels = ['{}'.format(band) for band in np.unique(currentBand)] secondSortLabels = ['Amplitude: {}'.format(amp) for amp in np.unique(currentAmp)] trialsEachCond = behavioranalysis.find_trials_each_combination(currentBand, numBands, currentAmp, numAmps) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) for ind, secondArrayVal in enumerate(numAmps): plt.subplot2grid((12, 15), (5*ind, 0), rowspan = 4, colspan = 7) trialsThisSecondVal = trialsEachCond[:, :, ind] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsThisSecondVal, labels=firstSortLabels) plt.setp(pRaster, ms=4) plt.title(secondSortLabels[ind]) plt.ylabel('bandwidth (octaves)') if ind == len(np.unique(currentAmp)) - 1: plt.xlabel("Time from sound onset (sec)") # -- plot Yashar plots for bandwidth data -- plt.subplot2grid((12,15), (10,0), rowspan = 2, colspan = 3) band_select_plot(spikeTimestamps, eventOnsetTimes, currentAmp, currentBand, [0.0, 1.0], title='bandwidth selectivity') plt.subplot2grid((12,15), (10,3), rowspan = 2, colspan = 3) band_select_plot(spikeTimestamps, eventOnsetTimes, currentAmp, currentBand, [0.2, 1.0], title='first 200ms excluded') # -- plot frequency tuning heat map -- plt.subplot2grid((12, 15), (5, 7), rowspan = 4, colspan = 4) eventData = ei2.loader.get_session_events(sessions[1]) spikeData = ei2.loader.get_session_spikes(sessions[1], tetrode, cluster=cluster) eventOnsetTimes = ei2.loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps dataplotter.two_axis_heatmap(spikeTimestamps=spikeTimestamps, eventOnsetTimes=eventOnsetTimes, firstSortArray=currentInt, secondSortArray=currentFreq, firstSortLabels=["%.1f" % inten for inten in np.unique(currentInt)], secondSortLabels=["%.1f" % freq for freq in np.unique(currentFreq)/1000.0], xlabel='Frequency (kHz)', ylabel='Intensity (dB SPL)', plotTitle='Frequency Tuning Curve', flipFirstAxis=True, flipSecondAxis=False, timeRange=[0, 0.1]) plt.ylabel('Intensity (dB SPL)') plt.xlabel('Frequency (kHz)') plt.title('Frequency Tuning Curve') # -- plot frequency tuning raster -- plt.subplot2grid((12,15), (0, 7), rowspan = 4, colspan = 4) freqLabels = ["%.1f" % freq for freq in np.unique(currentFreq)/1000.0] dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=currentFreq, timeRange=[-0.1, 0.5], labels=freqLabels) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Frequency (kHz)') plt.title('Frequency Tuning Raster') # -- plot AM PSTH -- eventData = ei2.loader.get_session_events(sessions[2]) spikeData = ei2.loader.get_session_spikes(sessions[2], tetrode, cluster=cluster) eventOnsetTimes = ei2.loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps timeRange = [-0.2, 1.5] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) colourList = ['b', 'g', 'y', 'orange', 'r'] numRates = np.unique(currentRate) trialsEachCond = behavioranalysis.find_trials_each_type(currentRate, numRates) binEdges = np.around(np.arange(-0.2, 0.85, 0.05), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) plt.subplot2grid((12,15), (5, 11), rowspan = 4, colspan = 4) pPSTH = extraplots.plot_psth(spikeCountMat/0.05, 1, binEdges[:-1], trialsEachCond, colorEachCond=colourList) plt.setp(pPSTH) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Firing rate (Hz)') plt.title('AM PSTH') # -- plot AM raster -- plt.subplot2grid((12,15), (0, 11), rowspan = 4, colspan = 4) rateLabels = ["%.1f" % rate for rate in np.unique(currentRate)] dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=currentRate, timeRange=[-0.2, 0.8], labels=rateLabels, colorEachCond=colourList) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Modulation Rate (Hz)') plt.title('AM Raster') # -- show cluster analysis -- tsThisCluster = oneTT.timestamps[oneTT.clusters==cluster] wavesThisCluster = oneTT.samples[oneTT.clusters==cluster] # -- Plot ISI histogram -- plt.subplot2grid((12,15), (10,6), rowspan=2, colspan=3) spikesorting.plot_isi_loghist(tsThisCluster) plt.ylabel('c%d'%cluster,rotation=0,va='center',ha='center') plt.xlabel('') # -- Plot waveforms -- plt.subplot2grid((12,15), (10,9), rowspan=2, colspan=3) spikesorting.plot_waveforms(wavesThisCluster) # -- Plot projections -- plt.subplot2grid((12,15), (10,12), rowspan=1, colspan=3) spikesorting.plot_projections(wavesThisCluster) # -- Plot events in time -- plt.subplot2grid((12,15), (11,12), rowspan=1, colspan=3) spikesorting.plot_events_in_time(tsThisCluster) plt.subplots_adjust(wspace = 1.5) plt.suptitle('{0}, {1}, {2}, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(mouse, date, siteName, tetrode, cluster, charfreq, modrate)) fig_path = oneTT.clustersDir fig_name = 'TT{0}Cluster{1}.png'.format(tetrode, cluster) full_fig_path = os.path.join(fig_path, fig_name) fig = plt.gcf() fig.set_size_inches(24, 12) fig.savefig(full_fig_path, format = 'png', bbox_inches='tight')
sortedTrials2 = [] #array that sorts trials for different frequencies for indf2,oneFreq2 in enumerate(possibleFreq): #indf is index of this freq and oneFreq is the frequency indsThisFreq2 = np.flatnonzero(targetFreqsTrials2==oneFreq2) #this gives indices of this frequency sortedTrials2.append(indsThisFreq2) #adds all indices to a list called sortedTrials colorEachFreq = [] strPossibleFreq = [] for indFreq, Freq in enumerate(possibleFreq): colorEachFreq.append('b') colorEachFreq.append('g') strPossibleFreq.append(str(Freq)) clf() rastorFreq1 = plt.subplot2grid((3,4), (0, 0), colspan=2, rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnsetTrials1, indexLimitsEachTrialTrials1, timeRange, sortedTrials1, labels=strPossibleFreq,colorEachCond = colorEachFreq) rastorFreq2 = plt.subplot2grid((3,4), (0, 2), colspan=2, rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnsetTrials2, indexLimitsEachTrialTrials2, timeRange, sortedTrials2, labels=strPossibleFreq,colorEachCond = colorEachFreq) ################################################################################################################################################################################### #####################################################THIS IS FOR THE HISTOGRAM##################################################################################################### ################################################################################################################################################################################### hist_Ymax = max(np.amax(spikeMeanInBin1),np.amax(spikeMeanInBin2))+0.1 histogram3 = plt.subplot2grid((3,4), (2, 0), colspan=2) bar(xCoordinatesPlot,spikeMeanInBin1, width=binTime)
eventData = loader.get_session_events(ephysDirs[bandIndex]) spikeData = loader.get_session_spikes(ephysDirs[bandIndex], int(cell['tetrode']), cluster=int(cell['cluster'])) eventOnsetTimes = loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps bdata = loader.get_session_behavior(behavDirs[bandIndex]) bandEachTrial = bdata['currentBand'] ampEachTrial = bdata['currentAmp'] spikeTimesFromEventOnset, indexLimitsEachTrial, trialsEachCond, firstSortLabels = bandwidths_analysis.bandwidth_raster_inputs(eventOnsetTimes, spikeTimestamps, bandEachTrial, ampEachTrial) ax1 = plt.subplot(gs[0, :-2]) trialsThisSecondVal = trialsEachCond[:, :, 0] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange = [-0.2, 1.5], trialsEachCond=trialsThisSecondVal, labels=firstSortLabels) plt.setp(pRaster, ms=4) extraplots.boxoff(plt.gca()) plt.xlabel('Time from stimulus onset (s)', fontsize=fontSizeLabels) plt.ylabel('Bandwidth (octaves)', fontsize=fontSizeLabels) extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks) ax1.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold') ax2 = plt.subplot(gs[1,:-2]) trialsThisSecondVal = trialsEachCond[:, :, 1] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange = [-0.2, 1.5],
# -- Load Spike Data From Certain Cluster -- spkData = ephyscore.CellData(oneCell) spkTimeStamps = spkData.spikes.timestamps (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) plt.clf() ax1 = plt.subplot2grid((3,1), (0, 0), rowspan=2) plt.setp(ax1.get_xticklabels(), visible=False) 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)')
ax1.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold') rasterFilename = 'example_movement_sel_raster_adap017_20160330a_T4_c11.npz' #adap013_20160406a_T8_c4 #test059_20150629a_T2_c7 rasterFullPath = os.path.join(dataDir, rasterFilename) rasterExample =np.load(rasterFullPath) trialsEachCond = rasterExample['trialsEachCond'] colorEachCond = rasterExample['colorEachCond'] condLabels = rasterExample['condLabels'] spikeTimesFromEventOnset = rasterExample['spikeTimesFromEventOnset'] indexLimitsEachTrial = rasterExample['indexLimitsEachTrial'] timeRange = rasterExample['timeRange'] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange=timeRangeMovement, trialsEachCond=trialsEachCond, colorEachCond=MOVEMENTCOLORS) plt.setp(pRaster, ms=msRaster) soundTimesFromEventOnset = rasterExample['soundTimesFromEventOnset'] trialsToUse = np.sum(trialsEachCond, axis=1).astype('bool') yLims = plt.gca().get_ylim() plt.hold('on') bplot = plt.boxplot(soundTimesFromEventOnset[trialsToUse], sym='', vert=False, positions=[yLims[-1]+15], widths=[25]) extraplots.boxoff(plt.gca()) plt.autoscale(enable=True, axis='y', tight=True) plt.axis('off') for element in ['boxes', 'whiskers', 'fliers', 'caps']: plt.setp(bplot[element], color='grey', linewidth=1)
def plot_bandwidth_report(cell, bandIndex): cellInfo = get_cell_info(cell) #pdb.set_trace() loader = dataloader.DataLoader(cell['subject']) if len(cellInfo['laserIndex'])>0: laser = True gs = gridspec.GridSpec(13, 6) else: laser = False gs = gridspec.GridSpec(9, 6) offset = 4*laser gs.update(left=0.15, right=0.85, top = 0.96, wspace=0.7, hspace=1.0) # -- plot bandwidth rasters -- plt.clf() eventData = loader.get_session_events(cellInfo['ephysDirs'][bandIndex]) spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][bandIndex], cellInfo['tetrode'], cluster=cellInfo['cluster']) eventOnsetTimes = loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps timeRange = [-0.2, 1.5] bandBData = loader.get_session_behavior(cellInfo['behavDirs'][bandIndex]) bandEachTrial = bandBData['currentBand'] ampEachTrial = bandBData['currentAmp'] charfreq = str(np.unique(bandBData['charFreq'])[0]/1000) modrate = str(np.unique(bandBData['modRate'])[0]) numBands = np.unique(bandEachTrial) numAmps = np.unique(ampEachTrial) firstSortLabels = ['{}'.format(band) for band in np.unique(bandEachTrial)] secondSortLabels = ['Amplitude: {}'.format(amp) for amp in np.unique(ampEachTrial)] spikeTimesFromEventOnset, indexLimitsEachTrial, trialsEachCond, firstSortLabels = bandwidth_raster_inputs(eventOnsetTimes, spikeTimestamps, bandEachTrial, ampEachTrial) colours = [np.tile(['#4e9a06','#8ae234'],len(numBands)/2+1), np.tile(['#5c3566','#ad7fa8'],len(numBands)/2+1)] for ind, secondArrayVal in enumerate(numAmps): plt.subplot(gs[5+2*ind+offset:7+2*ind+offset, 0:3]) trialsThisSecondVal = trialsEachCond[:, :, ind] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsThisSecondVal, labels=firstSortLabels, colorEachCond = colours[ind]) plt.setp(pRaster, ms=4) plt.title(secondSortLabels[ind]) plt.ylabel('bandwidth (octaves)') if ind == len(np.unique(ampEachTrial)) - 1: plt.xlabel("Time from sound onset (sec)") # -- plot Yashar plots for bandwidth data -- plt.subplot(gs[5+offset:, 3:]) spikeArray, errorArray, baseSpikeRate = band_select(spikeTimestamps, eventOnsetTimes, ampEachTrial, bandEachTrial, timeRange = [0.0, 1.0]) band_select_plot(spikeArray, errorArray, baseSpikeRate, numBands, legend=True) # -- plot frequency tuning heat map -- tuningBData = loader.get_session_behavior(cellInfo['behavDirs'][cellInfo['tuningIndex'][-1]]) freqEachTrial = tuningBData['currentFreq'] intEachTrial = tuningBData['currentIntensity'] eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['tuningIndex'][-1]]) spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['tuningIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster']) eventOnsetTimes = loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps plt.subplot(gs[2+offset:4+offset, 0:3]) dataplotter.two_axis_heatmap(spikeTimestamps=spikeTimestamps, eventOnsetTimes=eventOnsetTimes, firstSortArray=intEachTrial, secondSortArray=freqEachTrial, firstSortLabels=["%.0f" % inten for inten in np.unique(intEachTrial)], secondSortLabels=["%.1f" % freq for freq in np.unique(freqEachTrial)/1000.0], xlabel='Frequency (kHz)', ylabel='Intensity (dB SPL)', plotTitle='Frequency Tuning Curve', flipFirstAxis=False, flipSecondAxis=False, timeRange=[0, 0.1]) plt.ylabel('Intensity (dB SPL)') plt.xlabel('Frequency (kHz)') plt.title('Frequency Tuning Curve') # -- plot frequency tuning raster -- plt.subplot(gs[0+offset:2+offset, 0:3]) freqLabels = ["%.1f" % freq for freq in np.unique(freqEachTrial)/1000.0] dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=freqEachTrial, timeRange=[-0.1, 0.5], labels=freqLabels) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Frequency (kHz)') plt.title('Frequency Tuning Raster') # -- plot AM PSTH -- amBData = loader.get_session_behavior(cellInfo['behavDirs'][cellInfo['amIndex'][-1]]) rateEachTrial = amBData['currentFreq'] eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['amIndex'][-1]]) spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['amIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster']) eventOnsetTimes = loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps timeRange = [-0.2, 1.5] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) colourList = ['b', 'g', 'y', 'orange', 'r'] numRates = np.unique(rateEachTrial) trialsEachCond = behavioranalysis.find_trials_each_type(rateEachTrial, numRates) plt.subplot(gs[2+offset:4+offset, 3:]) dataplotter.plot_psth(spikeTimestamps, eventOnsetTimes, rateEachTrial, timeRange = [-0.2, 0.8], binsize = 25, colorEachCond = colourList) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Firing rate (Hz)') plt.title('AM PSTH') # -- plot AM raster -- plt.subplot(gs[0+offset:2+offset, 3:]) rateLabels = ["%.0f" % rate for rate in np.unique(rateEachTrial)] dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=rateEachTrial, timeRange=[-0.2, 0.8], labels=rateLabels, colorEachCond=colourList) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Modulation Rate (Hz)') plt.title('AM Raster') # -- plot laser pulse and laser train data (if available) -- if laser: # -- plot laser pulse raster -- plt.subplot(gs[0:2, 0:3]) 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 timeRange = [-0.1, 0.4] dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, timeRange=timeRange) plt.xlabel('Time from sound onset (sec)') plt.title('Laser Pulse Raster') # -- plot laser pulse psth -- plt.subplot(gs[2:4, 0:3]) dataplotter.plot_psth(spikeTimestamps, eventOnsetTimes, timeRange = timeRange, binsize = 10) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Pulse PSTH') # -- didn't record laser trains for some earlier sessions -- if len(cellInfo['laserTrainIndex']) > 0: # -- plot laser train raster -- plt.subplot(gs[0:2, 3:]) eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['laserTrainIndex'][-1]]) spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['laserTrainIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster']) eventOnsetTimes = loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps timeRange = [-0.2, 1.0] dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, timeRange=timeRange) plt.xlabel('Time from sound onset (sec)') plt.title('Laser Train Raster') # -- plot laser train psth -- plt.subplot(gs[2:4, 3:]) dataplotter.plot_psth(spikeTimestamps, eventOnsetTimes, timeRange = timeRange, binsize = 10) plt.xlabel('Time from sound onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Train PSTH') # -- show cluster analysis -- tsThisCluster, wavesThisCluster = load_cluster_waveforms(cellInfo) # -- Plot ISI histogram -- plt.subplot(gs[4+offset, 0:2]) spikesorting.plot_isi_loghist(tsThisCluster) plt.ylabel('c%d'%cellInfo['cluster'],rotation=0,va='center',ha='center') plt.xlabel('') # -- Plot waveforms -- plt.subplot(gs[4+offset, 2:4]) spikesorting.plot_waveforms(wavesThisCluster) # -- Plot events in time -- plt.subplot(gs[4+offset, 4:6]) spikesorting.plot_events_in_time(tsThisCluster) plt.suptitle('{0}, {1}, {2}um, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(cellInfo['subject'], cellInfo['date'], cellInfo['depth'], cellInfo['tetrode'], cellInfo['cluster'], charfreq, modrate)) fig_path = '/home/jarauser/Pictures/cell reports' fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}.png'.format(cellInfo['subject'], cellInfo['date'], cellInfo['depth'], cellInfo['tetrode'], cellInfo['cluster']) full_fig_path = os.path.join(fig_path, fig_name) fig = plt.gcf() fig.set_size_inches(20, 25) fig.savefig(full_fig_path, format = 'png', bbox_inches='tight')
def plot_rew_change_per_cell(oneCell,trialLimit=[],alignment='sound'): ''' Plots raster and PSTH for one cell during reward_change_freq_dis task, split by block; alignment parameter should be set to either 'sound', 'center-out', or 'side-in'. ''' bdata = load_behav_per_cell(oneCell) (spikeTimestamps,waveforms,eventOnsetTimes,eventData) = load_ephys_per_cell(oneCell) # -- Check to see if ephys has skipped trials, if so remove trials from behav data soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) soundOnsetTimeEphys = eventOnsetTimes[soundOnsetEvents] soundOnsetTimeBehav = bdata['timeTarget'] # Find missing trials missingTrials = behavioranalysis.find_missing_trials(soundOnsetTimeEphys,soundOnsetTimeBehav) # Remove missing trials bdata.remove_trials(missingTrials) currentBlock = bdata['currentBlock'] blockTypes = [bdata.labels['currentBlock']['same_reward'],bdata.labels['currentBlock']['more_left'],bdata.labels['currentBlock']['more_right']] #blockLabels = ['more_left', 'more_right'] if(not len(trialLimit)): validTrials = np.ones(len(currentBlock),dtype=bool) else: validTrials = np.zeros(len(currentBlock),dtype=bool) validTrials[trialLimit[0]:trialLimit[1]] = 1 trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes) if alignment == 'sound': soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] elif alignment == 'center-out': soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] diffTimes=bdata['timeCenterOut']-bdata['timeTarget'] EventOnsetTimes+=diffTimes elif alignment == 'side-in': soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] diffTimes=bdata['timeSideIn']-bdata['timeTarget'] EventOnsetTimes+=diffTimes freqEachTrial = bdata['targetFrequency'] possibleFreq = np.unique(freqEachTrial) 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'] incorrect = bdata['outcome']==bdata.labels['outcome']['error'] ######Split left and right trials into correct and incorrect categories to look at error trials######### rightcorrect = rightward&correct&validTrials leftcorrect = leftward&correct&validTrials #righterror = rightward&incorrect&validTrials #lefterror = leftward&incorrect&validTrials rightcorrectBlockSameReward = rightcorrect&trialsEachType[:,0] rightcorrectBlockMoreLeft = rightcorrect&trialsEachType[:,1] rightcorrectBlockMoreRight = rightcorrect&trialsEachType[:,2] leftcorrectBlockSameReward = leftcorrect&trialsEachType[:,0] leftcorrectBlockMoreLeft = leftcorrect&trialsEachType[:,1] leftcorrectBlockMoreRight = leftcorrect&trialsEachType[:,2] trialsEachCond = np.c_[leftcorrectBlockMoreLeft,rightcorrectBlockMoreLeft,leftcorrectBlockMoreRight,rightcorrectBlockMoreRight,leftcorrectBlockSameReward,rightcorrectBlockSameReward] colorEachCond = ['g','r','m','b','y','darkgray'] #trialsEachCond = np.c_[invalid,leftcorrect,rightcorrect,lefterror,righterror] #colorEachCond = ['0.75','g','r','b','m'] (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spikeTimestamps,EventOnsetTimes,timeRange) ###########Plot raster and PSTH################# plt.figure() ax1 = plt.subplot2grid((8,5), (0, 0), rowspan=4,colspan=5) extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None) plt.ylabel('Trials') plt.xlim(timeRange) plt.title('{0}_{1}_TT{2}_c{3}_{4}'.format(oneCell.animalName,oneCell.behavSession,oneCell.tetrode,oneCell.cluster,alignment)) timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = 3 ax2 = plt.subplot2grid((8,5), (4, 0),colspan=5,rowspan=2,sharex=ax1) extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1) plt.xlabel('Time from {0} onset (s)'.format(alignment)) plt.ylabel('Firing rate (spk/sec)') # -- Plot ISI histogram -- plt.subplot2grid((8,5), (6,0), rowspan=1, colspan=2) spikesorting.plot_isi_loghist(spikeTimestamps) plt.ylabel('c%d'%oneCell.cluster,rotation=0,va='center',ha='center') plt.xlabel('') # -- Plot waveforms -- plt.subplot2grid((8,5), (7,0), rowspan=1, colspan=3) spikesorting.plot_waveforms(waveforms) # -- Plot projections -- plt.subplot2grid((8,5), (6,2), rowspan=1, colspan=3) spikesorting.plot_projections(waveforms) # -- Plot events in time -- plt.subplot2grid((8,5), (7,3), rowspan=1, colspan=2) spikesorting.plot_events_in_time(spikeTimestamps) plt.subplots_adjust(wspace = 0.7) #plt.show() #fig_path = #fig_name = 'TT{0}Cluster{1}{2}.png'.format(tetrode, cluster, '_2afc plot_each_type') #full_fig_path = os.path.join(fig_path, fig_name) #print full_fig_path plt.gcf().set_size_inches((8.5,11))
def plot_rew_change_byblock_per_cell(oneCell,trialLimit=[],alignment='sound',choiceSide='both'): ''' Plots ephys data during behavior (reward_change_freq_discrim paradigm), data split according to the block in behavior and the choice (left or right). only plotting correct trials. oneCell is an CellInfo object as in celldatabase. 'trialLimit' (e.g. [0, 600]) is the indecies of trials wish to be plotted. 'choiceSide' is a string, either 'left' or 'right', to plot leftward and rightward trials, respectively. If not provided, will plot both sides. 'alignment' selects which event to align spike data to, should be 'sound', 'center-out', or 'side-in'. ''' SAMPLING_RATE=30000.0 soundTriggerChannel = 0 # channel 0 is the sound presentation, 1 is the trial binWidth = 0.010 # Size of each bin in histogram in seconds #timeRange = [-0.2,0.8] # In seconds. Time range for rastor plot to plot spikes (around some event onset as 0) #timeRange = [-0.25,1.0] timeRange = [-0.4,1.2] bdata = load_behav_per_cell(oneCell) (spikeTimestamps,waveforms,eventOnsetTimes,eventData)=load_ephys_per_cell(oneCell) # -- Check to see if ephys has skipped trials, if so remove trials from behav data soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) soundOnsetTimeEphys = eventOnsetTimes[soundOnsetEvents] soundOnsetTimeBehav = bdata['timeTarget'] # Find missing trials missingTrials = behavioranalysis.find_missing_trials(soundOnsetTimeEphys,soundOnsetTimeBehav) # Remove missing trials bdata.remove_trials(missingTrials) currentBlock = bdata['currentBlock'] if(not len(trialLimit)): validTrials = np.ones(len(currentBlock),dtype=bool) else: validTrials = np.zeros(len(currentBlock),dtype=bool) validTrials[trialLimit[0]:trialLimit[1]] = 1 bdata.find_trials_each_block() trialsEachBlock = bdata.blocks['trialsEachBlock'] #print trialsEachBlock nBlocks = bdata.blocks['nBlocks'] #blockLabels = ['more_left', 'more_right'] 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'] incorrect = bdata['outcome']==bdata.labels['outcome']['error'] ######Split left and right trials into correct and incorrect categories to look at error trials######### rightcorrect = rightward&correct&validTrials leftcorrect = leftward&correct&validTrials #righterror = rightward&incorrect&validTrials #lefterror = leftward&incorrect&validTrials colorEachCond=[] ####construct trialsEachCond and colorEachCond for ploting#### for block in range(nBlocks): rightcorrectThisBlock = rightcorrect&trialsEachBlock[:,block] leftcorrectThisBlock = leftcorrect&trialsEachBlock[:,block] #trialTypeVec = leftcorrect*1+rightcorrect*2 #trialTypePossibleValues = [1,2] #1 stands for left correct, 2 stands for right correct firstIndexThisBlock=np.nonzero(trialsEachBlock[:,block])[0][0] if currentBlock[firstIndexThisBlock]==bdata.labels['currentBlock']['more_left']: if choiceSide=='right': colorThisCond='r' elif choiceSide=='left': colorThisCond='g' elif choiceSide=='both': colorThisCond=['g','r'] if currentBlock[firstIndexThisBlock]==bdata.labels['currentBlock']['more_right']: if choiceSide=='right': colorThisCond='b' elif choiceSide=='left': colorThisCond='m' elif choiceSide=='both': colorThisCond=['m','b'] if currentBlock[firstIndexThisBlock]==bdata.labels['currentBlock']['same_reward']: if choiceSide=='right': colorThisCond='darkgray' elif choiceSide=='left': colorThisCond='y' elif choiceSide=='both': colorThisCond=['y','darkgray'] #trialsEachTypeEachBlock = behavioranalysis.find_trials_each_type_each_block(trialTypeVec, trialTypePossibleValues,currentBlock,blockTypes) if block==0: #trialsEachCond=np.c_[leftcorrectThisBlock,rightcorrectThisBlock] if choiceSide=='right': trialsEachCond=np.c_[rightcorrectThisBlock] elif choiceSide=='left': trialsEachCond=np.c_[leftcorrectThisBlock] elif choiceSide=='both': trialsEachCond=np.c_[leftcorrectThisBlock,rightcorrectThisBlock] else: if choiceSide=='right': trialsEachCond=np.c_[trialsEachCond,rightcorrectThisBlock] elif choiceSide=='left': trialsEachCond=np.c_[trialsEachCond,leftcorrectThisBlock] elif choiceSide=='both': trialsEachCond=np.c_[trialsEachCond,leftcorrectThisBlock,rightcorrectThisBlock] colorEachCond.append(colorThisCond) if alignment == 'sound': soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] elif alignment == 'center-out': soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] diffTimes=bdata['timeCenterOut']-bdata['timeTarget'] EventOnsetTimes+=diffTimes elif alignment == 'side-in': soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel) EventOnsetTimes = eventOnsetTimes[soundOnsetEvents] diffTimes=bdata['timeSideIn']-bdata['timeTarget'] EventOnsetTimes+=diffTimes freqEachTrial = bdata['targetFrequency'] possibleFreq = np.unique(freqEachTrial) (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spikeTimestamps,EventOnsetTimes,timeRange) plt.figure() ###########Plot raster and PSTH################# ax1 = plt.subplot2grid((3,1), (0, 0), rowspan=2) pRaster,hcond,zline =extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond, colorEachCond=colorEachCond,fillWidth=None,labels=None) #plt.setp(pRaster, ms=0.8) plt.ylabel('Trials') plt.xlim(timeRange) fig_title='{0}_{1}_TT{2}_c{3}_{4}_{5}'.format(oneCell.animalName,oneCell.behavSession,oneCell.tetrode,oneCell.cluster,alignment,choiceSide) plt.title(fig_title) 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=1.5,downsamplefactor=1) plt.xlabel('Time from sound onset (s)') plt.ylabel('Firing rate (spk/sec)') #plt.show() #fig_path= #full_fig_path = os.path.join(fig_path, fig_title) #print full_fig_path #plt.tight_layout() plt.gcf().set_size_inches((8.5,11))
def plot_two_axis_sorted_raster(self, session, tetrode, experiment=-1, site=-1, firstSort='currentFreq', secondSort='currentIntensity', cluster = None, replace=0, timeRange = [-0.5, 1], ms = 1, firstLabels=None, secondLabels=None, yLabel=None, plotTitle=None): ''' Plot rasters sorted by 2 arrays. By default, sorts by frequency and intensity to copy functionality of old plot_sorted_tuning_raster method. However, can specify different arrays to sort by. ''' sessionObj = self.get_session_obj(session, experiment, site) sessionDir = sessionObj.ephys_dir() behavFile = sessionObj.behav_filename() bdata = self.loader.get_session_behavior(behavFile) plotTitle = sessionDir eventData = self.loader.get_session_events(sessionDir) spikeData = self.loader.get_session_spikes(sessionDir, tetrode, cluster) eventOnsetTimes = self.loader.get_event_onset_times(eventData) spikeTimestamps=spikeData.timestamps firstSortArray = bdata[firstSort] secondSortArray = bdata[secondSort] if not firstLabels: possibleFirst = np.unique(firstSortArray) if firstSort == 'currentFreq': firstLabels = ['{0:.1f}'.format(freq/1000.0) for freq in possibleFirst] else: firstLabels = ['{}'.format(val) for val in possibleFirst] if not secondLabels: possibleSecond = np.unique(secondSortArray) if secondSort == 'currentIntensity': secondLabels = ['{:.0f} dB'.format(intensity) for intensity in possibleSecond] else: secondLabels = ['{}'.format(val) for val in possibleSecond] xLabel="Time from sound onset (sec)" if replace: fig = plt.gcf() plt.clf() else: fig = plt.figure() # dataplotter.two_axis_sorted_raster(spikeTimestamps, # eventOnsetTimes, # firstSortArray, # secondSortArray, # firstLabels, # secondLabels, # xLabel, # yLabel, # plotTitle, # flipFirstAxis=False, # flipSecondAxis=True, # timeRange=timeRange, # ms=ms) # We flip the second axis so that high intensities appear at the top flipFirstAxis=False flipSecondAxis=True if not firstSortLabels: firstSortLabels = [] if not secondSortLabels: secondSortLabels = [] if not xLabel: xlabel = '' if not yLabel: ylabel = '' if not plotTitle: plotTitle = '' #Set first and second possible val arrays and invert them if desired for plotting firstPossibleVals = np.unique(firstSortArray) secondPossibleVals = np.unique(secondSortArray) if flipFirstAxis: firstPossibleVals = firstPossibleVals[::-1] firstSortLabels = firstSortLabels[::-1] if flipSecondAxis: secondPossibleVals = secondPossibleVals[::-1] secondSortLabels = secondSortLabels[::-1] #Find the trials that correspond to each pair of sorting values trialsEachCond = behavioranalysis.find_trials_each_combination( firstSortArray, firstPossibleVals, secondSortArray, secondPossibleVals) #Calculate the spike times relative to event onset times spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) #Grab the current figure and clear it for plotting fig = plt.gcf() plt.clf() plt.suptitle(plotTitle) #Make a new plot for each unique value of the second sort array, and then plot a raster on that plot sorted by this second array for ind, secondArrayVal in enumerate(secondPossibleVals): if ind == 0: fig.add_subplot(len(secondPossibleVals), 1, ind + 1) plt.title(plotTitle) else: fig.add_subplot( len(secondPossibleVals), 1, ind + 1, sharex=fig.axes[0], sharey=fig.axes[0]) trialsThisSecondVal = trialsEachCond[:, :, ind] pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsThisSecondVal, labels=firstSortLabels) plt.setp(pRaster, ms=ms) if secondSortLabels: # plt.ylabel(secondSortLabels[ind]) plt.title(secondSortLabels[ind]) if ind == len(secondPossibleVals) - 1: plt.xlabel(xLabel) if yLabel: plt.ylabel(yLabel) plt.show()
def laser_tuning_raster(cell, gs): laserSessionInds = cell.get_session_inds('laserTuningCurve') for count, sessionInd in enumerate(laserSessionInds): bdata = cell.load_behavior_by_index(sessionInd) ephysData = cell.load_ephys_by_index(sessionInd) freqEachTrial = bdata['currentFreq'] laserEachTrial = bdata['laserOn'] intEachTrial = bdata['currentIntensity'] eventOnsetTimes = ephysData['events']['stimOn'] spikeTimeStamps = ephysData['spikeTimes'] timeRange = [-0.3, 0.6] baseTimeRange = [-0.15, -0.05] possiblefreqs = np.unique(freqEachTrial) freqLabels = [round(x/1000, 1) for x in possiblefreqs] possiblelaser = np.unique(laserEachTrial) possibleInts = np.unique(intEachTrial) laserOnsetTimes = ephysData['events']['laserOn'] laserOffsetTimes = ephysData['events']['laserOff'] laserDuration = laserOffsetTimes - laserOnsetTimes meanLaser = round(laserDuration.mean(), 2) #print(meanLaser) laserEventOnsetTimes = eventOnsetTimes[laserEachTrial == True] if len(laserOnsetTimes) > len(laserEventOnsetTimes): laserStartTimes = laserOnsetTimes[:-1] - laserEventOnsetTimes elif len(laserEventOnsetTimes) > len(laserOnsetTimes): laserStartTimes = laserOnsetTimes - laserEventOnsetTimes[:-1] else: laserStartTimes = laserOnsetTimes - laserEventOnsetTimes laserStart = round(laserStartTimes.mean(), 2) #print(laserStart) #trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs) laserTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser) intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) #plt.figure() baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange) for intInd, inten in enumerate(possibleInts): for indLaser in possiblelaser: #plt.subplot(2, 1, indLaser) ax = plt.subplot(gs[indLaser, intInd + (count * 2) + 1]) if indLaser == 0: title = "No Laser " + str(inten) + " dB" else: title = "Laser " + str(inten) + " dB" trialsEachCond = laserTrialsEachCond[:,:,indLaser] & intTrialsEachCond[:,:,intInd] ''' try: base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, baseIndexLimitsEachTrial) except: behavBaseIndexLimitsEachTrial = baseIndexLimitsEachTrial[0:2,:-1] base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavBaseIndexLimitsEachTrial) base_avg = np.mean(base_avgs) base_frs = np.divide(base_avg, baseTimeRange[1] - baseTimeRange[0]) ''' trialsThisIntLaser = np.all([bdata['laserOn']==indLaser, bdata['currentIntensity']==inten], axis=0) baseSpikeMatThisCond = baseSpikeMat[trialsThisIntLaser==True] base_avg = np.mean(baseSpikeMatThisCond) / (baseTimeRange[1] - baseTimeRange[0]) base_sem = stats.sem(baseSpikeMatThisCond) / (baseTimeRange[1] - baseTimeRange[0]) title += " (Base FR: {} +/- {} spikes/s)".format(round(base_avg, 2), round(base_sem, 2)) #title += " (Base FR: {} spikes/s)".format(round(base_avg, 2)) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond, labels=freqLabels) if indLaser == 1: laserbar = patches.Rectangle((laserStart, sum(sum(trialsEachCond)) + 2), meanLaser, 5, color="b", clip_on=False) #laserbar = patches.Rectangle((-0.05, 10), 2.0, 5, color="b") ax.add_patch(laserbar) xlabel = 'Time from sound onset (s)' ylabel = 'Frequency (kHz)' plt.title(title, fontsize = 'medium') plt.xlabel(xlabel) plt.ylabel(ylabel) '''
def two_axis_sorted_raster(spikeTimestamps, eventOnsetTimes, firstSortArray, secondSortArray, firstSortLabels=None, secondSortLabels=None, xLabel=None, yLabel=None, plotTitle=None, flipFirstAxis=False, flipSecondAxis=True, #Useful for making the highest intensity plot on top timeRange=[-0.5, 1], ms=4): ''' This function takes two arrays and uses them to sort spikes into trials by combinaion, and then plots the spikes in raster form. The first sort array will be used to sort each raster plot, and there will be a separate raster plot for each possible value of the second sort array. This method was developed for plotting frequency-intensity tuning curve data in raster form, in which case the frequency each trial is passed as the first sort array, and the intensity each trial is passed as the second sort array. Args: spikeTimestamps (array): An array of spike timestamps to plot eventOnsetTimes (array): An array of event onset times. Spikes will be plotted in raster form relative to these times firstSortArray (array): An array of parameter values for each trial. Must be the same length as eventOnsetTimes. secondSortArray (array): Another array of paramenter values the same length as eventOnsetTimes. Better if this array has less possible values. firstSortLabels (list): A list containing strings to use as labels for the first sort array. Must contain one item for each possible value of the first sort array. secondSortLabels (list): Same idea as above, must contain one element for each possible value of the second sort array. xLabel (str): A string to use for the x label of the bottom raster plot flipFirstAxis (bool): Whether to flip the first sorting axis. Will result in trials with high values for the first sort array appearing on the bottom of each raster. flipSecondAxis (bool): Will result in trials with high values for the second sorting array appearing in the top raster plot timeRange (list): A list containing the range of times relative to the event onset times that will be plotted ms (int): The marker size to use for the raster plots ''' if not firstSortLabels: firstSortLabels = [] if not secondSortLabels: secondSortLabels = [] if not xLabel: xlabel = '' if not yLabel: ylabel = '' if not plotTitle: plotTitle = '' #Set first and second possible val arrays and invert them if desired for plotting firstPossibleVals = np.unique(firstSortArray) secondPossibleVals = np.unique(secondSortArray) if flipFirstAxis: firstPossibleVals = firstPossibleVals[::-1] firstSortLabels = firstSortLabels[::-1] if flipSecondAxis: secondPossibleVals = secondPossibleVals[::-1] secondSortLabels = secondSortLabels[::-1] #Find the trials that correspond to each pair of sorting values trialsEachCond = behavioranalysis.find_trials_each_combination( firstSortArray, firstPossibleVals, secondSortArray, secondPossibleVals) #Calculate the spike times relative to event onset times spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) #Grab the current figure and clear it for plotting fig = plt.gcf() plt.clf() #Make a new plot for each unique value of the second sort array, and then plot a raster on that plot sorted by this second array for ind, secondArrayVal in enumerate(secondPossibleVals): if ind == 0: fig.add_subplot(len(secondPossibleVals), 1, ind + 1) plt.title(plotTitle) else: fig.add_subplot( len(secondPossibleVals), 1, ind + 1, sharex=fig.axes[0], sharey=fig.axes[0]) trialsThisSecondVal = trialsEachCond[:, :, ind] pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsThisSecondVal, labels=firstSortLabels) plt.setp(pRaster, ms=ms) if secondSortLabels: plt.ylabel(secondSortLabels[ind]) if ind == len(secondPossibleVals) - 1: plt.xlabel(xLabel)
spikeData.samples=spikeData.samples[spikeData.clusters==cluster] spikeData.timestamps=spikeData.timestamps[spikeData.clusters==cluster] # convert to seconds and millivolts spikeData.samples = spikeData.samples.astype(float)-2**15 spikeData.samples = (1000.0/spikeData.gain[0,0]) * spikeData.samples spikeData.timestamps = spikeData.timestamps/spikeData.samplingRate eventData.timestamps = eventData.timestamps/eventData.samplingRate return eventData, spikeData def load_behaviour_data(subject, fileName): behavFile = os.path.join(settings.BEHAVIOR_PATH,subject,fileName) bdata = loadbehavior.BehaviorData(behavFile,readmode='full') return bdata # LOAD YOUR SHIT eventData, spikeData = load_ephys_data(SUBJECT, EPHYSSESSION, tetrode, cluster) eventOnsetTimes = eventData.get_event_onset_times() spikeTimeStamps = spikeData.timestamps tuningBData = load_behaviour_data(SUBJECT, BEHAVIORSESSION) freqEachTrial = tuningBData['currentFreq'] trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, np.unique(freqEachTrial)) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange, trialsEachCond=trialsEachCond, *args, **kwargs) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.setp(pRaster, ms=ms)
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)
rasterFilename = 'example_freq_tuning_raster_adap017_20160317a_T5_c3.npz' rasterFullPath = os.path.join(dataDir, rasterFilename) rasterExample =np.load(rasterFullPath) possibleFreq = rasterExample['possibleFreq'] trialsEachCond = rasterExample['trialsEachFreq'] spikeTimesFromEventOnset = rasterExample['spikeTimesFromEventOnset'] indexLimitsEachTrial = rasterExample['indexLimitsEachTrial'] timeRange = timeRangeSound #rasterExample['timeRange'] labels = ['%.1f' % f for f in np.unique(possibleFreq)/1000.0] cm_subsection = np.linspace(1.0, 0.0, len(possibleFreq)) colorEachFreq = [colormapTuning(x) for x in cm_subsection] pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=trialsEachCond, colorEachCond=colorEachFreq, labels=labels) plt.setp(pRaster, ms=msRaster) #plt.setp(ax1.get_yticklabels(), fontsize=fontSizeTicks-1)#rotation=-15, horizontalalignment='right') locs, labels = plt.yticks() plt.yticks([locs[0],locs[-1]],[labels[0],labels[-1]]) plt.ylabel('Frequency (kHz)',fontsize=fontSizeLabels) #, labelpad=labelDis) plt.xlim(timeRangeSound[0],timeRangeSound[1]) plt.gca().set_xticklabels('') ax2 = plt.subplot(gs00[2,:]) psthFilename = 'example_freq_tuning_psth_adap017_20160317a_T5_c3.npz' psthFullPath = os.path.join(dataDir, psthFilename)