コード例 #1
0
ファイル: RR_rf.py プロジェクト: r-b-g-b/Lab
def add_field():

	savepath = '/Users/robert/Documents/Work/Bao/Fmr1_RR/Analysis/RRTFs.h5'
	fsave = h5py.File(savepath, 'a')

	sessnames = fsave.keys()

	for sessname in sessnames:
	
		fsess = fsave[sessname]
		rrblocks = fsess.keys()

		for rrblock in rrblocks:
	
			rrpath = os.path.join(basedir, 'Sessions', 'full_window', 'good', sessname, 'fileconversion', rrblock + '.h5')
			p = re.compile('RR')
			rfpath_ = p.sub('RF', rrblock)
			rfpath = os.path.join(basedir, 'Sessions', 'full_window', 'good', sessname, 'fileconversion', rfpath_+'.h5')
		
			p = re.compile('(\d+)')
			unitnum = np.int32(p.findall(rrblock)[0])

			funit = fsess[rrblock]
			# d = funit.require_dataset('unit', (), 'i4')
			# d.write_direct(np.array([unitnum]))

			if verbose:
				print rrblock
				print rfpath
			
			# LOAD RF FILECONVERSION FILE
			frf = h5py.File(rfpath, 'r')
			cf_ix = np.int32(frf['cf'].value)
			frf.close()

			cf = ix2freq[20:][cf_ix]
			
			# LOAD RR FILECONVERSION FILE
			frr = h5py.File(rrpath, 'r')
			rast = frr['rast'].value
			stimparams = frr['stimID'].value
			frr.close()
			
			# CALCULATE FREQ PLAYED TO THIS UNIT'S CF
			freqs = np.unique(stimparams[:, 0])
			rrs = np.unique(stimparams[:, 1])
			freq, _, freq_err = misc.closest(freqs, cf, log = True)
			freq = np.round(freq, 0)
			assert freq_err<0.3
			
			# COMPUTE NEW FIELD
			on, off = Spikes.calc_on_off(funit['ev_psth'].value)
			# vs, vs_p = RR.calc_vs_all(rast, stimparams, [0.], rrs)
			# rrtf = RR.calc_rrtf_all(rast, stimparams, freq, rrs)

			# ADD NEW FIELD
			d = funit.require_dataset('on_halfmax', (1,), float)
			d.write_direct(np.array([on]))
			d = funit.require_dataset('off_halfmax', (1,), float)
			d.write_direct(np.array([off]))
		
			# open the RR file, get rast and stimparams, then close it
			# frf = h5py.File(rfpath, 'r')
			# RF.add_rf_analysis(frf, funit)
			# frf.close()

	fsave.close()
コード例 #2
0
ファイル: RF_analysis.py プロジェクト: r-b-g-b/Lab
def characterize(sesss = sesss, experiment = 'Fmr1_RR', pplot = True, verbose = False):

	if type(sesss) == str:
		sesss = [sesss]

	# set up figure
	figsize = (12, 12)
	fig = plt.figure(figsize = figsize)

	# loop through sesss
	for sess in sesss:

		DB = np.empty(0, dtype = dtype)
		
		print '%s\n%s\n\n' % (sess, '-'*50)
		
		# build the output directory path
		savedir = os.path.join(basedir, experiment, 'Sessions', sess, 'analysis')
		if not os.path.exists(savedir):
			os.mkdir(savedir)
			
		# WT or KO / CTL or EXP
		gen, exp, date = sess.split('_')

		# find the RF blocks
		pens = glob.glob(os.path.join(basedir, experiment, 'Sessions', sess, 'fileconversion', 'RF*.h5'))

		# load the cfs for this sess
		cfs = np.loadtxt(os.path.join(basedir, experiment, 'Sessions', sess, 'cfs.txt'), ndmin = 1)
		
		# loop through blocks in this sess
		for pen in pens:
			
			absol, relat = os.path.split(pen)
			blockname = os.path.splitext(relat)[0]

			# get unit number from filename
			unitnum = np.int32(p.findall(relat))[0] # unit number
			ix = cfs[:, 0] == unitnum
			if ix.sum() > 0:
				cf_man = cfs[ix, 1][0]
				if verbose:
					print pen
			
				# load the RF block
				f = h5py.File(pen, 'r')
				spktimes = f['spktimes'].value
				# if not np.isnan(spktimes[0]):

				'''--------RF--------'''
				# load the RF block to get the RF
				rf = f['rf'].value;	rast = f['rast'].value; spktimes = f['spktimes'].value; stimparams = f['stimID'].value; spktrials = f['spktrials'].value; coord = f['coord'].value; ntrials = f['rast'].shape[0]; f.close()

				# calculate the psth (spk/s*trial, normalized by number of trials
				psth = Spikes.calc_psth(rast, normed = True) # spk/s
			
				# baseline firing rate
				base_mean = psth[:stim_on].mean() # spk/s
			
				# response onset/offset
				psth_smoo = Spikes.exp_smoo(psth, tau = 0.003) 
				resp_on, resp_off = Spikes.calc_on_off(psth_smoo, stim_on = stim_on)
			
				# rewindowed RF
				rf_rewin = RF.calc_rf(rast, stimparams, resp_on = resp_on + stim_on - 3, resp_off = resp_off + stim_on + 3, normed = True)
			
				# thresholded RF
				rf_thresh = rf_rewin.copy()
				rf_threshold = np.percentile(rf_thresh, 66)# upper quartile
				rf_peak = rf_rewin.max()
				rf_thresh[rf_thresh < rf_threshold] = 0
			
				# find maximum RF cluster
				(rf_clust, clust_sizes) = RF.findmaxcluster(rf_thresh, cf = cf_man, include_diagonal = False)
				# if clust_sizes.max() < 10: # if it's a tiny RF, set it to nans
				# 	rf_clust = np.empty(rf_clust.shape) * np.nan
			
				rf_mask = rf_clust > 0
				# find evoked psth
				ev_psth = RF.calc_evoked_psth(rast, stimparams, rf_mask)
				ev_psth_smoo = Spikes.exp_smoo(ev_psth, tau = 0.003)
				ev_resp_on, ev_resp_off = Spikes.calc_on_off(ev_psth_smoo, stim_on = stim_on)
				ev_mean = ev_psth[ev_resp_on : ev_resp_off].mean()
				
				# bandwidth and threshold
				bw, bw_lr, _, thresh = RF.calc_bw_cf_thresh(rf_mask)

				# center of mass
				com = RF.calc_rf_com(rf_clust)
				tip_top = np.max([thresh-2, 0])
				tip_bottom = thresh
				com_tip = RF.calc_rf_com(rf_clust[tip_top:tip_bottom, :])

				'''PLOT'''
				if pplot:
					
					rf1_ax = fig.add_subplot(221)
					rf2_ax = fig.add_subplot(222)
					psth1_ax = fig.add_subplot(223)
					psth2_ax = fig.add_subplot(224)
					
					RF.plot_RF(rf, bw_lr = bw_lr, thresh = thresh, cf = cf_man, ax = rf1_ax)
					RF.plot_RF(rf_clust, bw_lr = bw_lr, thresh = thresh, cf = cf_man, ax = rf2_ax)
					rf2_ax.axvline(com, color = 'g', ls = '--')
					rf2_ax.axvline(com_tip, color = 'b', ls = '--')
				
					psth1_ax.plot(psth_smoo)
					psth2_ax.plot(ev_psth_smoo)
					psth1_ax.axvline(resp_on+stim_on, color = 'r', ls = '--')
					psth1_ax.axvline(resp_off+stim_on, color = 'r', ls = '--')
				
					figpath = os.path.join(savedir, blockname + '.png')
					fig.savefig(figpath);
					fig.clf()
				'''PLOT'''
			

				DB.resize(DB.size + 1)
				DB[-1] = np.array((gen, exp, sess, unitnum, \
					psth[:333], ev_psth[:333], \
					rf, rf_clust, \
					cf_man, com, com_tip, \
					bw, bw_lr, thresh, coord, \
					resp_on, resp_off, ev_resp_on, ev_resp_off, \
					base_mean, ev_mean), dtype = dtype)
		
			# end unit loop
	
			np.savez(os.path.join(basedir, experiment, 'Sessions', sess, sess + '_RF.npz'), DB = DB)
		if verbose:
			print '\n'*4