def plot_lick_triggered_fr(obj, spikes, axis=None, min_inter_lick_time=0.5, preTime=1, postTime=2, plot=True, sdfSigma=0.01, returnSDF=False): if axis is None and plot: fig, axis = plt.subplots() frameTimes = obj.frameAppearTimes trial_start_frames = np.array(obj.trials['startframe']) trial_end_frames = np.array(obj.trials['endframe']) trial_start_times = frameTimes[trial_start_frames] trial_end_times = frameTimes[trial_end_frames] lick_times = probeSync.get_sync_line_data(obj.syncDataset, 'lick_sensor')[0] first_lick_times = lick_times[np.insert( np.diff(lick_times) >= min_inter_lick_time, 0, True)] first_lick_trials = analysis_utils.get_trial_by_time( first_lick_times, trial_start_times, trial_end_times) # hit = np.array(obj.trials['response_type']=='HIT') # earlyResponse = np.array(obj.trials['response_type']=='EARLY_RESPONSE') # falseAlarm = np.array(obj.trials['response_type']=='FA') hit = obj.hit earlyResponse = obj.earlyResponse falseAlarm = obj.falseAlarm hit_lick_times = first_lick_times[np.where(hit[first_lick_trials])[0]] bad_lick_times = first_lick_times[np.where( falseAlarm[first_lick_trials] | earlyResponse[first_lick_trials])[0]] hit_psth, t = analysis_utils.getSDF(spikes, hit_lick_times - preTime, preTime + postTime, sigma=sdfSigma) bad_psth, t = analysis_utils.getSDF(spikes, bad_lick_times - preTime, preTime + postTime, sigma=sdfSigma) if plot: hit, = axis.plot(t - 1, hit_psth, 'k') bad, = axis.plot(t - 1, bad_psth, 'r') axis.legend((hit, bad), ('hit', 'aborted/FA'), loc='best', prop={'size': 8}) formatFigure(plt.gcf(), axis, xLabel='Time to lick (s)', yLabel='Lick-Trig. FR (Hz)') axis.plot([0, 0], axis.get_ylim(), 'k--') if returnSDF: return hit_psth, bad_psth
def plot_psth_hits_vs_misses(obj, spikes, axes=None, preTime=1.55, postTime=4.5, sdfSigma=0.02): if axes is None: fig, axes = plt.subplots(9) hitSDFs = [] missSDFs = [] for resp, s in zip((obj.hit, obj.miss), (hitSDFs, missSDFs)): for img in obj.imageNames: selectedTrials = resp & (obj.changeImage == img) & (~obj.ignore) changeTimes = obj.frameAppearTimes[np.array( obj.trials['change_frame'][selectedTrials]).astype(int)] sdf, t = analysis_utils.getSDF(spikes, changeTimes - preTime, preTime + postTime, sigma=sdfSigma) s.append(sdf) #plot mean across images at end selectedTrials = resp & (~obj.ignore) changeTimes = obj.frameAppearTimes[np.array( obj.trials['change_frame'][selectedTrials]).astype(int)] sdf, t = analysis_utils.getSDF(spikes, changeTimes - preTime, preTime + postTime, sigma=sdfSigma) s.append(sdf) ymax = round( max([max(h.max(), m.max()) for h, m in zip(hitSDFs, missSDFs)]) + 0.5) stimdur = obj.behaviorStimDur.mean() stimint = stimdur + obj.preGrayDur[0, 0] stimStarts = np.concatenate( (np.arange(-stimint, -preTime, -stimint), np.arange(0, postTime, stimint))) for ax, h, m in zip(axes, hitSDFs, missSDFs): for s, clr in zip(stimStarts, ['0.9'] * 2 + ['0.5'] * 6): ax.add_patch( patches.Rectangle([s, 0], width=stimdur, height=ymax, color=clr, alpha=0.5)) ax.plot(t - preTime, h, 'b', linewidth=2) ax.plot(t - preTime, m, 'k', linewidth=2) for side in ('right', 'top'): ax.spines[side].set_visible(False) ax.tick_params(direction='out', top=False, right=False, labelsize=10) ax.set_ylim([0, ymax]) ax.set_xlim([-preTime, postTime]) ax.set_yticks([0, ymax]) if ax is not axes[0]: ax.set_yticklabels([]) if ax is not axes[-1]: ax.set_xticklabels([]) axes[-1].set_xlabel('Time from change (s)', fontsize=12)
def plot_psth_omitted_flashes(obj, spikes, axes=None, preTime=0.05, postTime=0.55, sdfSigma=0.005): if axes is None: fig, axes = plt.subplots(9) image_flash_times = obj.frameAppearTimes[obj.omittedFlashFrames] image_id = np.array(obj.omittedFlashImage) sdfs = [] latencies = [] for i, img in enumerate(obj.imageNames): this_image_times = image_flash_times[image_id == img] sdf, t = analysis_utils.getSDF(spikes, this_image_times - preTime, preTime + postTime, sigma=sdfSigma) latency = analysis_utils.find_latency( sdf[:int(1000 * (preTime + 0.25 + 0.05))], int(preTime * 1000), 5) latencies.append(latency) sdfs.append(sdf) #plot mean response to all flashes at end allsdf, t = analysis_utils.getSDF(spikes, image_flash_times - preTime, preTime + postTime, sigma=sdfSigma) latency = analysis_utils.find_latency( allsdf[:int(1000 * (preTime + 0.25 + 0.05))], int(preTime * 1000), 5) latencies.append(latency) sdfs.append(allsdf) ymax = round(max([s.max() for s in sdfs]) + 0.5) for ax, sdf, lat in zip(axes, sdfs, latencies): ax.add_patch( patches.Rectangle([0, 0], width=obj.behaviorStimDur.mean(), height=ymax, color='0.9', alpha=0.5)) ax.plot(t - preTime, sdf, 'k') if not np.isnan(lat): ax.plot(lat / 1000 - preTime, sdf[lat], 'ro') for side in ('right', 'top'): ax.spines[side].set_visible(False) ax.tick_params(direction='out', top=False, right=False, labelsize=10) ax.set_ylim([0, ymax]) ax.set_xlim([-preTime, postTime]) ax.set_yticks([0, ymax]) if ax is not axes[0]: ax.set_yticklabels([]) if ax is not axes[-1]: ax.set_xticklabels([]) axes[-1].set_xlabel('Time to omitted flash (s)', fontsize=12)
def plot_run_triggered_fr(obj, spikes, axis=None, preTime=1, postTime=2): if axis is None: fig, axis = plt.subplots() if len(obj.behaviorRunStartTimes)>0: run_psth, t = analysis_utils.getSDF(spikes,obj.behaviorRunStartTimes-preTime,preTime+postTime) axis.plot(t-1,run_psth, 'k') axis.plot([0,0], axis.get_ylim(), 'k--') formatFigure(plt.gcf(), axis, xLabel='Time to run (s)', yLabel='Run-Trig. FR (Hz)')
def getVisualResponsiveness(self): image_flash_times = self.frameAppearTimes[np.array(self.core_data['visual_stimuli']['frame'])] image_id = np.array(self.core_data['visual_stimuli']['image_name']) #take first 50 flashes of each image image_flash_times = np.array([image_flash_times[np.where(image_id==im)[0][:50]] for im in np.unique(image_id)]).flatten() for pid in self.probes_to_analyze: for u in self.units[pid]: spikes = self.units[pid][u]['times'] #find mean response to all flashes p, t = analysis_utils.getSDF(spikes,image_flash_times-.25,0.5, sigma=0.01) self.units[pid][u]['peakMeanVisualResponse'] = p.max() - p[:250].mean()
def plot_saccade_triggered_fr(obj, spikes, axis=None, preTime=2, postTime=2, sdfSigma=0.02, latThresh=5, minPtsAboveThresh=50): if obj.eyeData is None: return if axis is None: fig, axis = plt.subplots() latFilt = np.ones(minPtsAboveThresh) axis.plot([0,0],[0,1000],'k--') ymax = 0 plotlines = [] for j,(saccades,clr) in enumerate(zip((obj.negSaccades,obj.posSaccades),'rb')): saccadeTimes = obj.eyeFrameTimes[saccades] sdf,t = analysis_utils.getSDF(spikes,saccadeTimes-preTime,preTime+postTime,sigma=sdfSigma) plotline, = axis.plot(t-preTime,sdf,clr) plotlines.append(plotline) ymax = max(ymax,sdf.max()) z = sdf-sdf[t<1].mean() z /= sdf[t<1].std() posLat = np.where(np.correlate(z>latThresh,latFilt,mode='valid')==minPtsAboveThresh)[0] posLat = posLat[0] if posLat.size>0 else None negLat = np.where(np.correlate(z<-latThresh,latFilt,mode='valid')==minPtsAboveThresh)[0] negLat = negLat[0] if negLat.size>0 else None # posLat = np.where(z[:np.argmax(z)]<latencyThresh)[0][-1]+1 if z.max()>latencyThresh else None # negLat = np.where(z[:np.argmin(z)]>-latencyThresh)[0][-1]+1 if z.min()<-latencyThresh else None if posLat is not None or negLat is not None: if posLat is None: latInd = negLat elif negLat is None: latInd = posLat else: latInd = min(posLat,negLat) axis.plot(t[latInd]-preTime,sdf[latInd],'o',mfc=clr,mec=clr,ms=10) for side in ('right','top'): axis.spines[side].set_visible(False) axis.tick_params(direction='out',top=False,right=False,labelsize=12) axis.set_xlim([-preTime,postTime]) axis.set_ylim([0,1.02*ymax]) axis.set_xlabel('Time relative to saccade (s)',fontsize=14) axis.set_ylabel('Spike/s',fontsize=14) axis.legend((plotlines[0], plotlines[1]), ('temporal', 'nasal'), loc='best', prop={'size':8})
b.core_data['visual_stimuli']['frame'])] changeTimes = frameAppearTimes[np.array( b.trials['change_frame'][selectedTrials]).astype(int) + 1] preChangeTimes = flash_times[preChangeIndices] changeFano = [] preChangeFano = [] changesdfs = [] presdfs = [] for im in np.unique(preChangeIDs): imPrechangeTimes = preChangeTimes[preChangeIDs == im] imChangeTimes = changeTimes[changeIDs == im] imPrechangeSDF, time = getSDF(spikes, imPrechangeTimes - preTime, preTime + postTime, avg=False, filt='exp', sigma=0.02) imChangeSDF, time = getSDF(spikes, imChangeTimes - preTime, preTime + postTime, avg=False, filt='exp', sigma=0.02) changesdfs.append(imChangeSDF) presdfs.append(imPrechangeSDF) # changeFano.append(findFano(imChangeSDF - np.mean(imChangeSDF[:, baseline], axis=1)[:, None])) # preChangeFano.append(findFano(imPrechangeSDF - np.mean(imPrechangeSDF[:, baseline], axis=1)[:, None])) changeFano.append(findFano(imChangeSDF)) preChangeFano.append(findFano(imPrechangeSDF))
data[mouse]['ccfRegions'][probe] = ccf[goodUnits] data[mouse]['spikeTimes'][probe] = OrderedDict() data[mouse]['sdfs'][probe] = { epoch: [] for epoch in ('preChange', 'change') } for u in units[goodUnits]: spikes = nwb['processing'][probe]['UnitTimes'][str(u)]['times'][:] data[mouse]['spikeTimes'][probe][str(u)] = spikes for epoch, times in zip(('preChange', 'change'), (preChangeTimes, changeTimes)): data[mouse]['sdfs'][probe][epoch].append( analysis_utils.getSDF(spikes, times - 0.25, 1, sampInt=0.001, filt='exp', sigma=0.005, avg=False)[0]) fileIO.objToHDF5(obj=None, saveDict=data, filePath=os.path.join(dirPath, 'naiveMiceData2.hdf5')) nwb.close() # make population data hdf5 from experiment nwb files #for mouse in mouseIDs: # print(mouse) # nwb = h5py.File(os.path.join(dirPath,'mouse'+mouse+'.spikes.nwb')) # data = {mouse:{}} # data[mouse]['runTime'] = nwb['acquisition']['timeseries']['RunningSpeed']['timestamps'][:] # data[mouse]['runSpeed'] = nwb['acquisition']['timeseries']['RunningSpeed']['data'][:]