def hist_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'] timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromMovementOnset, indexLimitsEachMovementTrial, timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, linestyle=None, linewidth=3, downsamplefactor=1) plt.xlabel('Time from center poke out (s)') plt.ylabel('Firing rate (spk/sec)') '''
def hist_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'] timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond, colorEachCond=colorEachCond,linestyle=None,linewidth=2,downsamplefactor=1) plt.xlabel('Time from sound onset (s)') plt.ylabel('Firing rate (spk/sec)')
def hist_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'] timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromMovementOnset,indexLimitsEachMovementTrial,timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond, colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1) plt.xlabel('Time from center poke out (s)') plt.ylabel('Firing rate (spk/sec)') '''
def hist_sound_block_switching(ax): 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'] timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond, colorEachCond=colorEachBlock,linestyle=None,linewidth=2,downsamplefactor=1) ax.axvspan(0.0, 0.1, color=[0.8,0.8,0.8], alpha=0.5, lw=0)
def hist_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'] timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond, colorEachCond=colorEachBlock,linestyle=None,linewidth=2,downsamplefactor=1) plt.xlabel('Time from sound onset (s)') plt.ylabel('Firing rate (spk/sec)')
def hist_movement_allFreq_switching(ax): 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'] timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromMovementOnset,indexLimitsEachMovementTrial,timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond, colorEachCond=colorEachCond,linestyle=None,linewidth=2,downsamplefactor=1) ax.axvline(x=0, ymin=0, ymax=1, color='r')
def hist_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'] timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromMovementOnset, indexLimitsEachMovementTrial, timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, linestyle=None, linewidth=2, downsamplefactor=1)
def plot_switching_PSTH(oneCell, freqToPlot='middle', alignment='sound', timeRange=[-0.5, 1], byBlock=True, binWidth=0.010): # -- calls load_remote_2afc_data(oneCell) to get the data, then plot raster -- # (eventData, spikeData, oldBdata) = load_remote_2afc_data(oneCell) spikeTimestamps = spikeData.timestamps # -- Get trialsEachCond and colorEachCond for plotting -- # (bdata, trialsEachCond, colorEachCond) = get_trials_each_cond_switching(oneCell=oneCell, freqToPlot=freqToPlot, byBlock=byBlock) # -- Calculate eventOnsetTimes based on alignment parameter -- # eventOnsetTimes = np.array(eventData.timestamps) 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) timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec) smoothWinSize = 3 #plt.figure() extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, linestyle=None, linewidth=2, downsamplefactor=1) plt.xlabel('Time from {0} (s)'.format(alignment)) plt.xlim(timeRange[0] + 0.1, timeRange[1]) plt.ylabel('Firing rate (spk/sec)') plt.fill([0, 0.1, 0.1, 0], [plt.ylim()[0], plt.ylim()[0], plt.ylim()[1], plt.ylim()[1]], color='0.75') extraplots.set_ticks_fontsize(plt.gca(), fontSize=16)
def plot_rew_change_per_cell_PSTH(oneCell, alignment='sound', freqToPlot='left', byBlock=False, timeRange=[-0.4, 1.2], binWidth=0.010): ''' Function to plot PSTH 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 PSTH -- # timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec) smoothWinSize = 3 plt.figure() #plt.subplot2grid((3,1), (2, 0)) 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)') plt.xlim(timeRange[0] + 0.1, timeRange[-1])
def plot_sorted_psth(spikeTimeStamps, eventOnsetTimes, sortArray, timeRange=[-0.5,1], binsize = 50, lw=2, plotLegend=False, *args, **kwargs): ''' Function to accept spike timestamps, event onset times, and a sorting array and plot a PSTH sorted by the sorting array Args: binsize (float) = size of bins for PSTH in ms ''' binsize = binsize/1000.0 # 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)) else: trialsEachCond = [] # Align spiketimestamps to the event onset times for plotting spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, [timeRange[0]-binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1], trialsEachCond, *args, **kwargs) plt.setp(pPSTH, lw=lw) plt.hold(True) zline = plt.axvline(0,color='0.75',zorder=-10) plt.xlim(timeRange) if plotLegend: if len(sortArray)>0: sortElems = np.unique(sortArray) for ind, pln in enumerate(pPSTH): pln.set_label(sortElems[ind]) # ax = plt.gca() # plt.legend(mode='expand', ncol=3, loc='best') plt.legend(ncol=3, loc='best')
def plot_movement_response_psth(animal, behavSession, ephysSession, tetrode, cluster, alignment='center-out', timeRange=[-0.3,0.5], binWidth=0.010, colorCondDict=colorDictMovement, smoothWinSize=3): ''' Function to plot activity during movement as psth. ''' 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 PSTH -- # timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = smoothWinSize #plt.subplot2grid((3,1), (2, 0)) pPSTH = extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1) # -- Add legend -- # for ind,line in enumerate(pPSTH): plt.setp(line, label=condLabels[ind]) plt.legend(loc='upper right', fontsize=10, handlelength=0.2, frameon=False, labelspacing=0, borderaxespad=0.1) plt.axvline(x=0,linewidth=1, color='darkgrey') plt.xlabel('Time from {0} onset (s)'.format(alignment)) plt.ylabel('Firing rate (spk/sec)') plt.xlim(timeRange[0]+0.1,timeRange[-1])
def plot_reward_change_psth(animal, behavSession, ephysSession, tetrode, cluster, alignment='sound', timeRange=[-0.3,0.4], binWidth=0.010, freqToPlot='low', byBlock=False, colorCondDict=colorDictRC, smoothWinSize=3): ''' Function to plot reward change psth. ''' spikeTimesFromEventOnset,indexLimitsEachTrial = get_intermediate_data_for_raster_psth(animal, behavSession, ephysSession, tetrode, cluster, alignment, timeRange) if freqToPlot == 'low' or freqToPlot=='high': trialsEachCond, colorEachCond, labelEachCond = get_trials_each_cond_reward_change(animal, behavSession, ephysSession, tetrode, cluster, freqToPlot=freqToPlot, byBlock=byBlock, colorCondDict=colorCondDict) elif freqToPlot == 'both': trialsEachCondList = [] colorEachCond = [] labelEachCond = [] for freq in ['low','high']: trialsEachCondThisFreq, colorEachCondThisFreq, labelEachCondThisFreq = get_trials_each_cond_reward_change(animal, behavSession, ephysSession, tetrode, cluster, freqToPlot=freq, byBlock=byBlock, colorCondDict=colorCondDict) trialsEachCondList.append(trialsEachCondThisFreq) colorEachCond.extend(colorEachCondThisFreq) labelEachCond.extend(labelEachCondThisFreq) trialsEachCond = np.concatenate(trialsEachCondList, axis=1) # -- Plot PSTH -- # timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = smoothWinSize #plt.subplot2grid((3,1), (2, 0)) pPSTH = extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1) # -- Add legend -- # for ind,line in enumerate(pPSTH): plt.setp(line, label=labelEachCond[ind]) plt.legend(loc='upper right', fontsize=10, handlelength=0.2, frameon=False, labelspacing=0, borderaxespad=0.1) plt.axvline(x=0,linewidth=1, color='darkgrey') plt.xlabel('Time from {0} onset (s)'.format(alignment)) plt.ylabel('Firing rate (spk/sec)') plt.xlim(timeRange[0]+0.1,timeRange[-1])
def hist_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'] timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, linestyle=None, linewidth=2, downsamplefactor=1) plt.xlabel('Time from sound onset (s)') plt.ylabel('Firing rate (spk/sec)')
def hist_allfreq_sound_psycurve(ax): 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]] timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec) #print np.shape(spikeCountMat) #print 'timeVec ',np.shape(timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, linestyle=None, linewidth=3, downsamplefactor=1) ax.axvspan(0.0, 0.1, color=[0.8, 0.8, 0.8], alpha=0.5, lw=0)
def hist_sound_psycurve(Frequency,ax): 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'] timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = 3 extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond, colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1) ax.axvspan(0.0, 0.1, color=[0.8,0.8,0.8], alpha=0.5, lw=0)
def plot_sorted_psth(spikeTimeStamps, eventOnsetTimes, sortArray, timeRange=[-0.5, 1], binsize=50, lw=2, plotLegend=False, *args, **kwargs): ''' Function to accept spike timestamps, event onset times, and a sorting array and plot a PSTH sorted by the sorting array Args: binsize (float) = size of bins for PSTH in ms ''' binsize = binsize / 1000.0 # 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)) else: trialsEachCond = [] # Align spiketimestamps to the event onset times for plotting spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, [timeRange[0] - binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0] - binsize, timeRange[1] + 2 * binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1], trialsEachCond, *args, **kwargs) plt.setp(pPSTH, lw=lw) plt.hold(True) zline = plt.axvline(0, color='0.75', zorder=-10) plt.xlim(timeRange) if plotLegend: if len(sortArray) > 0: sortElems = np.unique(sortArray) for ind, pln in enumerate(pPSTH): pln.set_label(sortElems[ind]) # ax = plt.gca() # plt.legend(mode='expand', ncol=3, loc='best') plt.legend(ncol=3, loc='best')
fontsize=fontSizeLabels) extraplots.boxoff(plt.gca(), keep='none') ax2 = plt.subplot(gs00[2, :]) spikeCountMat = intData['spikeCountMat'] timeVec = intData['timeVec'] binWidth = intData['binWidth'] condLabels = intData['condLabels'] condLabelsStr = [condDict[label] for label in condLabels] pPSTH = extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=trialsEachCond, colorEachCond=colorEachCond, linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth) extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks) plt.axvline(x=0, linewidth=1, color='darkgrey') yLims = [0, 45] #soundBarHeight = 0.1*yLims[-1] #plt.fill([0,0.1,0.1,0],yLims[-1]+np.array([0,0,soundBarHeight,soundBarHeight]), ec='none', fc=soundColor, clip_on=False) plt.ylim(yLims) plt.yticks(yLims) plt.xlim(timeRangeToPlot) plt.xticks(np.arange(-0.2, 0.6, 0.2)) plt.xlabel('Time from movement onset (s)', fontsize=fontSizeLabels) plt.ylabel('Firing rate\n(spk/s)',
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')
spikeCountMatSecondOddballA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, secondOddballIndexLimitsA, timeVec) spikeCountMatThirdOddballA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, thirdOddballIndexLimitsA, timeVec) spikeCountMatFirstStdA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, firstStandardIndexLimitsA, timeVec) spikeCountMatSecondStdA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, secondStandardIndexLimitsA, timeVec) spikeCountMatThirdStdA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, thirdStandardIndexLimitsA, timeVec) ax9 = plt.subplot2grid((4, 8), (3, 2)) extraplots.plot_psth(spikeCountMatFirstOddballA / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], colorEachCond='b', linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth) extraplots.plot_psth(spikeCountMatFirstStdA / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], colorEachCond='k', linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth) plt.xlabel('Time from event onset [s]', fontsize=9) plt.ylabel('Firing Rate [Hz]', fontsize=9) plt.title('{} kHz Sound'.format(arrayOfFrequenciesAkHz[2]), fontsize=9) plt.legend(handles=[oddball_patch, standard_patch], fontsize=7)
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)') nameFreq = str(Freq) 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,nameFreq,tetrodeClusterName,figformat) fulloutputDir = outputDir+subject+'/'+ nameFreq +'/' fullFileName = os.path.join(fulloutputDir,filename) directory = os.path.dirname(fulloutputDir) if not os.path.exists(directory): os.makedirs(directory)
def plot_tuning_PSTH_one_intensity(oneCell, intensity=50.0, timeRange=[-0.5, 1], binWidth=0.010, halfFreqs=True): #calls load_remote_tuning_data(oneCell) to get the data, then plot raster eventOnsetTimes, spikeTimestamps, bdata = load_remote_tuning_data( oneCell, BEHAVDIR_MOUNTED, EPHYSDIR_MOUNTED) freqEachTrial = bdata['currentFreq'] intensityEachTrial = bdata['currentIntensity'] possibleIntensity = np.unique(intensityEachTrial) if len(possibleIntensity) != 1: intensity = intensity #50dB is the stimulus intensity used in 2afc task ###Just select the trials with a given intensity### trialsThisIntensity = [intensityEachTrial == intensity] freqEachTrial = freqEachTrial[trialsThisIntensity] intensityEachTrial = intensityEachTrial[trialsThisIntensity] eventOnsetTimes = eventOnsetTimes[trialsThisIntensity] possibleFreq = np.unique(freqEachTrial) if halfFreqs: possibleFreq = possibleFreq[ 1::3] #slice to get every other frequence presented numFreqs = len(possibleFreq) #print len(intensityEachTrial),len(eventOnsetTimes),len(spikeTimestamps) trialsEachFreq = behavioranalysis.find_trials_each_type( freqEachTrial, possibleFreq) #pdb.set_trace() #for debug #colormap = plt.cm.gist_ncar #colorEachFreq = [colormap(i) for i in np.linspace(0, 0.9, numFreqs)] #from jaratoolbox.colorpalette import TangoPalette as Tango #colorEachFreq = [Tango['Aluminium3'], Tango['Orange2'],Tango['Chameleon1'],Tango['Plum1'],Tango['Chocolate1'],Tango['SkyBlue2'],Tango['ScarletRed1'],'k'] #Creat colorEachCond from color map from matplotlib import cm cm_subsection = np.linspace(0.0, 1.0, numFreqs) colorEachFreq = [cm.winter(x) for x in cm_subsection] #Create legend import matplotlib.patches as mpatches handles = [] for (freq, color) in zip(possibleFreq, colorEachFreq): patch = mpatches.Patch(color=color, label=str(freq) + ' Hz') handles.append(patch) (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange) timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec) smoothWinSize = 3 #plt.figure() extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=trialsEachFreq, colorEachCond=colorEachFreq, linestyle=None, linewidth=2, downsamplefactor=1) extraplots.set_ticks_fontsize(ax=plt.gca(), fontSize=14) plt.xlim(timeRange[0] + 0.1, timeRange[1]) plt.legend(handles=handles, loc=2) plt.xlabel('Time from sound onset (s)', fontsize=18) plt.ylabel('Firing rate (spk/sec)', fontsize=18)
def rasterBlock(oneCell): subject = oneCell.animalName behavSession = oneCell.behavSession ephysSession = oneCell.ephysSession ephysRoot = os.path.join(ephysRootDir,subject) # -- Load Behavior Data -- behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession) bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename) bdata.find_trials_each_block() # -- Load event data and convert event timestamps to ms -- ephysDir = os.path.join(ephysRoot, ephysSession) eventFilename=os.path.join(ephysDir, 'all_channels.events') events = loadopenephys.Events(eventFilename) # Load events data eventTimes=np.array(events.timestamps)/SAMPLING_RATE soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel) # -- Load Spike Data From Certain Cluster -- spkData = ephyscore.CellData(oneCell) spkTimeStamps = spkData.spikes.timestamps eventOnsetTimes = eventTimes[soundOnsetEvents] correct = bdata['outcome']==bdata.labels['outcome']['correct'] possibleFreq = np.unique(bdata['targetFrequency']) oneFreq = bdata['targetFrequency'] == possibleFreq[middleFreq] correctOneFreq = oneFreq & correct correctTrialsEachBlock = bdata.blocks['trialsEachBlock'] & correctOneFreq[:,np.newaxis] #trialsEachCond = np.c_[invalid,leftward,rightward]; colorEachCond = ['0.75','g','r'] #trialsEachCond = np.c_[leftward,rightward]; colorEachCond = ['0.5','0.7','0'] trialsEachCond = correctTrialsEachBlock; if bdata['currentBlock'][0]==bdata.labels['currentBlock']['low_boundary']: colorEachBlock = 3*['g','r'] else: colorEachBlock = 3*['r','g'] (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) #plot(spikeTimesFromEventOnset,trialIndexForEachSpike,'.') plt.clf() ax1 = plt.subplot2grid((3,1), (0, 0), rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=correctTrialsEachBlock, colorEachCond=colorEachBlock,fillWidth=None,labels=None) #plt.yticks([0,trialsEachCond.sum()]) #ax1.set_xticklabels([]) plt.ylabel('Trials') timeVec = np.arange(timeRange[0],timeRange[-1],binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec) smoothWinSize = 3 ax2 = plt.subplot2grid((3,1), (2, 0), sharex=ax1) extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=correctTrialsEachBlock, colorEachCond=colorEachBlock,linestyle=None,linewidth=3,downsamplefactor=1) plt.xlabel('Time from sound onset (s)') plt.ylabel('Firing rate (spk/sec)') #plt.show() nameFreq = str(possibleFreq[middleFreq]) tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster) plt.gcf().set_size_inches((8.5,11)) figformat = 'png' #'png' #'pdf' #'svg' filename = 'block_%s_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,nameFreq,figformat) fulloutputDir = outputDir+subject +'/' fullFileName = os.path.join(fulloutputDir,filename) directory = os.path.dirname(fulloutputDir) if not os.path.exists(directory): os.makedirs(directory) print 'saving figure to %s'%fullFileName plt.gcf().savefig(fullFileName,format=figformat)
indexLimitsEachTrial, timeRange, trialsEachCond=correctTrialsEachBlock, colorEachCond=colorEachBlock, fillWidth=None, labels=None) #plt.yticks([0,trialsEachCond.sum()]) #ax1.set_xticklabels([]) plt.ylabel('Trials') timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec) smoothWinSize = 3 ax2 = plt.subplot2grid((3, 1), (2, 0), sharex=ax1) extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=correctTrialsEachBlock, colorEachCond=colorEachBlock, linestyle=None, linewidth=3, downsamplefactor=1) plt.xlabel('Time from sound onset (s)') plt.ylabel('Firing rate (spk/sec)') plt.show()
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')
trialsEachCondOdd[:, 0]] spikeCountMatLowFreqStdInOddPara = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetOdd, iletLowFreqStdInOddPara, timeVec) iletHighFreqOddInOddPara = indexLimitsEachTrialOdd[:, trialsEachCondOdd[:, 1]] spikeCountMatHighFreqOddInOddPara = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetOdd, iletHighFreqOddInOddPara, timeVec) ax8 = plt.subplot2grid((3, 4), (1, 3)) extraplots.plot_psth(spikeCountMatHighFreqStdInStdPara / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], colorEachCond='k', linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth) extraplots.plot_psth(spikeCountMatHighFreqOddInOddPara / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], colorEachCond='b', linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth) plt.xlabel('Time from event onset [s]') plt.ylabel('Firing Rate [Hz]') plt.title('{} Hz Sound'.format(arrayOfFrequenciesOdd[1])) # Legend for PSTH
timeRange, trialsEachCond=[], colorEachCond='g') plt.setp(pRaster, ms=msRaster) plt.setp(hcond, zorder=3) plt.ylabel('Trial') axNoiseburstRaster.set_xlim(-0.3, 0.5) plt.title(con.title()) # PSTH plotting plt.sca(axNoiseburstPSTH) pPSTH = extraplots.plot_psth( spkMat[sessInd] / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth, colorEachCond='g') extraplots.boxoff(plt.gca()) plt.ylabel('Firing rate\n(spk/s)') plt.xlabel('time from onset of the sound(s)') # Laserpulse plotting elif con == 'laserpulse': # Raster plotting plt.sca(axLaserpulseRaster) pRaster, hcond, zline = extraplots.raster_plot( rast1[sessInd], rast2[sessInd],
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_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))
--- PSTH --- """ spikeCountMatFirstOddballA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, firstOddballIndexLimitsA, timeVec) spikeCountMatSecondOddballA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, secondOddballIndexLimitsA, timeVec) spikeCountMatFirstStdA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, firstStandardIndexLimitsA, timeVec) spikeCountMatSecondStdA = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnsetA, secondStandardIndexLimitsA, timeVec) plt.figure() extraplots.plot_psth(spikeCountMatFirstOddballA / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], colorEachCond=[(0.13, 0.86, 0.27)], linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth) extraplots.plot_psth(spikeCountMatFirstStdA / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], colorEachCond=[(0.13, 0.86, 0.27)], linestyle=['dotted'], linewidth=lwPsth, downsamplefactor=downsampleFactorPsth) plt.xticks(fontsize=16) plt.yticks(fontsize=16) plt.xlabel('Time from event onset [s]', fontsize=18) plt.ylabel('Firing Rate [Hz]', fontsize=18)
def plot_bandwidth_report(cell, bandIndex, type='normal'): plt.clf() if bandIndex is None: print 'No bandwidth session given' return #create cell object for loading data cellObj = ephyscore.Cell(cell) #change dimensions of report to add laser trials if they exist if len(cellObj.get_session_inds('laserPulse'))>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) tetrode=int(cell['tetrode']) cluster=int(cell['cluster']) #load bandwidth ephys and behaviour data bandEphysData, bandBData = cellObj.load_by_index(bandIndex) bandEventOnsetTimes = ephysanalysis.get_sound_onset_times(bandEphysData, 'bandwidth') bandSpikeTimestamps = bandEphysData['spikeTimes'] timeRange = [-0.2, 1.5] bandEachTrial = bandBData['currentBand'] numBands = np.unique(bandEachTrial) #change the trial type that the bandwidth session is split by so we can use this report for Arch-inactivation experiments #also changes the colours to be more thematically appropriate! (in Anna's opinion) if type=='laser': secondSort = bandBData['laserTrial'] secondSortLabels = ['no laser','laser'] colours = ['k', '#c4a000'] errorColours = ['0.5', '#fce94f'] gaussFitCol = 'gaussFit' tuningR2Col = 'tuningFitR2' elif type=='normal': secondSort = bandBData['currentAmp'] secondSortLabels = ['{} dB'.format(amp) for amp in np.unique(secondSort)] colours = ['#4e9a06','#5c3566'] errorColours = ['#8ae234','#ad7fa8'] gaussFitCol = 'gaussFit' tuningR2Col = 'tuningFitR2' charfreq = str(np.unique(bandBData['charFreq'])[0]/1000) modrate = str(np.unique(bandBData['modRate'])[0]) numBands = np.unique(bandEachTrial) # -- plot rasters of the bandwidth trials -- rasterColours = [np.tile([colours[0],errorColours[0]],len(numBands)/2+1), np.tile([colours[1],errorColours[1]],len(numBands)/2+1)] plot_separated_rasters(gs, [0,3], 5+offset, bandEachTrial, secondSort, bandSpikeTimestamps, bandEventOnsetTimes, colours=rasterColours, titles=secondSortLabels, plotHeight=2) # -- plot bandwidth tuning curves -- plt.subplot(gs[5+offset:, 3:]) timeRange = [0.2, 1.0]# if type=='normal' else [0.1, 1.1] baseRange = [-1.1, -0.3] tuningDict = ephysanalysis.calculate_tuning_curve_inputs(bandSpikeTimestamps, bandEventOnsetTimes, bandEachTrial, secondSort, timeRange, info='plotting') plot_tuning_curve(tuningDict['responseArray'], tuningDict['errorArray'], numBands, tuningDict['baselineSpikeRate'], linecolours=colours, errorcolours=errorColours) # load tuning ephys and behaviour data tuningEphysData, tuningBData = cellObj.load('tuningCurve') tuningEventOnsetTimes = ephysanalysis.get_sound_onset_times(tuningEphysData,'tuningCurve') tuningSpikeTimestamps = tuningEphysData['spikeTimes'] # -- plot frequency tuning at intensity used in bandwidth trial with gaussian fit -- # high amp bandwidth trials used to select appropriate frequency maxAmp = max(np.unique(bandBData['currentAmp'])) if maxAmp < 1: maxAmp = 66.0 #HARDCODED dB VALUE FOR SESSIONS DONE BEFORE NOISE CALIBRATION # find tone intensity that corresponds to tone sessions in bandwidth trial toneInt = maxAmp - 15.0 #HARDCODED DIFFERENCE IN TONE AND NOISE AMP BASED ON OSCILLOSCOPE READINGS FROM RIG 2 freqEachTrial = tuningBData['currentFreq'] plt.subplot(gs[2+offset:4+offset, 0:3]) plot_tuning_fitted_gaussian(tuningSpikeTimestamps, tuningEventOnsetTimes, tuningBData, toneInt, cell[gaussFitCol], cell[tuningR2Col], timeRange=cell['tuningTimeRange']) # -- plot frequency tuning raster -- plt.subplot(gs[0+offset:2+offset, 0:3]) freqLabels = ["%.1f" % freq for freq in np.unique(freqEachTrial)/1000.0] plot_sorted_raster(tuningSpikeTimestamps, tuningEventOnsetTimes, freqEachTrial, timeRange=[-0.2,0.6], labels=freqLabels) plt.title('Frequency Tuning Raster') # -- plot AM PSTH -- amEphysData, amBData = cellObj.load('AM') amEventOnsetTimes = ephysanalysis.get_sound_onset_times(amEphysData, 'AM') amSpikeTimestamps = amEphysData['spikeTimes'] rateEachTrial = amBData['currentFreq'] timeRange = [-0.2, 1.5] colourList = ['b', 'g', 'y', 'orange', 'r'] plt.subplot(gs[2+offset:4+offset, 3:]) plot_sorted_psth(amSpikeTimestamps, amEventOnsetTimes, 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)] plot_sorted_raster(amSpikeTimestamps, amEventOnsetTimes, 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 -- laserEphysData, noBehav = cellObj.load('laserPulse') laserEventOnsetTimes = laserEphysData['events']['laserOn'] laserSpikeTimestamps = laserEphysData['spikeTimes'] timeRange = [-0.1, 0.4] plt.subplot(gs[0:2, 0:3]) laserSpikeTimesFromEventOnset, trialIndexForEachSpike, laserIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserSpikeTimestamps, laserEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot(laserSpikeTimesFromEventOnset,laserIndexLimitsEachTrial,timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Pulse Raster') # -- plot laser pulse psth -- plt.subplot(gs[2:4, 0:3]) binsize = 10/1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(laserSpikeTimestamps, laserEventOnsetTimes, [timeRange[0]-binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Pulse PSTH') # -- didn't record laser trains for some earlier sessions -- if len(cellObj.get_session_inds('laserTrain')) > 0: # -- plot laser train raster -- laserTrainEphysData, noBehav = cellObj.load('laserTrain') laserTrainEventOnsetTimes = laserTrainEphysData['events']['laserOn'] laserTrainSpikeTimestamps = laserTrainEphysData['spikeTimes'] laserTrainEventOnsetTimes = spikesanalysis.minimum_event_onset_diff(laserTrainEventOnsetTimes, 0.5) timeRange = [-0.2, 1.0] plt.subplot(gs[0:2, 3:]) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Train Raster') # -- plot laser train psth -- plt.subplot(gs[2:4, 3:]) binsize = 10/1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, [timeRange[0]-binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Train PSTH') # -- show cluster analysis -- #tsThisCluster, wavesThisCluster, recordingNumber = celldatabase.load_all_spikedata(cell) # -- Plot ISI histogram -- plt.subplot(gs[4+offset, 0:2]) spikesorting.plot_isi_loghist(bandSpikeTimestamps) # -- Plot waveforms -- plt.subplot(gs[4+offset, 2:4]) spikesorting.plot_waveforms(bandEphysData['samples']) # -- Plot events in time -- plt.subplot(gs[4+offset, 4:6]) spikesorting.plot_events_in_time(bandSpikeTimestamps) title = '{0}, {1}, {2}um, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(cell['subject'], cell['date'], cell['depth'], tetrode, cluster, charfreq, modrate) plt.suptitle(title) fig_path = '/home/jarauser/Pictures/cell reports' fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}.png'.format(cell['subject'], cell['date'], cell['depth'], tetrode, 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')
# -- Panel B2: representative sound-evoked psth from psychometric task, Not modulated -- # ax3 = plt.subplot(gs01[3, :]) psthFilename = 'example_psycurve_soundaligned_psth_{}.npz'.format(exampleNonMod) psthFullPath = os.path.join(dataDir, psthFilename) psthExample =np.load(psthFullPath) condLabels = psthExample['condLabels'] trialsEachCond = psthExample['trialsEachCond'] colorEachCond = psthExample['colorEachCond'] spikeCountMat = psthExample['spikeCountMat'] timeVec = psthExample['timeVec'] binWidth = psthExample['binWidth'] #timeRange = psthExample['timeRange'] pPSTH = extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSizePsth,timeVec,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,linestyle=None,linewidth=lwPsth,downsamplefactor=downsampleFactorPsth) extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks) plt.axvline(x=0,linewidth=1, color='darkgrey') yLims = [0,100] soundBarHeight = 0.1*yLims[-1] plt.fill([0,0.1,0.1,0],yLims[-1]+np.array([0,0,soundBarHeight,soundBarHeight]), ec='none', fc=soundColor, clip_on=False) plt.ylim(yLims) plt.yticks(yLims) plt.xlim(timeRange) plt.xticks(np.arange(-0.2,0.6,0.2)) plt.xlabel('Time from sound onset (s)',fontsize=fontSizeLabels) plt.ylabel('Firing rate\n(spk/s)',fontsize=fontSizeLabels) #,labelpad=labelDis) extraplots.boxoff(plt.gca()) plt.legend(['Left','Right'], loc='upper right', fontsize=fontSizeTicks, handlelength=0.2,
def plot_blind_cell_quality(cell): plt.clf() gs = gridspec.GridSpec(5, 6) #create cell object for loading data cellObj = ephyscore.Cell(cell) # -- plot laser pulse raster -- laserEphysData, noBehav = cellObj.load('laserPulse') laserEventOnsetTimes = laserEphysData['events']['laserOn'] laserSpikeTimestamps = laserEphysData['spikeTimes'] timeRange = [-0.1, 0.4] plt.subplot(gs[0:2, 0:3]) laserSpikeTimesFromEventOnset, trialIndexForEachSpike, laserIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserSpikeTimestamps, laserEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot(laserSpikeTimesFromEventOnset,laserIndexLimitsEachTrial,timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Pulse Raster') # -- plot laser pulse psth -- plt.subplot(gs[2:4, 0:3]) binsize = 10/1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(laserSpikeTimestamps, laserEventOnsetTimes, [timeRange[0]-binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Pulse PSTH') # -- didn't record laser trains for some earlier sessions -- if len(cellObj.get_session_inds('laserTrain')) > 0: # -- plot laser train raster -- laserTrainEphysData, noBehav = cellObj.load('laserTrain') laserTrainEventOnsetTimes = laserTrainEphysData['events']['laserOn'] laserTrainSpikeTimestamps = laserTrainEphysData['spikeTimes'] laserTrainEventOnsetTimes = spikesanalysis.minimum_event_onset_diff(laserTrainEventOnsetTimes, 0.5) timeRange = [-0.2, 1.0] plt.subplot(gs[0:2, 3:]) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Train Raster') # -- plot laser train psth -- plt.subplot(gs[2:4, 3:]) binsize = 10/1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, [timeRange[0]-binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Train PSTH') # -- show cluster analysis -- #tsThisCluster, wavesThisCluster, recordingNumber = celldatabase.load_all_spikedata(cell) # -- Plot ISI histogram -- plt.subplot(gs[4, 0:2]) spikesorting.plot_isi_loghist(tsThisCluster) # -- Plot waveforms -- plt.subplot(gs[4, 2:4]) spikesorting.plot_waveforms(wavesThisCluster) # -- Plot events in time -- plt.subplot(gs[4, 4:6]) spikesorting.plot_events_in_time(tsThisCluster)
def main(oneCell): 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'] correct = bdata['outcome']==bdata.labels['outcome']['correct'] correctRightward = rightward & correct correctLeftward = leftward & correct possibleFreq = np.unique(bdata['targetFrequency']) Freq = possibleFreq[Frequency] oneFreq = bdata['targetFrequency'] == possibleFreq[Frequency] trialsToUseRight = correctRightward & oneFreq trialsToUseLeft = correctLeftward & oneFreq trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['g','r'] # -- 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) 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)') nameFreq = str(Freq) 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,nameFreq,tetrodeClusterName,figformat) fulloutputDir = outputDir+subject+'/'+ nameFreq +'/' 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)
noiseIndexLimitsEachTrial, timeRange, trialsEachCond=[], colorEachCond='g') plt.setp(pRaster, ms=msRaster) plt.setp(hcond, zorder=3) plt.ylabel('Trial') axNoiseburstRaster.set_xlim(-0.3, 0.5) plt.title("Noiseburst") # Plotting PSTH plt.sca(axNoiseburstPSTH) pPSTH = extraplots.plot_psth(noiseSpikeCountMat / binWidth, smoothWinSizePsth, timeVec, trialsEachCond=[], linestyle=None, linewidth=lwPsth, downsamplefactor=downsampleFactorPsth, colorEachCond='g') axNoiseburstPSTH.set_xlim(-0.3, 0.5) extraplots.boxoff(plt.gca()) plt.ylabel('Firing rate\n(spk/s)') plt.xlabel('Time from onset of the sound') # -----------Laserpulse------------ if "laserpulse" in sessions: # Loading data for session laserEphysData, noBehav = oneCell.load('laserpulse') # Variables needed for plotting laserSpikeTimes = laserEphysData['spikeTimes']
def rasterBlock(oneCell): subject = oneCell.animalName behavSession = oneCell.behavSession ephysSession = oneCell.ephysSession ephysRoot = os.path.join(ephysRootDir, subject) # -- Load Behavior Data -- behaviorFilename = loadbehavior.path_to_behavior_data( subject, experimenter, paradigm, behavSession) bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename) bdata.find_trials_each_block() # -- Load event data and convert event timestamps to ms -- ephysDir = os.path.join(ephysRoot, ephysSession) eventFilename = os.path.join(ephysDir, 'all_channels.events') events = loadopenephys.Events(eventFilename) # Load events data eventTimes = np.array(events.timestamps) / SAMPLING_RATE soundOnsetEvents = (events.eventID == 1) & (events.eventChannel == soundTriggerChannel) # -- Load Spike Data From Certain Cluster -- spkData = ephyscore.CellData(oneCell) spkTimeStamps = spkData.spikes.timestamps eventOnsetTimes = eventTimes[soundOnsetEvents] correct = bdata['outcome'] == bdata.labels['outcome']['correct'] possibleFreq = np.unique(bdata['targetFrequency']) oneFreq = bdata['targetFrequency'] == possibleFreq[middleFreq] correctOneFreq = oneFreq & correct correctTrialsEachBlock = bdata.blocks[ 'trialsEachBlock'] & correctOneFreq[:, np.newaxis] #trialsEachCond = np.c_[invalid,leftward,rightward]; colorEachCond = ['0.75','g','r'] #trialsEachCond = np.c_[leftward,rightward]; colorEachCond = ['0.5','0.7','0'] trialsEachCond = correctTrialsEachBlock if bdata['currentBlock'][0] == bdata.labels['currentBlock'][ 'low_boundary']: colorEachBlock = 3 * ['g', 'r'] else: colorEachBlock = 3 * ['r', 'g'] (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) #plot(spikeTimesFromEventOnset,trialIndexForEachSpike,'.') plt.clf() ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond=correctTrialsEachBlock, colorEachCond=colorEachBlock, fillWidth=None, labels=None) #plt.yticks([0,trialsEachCond.sum()]) #ax1.set_xticklabels([]) plt.ylabel('Trials') timeVec = np.arange(timeRange[0], timeRange[-1], binWidth) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec) smoothWinSize = 3 ax2 = plt.subplot2grid((3, 1), (2, 0), sharex=ax1) extraplots.plot_psth(spikeCountMat / binWidth, smoothWinSize, timeVec, trialsEachCond=correctTrialsEachBlock, colorEachCond=colorEachBlock, linestyle=None, linewidth=3, downsamplefactor=1) plt.xlabel('Time from sound onset (s)') plt.ylabel('Firing rate (spk/sec)') #plt.show() nameFreq = str(possibleFreq[middleFreq]) tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str( oneCell.cluster) plt.gcf().set_size_inches((8.5, 11)) figformat = 'png' #'png' #'pdf' #'svg' filename = 'block_%s_%s_%s_%s.%s' % ( subject, behavSession, tetrodeClusterName, nameFreq, figformat) fulloutputDir = outputDir + subject + '/' fullFileName = os.path.join(fulloutputDir, filename) directory = os.path.dirname(fulloutputDir) if not os.path.exists(directory): os.makedirs(directory) print 'saving figure to %s' % fullFileName plt.gcf().savefig(fullFileName, format=figformat)
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)
def plot_blind_cell_quality(cell): plt.clf() gs = gridspec.GridSpec(5, 6) #create cell object for loading data cellObj = ephyscore.Cell(cell) # -- plot laser pulse raster -- laserEphysData, noBehav = cellObj.load('laserPulse') laserEventOnsetTimes = laserEphysData['events']['laserOn'] laserSpikeTimestamps = laserEphysData['spikeTimes'] timeRange = [-0.1, 0.4] plt.subplot(gs[0:2, 0:3]) laserSpikeTimesFromEventOnset, trialIndexForEachSpike, laserIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserSpikeTimestamps, laserEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot( laserSpikeTimesFromEventOnset, laserIndexLimitsEachTrial, timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Pulse Raster') # -- plot laser pulse psth -- plt.subplot(gs[2:4, 0:3]) binsize = 10 / 1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserSpikeTimestamps, laserEventOnsetTimes, [timeRange[0] - binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0] - binsize, timeRange[1] + 2 * binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Pulse PSTH') # -- didn't record laser trains for some earlier sessions -- if len(cellObj.get_session_inds('laserTrain')) > 0: # -- plot laser train raster -- laserTrainEphysData, noBehav = cellObj.load('laserTrain') laserTrainEventOnsetTimes = laserTrainEphysData['events']['laserOn'] laserTrainSpikeTimestamps = laserTrainEphysData['spikeTimes'] laserTrainEventOnsetTimes = spikesanalysis.minimum_event_onset_diff( laserTrainEventOnsetTimes, 0.5) timeRange = [-0.2, 1.0] plt.subplot(gs[0:2, 3:]) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Train Raster') # -- plot laser train psth -- plt.subplot(gs[2:4, 3:]) binsize = 10 / 1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, [timeRange[0] - binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0] - binsize, timeRange[1] + 2 * binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Train PSTH') # -- show cluster analysis -- #tsThisCluster, wavesThisCluster, recordingNumber = celldatabase.load_all_spikedata(cell) # -- Plot ISI histogram -- plt.subplot(gs[4, 0:2]) spikesorting.plot_isi_loghist(tsThisCluster) # -- Plot waveforms -- plt.subplot(gs[4, 2:4]) spikesorting.plot_waveforms(wavesThisCluster) # -- Plot events in time -- plt.subplot(gs[4, 4:6]) spikesorting.plot_events_in_time(tsThisCluster)
def plot_bandwidth_report(cell, type='normal', bandTimeRange=[0.2, 1.0], bandBaseRange=[-1.0, -0.2]): plt.clf() bandIndex = int(cell['bestBandSession']) if bandIndex is None: print 'No bandwidth session given' return #create cell object for loading data cellObj = ephyscore.Cell(cell) #change dimensions of report to add laser trials if they exist if len(cellObj.get_session_inds('laserPulse')) > 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) tetrode = int(cell['tetrode']) cluster = int(cell['cluster']) #load bandwidth ephys and behaviour data bandEphysData, bandBData = cellObj.load_by_index(bandIndex) bandEventOnsetTimes = ephysanalysis.get_sound_onset_times( bandEphysData, 'bandwidth') bandSpikeTimestamps = bandEphysData['spikeTimes'] timeRange = [-0.2, 1.5] bandEachTrial = bandBData['currentBand'] numBands = np.unique(bandEachTrial) #change the trial type that the bandwidth session is split by so we can use this report for Arch-inactivation experiments #also changes the colours to be more thematically appropriate! (in Anna's opinion) if type == 'laser': secondSort = bandBData['laserTrial'] secondSortLabels = ['no laser', 'laser'] colours = ['k', '#c4a000'] errorColours = ['0.5', '#fce94f'] gaussFitCol = 'gaussFit' tuningR2Col = 'tuningFitR2' elif type == 'normal': secondSort = bandBData['currentAmp'] secondSortLabels = [ '{} dB'.format(amp) for amp in np.unique(secondSort) ] colours = ['#4e9a06', '#5c3566'] errorColours = ['#8ae234', '#ad7fa8'] gaussFitCol = 'gaussFit' tuningR2Col = 'tuningFitR2' charfreq = str(np.unique(bandBData['charFreq'])[0] / 1000) modrate = str(np.unique(bandBData['modRate'])[0]) numBands = np.unique(bandEachTrial) # -- plot rasters of the bandwidth trials -- rasterColours = [ np.tile([colours[0], errorColours[0]], len(numBands) / 2 + 1), np.tile([colours[1], errorColours[1]], len(numBands) / 2 + 1) ] plot_separated_rasters(gs, [0, 3], 5 + offset, bandEachTrial, secondSort, bandSpikeTimestamps, bandEventOnsetTimes, colours=rasterColours, titles=secondSortLabels, plotHeight=2) # -- plot bandwidth tuning curves -- plt.subplot(gs[5 + offset:, 3:]) tuningDict = ephysanalysis.calculate_tuning_curve_inputs( bandSpikeTimestamps, bandEventOnsetTimes, bandEachTrial, secondSort, bandTimeRange, baseRange=bandBaseRange, info='plotting') plot_tuning_curve(tuningDict['responseArray'], tuningDict['errorArray'], numBands, tuningDict['baselineSpikeRate'], linecolours=colours, errorcolours=errorColours) # load tuning ephys and behaviour data tuningEphysData, tuningBData = cellObj.load('tuningCurve') tuningEventOnsetTimes = ephysanalysis.get_sound_onset_times( tuningEphysData, 'tuningCurve') tuningSpikeTimestamps = tuningEphysData['spikeTimes'] # -- plot frequency tuning at intensity used in bandwidth trial with gaussian fit -- # high amp bandwidth trials used to select appropriate frequency maxAmp = max(np.unique(bandBData['currentAmp'])) if maxAmp < 1: maxAmp = 66.0 #HARDCODED dB VALUE FOR SESSIONS DONE BEFORE NOISE CALIBRATION # find tone intensity that corresponds to tone sessions in bandwidth trial toneInt = maxAmp - 15.0 #HARDCODED DIFFERENCE IN TONE AND NOISE AMP BASED ON OSCILLOSCOPE READINGS FROM RIG 2 freqEachTrial = tuningBData['currentFreq'] plt.subplot(gs[2 + offset:4 + offset, 0:3]) plot_tuning_fitted_gaussian(tuningSpikeTimestamps, tuningEventOnsetTimes, tuningBData, toneInt, cell[gaussFitCol], cell[tuningR2Col], timeRange=cell['tuningTimeRange']) # -- plot frequency tuning raster -- plt.subplot(gs[0 + offset:2 + offset, 0:3]) freqLabels = ["%.1f" % freq for freq in np.unique(freqEachTrial) / 1000.0] plot_sorted_raster(tuningSpikeTimestamps, tuningEventOnsetTimes, freqEachTrial, timeRange=[-0.2, 0.6], labels=freqLabels) plt.title('Frequency Tuning Raster') # -- plot AM PSTH -- amEphysData, amBData = cellObj.load('AM') amEventOnsetTimes = ephysanalysis.get_sound_onset_times(amEphysData, 'AM') amSpikeTimestamps = amEphysData['spikeTimes'] rateEachTrial = amBData['currentFreq'] timeRange = [-0.2, 1.5] colourList = ['b', 'g', 'y', 'orange', 'r'] plt.subplot(gs[2 + offset:4 + offset, 3:]) plot_sorted_psth(amSpikeTimestamps, amEventOnsetTimes, 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)] plot_sorted_raster(amSpikeTimestamps, amEventOnsetTimes, 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 -- laserEphysData, noBehav = cellObj.load('laserPulse') laserEventOnsetTimes = laserEphysData['events']['laserOn'] laserSpikeTimestamps = laserEphysData['spikeTimes'] timeRange = [-0.1, 0.4] plt.subplot(gs[0:2, 0:3]) laserSpikeTimesFromEventOnset, trialIndexForEachSpike, laserIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserSpikeTimestamps, laserEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot( laserSpikeTimesFromEventOnset, laserIndexLimitsEachTrial, timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Pulse Raster') # -- plot laser pulse psth -- plt.subplot(gs[2:4, 0:3]) binsize = 10 / 1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserSpikeTimestamps, laserEventOnsetTimes, [timeRange[0] - binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0] - binsize, timeRange[1] + 2 * binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Pulse PSTH') # -- didn't record laser trains for some earlier sessions -- if len(cellObj.get_session_inds('laserTrain')) > 0: # -- plot laser train raster -- laserTrainEphysData, noBehav = cellObj.load('laserTrain') laserTrainEventOnsetTimes = laserTrainEphysData['events'][ 'laserOn'] laserTrainSpikeTimestamps = laserTrainEphysData['spikeTimes'] laserTrainEventOnsetTimes = spikesanalysis.minimum_event_onset_diff( laserTrainEventOnsetTimes, 0.5) timeRange = [-0.2, 1.0] plt.subplot(gs[0:2, 3:]) spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, timeRange) pRaster, hcond, zline = extraplots.raster_plot( spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange) plt.xlabel('Time from laser onset (sec)') plt.title('Laser Train Raster') # -- plot laser train psth -- plt.subplot(gs[2:4, 3:]) binsize = 10 / 1000.0 spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, [timeRange[0] - binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0] - binsize, timeRange[1] + 2 * binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts( spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1]) plt.xlim(timeRange) plt.xlabel('Time from laser onset (sec)') plt.ylabel('Firing Rate (Hz)') plt.title('Laser Train PSTH') # -- show cluster analysis -- #tsThisCluster, wavesThisCluster, recordingNumber = celldatabase.load_all_spikedata(cell) # -- Plot ISI histogram -- plt.subplot(gs[4 + offset, 0:2]) spikesorting.plot_isi_loghist(bandSpikeTimestamps) # -- Plot waveforms -- plt.subplot(gs[4 + offset, 2:4]) spikesorting.plot_waveforms(bandEphysData['samples']) # -- Plot events in time -- plt.subplot(gs[4 + offset, 4:6]) spikesorting.plot_events_in_time(bandSpikeTimestamps) title = '{0}, {1}, {2}um, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format( cell['subject'], cell['date'], cell['depth'], tetrode, cluster, charfreq, modrate) plt.suptitle(title) fig_path = '/home/jarauser/Pictures/cell reports' fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}.png'.format( cell['subject'], cell['date'], cell['depth'], tetrode, 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')
# plotLegend=0) if spikeData.timestamps is not None: #NOTE: I am here. # dataplotter.plot_psth(spikeData.timestamps, eventOnsetTimes, plotLegend=0) binsize=0.02 (spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(spikeData.timestamps, eventOnsetTimes, [timeRange[0]-binsize, timeRange[1]]) binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2) spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges) pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1], trialsEachCond, colorEachCond=colors) plt.setp(pPSTH, lw=2) plt.hold(True) zline = plt.axvline(0,color='0.75',zorder=-10) plt.xlim(timeRange) extraplots.set_ticks_fontsize(ax7, 9) except IndexError: print "No AM for this cell" (timestamps, samples, recordingNumber) = dataloader.load_all_spikedata(cell)