ephysDir='/home/nick/data/ephys/test075/2014-11-06_17-27-43' event_filename=os.path.join(ephysDir, 'all_channels.events') behaviorDir='/home/nick/data/behavior/nick/test075/' behavDataFileName=os.path.join(behaviorDir, 'test075_tuning_curve_20141106a.h5') #Extract the frequency presented each trial from the behavior data bdata = loadbehavior.BehaviorData(behavDataFileName,readmode='full') freqEachTrial = bdata['currentFreq'] intensityEachTrial = bdata['currentIntensity'] possibleFreq = np.unique(freqEachTrial) possibleIntensity = np.unique(intensityEachTrial) #Get the event timestamps from openEphys ev=loadopenephys.Events(event_filename) evID=np.array(ev.eventID) eventOnsetTimes=ev.timestamps[evID==1] #The timestamps of all of the stimulus onsets #These are the active channels in this recording, sorted by tetrode tetrodeChannels = np.array([[9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]) #Get the continuous data channel = 24 #The channel to plot reference = 9 #Experimental: plotting without subtracting a reference made all channels look the same. cont_filename = os.path.join(ephysDir, '109_CH{0}.continuous'.format(channel)) ref_filename = os.path.join(ephysDir, '109_CH{0}.continuous'.format(reference)) ephysData = loadopenephys.DataCont(cont_filename) refData = loadopenephys.DataCont(ref_filename) #Subtract the reference channel (not sure yet if this is a good thing to include.)
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)
def main(): global behavSession global subject global bdata global eventOnsetTimes global spikeTimesFromEventOnset global indexLimitsEachTrial global spikeTimesFromMovementOnset global indexLimitsEachMovementTrial global titleText for cellID in range(0, numOfCells): oneCell = allcells.cellDB[cellID] if (behavSession != oneCell.behavSession): subject = oneCell.animalName behavSession = oneCell.behavSession ephysSession = oneCell.ephysSession ephysRoot = os.path.join(ephysRootDir, subject) # -- Load Behavior Data -- behaviorFilename = loadbehavior.path_to_behavior_data( subject, experimenter, paradigm, behavSession) bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename) #bdata = loadbehavior.BehaviorData(behaviorFilename) bdata.find_trials_each_block() numberOfTrials = len(bdata['choice']) # -- Load event data and convert event timestamps to ms -- ephysDir = os.path.join(ephysRoot, ephysSession) eventFilename = os.path.join(ephysDir, 'all_channels.events') events = loadopenephys.Events(eventFilename) # Load events data eventTimes = np.array( events.timestamps ) / SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and soundOnsetEvents = (events.eventID == 1) & (events.eventChannel == soundTriggerChannel) eventOnsetTimes = eventTimes[soundOnsetEvents] ################################################################################################# centerOutTimes = bdata[ 'timeCenterOut'] #This is the times that the mouse goes out of the center port soundStartTimes = bdata[ 'timeTarget'] #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial timeDiff = centerOutTimes - soundStartTimes if (len(eventOnsetTimes) < len(timeDiff)): timeDiff = timeDiff[:-1] eventOnsetTimesCenter = eventOnsetTimes + timeDiff ################################################################################################# # -- Load Spike Data From Certain Cluster -- spkData = ephyscore.CellData(oneCell) spkTimeStamps = spkData.spikes.timestamps (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange) plt.clf() if (len(spkTimeStamps) > 0): ax1 = plt.subplot2grid((numRows, numCols), ((numRows - sizeClusterPlot), 0), colspan=(numCols / 3)) spikesorting.plot_isi_loghist(spkData.spikes.timestamps) ax3 = plt.subplot2grid( (numRows, numCols), ((numRows - sizeClusterPlot), (numCols / 3) * 2), colspan=(numCols / 3)) spikesorting.plot_events_in_time(spkTimeStamps) samples = spkData.spikes.samples.astype(float) - 2**15 samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples ax2 = plt.subplot2grid( (numRows, numCols), ((numRows - sizeClusterPlot), (numCols / 3)), colspan=(numCols / 3)) spikesorting.plot_waveforms(samples) ############################################################################### ax4 = plt.subplot2grid((numRows, numCols), (0, 0), colspan=(numCols / 2), rowspan=sizeRasters) raster_sound_block_switching() ax5 = plt.subplot2grid((numRows, numCols), (sizeRasters, 0), colspan=(numCols / 2), rowspan=sizeHists) hist_sound_block_switching() ax6 = plt.subplot2grid((numRows, numCols), (0, (numCols / 2)), colspan=(numCols / 2), rowspan=sizeRasters) raster_movement_block_switching() ax7 = plt.subplot2grid((numRows, numCols), (sizeRasters, (numCols / 2)), colspan=(numCols / 2), rowspan=sizeHists) hist_movement_block_switching() ax8 = plt.subplot2grid((numRows, numCols), ((sizeRasters + sizeHists), 0), colspan=(numCols / 2), rowspan=sizeRasters) raster_sound_allFreq_switching() ax9 = plt.subplot2grid((numRows, numCols), ((2 * sizeRasters + sizeHists), 0), colspan=(numCols / 2), rowspan=sizeHists) hist_sound_allFreq_switching() ax10 = plt.subplot2grid((numRows, numCols), ((sizeRasters + sizeHists), (numCols / 2)), colspan=(numCols / 2), rowspan=sizeRasters) raster_sound_switching() ax11 = plt.subplot2grid((numRows, numCols), ((2 * sizeRasters + sizeHists), (numCols / 2)), colspan=(numCols / 2), rowspan=sizeHists) hist_sound_switching() ############################################################################### #plt.tight_layout() modulation_index_switching() plt.suptitle(titleText) tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str( oneCell.cluster) plt.gcf().set_size_inches((8.5, 11)) figformat = 'png' #'png' #'pdf' #'svg' filename = 'report_%s_%s_%s.%s' % (subject, behavSession, tetrodeClusterName, figformat) fulloutputDir = outputDir + subject + '/' fullFileName = os.path.join(fulloutputDir, filename) directory = os.path.dirname(fulloutputDir) if not os.path.exists(directory): #makes sure output folder exists os.makedirs(directory) print 'saving figure to %s' % fullFileName plt.gcf().savefig(fullFileName, format=figformat)
### Using cellDB methode to find the index of this cell in the cellDB ### cellIndex = allcells.cellDB.findcell(**cellParams) oneCell = allcells.cellDB[cellIndex] ######################## 2afc task ################################## ## Get behavior data associated with 2afc session ### behavFileName = '{0}_{1}_{2}.h5'.format(oneCell.animalName,'2afc',oneCell.behavSession) behavFile = os.path.join(BEHAVIOR_PATH,oneCell.animalName,behavFileName) bdata = loadbehavior.BehaviorData(behavFile,readmode='full') ### Get events data ### fullEventFilename=os.path.join(EPHYS_PATH, oneCell.animalName, oneCell.ephysSession, 'all_channels.events') eventData = loadopenephys.Events(fullEventFilename) ##### Get event onset times ##### eventData.timestamps = np.array(eventData.timestamps)/EPHYS_SAMPLING_RATE #hard-coded ephys sampling rate!! ### GEt spike data of just this cluster ### spikeFilename = os.path.join(EPHYS_PATH,oneCell.animalName,oneCell.ephysSession, 'Tetrode{}.spikes'.format(oneCell.tetrode)) spikeData = loadopenephys.DataSpikes(spikeFilename) spikeData.timestamps = spikeData.timestamps/EPHYS_SAMPLING_RATE clustersDir = os.path.join(EPHYS_PATH,oneCell.animalName,oneCell.ephysSession)+'_kk' clusterFilename = os.path.join(clustersDir, 'Tetrode{}.clu.1'.format(oneCell.tetrode)) clusters = np.fromfile(clusterFilename, dtype='int32', sep=' ')[1:] spikeData.timestamps = spikeData.timestamps[clusters==oneCell.cluster] spikeData.samples = spikeData.samples[clusters==oneCell.cluster, :, :] spikeData.samples = spikeData.samples.astype(float)-2**15# FIXME: this is specific to OpenEphys # FIXME: This assumes the gain is the same for all channels and records
def plot_raster(self, sessionName, sort=False, plot_tuning_curve=False): ''' Plots the spikes in a particular session with respect to a stimulus Arguments sessionName (string) - The name of the directory containing the .spikes and .events files sort (bool) - Whether to sort the spikes by frequency. Requires a behavior data file. plot_tuning_curve (bool) - Whether to plot frequency tuning curves. ''' ephysSession = sessionName event_filename = os.path.join(ephysSession, 'all_channels.events') ev = loadopenephys.Events(self.event_filename) eventTimes = np.array(ev.timestamps) / SAMPLING_RATE evID = np.array(ev.eventID) eventOnsetTimes = eventTimes[evID == 1] eventOnsetTimes = eventOnsetTimes[:-1] #Remove last started, but #not finished trial if sort: freqEachTrial = self.bdata['currentFreq'] possibleFreq = np.unique(freqEachTrial) sortedTrials = [] for indf, oneFreq in enumerate(possibleFreq): indsThisFreq = np.flatnonzero(freqEachTrial == oneFreq) sortedTrials = np.concatenate((sortedTrials, indsThisFreq)) sortingInds = argsort(sortedTrials) for ind in range(numTetrodes): tetrodeID = ind + 1 spike_filename = os.path.join( ephysSession, 'Tetrode{0}.spikes'.format(tetrodeID)) sp = loadopenephys.DataSpikes(spike_filename) try: #FIXME: We should keep the code inside the try to a minimum. spkTimeStamps = np.array(sp.timestamps) / SAMPLING_RATE (spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes( spkTimeStamps, eventOnsetTimes, timeRange) subplot(numTetrodes, 1, ind + 1) if sort: sortedIndexForEachSpike = sortingInds[ trialIndexForEachSpike] plot(spikeTimesFromEventOnset, sortedIndexForEachSpike, '.', ms=1) else: plot(spikeTimesFromEventOnset, trialIndexForEachSpike, '.') axvline(x=0, ymin=0, ymax=1, color='r') if ind == 0: title(ephysSession) #title('Channel {0} spikes'.format(ind+1)) except AttributeError: #Spikes files without any spikes will throw an error pass xlabel('time(sec)')
paradigm = 'am_tuning_curve' session = '20190731h' ephysSession = '2019-07-31_16-09-08' # subject = 'd1pi039' # paradigm = 'am_tuning_curve' # session = '20190731b' # ephysSession = '2019-07-31_11-17-46' eventsFilename = os.path.join(settings.EPHYS_PATH, subject, ephysSession, 'all_channels.events') behavFile = loadbehavior.path_to_behavior_data(subject, paradigm, session) behavData = loadbehavior.BehaviorData(behavFile, readmode='full') eventData = loadopenephys.Events(eventsFilename) channelID = 0 thisChannelOn = eventData.get_event_onset_times(eventID=1, eventChannel=channelID) behavDataSize = len(behavData['currentAmpL']) ephysDataSize = len(thisChannelOn) print('Behavior: {}'.format(behavDataSize)) print('Ephys: {}'.format(ephysDataSize)) trialsToRemove = behavDataSize - ephysDataSize + 1 if trialsToRemove > 0: for key, value in behavData.items(): behavData[key] = value[0:-trialsToRemove]
numTrialsEachFreq = [] #Used to plot lines after each group of sorted trials for indf, oneFreq in enumerate( possibleFreq ): #indf is index of this freq and oneFreq is the frequency indsThisFreq = np.flatnonzero( freqEachTrial == oneFreq) #this gives indices of this frequency sortedTrials = np.concatenate( (sortedTrials, indsThisFreq)) #adds all indices to a list called sortedTrials numTrialsEachFreq.append( len(indsThisFreq)) #finds number of trials each frequency has sortingInds = argsort( sortedTrials) #gives array of indices that would sort the sortedTrials # -- Load event data and convert event timestamps to ms -- ev = loadopenephys.Events( event_filename) #load ephys data (like bdata structure) eventTimes = np.array( ev.timestamps ) / SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and evID = np.array( ev.eventID ) #loads the onset times of events (matches up with eventID to say if event 1 went on (1) or off (0) eventOnsetTimes = eventTimes[ evID == 1] #array that is a time stamp for when the chosen event happens. #ev.eventChannel woul load array of events like trial start and sound start and finish times (sound event is 0 and trial start is 1 for example). There is only one event though and its sound start while (numberOfTrials < len(eventOnsetTimes)): eventOnsetTimes = eventOnsetTimes[:-1] spike_filename = os.path.join( ephysDir, 'Tetrode{0}.spikes'.format(tetrodeID) ) #make a path to ephys spike data of specified tetrode tetrodeID
def main(): global behavSession global subject global tetrode global cluster global tuningBehavior#behavior file name of tuning curve global tuningEphys#ephys session name of tuning curve global bdata global eventOnsetTimes global spikeTimesFromEventOnset global indexLimitsEachTrial global spikeTimesFromMovementOnset global indexLimitsEachMovementTrial global titleText print "switch_tuning_report" for cellID in range(0,numOfCells): oneCell = allcells.cellDB[cellID] try: if (behavSession != oneCell.behavSession): subject = oneCell.animalName behavSession = oneCell.behavSession ephysSession = oneCell.ephysSession tuningSession = oneCell.tuningSession ephysRoot = os.path.join(ephysRootDir,subject) tuningBehavior = oneCell.tuningBehavior tuningEphys = oneCell.tuningSession print behavSession # -- Load Behavior Data -- behaviorFilename = loadbehavior.path_to_behavior_data(subject=subject,paradigm=paradigm,sessionstr=behavSession) bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename) #bdata = loadbehavior.BehaviorData(behaviorFilename) numberOfTrials = len(bdata['choice']) # -- Load event data and convert event timestamps to ms -- ephysDir = os.path.join(ephysRoot, ephysSession) eventFilename=os.path.join(ephysDir, 'all_channels.events') events = loadopenephys.Events(eventFilename) # Load events data eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel) eventOnsetTimes = eventTimes[soundOnsetEvents] soundOnsetTimeBehav = bdata['timeTarget'] # Find missing trials missingTrials = behavioranalysis.find_missing_trials(eventOnsetTimes,soundOnsetTimeBehav) # Remove missing trials bdata.remove_trials(missingTrials) bdata.find_trials_each_block() ############################################################################################### centerOutTimes = bdata['timeCenterOut'] #This is the times that the mouse goes out of the center port soundStartTimes = bdata['timeTarget'] #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial timeDiff = centerOutTimes - soundStartTimes if (len(eventOnsetTimes) < len(timeDiff)): timeDiff = timeDiff[:-1] eventOnsetTimesCenter = eventOnsetTimes + timeDiff elif (len(eventOnsetTimes) > len(timeDiff)): eventOnsetTimesCenter = eventOnsetTimes[:-1] + timeDiff else: eventOnsetTimesCenter = eventOnsetTimes + timeDiff ############################################################################################### tetrode = oneCell.tetrode cluster = oneCell.cluster # -- Load Spike Data From Certain Cluster -- spkData = ephyscore.CellData(oneCell) spkTimeStamps = spkData.spikes.timestamps (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange) plt.clf() if (len(spkTimeStamps)>0): ax1 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),0), colspan = (numCols/3)) spikesorting.plot_isi_loghist(spkData.spikes.timestamps) ax3 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)*2), colspan = (numCols/3)) spikesorting.plot_events_in_time(spkTimeStamps) samples = spkData.spikes.samples.astype(float)-2**15 samples = (1000.0/spkData.spikes.gain[0,0]) *samples ax2 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)), colspan = (numCols/3)) spikesorting.plot_waveforms(samples) ############################################################################### ax4 = plt.subplot2grid((numRows,numCols), (0,0), colspan = (numCols/2), rowspan = 3*sizeRasters) #plt.setp(ax4.get_xticklabels(), visible=False) #fig.axes.get_xaxis().set_visible(False) raster_tuning(ax4) axvline(x=0, ymin=0, ymax=1, color='r') plt.gca().set_xlim(tuning_timeRange) ax6 = plt.subplot2grid((numRows,numCols), (0,(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters) plt.setp(ax6.get_xticklabels(), visible=False) plt.setp(ax6.get_yticklabels(), visible=False) raster_sound_block_switching() plt.title('middle freq blocks, Top: sound aligned, Bottom: movement aligned') ax7 = plt.subplot2grid((numRows,numCols), (sizeRasters,(numCols/2)), colspan = (numCols/2), rowspan = sizeHists, sharex=ax6) hist_sound_block_switching(ax7) #plt.setp(ax7.get_yticklabels(), visible=False) ax7.yaxis.tick_right() ax7.yaxis.set_ticks_position('both') plt.setp(ax7.get_xticklabels(), visible=False) plt.gca().set_xlim(timeRange) ax10 = plt.subplot2grid((numRows,numCols), ((sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters) plt.setp(ax10.get_xticklabels(), visible=False) plt.setp(ax10.get_yticklabels(), visible=False) raster_movement_block_switching() ax11 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeHists, sharex=ax10) hist_movement_block_switching(ax11) ax11.yaxis.tick_right() ax11.yaxis.set_ticks_position('both') #plt.setp(ax11.get_yticklabels(), visible=False) plt.gca().set_xlim(timeRange) ############################################################################### #plt.tight_layout() modulation_index_switching() plt.suptitle(titleText) tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster) plt.gcf().set_size_inches((8.5,11)) figformat = 'png' #'png' #'pdf' #'svg' filename = 'tuning_report_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,figformat) fulloutputDir = outputDir+subject +'/' fullFileName = os.path.join(fulloutputDir,filename) directory = os.path.dirname(fulloutputDir) if not os.path.exists(directory): #makes sure output folder exists os.makedirs(directory) #print 'saving figure to %s'%fullFileName plt.gcf().savefig(fullFileName,format=figformat) except: #print "error with session "+oneCell.behavSession if (oneCell.behavSession not in badSessionList): badSessionList.append(oneCell.behavSession) print 'error with sessions: ' for badSes in badSessionList: print badSes
def raster_tuning(ax): fullbehaviorDir = behaviorDir+subject+'/' behavName = subject+'_tuning_curve_'+tuningBehavior+'.h5' tuningBehavFileName=os.path.join(fullbehaviorDir, behavName) tuning_bdata = loadbehavior.BehaviorData(tuningBehavFileName,readmode='full') freqEachTrial = tuning_bdata['currentFreq'] possibleFreq = np.unique(freqEachTrial) numberOfTrials = len(freqEachTrial) # -- The old way of sorting (useful for plotting sorted raster) -- sortedTrials = [] numTrialsEachFreq = [] #Used to plot lines after each group of sorted trials for indf,oneFreq in enumerate(possibleFreq): #indf is index of this freq and oneFreq is the frequency indsThisFreq = np.flatnonzero(freqEachTrial==oneFreq) #this gives indices of this frequency sortedTrials = np.concatenate((sortedTrials,indsThisFreq)) #adds all indices to a list called sortedTrials numTrialsEachFreq.append(len(indsThisFreq)) #finds number of trials each frequency has sortingInds = argsort(sortedTrials) #gives array of indices that would sort the sortedTrials # -- Load event data and convert event timestamps to ms -- tuning_ephysDir = os.path.join(settings.EPHYS_PATH, subject,tuningEphys) tuning_eventFilename=os.path.join(tuning_ephysDir, 'all_channels.events') tuning_ev=loadopenephys.Events(tuning_eventFilename) #load ephys data (like bdata structure) tuning_eventTimes=np.array(tuning_ev.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and tuning_evID=np.array(tuning_ev.eventID) #loads the onset times of events (matches up with eventID to say if event 1 went on (1) or off (0) tuning_eventOnsetTimes=tuning_eventTimes[tuning_evID==1] #array that is a time stamp for when the chosen event happens. #ev.eventChannel woul load array of events like trial start and sound start and finish times (sound event is 0 and trial start is 1 for example). There is only one event though and its sound start while (numberOfTrials < len(tuning_eventOnsetTimes)): tuning_eventOnsetTimes = tuning_eventOnsetTimes[:-1] ####################################################################################################### ###################THIS IS SUCH A HACK TO GET SPKDATA FROM EPHYSCORE################################### ####################################################################################################### thisCell = celldatabase.CellInfo(animalName=subject,############################################ ephysSession = tuningEphys, tuningSession = 'DO NOT NEED THIS', tetrode = tetrode, cluster = cluster, quality = 1, depth = 0, tuningBehavior = 'DO NOT NEED THIS', behavSession = tuningBehavior) tuning_spkData = ephyscore.CellData(thisCell) tuning_spkTimeStamps = tuning_spkData.spikes.timestamps (tuning_spikeTimesFromEventOnset,tuning_trialIndexForEachSpike,tuning_indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(tuning_spkTimeStamps,tuning_eventOnsetTimes,tuning_timeRange) #print 'numTrials ',max(tuning_trialIndexForEachSpike)##################################### ''' Create a vector with the spike timestamps w.r.t. events onset. (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = eventlocked_spiketimes(timeStamps,eventOnsetTimes,timeRange) timeStamps: (np.array) the time of each spike. eventOnsetTimes: (np.array) the time of each instance of the event to lock to. timeRange: (list or np.array) two-element array specifying time-range to extract around event. spikeTimesFromEventOnset: 1D array with time of spikes locked to event. o trialIndexForEachSpike: 1D array with the trial corresponding to each spike. The first spike index is 0. indexLimitsEachTrial: [2,nTrials] range of spikes for each trial. Note that the range is from firstSpike to lastSpike+1 (like in python slices) spikeIndices ''' tuning_sortedIndexForEachSpike = sortingInds[tuning_trialIndexForEachSpike] #Takes values of trialIndexForEachSpike and finds value of sortingInds at that index and makes array. This array gives an array with the sorted index of each trial for each spike # -- Calculate tuning -- #nSpikes = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,responseRange) #array of the number of spikes in range for each trial '''Count number of spikes on each trial in a given time range. spikeTimesFromEventOnset: vector of spikes timestamps with respect to the onset of the event. indexLimitsEachTrial: each column contains [firstInd,lastInd+1] of the spikes on a trial. timeRange: time range to evaluate. Spike times exactly at the limits are not counted. returns nSpikes ''' ''' meanSpikesEachFrequency = np.empty(len(possibleFreq)) #make empty array of same size as possibleFreq # -- This part will be replace by something like behavioranalysis.find_trials_each_type -- trialsEachFreq = [] for indf,oneFreq in enumerate(possibleFreq): trialsEachFreq.append(np.flatnonzero(freqEachTrial==oneFreq)) #finds indices of each frequency. Appends them to get an array of indices of trials sorted by freq # -- Calculate average firing for each freq -- for indf,oneFreq in enumerate(possibleFreq): meanSpikesEachFrequency[indf] = np.mean(nSpikes[trialsEachFreq[indf]]) ''' #clf() #if (len(tuning_spkTimeStamps)>0): #ax1 = plt.subplot2grid((4,4), (3, 0), colspan=1) #spikesorting.plot_isi_loghist(spkData.spikes.timestamps) #ax3 = plt.subplot2grid((4,4), (3, 3), colspan=1) #spikesorting.plot_events_in_time(tuning_spkTimeStamps) #samples = tuning_spkData.spikes.samples.astype(float)-2**15 #samples = (1000.0/tuning_spkData.spikes.gain[0,0]) *samples #ax2 = plt.subplot2grid((4,4), (3, 1), colspan=2) #spikesorting.plot_waveforms(samples) #ax4 = plt.subplot2grid((4,4), (0, 0), colspan=3,rowspan = 3) plot(tuning_spikeTimesFromEventOnset, tuning_sortedIndexForEachSpike, '.', ms=3) #axvline(x=0, ymin=0, ymax=1, color='r') #The cumulative sum of the list of specific frequency presentations, #used below for plotting the lines across the figure. numTrials = cumsum(numTrialsEachFreq) #Plot the lines across the figure in between each group of sorted trials for indf, num in enumerate(numTrials): ax.axhline(y = num, xmin = 0, xmax = 1, color = '0.90', zorder = 0) tickPositions = numTrials - mean(numTrialsEachFreq)/2 tickLabels = ["%0.2f" % (possibleFreq[indf]/1000) for indf in range(len(possibleFreq))] ax.set_yticks(tickPositions) ax.set_yticklabels(tickLabels) ax.set_ylim([-1,numberOfTrials]) ylabel('Frequency Presented (kHz), {} total trials'.format(numTrials[-1])) #title(ephysSession+' T{}c{}'.format(tetrodeID,clusterID)) xlabel('Time (sec)') ''' ax5 = plt.subplot2grid((4,4), (0, 3), colspan=1,rowspan=3) ax5.set_xscale('log') plot(possibleFreq,meanSpikesEachFrequency,'o-') ylabel('Avg spikes in window {0}-{1} sec'.format(*responseRange)) xlabel('Frequency') ''' #show() '''
subject = oneCell.animalName behavSession = oneCell.behavSession ephysSession = oneCell.ephysSession laserSession = oneCell.laserSession ephysRoot = os.path.join(ephysRootDir, subject) tetrode = oneCell.tetrode cluster = oneCell.cluster print oneCell.behavSession, tetrode, cluster # -- Load laser event data and convert event timestamps to ms -- laserephysDir = os.path.join(ephysRoot, laserSession) lasereventFilename = os.path.join(laserephysDir, 'all_channels.events') lasereventData = loadopenephys.Events( lasereventFilename) # Load events data lasereventTimes = np.array( lasereventData.timestamps) / SAMPLING_RATE laserOnsetEvents = (lasereventData.eventID == 1) & ( lasereventData.eventChannel == laserTriggerChannel) laserOnsetTimes = lasereventTimes[laserOnsetEvents] # -- Load sound event data and convert event timestamps to ms -- soundephysDir = os.path.join(ephysRoot, ephysSession) soundeventFilename = os.path.join(soundephysDir, 'all_channels.events') soundeventData = loadopenephys.Events( soundeventFilename) # Load events data soundeventTimes = np.array( soundeventData.timestamps) / SAMPLING_RATE soundOnsetEvents = (soundeventData.eventID == 1) & (
for indcell, cell in cellsThisTetrode.iterrows(): #Get data filenames ephysPath = os.path.join( settings.EPHYS_PATH, cell['subject'], '{}_{}'.format(cell['date'], cell['timestamp'])) ephysFn = os.path.join(ephysPath, 'Tetrode{}.spikes'.format(int(cell['tetrode']))) clusterFn = os.path.join( '{}_kk'.format(ephysPath), 'Tetrode{}.clu.1'.format(int(cell['tetrode']))) eventFn = os.path.join(ephysPath, 'all_channels.events') #Load the event data dataEvents = loadopenephys.Events(eventFn) dataEvents.timestamps = dataEvents.timestamps / SAMPLING_RATE #Limit the events to ID 1 and Channel 0 dataEvents.timestamps = dataEvents.timestamps[( (dataEvents.eventID == 1) & (dataEvents.eventChannel == 0))] #Split the events into groups of 100 trials splitInds = np.arange(0, len(dataEvents.timestamps), 50) splitEvents = np.split(dataEvents.timestamps, splitInds) #Load the spike data for this cell dataSpikes = loadopenephys.DataSpikes(ephysFn) dataSpikes.set_clusters(clusterFn) dataSpikes.timestamps = dataSpikes.timestamps[dataSpikes.clusters == int(cell['cluster'])]