def test_vertex_to_mni_fs_nibabel(monkeypatch): """Test equivalence of vert_to_mni for nibabel and freesurfer.""" n_check = 1000 subject = 'sample' vertices = rng.randint(0, 100000, n_check) hemis = rng.randint(0, 1, n_check) coords = vertex_to_mni(vertices, hemis, subject, subjects_dir) monkeypatch.setattr(mne.source_space, 'has_nibabel', lambda: False) coords_2 = vertex_to_mni(vertices, hemis, subject, subjects_dir) # less than 0.1 mm error assert_allclose(coords, coords_2, atol=0.1)
def test_vertex_to_mni_fs_nibabel(): """Test equivalence of vert_to_mni for nibabel and freesurfer """ n_check = 1000 for subject in ['sample', 'fsaverage']: vertices = np.random.randint(0, 100000, n_check) hemis = np.random.randint(0, 1, n_check) coords = vertex_to_mni(vertices, hemis, subject, mode='nibabel') coords_2 = vertex_to_mni(vertices, hemis, subject, mode='freesurfer') # less than 0.1 mm error assert_allclose(coords, coords_2, atol=0.1)
def test_vertex_to_mni_fs_nibabel(): """Test equivalence of vert_to_mni for nibabel and freesurfer.""" n_check = 1000 subject = 'sample' vertices = rng.randint(0, 100000, n_check) hemis = rng.randint(0, 1, n_check) coords = vertex_to_mni(vertices, hemis, subject, subjects_dir, 'nibabel') coords_2 = vertex_to_mni(vertices, hemis, subject, subjects_dir, 'freesurfer') # less than 0.1 mm error assert_allclose(coords, coords_2, atol=0.1)
def location(self): if self.locate is True: self.locate=1 print "Locate ",self.locate," dipoles" if self.selection is 'all': nd=self.stc[0].data.shape[0] ns=self.stc[0].data.shape[1] loc=np.zeros((len(self.stc),ns,3*self.locate)) vtx = self.stc[0].vertices vtx_long = np.hstack((self.stc[0].vertices[0],self.stc[0].vertices[1])) hem0 = np.size(vtx[0]) hem1 = np.size(vtx[1]) for s in range(0,len(self.stc)): #max location (index) mxloca = np.argsort(np.abs(self.stc[s].data),axis=0) mxloc=mxloca[-1-self.locate:-1,:] assert mxloc.shape[0]==self.locate and mxloc.shape[1]==ns hemi = np.where(mxloc<nd/2,0,1).reshape([-1]) mxvtx_long =vtx_long[mxloc].reshape([-1]) if self.subject is 'sample': loc[s,: ,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,subjects_dir='/home/jcasa/mne_data/MNE-sample-data/subjects',verbose=False).reshape([-1,self.locate*3]) else: loc[s,: ,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,verbose=False).reshape([-1,self.locate*3]) self.qtrue_all = loc self.p=loc.shape[2] else: nd=self.stc[0].data.shape[0] ns=self.stc[0].data.shape[1] loc=np.zeros((len(self.selection),ns,3*self.locate)) vtx = self.stc[0].vertices vtx_long = np.hstack((self.stc[0].vertices[0],self.stc[0].vertices[1])) hem0 = np.size(vtx[0]) hem1 = np.size(vtx[1]) ind_s = 0 for s in self.selection: #max location (index) mxloca = np.argsort(np.abs(self.stc[s].data),axis=0) mxloc=mxloca[-1-self.locate:-1,:] assert mxloc.shape[0]==self.locate and mxloc.shape[1]==ns hemi = np.where(mxloc<nd/2,0,1).reshape([-1]) mxvtx_long =vtx_long[mxloc].reshape([-1]) if self.subject is 'sample': loc[ind_s,: ,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,subjects_dir='/home/jcasa/mne_data/MNE-sample-data/subjects',verbose=False).reshape([-1,self.locate*3]) else: loc[ind_s,: ,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,verbose=False).reshape([-1,self.locate*3]) ind_s+=1 self.qtrue_all = loc self.p=loc.shape[2]
def test_vertex_to_mni_fs_nibabel(monkeypatch): """Test equivalence of vert_to_mni for nibabel and freesurfer.""" n_check = 1000 subject = 'sample' vertices = rng.randint(0, 100000, n_check) hemis = rng.randint(0, 1, n_check) coords = vertex_to_mni(vertices, hemis, subject, subjects_dir) read_mri = mne._freesurfer._read_mri_info monkeypatch.setattr( mne._freesurfer, '_read_mri_info', lambda *args, **kwargs: read_mri(*args, use_nibabel=True, **kwargs)) coords_2 = vertex_to_mni(vertices, hemis, subject, subjects_dir) # less than 0.1 mm error assert_allclose(coords, coords_2, atol=0.1)
def locationXYZT(self): if self.locate is True: self.locate=1 print "Locate ",self.locate," dipoles" if self.selection is 'all': nd=self.stc[0].data.shape[0] ns=self.stc[0].data.shape[1] loc=np.zeros((len(self.stc),ns,3*self.locate)) vtx = self.stc[0].vertices vtx_long = np.hstack((self.stc[0].vertices[0],self.stc[0].vertices[1])) hem0 = np.size(vtx[0]) hem1 = np.size(vtx[1]) for s in range(0,len(self.stc)): #max location (index) [i,j] = np.unravel_index(np.argsort(np.ravel(np.abs(self.stc[s].data))),self.stc[s].data.shape) I,J=i[-1-self.locate:-1],j[-1-self.locate:-1]#I is neuron index,J is temporal index hemi = np.where(I<nd/2,0,1).reshape([-1]) mxvtx_long =vtx_long[I].reshape([-1]) if self.subject is 'sample': loc[s,-1,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,subjects_dir='/home/jcasa/mne_data/MNE-sample-data/subjects',verbose=False).reshape([-1,self.locate*3]) else: loc[s,-1,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,verbose=False).reshape([-1,self.locate*3]) self.qtrue_all = loc self.p=loc.shape[2] else: nd=self.stc[0].data.shape[0] ns=self.stc[0].data.shape[1] loc=np.zeros((len(self.selection),ns,3*self.locate)) vtx = self.stc[0].vertices vtx_long = np.hstack((self.stc[0].vertices[0],self.stc[0].vertices[1])) hem0 = np.size(vtx[0]) hem1 = np.size(vtx[1]) ind_s = 0 for s in self.selection: #max location (index) [i,j] = np.unravel_index(np.argsort(np.ravel(np.abs(self.stc[s].data))),self.stc[s].data.shape) I,J=i[-1-self.locate:-1],j[-1-self.locate:-1]#I is neuron index,J is temporal index hemi = np.where(I<nd/2,0,1).reshape([-1]) mxvtx_long =vtx_long[I].reshape([-1]) if self.subject is 'sample': loc[ind_s,-1,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,subjects_dir='/home/jcasa/mne_data/MNE-sample-data/subjects',verbose=False).reshape([-1,self.locate*3]) else: loc[ind_s,-1,:] = mne.vertex_to_mni(mxvtx_long,hemi,self.subject,verbose=False).reshape([-1,self.locate*3]) ind_s+=1 self.qtrue_all = loc self.p=loc.shape[2]
def convert_cortex_mri_to_mni(labels_cortex, vertno_left, vertno_right, sbj, sbj_dir): """Convert the coordinates of the ROIs cortex to MNI space. Parameters ---------- labels_cortex : list List of labels. """ import mne import numpy as np roi_mni_coords = list() roi_name = list() roi_color = list() # labels_cortex is in MRI (surface RAS) space for label in labels_cortex: if label.hemi == 'lh': # from MRI (surface RAS) -> MNI roi_coo_mni = mne.vertex_to_mni(label.vertices, 0, sbj, sbj_dir) # get the vertices of the ROI used in the src space (index points # to dense src space of FS segmentation) this_vertno = np.intersect1d(vertno_left, label.vertices) elif label.hemi == 'rh': roi_coo_mni = mne.vertex_to_mni(label.vertices, 1, sbj, sbj_dir) this_vertno = np.intersect1d(vertno_right, label.vertices) # find vertidx_roi = np.searchsorted(label.vertices, this_vertno) roi_mni_coords.append(roi_coo_mni[vertidx_roi, :]) roi_name.append(label.name) roi_color.append(label.color) # TODO check! # nvert_ROI = [len(vn) for vn in roi_mni_coords] # if np.sum(nvert_ROI) != (len(vertno_left) + len(vertno_right)): # raise RuntimeError('number of src space vertices must be equal to \ # the total number of ROI vertices') roi_mni = dict(ROI_name=roi_name, ROI_MNI_coords=roi_mni_coords, ROI_color=roi_color) return roi_mni
def plot_aparc_parcels(matrix, ax, fig, title): """ :param matrix: The connectivity matrix (real or simulated) representing aparc parcels :param ax: axes to plot on :return: """ # get labels and coordinates labels = mne.read_labels_from_annot('fsaverage_1', parc='aparc', subjects_dir=join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS','FS_SUBDIR')) labels = labels[0:-1] label_names = [label.name for label in labels] coords = [] # TODO: Find a better way to get centre of parcel #get coords of centre of mass for i in range(len(labels)): if 'lh' in label_names[i]: hem = 1 else: hem = 0 coord = mne.vertex_to_mni(labels[i].center_of_mass(subjects_dir=join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS','FS_SUBDIR')), subject='fsaverage_1',hemis=hem,subjects_dir=join(MAINDIR,'FS_SUBDIR')) coords.append(coord[0]) plotting.plot_connectome_strength(matrix, node_coords=coords, title=title, figure=fig, axes=ax, cmap=plt.cm.YlOrRd)
def plot_perm_ttest_results(events_id, inverse_method='dSPM', plot_type='scatter_plot'): print('plot_perm_ttest_results') all_data = defaultdict(dict) fsave_vertices = [np.arange(10242), np.arange(10242)] fs_pts = mne.vertex_to_mni(fsave_vertices, [0, 1], 'fsaverage', LOCAL_SUBJECTS_DIR) # 0 for lh for cond_id, cond_name, patient, hc, data in patients_hcs_conds_gen(events_id, True, inverse_method): all_data[patient][hc] = data[()] print(all_data.keys()) for patient, pat_data in all_data.iteritems(): print(patient) fol = op.join(LOCAL_ROOT_DIR, 'permutation_ttest_results', patient) utils.make_dir(fol) if op.isfile(op.join(fol, 'perm_ttest_points.npz')): d = np.load(op.join(fol, 'perm_ttest_points.npz')) if plot_type == 'scatter_plot': points, values = d['points'][()], d['values'][()] elif plot_type == 'pysurfer': vertices, vertives_values = d['vertices'][()], d['vertives_values'][()] else: points, values, vertices, vertives_values = calc_points(pat_data, fs_pts) np.savez(op.join(fol, 'perm_ttest_points'), points=points, values=values, vertices=vertices, vertives_values=vertives_values) max_vals = 8 # int(np.percentile([max(v) for v in values.values()], 70)) print(max_vals) fol = op.join(fol, '{}_figures'.format(plot_type)) utils.make_dir(fol) if plot_type == 'scatter_plot': scatter_plot_perm_ttest_results(points, values, fs_pts, max_vals, fol) elif plot_type == 'pysurfer': pysurfer_plot_perm_ttest_results(vertices, vertives_values, max_vals, fol)
def mne_connec(matrix, this_title, fig, *labels): MAINDIR = join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS') if labels is None: labels = mne.read_labels_from_annot('fsaverage_1', parc='aparc', subjects_dir=join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS', 'FS_SUBDIR')) labels = labels[0:-1] label_colors = [label.color for label in labels] label_names = [label.name for label in labels] coords = [] # TODO: Find a better way to get centre of parcel # get coords of centre of mass for i in range(len(labels)): if 'lh' in label_names[i]: hem = 1 else: hem = 0 coord = mne.vertex_to_mni( labels[i].center_of_mass(subjects_dir=join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS', 'FS_SUBDIR')), subject='fsaverage_1', hemis=hem, subjects_dir=join(MAINDIR, 'FS_SUBDIR')) coords.append(coord[0]) # First, we reorder the labels based on their location in the left hemi lh_labels = [name for name in label_names if name.endswith('lh')] rh_labels = [name for name in label_names if name.endswith('rh')] # Get the y-location of the label label_ypos = list() for name in lh_labels: idx = label_names.index(name) ypos = np.mean(labels[idx].pos[:, 1]) label_ypos.append(ypos) lh_labels = [label for (yp, label) in sorted(zip(label_ypos, lh_labels))] # For the right hemi rh_labels = [label[:-2] + 'rh' for label in lh_labels] # make a list with circular plot order node_order = list() node_order.extend(lh_labels[::-1]) # reverse the order node_order.extend(rh_labels) node_order = node_order[::-1] # reverse the whole thing # get a mapping to the original list re_order_ind = [label_names.index(x) for x in node_order] node_angles = mne.viz.circular_layout(label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) / 2]) fig2, ax = mne.viz.plot_connectivity_circle(matrix, label_names, n_lines=300, node_angles=node_angles, node_colors=label_colors, title=this_title, fig=fig, facecolor='white', textcolor='black') return fig2, ax
def test_vertex_to_mni(): """Test conversion of vertices to MNI coordinates.""" # obtained using "tksurfer (sample) (l/r)h white" vertices = [100960, 7620, 150549, 96761] coords = np.array([[-60.86, -11.18, -3.19], [-36.46, -93.18, -2.36], [-38.00, 50.08, -10.61], [47.14, 8.01, 46.93]]) hemis = [0, 0, 0, 1] coords_2 = vertex_to_mni(vertices, hemis, 'sample', subjects_dir) # less than 1mm error assert_allclose(coords, coords_2, atol=1.0)
def test_vertex_to_mni(): """Test conversion of vertices to MNI coordinates """ # obtained using "tksurfer (sample/fsaverage) (l/r)h white" vertices = [100960, 7620, 150549, 96761] coords_s = np.array([[-60.86, -11.18, -3.19], [-36.46, -93.18, -2.36], [-38.00, 50.08, -10.61], [47.14, 8.01, 46.93]]) coords_f = np.array([[-41.28, -40.04, 18.20], [-6.05, 49.74, -18.15], [-61.71, -14.55, 20.52], [21.70, -60.84, 25.02]]) hemis = [0, 0, 0, 1] for coords, subj in zip([coords_s, coords_f], ['sample', 'fsaverage']): coords_2 = vertex_to_mni(vertices, hemis, subj) # less than 1mm error assert_allclose(coords, coords_2, atol=1.0)
def test_vertex_to_mni(): """Test conversion of vertices to MNI coordinates """ # obtained using "tksurfer (sample/fsaverage) (l/r)h white" vertices = [100960, 7620, 150549, 96761] coords_s = np.array([[-60.86, -11.18, -3.19], [-36.46, -93.18, -2.36], [-38.00, 50.08, -10.61], [47.14, 8.01, 46.93]]) coords_f = np.array([[-41.28, -40.04, 18.20], [-6.05, 49.74, -18.15], [-61.71, -14.55, 20.52], [21.70, -60.84, 25.02]]) hemis = [0, 0, 0, 1] for coords, subject in zip([coords_s, coords_f], ['sample', 'fsaverage']): coords_2 = vertex_to_mni(vertices, hemis, subject, subjects_dir) # less than 1mm error assert_allclose(coords, coords_2, atol=1.0)
def test_vertex_to_mni(): """Test conversion of vertices to MNI coordinates """ # these were random vertices pulled from "sample" in mne_analyze # but mne_analyze won't load the xfm file! So we must use fsaverage, # which is sily because the xfm is the identity matrix.. #vertices = [109445, 82962, 137444] #coords = [[-33.3, 11.5, 50.7], [51.8, -15.4, 30.5], [37.6, 38.4, 57.1]] #hemi = [0, 1, 1] #coords_2 = vertex_to_mni(vertices, hemis, 'sample') vertices = [148611, 157229, 95466] coords = [[-55.7, -36.6, -9.6], [-48.5, -35.7, -1.1], [44.0, -34.9, -0.9]] hemis = [0, 0, 1] # , 1] coords_2 = np.round(vertex_to_mni(vertices, hemis, 'fsaverage'), 1) for vi in range(len(vertices)): assert_true(coords[vi] == coords_2[vi].tolist())
def get_labels(): MAINDIR = join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS') labels = mne.read_labels_from_annot('fsaverage_1', parc='aparc', subjects_dir=join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS','FS_SUBDIR')) labels = labels[0:-1] label_names = [label.name for label in labels] coords = [] # TODO: Find a better way to get centre of parcel #get coords of centre of mass for i in range(len(labels)): if 'lh' in label_names[i]: hem = 1 else: hem = 0 coord = mne.vertex_to_mni(labels[i].center_of_mass(subjects_dir=join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS','FS_SUBDIR')), subject='fsaverage_1',hemis=hem,subjects_dir=join(MAINDIR,'FS_SUBDIR')) coords.append(coord[0]) # First, we reorder the labels based on their location in the left hemi lh_labels = [name for name in label_names if name.endswith('lh')] rh_labels = [name for name in label_names if name.endswith('rh')] # Get the y-location of the label label_ypos = list() for name in lh_labels: idx = label_names.index(name) ypos = np.mean(labels[idx].pos[:, 1]) label_ypos.append(ypos) lh_labels = [label for (yp, label) in sorted(zip(label_ypos, lh_labels))] # For the right hemi rh_labels = [label[:-2] + 'rh' for label in lh_labels] # make a list with circular plot order node_order = list() node_order.extend(lh_labels[::-1]) # reverse the order node_order.extend(rh_labels) node_order = node_order[::-1] # reverse the whole thing # get a mapping to the original list re_order_ind = [label_names.index(x) for x in node_order] return labels, label_names, re_order_ind
def find_mni_coordinates(label, parc='HCPMMP1_5_8'): """Returns MNI-coordinates of center of mass for selected labels.""" if type(label) is mne.label.Label: labels = [label] else: labels = mne.read_labels_from_annot('fsaverage', parc=parc, regexp=label) mnicoords = {} for label in labels: if label.name.startswith('L'): hemi = 0 else: hemi = 1 vertno = label.center_of_mass() mnicoords[label.name] = mne.vertex_to_mni(vertno, hemi, 'fsaverage') return mnicoords
def coordinates_computation( subject: str, subjects_dir: str, labels: List[mne.Label], _subject_tree: Optional[SubjectTree] = None, _priority: Optional[int] = None) -> Dict[str, np.ndarray]: """computes central coordinates for given brain regions, uses :func:`nodestimation.project.read_or_write` decorator :param subject: patient`s ID :type subject: str :param subjects_dir: path to directory with patient`s files :type subjects_dir: str :param labels: brain regions representation :type labels: |ilist|_ *of* |imne.Label|_ :param _subject_tree: representation of patient`s files structure, default None :type _subject_tree: *look for SubjectTree in* :mod:`nodestimation.project.annotations` *, optional* :param _priority: if several files are read, which one to choose, if None, read all of them, default None :type _priority: int, optional :return: central coordinates relatively to brain region names :rtype: |idict|_ *of* |istr|_ *to* |inp.ndarray|_ .. _labels: .. _imne.Label: .. _mne.Label: https://mne.tools/stable/generated/mne.Label.html?highlight=label#mne.Label .. |imne.Label| replace:: *mne.Label* """ vertexes = [ mne.vertex_to_mni(label.vertices, hemis=0 if label.hemi == 'lh' else 1, subject=subject, subjects_dir=subjects_dir) for label in labels ] return { label.name: np.mean(vertex, axis=0) for label, vertex in zip(labels, vertexes) }
#common indexes for vertices in label vertices_max_list = ind[:10].tolist() common_indexes_max = [] for ind in vertices_max_list: # for left hemishere #common_indexes_max.append(stc_in_label.vertices[0][ind]) # for left hemishere common_indexes_max.append(stc_in_label.vertices[1][ind]) common_indexes_max = np.array(common_indexes_max) #for left hemishere #mni_coordinate = mne.vertex_to_mni(common_indexes_max, 0, 'avg_platon_27sub', subjects_dir=subjects_dir) #for right hemishere mni_coordinate = mne.vertex_to_mni(common_indexes_max, 1, 'avg_platon_27sub', subjects_dir=subjects_dir) df = pd.DataFrame() df['p_value'] = max_pval_10.tolist() df['MNI_coordinates'] = mni_coordinate.tolist() df.to_csv('/home/vtretyakova/Рабочий стол/speach_learn/Labels/p_val_mne_coordinate/{0}.csv'.format(l))
# load the stc stc = mne.read_source_estimate(meg_path + '/sample_audvis-meg') # load the labels aud_lh = mne.read_label(meg_path + '/labels/Aud-lh.label') aud_rh = mne.read_label(meg_path + '/labels/Aud-rh.label') # extract the time course for different labels from the stc stc_lh = stc.in_label(aud_lh) stc_rh = stc.in_label(aud_rh) stc_bh = stc.in_label(aud_lh + aud_rh) # calculate center of mass and transform to mni coordinates vtx, _, t_lh = stc_lh.center_of_mass('sample') mni_lh = mne.vertex_to_mni(vtx, 0, 'sample')[0] vtx, _, t_rh = stc_rh.center_of_mass('sample') mni_rh = mne.vertex_to_mni(vtx, 1, 'sample')[0] # plot the activation plt.figure() plt.axes([.1, .275, .85, .625]) hl = plt.plot(stc.times, stc_lh.data.mean(0), 'b')[0] hr = plt.plot(stc.times, stc_rh.data.mean(0), 'g')[0] hb = plt.plot(stc.times, stc_bh.data.mean(0), 'r')[0] plt.xlabel('Time (s)') plt.ylabel('Source amplitude (dSPM)') plt.xlim(stc.times[0], stc.times[-1]) # add a legend including center-of-mass mni coordinates to the plot labels = ['LH: center of mass = %s' % mni_lh.round(2),
def _cluster_sel(sel_path, label_list, stc, src, min_dist, weight, mni_subject='fsaverage'): """ subfunctions of sel_ROIs ---------- sel_path: string or list The directory for storing selected ROIs. label_list: list Labels to be selected. stc: the object of source estimates. src: the object of the common source space min_dist: int (mm) Least distance between ROIs candidates. weight: float Euclidean_norms weight related to the larger candidate's standard deviation. """ class_list = [] class_list.append(label_list[0]) for test_fn in label_list[1:]: test_label = mne.read_label(test_fn) i = 0 belong = False while (i < len(class_list)) and (belong is False): class_label = mne.read_label(class_list[i]) if test_label.hemi != class_label.hemi: i = i + 1 continue else: class_pca = stc.extract_label_time_course(class_label, src, mode='pca_flip') test_pca = stc.extract_label_time_course(test_label, src, mode='pca_flip') class_pow = np.sum(class_pca ** 2) test_pow = np.sum(test_pca ** 2) max_pca = class_pca exch = False if class_pow < test_pow: max_pca = test_pca exch = True nearby = False class_stc = stc.in_label(class_label) test_stc = stc.in_label(test_label) if class_label.hemi == 'lh': class_vtx, _ = class_stc.get_peak(hemi='lh') test_vtx, _ = test_stc.get_peak(hemi='lh') class_mni = mne.vertex_to_mni(class_vtx, 0, mni_subject)[0] test_mni = mne.vertex_to_mni(test_vtx, 0, mni_subject)[0] elif class_label.hemi == 'rh': class_vtx, _ = class_stc.get_peak(hemi='rh') test_vtx, _ = test_stc.get_peak(hemi='rh') class_mni = mne.vertex_to_mni(class_vtx, 1, mni_subject)[0] test_mni = mne.vertex_to_mni(test_vtx, 1, mni_subject)[0] if np.linalg.norm(class_mni - test_mni) < min_dist: if exch == True: os.remove(class_list[i]) class_list[i] = test_fn elif exch == False: os.remove(test_fn) nearby = True belong = True if nearby == False: thre = max_pca.std() * weight diff = np.abs(np.linalg.norm(class_pca) - np.linalg.norm(test_pca)) if diff < thre: if exch == True: os.remove(class_list[i]) class_list[i] = test_fn elif exch == False: os.remove(test_fn) belong = True i = i + 1 if belong is False: class_list.append(test_fn) return len(class_list)
def create_mxne_summary( subjects, p, morph_subject=None, n_display=None, pattern_in='', pattern_out='_mxne', path_out='./', title='%s Dipoles', ): '''Create a report and spreadsheet about mixed-norm dipoles.''' src_file = os.path.join(p.subjects_dir, 'fsaverage', 'bem', 'fsaverage-ico-5-src.fif') src_fsavg = mne.read_source_spaces(src_file) src_file = os.path.join(p.subjects_dir, '14mo_surr', 'bem', '14mo_surr-oct-6-src.fif') src_14mo = mne.read_source_spaces(src_file) mni_labels = mne.read_labels_from_annot('fsaverage', 'HCPMMP1', subjects_dir=p.subjects_dir) labels = mne.read_labels_from_annot('14mo_surr', use_parc, subjects_dir=p.subjects_dir) for subject in subjects: # Load STCs and other saved data # cond = p.stc_params['condition'] stc_path = os.path.join(p.work_dir, subject, p.stc_dir) stc_stem = subject + '_' + cond + pattern_in stc_file = os.path.join(stc_path, stc_stem) if not os.path.isfile(stc_file + '-lh.stc'): print(f'** STC file matching {stc_stem} not found ********.\n') continue stc_mxne = mne.read_source_estimate(stc_file) n_dipoles, n_times = stc_mxne.data.shape meta_data = np.load(stc_file + '.npy', allow_pickle=True) gof_mxne = meta_data[0] residual_mxne = meta_data[1] evk_path = os.path.join(p.work_dir, subject, p.inverse_dir) evk_file = f'Locations_40-sss_eq_{subject}-ave.fif' evk_file = os.path.join(evk_path, evk_file) evoked = mne.read_evokeds(evk_file, condition=cond, kind='average') evoked.pick_types(meg=True) cov_path = os.path.join(p.work_dir, subject, p.cov_dir) cov_file = f'{subject}-40-sss-cov.fif' cov_file = os.path.join(cov_path, cov_file) cov = mne.read_cov(cov_file) trans_path = os.path.join(p.work_dir, subject, p.trans_dir) trans_file = f'{subject}-trans.fif' trans_file = os.path.join(trans_path, trans_file) trans = mne.read_trans(trans_file, verbose=False) fwd_path = os.path.join(p.work_dir, subject, p.forward_dir) fwd_file = f'{subject}-sss-fwd.fif' fwd_file = os.path.join(fwd_path, fwd_file) fwd = mne.read_forward_solution(fwd_file, verbose=False) assert fwd['src'][0]['nuse'] == src_14mo[0]['nuse'] assert fwd['src'][1]['nuse'] == src_14mo[1]['nuse'] # Run analysis on the dipoles, then sort then by goodness-of-fit # results = analyze_dipoles(stc_mxne, gof_mxne, evoked, cov, p.stc_params['gof_t_range']) results, sort_idx = sort_dipoles(results) # stc still unsorted gof_results, amp_results = results assert len(gof_results) == n_dipoles # Collect info for the top dipoles, in order # n_show = n_dipoles if n_display: n_show = min(n_display, n_show) n_left = len(stc_mxne.vertices[0]) # .data stacked lh then rh postop, mnitop, wavtop = [], [], [] for i in range(n_dipoles): di = sort_idx[i] hemid = int(di >= n_left) vidx = di - hemid * n_left vert = stc_mxne.vertices[hemid][vidx] pos = fwd['src'][hemid]['rr'][vert] postop.append(pos) mni = mne.vertex_to_mni(vert, hemid, subject, subjects_dir=p.subjects_dir) mnitop.append(mni) wav = stc_mxne.data[di, :] wavtop.append(wav) assert wav[amp_results[i].pidx] == amp_results[i].peak # check last # Make various figures # figure_list, figure_info, figure_comment = [], [], [] # 1) Top dipoles in one set of surface maps. if morph_subject: src_subject = morph_subject caption = 'Surface Plots | ' + morph_subject else: src_subject = subject caption = 'Surface Plots | Coreg.' fig_surface = make_surfaceplots(stc_mxne, src_subject, p.subjects_dir, sort_idx, parc=use_parc) figure_list.append(fig_surface) figure_info.append([caption, 'Surface Plots']) figure_comment.append(color_comment) # 2) Top dipoles in 3D slices (non-morphed and MNI). mri_file = os.path.join(p.subjects_dir, subject, 'mri', 'T1.mgz') postop_mri = mne.head_to_mri(postop, mri_head_t=trans, subject=subject, subjects_dir=p.subjects_dir) postop_mni = mne.head_to_mni(postop, mri_head_t=trans, subject=subject, subjects_dir=p.subjects_dir) assert_allclose(mnitop[0], postop_mni[0], atol=0.01) assert_allclose(mnitop[-1], postop_mni[-1], atol=0.01) fig_orthog1 = make_orthogplots(mri_file, postop_mri[:n_show]) fig_orthog2 = make_orthogplots(mni_template, postop_mni[:n_show]) figure_list.append(fig_orthog1) figure_info.append(['Orthogonal Plots | Coreg.', 'Orthogonal Plots']) figure_comment.append(None) figure_list.append(fig_orthog2) figure_info.append(['Orthogonal Plots | MNI)', 'Orthogonal Plots']) figure_comment.append(f'Top {n_show} of {n_dipoles} dipoles ' 'displayed.') # 3) Top dipoles' time waveforms. fig_wav = make_sourcewavs(wavtop, stc_mxne.times, p.stc_params['gof_t_range']) figure_list.append(fig_wav) figure_info.append(['STC Time Course', 'Temporal Waveforms']) figure_comment.append(None) # 4) Evoked and residual waveforms (averages across sensors) fig_sensor = make_sensorwavs(evoked, residual_mxne) figure_list.append(fig_sensor) figure_info.append(['Sensor Time Course', 'Temporal Waveforms']) figure_comment.append(None) # Determine 14-mo surrogate "aparc" label for each dipole # labels_stc = [] # note these are not gof-ordered for hh, hemi in enumerate(('lh', 'rh')): for vert in stc_mxne.vertices[hh]: label = which_label(vert, hemi, labels) if label: labels_stc.append(label.name) else: labels_stc.append('no_label') # Expand the sparse STC so it can be morphed (X='expanded') # # v_lh = fwd['src'][0]['vertno'] # the full source space # v_rh = fwd['src'][1]['vertno'] # n_vtotal = vertices = len(v_lh) + len(v_rh) # data_mxneX = np.zeros((n_vtotal, n_times)) # idx_vrts = np.isin(v_lh, stc_mxne.vertices[0]) # idx_vrts = np.where(idx_vrts)[0] # data_mxneX[idx_vrts, :] = stc_mxne.data[:n_left, :] # idx_vrts = np.isin(v_rh, stc_mxne.vertices[1]) # idx_vrts = np.where(idx_vrts)[0] # data_mxneX[idx_vrts, :] = stc_mxne.data[n_left:, :] # stc_mxneX = mne.SourceEstimate(data_mxneX, [v_lh, v_rh], # tmin=stc_mxne.tmin, tstep=stc_mxne.tstep, # subject=stc_mxne.subject) # Determine fsaverage "HCPMMP1" labels for each dipole # # Note: 'sparse' doesn't give a 1-to-1 mapping. morph_fcn = mne.compute_source_morph(stc_mxne, src_to=src_fsavg, smooth='nearest', spacing=None, warn=False, subjects_dir=p.subjects_dir, niter_sdr=(), sparse=True, subject_from=subject, subject_to='fsaverage') mlabels_stc = [] # like above, but now for fsaverage:HCPMMP1 verts_mni = [] for di in range(n_dipoles): stc_temp = stc_mxne.copy() # zero all but dipole of interest stc_temp.data = np.zeros((n_dipoles, n_times)) stc_temp.data[di, :] = stc_mxne.data[di, :] mstc_temp = morph_fcn.apply(stc_temp) vidx = np.where(mstc_temp.data[:, 0] > 0)[0] vidx_lh = [i for i in vidx if i < n_left] # don't assume hemi vidx_rh = [i - n_left for i in vidx if i >= n_left] verts_byhemi = [None, None] verts_byhemi[0] = mstc_temp.vertices[0][vidx_lh] verts_byhemi[1] = mstc_temp.vertices[1][vidx_rh] verts_mni.append(verts_byhemi) cnt = 0 for verts, hemi, prefix in zip(verts_byhemi, ['lh', 'rh'], ['L_', 'R_']): if not verts: continue vert = verts[0] # should only be one with sparse arg. lbl = which_label(vert, hemi, mni_labels) if lbl: lbl = lbl.name else: lbl = 'no_label' lbl = re.sub(rf"^{prefix}", "", lbl) lbl = re.sub(r"_ROI", "", lbl) cnt += 1 assert cnt == 1 # only one hemisphere should be valid mlabels_stc.append(lbl) # Create formatted tables for a report section # # SMB: Saving as string objects in case they can be added to report. strobj1 = StringIO() # TABLE 1: sorted gof and amplitude info sprint = lambda *x: print(*x, file=strobj1, end='') ff = '<8.2f' # format: center on 8-char field, 2 decimal places sprint(f'{"Dip #":^6} {"Peak/Mean Amp":<16} ' f'{"Peak/Mean GOF":<16} {"GOF Time":<8}\n') for i in range(n_dipoles): amp_m = 1e9 * amp_results[i].mean amp_p = 1e9 * amp_results[i].peak gof_m = gof_results[i].mean gof_p = gof_results[i].peak time_p = evoked.times[gof_results[i].pidx] sprint(f'{i:^6} {amp_p:{ff}}{amp_m:{ff}} ' f'{gof_p:{ff}}{gof_m:{ff}} ' f'{time_p:{"<8.3f"}}\n') sprint('\n') strobj2 = StringIO() # TABLE 2: coordinate and label info sprint = lambda *x: print(*x, file=strobj2, end='') ff = '<20' sprint(f'{"Dip #":^6} {"14mo Coord":{ff}} {"MNI Coord":{ff}} ' f'{"14mo Aparc | Fsavg HCPMMP1":{ff}}\n') for i in range(n_dipoles): di = sort_idx[i] hemid = int(di >= n_left) # hemi = 'rh' if hemid else 'lh' vidx = di - hemid * n_left vert = stc_mxne.vertices[hemid][vidx] coord = src_14mo[hemid]['rr'][vert] * 1000 coord_str = ' '.join([f'{x:.1f}' for x in coord]) vert = verts_mni[di][hemid][0] # just the first one coord = src_fsavg[hemid]['rr'][vert] * 1000 mcoord_str = ' '.join([f'{x:.1f}' for x in coord]) sprint(f'{i:^6} {coord_str:{ff}} {mcoord_str:{ff}} ' f'{labels_stc[di]:{ff}}\n {"":<47} ' f'{mlabels_stc[di]:{ff}}\n') # Print out the tables # print(f'\nGOF-sorted dipole info for {subject}:') strobj1.seek(0) print(strobj1.read()) strobj1.close() print(f'\nGOF-sorted position info for {subject}:') strobj2.seek(0) print(strobj2.read()) strobj2.close() # Compile all figures into a report # print(f'Compiling report for {subject}.') if not os.path.exists(path_out): os.mkdir(path_out) if '%s ' in title: title_use = title.replace('%s ', 'Group') else: title_use = title report = mne.Report(title=title_use, image_format='png') for fig, info, cstr in zip(figure_list, figure_info, figure_comment): report.add_figs_to_section(fig, captions=info[0], scale=1.0, section=info[1], comments=cstr) report_file = os.path.join(path_out, subject + pattern_out + '.html') report.save(report_file, open_browser=False, overwrite=True)
fid.close() # prepare the fsaverage subject if we're dealing with AFNI mask if roi.find('+tlrc') > 0: mask_fname = '/lscratch/' + os.environ['SLURM_JOBID'] + '/mask.txt' os.system('3dmaskdump -xyz -o ' + mask_fname + ' ' + roi) a = np.genfromtxt(mask_fname) os.system('rm ' + mask_fname) gv = a[a[:, 6] > 0, 3:6] # separate good voxels in the mask # change AFNI results from RAI to LPI gv[:, 0] = gv[:, 0] * -1 gv[:, 1] = gv[:, 1] * -1 src = mne.setup_source_space(subject='fsaverage_mne', fname=None, spacing='ico5', surface='inflated', n_jobs=2) # get left and right coordinates for all the sources coord0 = mne.vertex_to_mni(vertices=src[0]['vertno'], hemis=0, subject='fsaverage_mne') coord1 = mne.vertex_to_mni(vertices=src[1]['vertno'], hemis=1, subject='fsaverage_mne') coord = np.vstack([coord0, coord1]) # store the index of the sources within min_dist of the mask voxels b = [] for i in range(gv.shape[0]): dist = np.sqrt((coord[:, 0] - gv[i, 0]) ** 2 + (coord[:, 1] - gv[i, 1]) ** 2 + (coord[:, 2] - gv[i, 2]) ** 2) if min(dist) <= min_dist: b.append(np.argmin(dist)) # create a stc with 1s for the near sources d = np.zeros([coord.shape[0], 1]) d[b] = 1 stc = mne.SourceEstimate(d, vertices=[src[0]['vertno'], src[1]['vertno']], tmin=0, tstep=1, subject='fsaverage_mne') # convert the stc to a label so we can morph it per subject later avg_label = mne.stc_to_label(stc, src=src, smooth=True, connected=False)
def test_scale_mri_xfm(tmp_path, few_surfaces): """Test scale_mri transforms and MRI scaling.""" # scale fsaverage tempdir = str(tmp_path) fake_home = testing.data_path() # add fsaverage create_default_subject(subjects_dir=tempdir, fs_home=fake_home, verbose=True) # add sample (with few files) sample_dir = op.join(tempdir, 'sample') os.mkdir(sample_dir) os.mkdir(op.join(sample_dir, 'bem')) for dirname in ('mri', 'surf'): copytree(op.join(fake_home, 'subjects', 'sample', dirname), op.join(sample_dir, dirname)) subject_to = 'flachkopf' spacing = 'oct2' for subject_from in ('fsaverage', 'sample'): if subject_from == 'fsaverage': scale = 1. # single dim else: scale = [0.9, 2, .8] # separate src_from_fname = op.join(tempdir, subject_from, 'bem', '%s-%s-src.fif' % (subject_from, spacing)) src_from = mne.setup_source_space(subject_from, spacing, subjects_dir=tempdir, add_dist=False) write_source_spaces(src_from_fname, src_from) vertices_from = np.concatenate([s['vertno'] for s in src_from]) assert len(vertices_from) == 36 hemis = ([0] * len(src_from[0]['vertno']) + [1] * len(src_from[0]['vertno'])) mni_from = mne.vertex_to_mni(vertices_from, hemis, subject_from, subjects_dir=tempdir) if subject_from == 'fsaverage': # identity transform source_rr = np.concatenate( [s['rr'][s['vertno']] for s in src_from]) * 1e3 assert_allclose(mni_from, source_rr) if subject_from == 'fsaverage': overwrite = skip_fiducials = False else: with pytest.raises(IOError, match='No fiducials file'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir) skip_fiducials = True with pytest.raises(IOError, match='already exists'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, skip_fiducials=skip_fiducials) overwrite = True if subject_from == 'sample': # support for not needing all surf files os.remove(op.join(sample_dir, 'surf', 'lh.curv')) scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, verbose='debug', overwrite=overwrite, skip_fiducials=skip_fiducials) if subject_from == 'fsaverage': assert _is_mri_subject(subject_to, tempdir), "Scaling failed" src_to_fname = op.join(tempdir, subject_to, 'bem', '%s-%s-src.fif' % (subject_to, spacing)) assert op.exists(src_to_fname), "Source space was not scaled" # Check MRI scaling fname_mri = op.join(tempdir, subject_to, 'mri', 'T1.mgz') assert op.exists(fname_mri), "MRI was not scaled" # Check MNI transform src = mne.read_source_spaces(src_to_fname) vertices = np.concatenate([s['vertno'] for s in src]) assert_array_equal(vertices, vertices_from) mni = mne.vertex_to_mni(vertices, hemis, subject_to, subjects_dir=tempdir) assert_allclose(mni, mni_from, atol=1e-3) # 0.001 mm
# load the stc stc = mne.read_source_estimate(meg_path + '/sample_audvis-meg') # load the labels aud_lh = mne.read_label(meg_path + '/labels/Aud-lh.label') aud_rh = mne.read_label(meg_path + '/labels/Aud-rh.label') # extract the time course for different labels from the stc stc_lh = stc.in_label(aud_lh) stc_rh = stc.in_label(aud_rh) stc_bh = stc.in_label(aud_lh + aud_rh) # calculate center of mass and transform to mni coordinates vtx, _, t_lh = stc_lh.center_of_mass('sample') mni_lh = mne.vertex_to_mni(vtx, 0, 'sample')[0] vtx, _, t_rh = stc_rh.center_of_mass('sample') mni_rh = mne.vertex_to_mni(vtx, 1, 'sample')[0] # plot the activation plt.figure() plt.axes([.1, .275, .85, .625]) hl = plt.plot(stc.times, stc_lh.data.mean(0), 'b') hr = plt.plot(stc.times, stc_rh.data.mean(0), 'g') hb = plt.plot(stc.times, stc_bh.data.mean(0), 'r') plt.xlabel('Time (s)') plt.ylabel('Source amplitude (dSPM)') plt.xlim(stc.times[0], stc.times[-1]) # add a legend including center-of-mass mni coordinates to the plot labels = [
def source_loc(evoked, cov, fwd, subj, img_type, study_path, plot=False): cond = evoked.info['description'] stim_coords = find_stim_coords(cond, subj, study_path) stim_params = get_stim_params(cond) inv = mne.minimum_norm.make_inverse_operator(evoked.info, fwd, cov, loose=0.2, depth=0.8) method = "dSPM" snr = 300. lambda2 = 1. / snr**2 stc = mne.minimum_norm.apply_inverse(evoked, inv, lambda2, method=method, pick_ori=None) stc.save( op.join(study_path, 'source_stim', subj, 'source_files', img_type, 'stc', '%s_%s' % (subj, cond))) # plot_source_space(subj, study_path, subjects_dir) hemi = 'lh' if stim_params['is_left'] else 'rh' contact_nr = int(re.findall('\d+', stim_params['ch'])[0]) view = 'medial' if contact_nr < 5 else 'lateral' # improve view selection vertno_max, time_max = stc.get_peak(hemi=hemi) stc_max = np.max(stc.data) if plot: brain_inf = stc.plot(surface='inflated', hemi=hemi, subjects_dir=subjects_dir, subject=fs_subj, clim=dict(kind='value', lims=[0, stc_max * 0.75, stc_max]), initial_time=time_max, time_unit='s', alpha=1, background='w', foreground='k') brain_inf.add_foci(vertno_max, coords_as_verts=True, hemi=hemi, color='blue', scale_factor=0.8) brain_inf.add_foci(stim_coords['surf_ori'], map_surface='pial', hemi=hemi, color='green', scale_factor=0.8) brain_inf.show_view(view) # mlab.view(130, 90) fig_fname = op.join(study_path, 'source_stim', subj, 'figures', 'distributed', '%s_inf_foci.eps' % cond) #brain_inf.save_image(fig_fname) mlab.show() #mlab.clf() max_mni = mne.vertex_to_mni( vertno_max, hemis=0, subject=subj, subjects_dir=subjects_dir ) # mni coords of vertex (ojo vertex resolution ico-5) stim_mni = stim_coords['mni'] # mni coords of stimulation dist_mni = euclidean(max_mni, stim_mni) print(dist_mni) return dist_mni
# load the stc stc = mne.read_source_estimate(meg_path / 'sample_audvis-meg') # load the labels aud_lh = mne.read_label(meg_path / 'labels' / 'Aud-lh.label') aud_rh = mne.read_label(meg_path / 'labels' / 'Aud-rh.label') # extract the time course for different labels from the stc stc_lh = stc.in_label(aud_lh) stc_rh = stc.in_label(aud_rh) stc_bh = stc.in_label(aud_lh + aud_rh) # calculate center of mass and transform to mni coordinates vtx, _, t_lh = stc_lh.center_of_mass('sample', subjects_dir=subjects_dir) mni_lh = mne.vertex_to_mni(vtx, 0, 'sample', subjects_dir=subjects_dir)[0] vtx, _, t_rh = stc_rh.center_of_mass('sample', subjects_dir=subjects_dir) mni_rh = mne.vertex_to_mni(vtx, 1, 'sample', subjects_dir=subjects_dir)[0] # plot the activation plt.figure() plt.axes([.1, .275, .85, .625]) hl = plt.plot(stc.times, stc_lh.data.mean(0), 'b')[0] hr = plt.plot(stc.times, stc_rh.data.mean(0), 'g')[0] hb = plt.plot(stc.times, stc_bh.data.mean(0), 'r')[0] plt.xlabel('Time (s)') plt.ylabel('Source amplitude (dSPM)') plt.xlim(stc.times[0], stc.times[-1]) # add a legend including center-of-mass mni coordinates to the plot labels = [
tonetype = 'pure' hemi = 'rh' hem = 1 cmap = cm.rainbow(np.linspace(0,1,len(frequencies))) t_bin = [] b = Brain('fsaverage', hemi = hemi , surf = 'pial',background='white') for f,freq in enumerate(frequencies): vtx, _, t = np.load(meg_dir + '_STCS/%s/%s/_CM_%s_%s_%s_cropped.npy' % (tonetype,freq,tonetype,freq,hemi)) # vtx, _, t = np.load(meg_dir + '_STCS/%s/%s/_CM_%s_%s_%s_cropped.npy' % (tonetype,freq,tonetype,freq,hemi)) # get the mni co-ordinates of the center of mass coords = vertex_to_mni(int(vtx), hemis=hem, subject='fsaverage') print (coords) # plot result b.add_foci(coords, color=cmap[f], map_surface='pial', scale_factor=0.5) t_bin.append(t) key = 'A' if key == 'A': frequencies = [220, 247, 277, 294, 330, 370, 415, 440] elif key == 'C': frequencies = [262, 294, 330, 349, 392, 440, 494, 523] elif key == 'Eb': frequencies = [312, 349, 392, 415, 466, 523, 587, 624]
def test_scale_mri_xfm(tmp_path, few_surfaces, subjects_dir_tmp_few): """Test scale_mri transforms and MRI scaling.""" # scale fsaverage tempdir = str(subjects_dir_tmp_few) sample_dir = subjects_dir_tmp_few / 'sample' subject_to = 'flachkopf' spacing = 'oct2' for subject_from in ('fsaverage', 'sample'): if subject_from == 'fsaverage': scale = 1. # single dim else: scale = [0.9, 2, .8] # separate src_from_fname = op.join(tempdir, subject_from, 'bem', '%s-%s-src.fif' % (subject_from, spacing)) src_from = mne.setup_source_space(subject_from, spacing, subjects_dir=tempdir, add_dist=False) write_source_spaces(src_from_fname, src_from) vertices_from = np.concatenate([s['vertno'] for s in src_from]) assert len(vertices_from) == 36 hemis = ([0] * len(src_from[0]['vertno']) + [1] * len(src_from[0]['vertno'])) mni_from = mne.vertex_to_mni(vertices_from, hemis, subject_from, subjects_dir=tempdir) if subject_from == 'fsaverage': # identity transform source_rr = np.concatenate( [s['rr'][s['vertno']] for s in src_from]) * 1e3 assert_allclose(mni_from, source_rr) if subject_from == 'fsaverage': overwrite = skip_fiducials = False else: with pytest.raises(IOError, match='No fiducials file'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir) skip_fiducials = True with pytest.raises(IOError, match='already exists'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, skip_fiducials=skip_fiducials) overwrite = True if subject_from == 'sample': # support for not needing all surf files os.remove(op.join(sample_dir, 'surf', 'lh.curv')) scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, verbose='debug', overwrite=overwrite, skip_fiducials=skip_fiducials) if subject_from == 'fsaverage': assert _is_mri_subject(subject_to, tempdir), "Scaling failed" src_to_fname = op.join(tempdir, subject_to, 'bem', '%s-%s-src.fif' % (subject_to, spacing)) assert op.exists(src_to_fname), "Source space was not scaled" # Check MRI scaling fname_mri = op.join(tempdir, subject_to, 'mri', 'T1.mgz') assert op.exists(fname_mri), "MRI was not scaled" # Check MNI transform src = mne.read_source_spaces(src_to_fname) vertices = np.concatenate([s['vertno'] for s in src]) assert_array_equal(vertices, vertices_from) mni = mne.vertex_to_mni(vertices, hemis, subject_to, subjects_dir=tempdir) assert_allclose(mni, mni_from, atol=1e-3) # 0.001 mm # Check head_to_mni (the `trans` here does not really matter) trans = rotation(0.001, 0.002, 0.003) @ translation(0.01, 0.02, 0.03) trans = Transform('head', 'mri', trans) pos_head_from = np.random.RandomState(0).randn(4, 3) pos_mni_from = mne.head_to_mni(pos_head_from, subject_from, trans, tempdir) pos_mri_from = apply_trans(trans, pos_head_from) pos_mri = pos_mri_from * scale pos_head = apply_trans(invert_transform(trans), pos_mri) pos_mni = mne.head_to_mni(pos_head, subject_to, trans, tempdir) assert_allclose(pos_mni, pos_mni_from, atol=1e-3)
fid = open(subjs_fname, 'r') subjs = [line.rstrip() for line in fid] # find closest source to seed if seed[0] < 0: hemis = 0 # LH else: hemis = 1 # RH # important to do this by source, because not every vertex has a source fname = data_dir + 'morphed-lcmv-%dto%d-' % (bands[0][0], bands[0][1]) + subjs[0] stc = mne.read_source_estimate(fname) # this is what we get when we read in the fsaverage subject coord = mne.vertex_to_mni(vertices=stc.vertno[hemis], hemis=hemis, subject='fsaverage') dist = np.sqrt((coord[:, 0] - seed[0])**2 + (coord[:, 1] - seed[1])**2 + (coord[:, 2] - seed[2])**2) seed_src = np.argmin(dist) + hemis * len(stc.lh_vertno) print 'Distance to seed: %.2fmm' % np.min(dist) # for each band, compute subject-based correlation map for l_freq, h_freq in bands: subj_corrs = [] print 'Band %d to %d Hz' % (l_freq, h_freq) cnt = 0 for s in subjs: print cnt + 1, '/', len(subjs) fname = data_dir + 'morphed-lcmv-%dto%d-' % (l_freq, h_freq) + s stc = mne.read_source_estimate(fname)
subject = 'fsaverage' # Plot brain in 3D with PySurfer if available brain = new_stc.plot(subject, hemi='lh', subjects_dir=subjects_dir) brain.show_view('lateral') # use peak getter to move vizualization to the time point of the peak vertno_max, time_idx = new_stc.get_peak(hemi='lh', time_as_index=True) brain.set_data_time_index(time_idx) # draw marker at maximum peaking vertex brain.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue', scale_factor=0.6, map_surface='white') mni_coords = mne.vertex_to_mni(vertno_max, hemis=0, subject=subject, subjects_dir=subjects_dir) print 'The MNI coords are ', mni_coords #my_trans = mne.read_trans(?) #src_pts = apply_trans(trans, some_tgt_pts) from surfer import utils utils.coord_to_label(subject, mni_coords[0], label='mycoord', hemi='lh', n_steps=25, map_surface="white") brain.add_label('mycoord-lh.label', color="darkseagreen", alpha=.8) # if the new mni_coords are computed brain.add_foci(mni_coords[0], coords_as_verts=False, hemi='lh', color='red', map_surface='white', scale_factor=0.6)
parc='aparc') # nodes in one hemisphere can be plotted as well aparc_lh = [lab for lab in aparc if lab.hemi == 'lh'] coords = [] # plot 10 nodes from left hemisphere only for better viz for lab in aparc_lh[:10]: if lab.name is 'unknown-lh': continue # get the center of mass com = lab.center_of_mass('fsaverage') # obtain mni coordinated to the vertex from left hemi coords_ = mne.vertex_to_mni(com, hemis=0, subject=subject, subjects_dir=subjects_dir)[0] coords.append(coords_) n_nodes = np.array(coords).shape[0] # make a random connectivity matrix con = np.random.random((n_nodes, n_nodes)) con[np.diag_indices(5)] = 0. con[np.triu_indices(5, k=1)] = 0. con += con.T con[con < 0.6] = 0. # plot the connectome on a glass brain background plotting.plot_connectome(con, coords) plt.show()
def _cluster_rois(sel_path, label_list, stc, src, min_dist, weight, mni_subject='fsaverage'): """ subfunctions of merge_ROIs ---------- mer_path: str The directory for storing merged ROIs. label_list: list Labels to be merged """ class_list = [] class_list.append(label_list[0]) for test_fn in label_list[1:]: test_label = mne.read_label(test_fn) i = 0 belong = False while (i < len(class_list)) and (belong is False): class_label = mne.read_label(class_list[i]) if test_label.hemi != class_label.hemi: i = i + 1 continue else: # Get the centroids class_stc = stc.in_label(class_label) test_stc = stc.in_label(test_label) class_pow = np.sum(class_stc.data ** 2, axis=1) test_pow = np.sum(test_stc.data ** 2, axis=1) if class_label.hemi == 'lh': h = 0 elif class_label.hemi == 'rh': h = 1 class_seed = class_stc.vertices[h][np.argmax(class_pow)] test_seed = test_stc.vertices[h][np.argmax(test_pow)] class_vtx = np.searchsorted(stc.vertices[h], class_seed) test_vtx = np.searchsorted(stc.vertices[h], test_seed) class_mni = mne.vertex_to_mni(class_vtx, h, mni_subject)[0] test_mni = mne.vertex_to_mni(test_vtx, h, mni_subject)[0] # Get the representative STCs for class label and test label class_ts = stc.data[class_vtx, :] test_ts = stc.data[test_vtx, :] # Mark the more apparent ROI max_ts = class_ts exch = False if np.max(class_pow) < np.max(test_pow): max_ts = test_ts exch = True # Compute the centroids distance if np.linalg.norm(class_mni - test_mni) < min_dist: if exch == True: os.remove(class_list[i]) class_list[i] = test_fn elif exch == False: os.remove(test_fn) belong = True # Compute the similarity else: thre = max_ts.std() * weight diff = np.abs(np.linalg.norm(class_ts) - np.linalg.norm(test_ts)) if diff < thre: if exch == True: os.remove(class_list[i]) class_list[i] = test_fn elif exch == False: os.remove(test_fn) belong = True i = i + 1 if belong is False: class_list.append(test_fn) return len(class_list)
def test_brain_traces(renderer_interactive_pyvistaqt, hemi, src, tmpdir, brain_gc): """Test brain traces.""" hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain._scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker(current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni(vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir) label = "{}:{} MNI: {}".format(hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert op.basename(fname) in rst assert op.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2]
def _cluster_rois(sel_path, label_list, stc, src, min_dist, weight, mni_subject='fsaverage'): """ subfunctions of merge_ROIs ---------- mer_path: str The directory for storing merged ROIs. label_list: list Labels to be merged """ class_list = [] class_list.append(label_list[0]) for test_fn in label_list[1:]: test_label = mne.read_label(test_fn) i = 0 belong = False while (i < len(class_list)) and (belong is False): class_label = mne.read_label(class_list[i]) if test_label.hemi != class_label.hemi: i = i + 1 continue else: class_pca = stc.extract_label_time_course(class_label, src, mode='pca_flip') test_pca = stc.extract_label_time_course(test_label, src, mode='pca_flip') class_pow = np.sum(class_pca ** 2) test_pow = np.sum(test_pca ** 2) max_pca = class_pca exch = False if class_pow < test_pow: max_pca = test_pca exch = True nearby = False class_stc = stc.in_label(class_label) test_stc = stc.in_label(test_label) if class_label.hemi == 'lh': class_vtx, _ = class_stc.get_peak(hemi='lh') test_vtx, _ = test_stc.get_peak(hemi='lh') class_mni = mne.vertex_to_mni(class_vtx, 0, mni_subject)[0] test_mni = mne.vertex_to_mni(test_vtx, 0, mni_subject)[0] elif class_label.hemi == 'rh': class_vtx, _ = class_stc.get_peak(hemi='rh') test_vtx, _ = test_stc.get_peak(hemi='rh') class_mni = mne.vertex_to_mni(class_vtx, 1, mni_subject)[0] test_mni = mne.vertex_to_mni(test_vtx, 1, mni_subject)[0] if np.linalg.norm(class_mni - test_mni) < min_dist: if exch == True: os.remove(class_list[i]) class_list[i] = test_fn elif exch == False: os.remove(test_fn) nearby = True belong = True if nearby == False: thre = max_pca.std() * weight diff = np.abs(np.linalg.norm(class_pca) - np.linalg.norm(test_pca)) if diff < thre: if exch == True: os.remove(class_list[i]) class_list[i] = test_fn elif exch == False: os.remove(test_fn) belong = True i = i + 1 if belong is False: class_list.append(test_fn) return len(class_list)
def location(stc, subject, selection='all', locate=True): if locate is True: locate = 1 print "Locate ", locate, " dipoles" if selection is 'all': nd = stc[0].data.shape[0] ns = stc[0].data.shape[1] loc = np.zeros((len(stc), ns, 3 * locate)) vtx = stc[0].vertices vtx_long = np.hstack((stc[0].vertices[0], stc[0].vertices[1])) hem0 = np.size(vtx[0]) hem1 = np.size(vtx[1]) for s in range(0, len(stc)): #max location (index) mxloca = np.argsort(np.abs(stc[s].data), axis=0) mxloc = mxloca[-1 - locate:-1, :] assert mxloc.shape[0] == locate and mxloc.shape[1] == ns hemi = np.where(mxloc < nd / 2, 0, 1).reshape([-1]) mxvtx_long = vtx_long[mxloc].reshape([-1]) if subject is 'sample': #ns*locatex3 tmp = mne.vertex_to_mni( mxvtx_long, hemi, subject, subjects_dir= '/home/jcasa/mne_data/MNE-sample-data/subjects', verbose=False) else: tmp = mne.vertex_to_mni(mxvtx_long, hemi, subject, verbose=False) assert tmp.shape[1] == 3 and tmp.shape[0] == ns * locate, tmp.shape tmp = tmp.reshape([locate, ns, 3]) tmp = np.transpose(tmp, (1, 0, 2)).reshape([-1, locate * 3]) assert tmp.shape[1] == 3 * locate and tmp.shape[0] == ns, tmp.shape loc[s, :, :] = tmp qtrue_all = loc p = loc.shape[2] return qtrue_all, p else: nd = stc[0].data.shape[0] ns = stc[0].data.shape[1] loc = np.zeros((len(selection), ns, 3 * locate)) vtx = stc[0].vertices vtx_long = np.hstack((stc[0].vertices[0], stc[0].vertices[1])) hem0 = np.size(vtx[0]) hem1 = np.size(vtx[1]) ind_s = 0 for s in selection: #max location (index) mxloca = np.argsort(np.abs(stc[s].data), axis=0) mxloc = mxloca[-1 - locate:-1, :] assert mxloc.shape[0] == locate and mxloc.shape[1] == ns hemi = np.where(mxloc < nd / 2, 0, 1).reshape([-1]) mxvtx_long = vtx_long[mxloc].reshape([-1]) if subject is 'sample': #ns*locatex3 tmp = mne.vertex_to_mni( mxvtx_long, hemi, subject, subjects_dir= '/home/jcasa/mne_data/MNE-sample-data/subjects', verbose=False) else: tmp = mne.vertex_to_mni(mxvtx_long, hemi, subject, verbose=False) assert tmp.shape[1] == 3 and tmp.shape[0] == ns * locate, tmp.shape tmp = tmp.reshape([locate, ns, 3]) tmp = np.transpose(tmp, (1, 0, 2)).reshape([-1, locate * 3]) assert tmp.shape[1] == 3 * locate and tmp.shape[0] == ns, tmp.shape loc[ind_s, :, :] = tmp ind_s += 1 qtrue_all = loc p = loc.shape[2] return qtrue_all, p
def _cluster_rois(sel_path, label_list, stc, src, min_dist, mni_subject='fsaverage'): """ subfunctions of merge_ROIs ---------- mer_path: str The directory for storing merged ROIs. label_list: list Labels to be merged """ class_list = [] label_list = _sortlist(label_list, stc, src) class_list.append(label_list[0]) for test_fn in label_list[1:]: test_label = mne.read_label(test_fn) i = 0 belong = False while (i < len(class_list)) and (belong is False): class_label = mne.read_label(class_list[i]) if test_label.hemi != class_label.hemi: i = i + 1 continue else: # Get the centroids class_stc = stc.in_label(class_label) test_stc = stc.in_label(test_label) class_pca = stc.extract_label_time_course(class_label, src, mode='pca_flip') test_pca = stc.extract_label_time_course(test_label, src, mode='pca_flip') class_pca = np.squeeze(class_pca) test_pca = np.squeeze(test_pca) class_pow = np.sum(class_pca ** 2) test_pow = np.sum(test_pca ** 2) if class_label.hemi == 'lh': h = 0 elif class_label.hemi == 'rh': h = 1 class_seed, _, _ = class_stc.center_of_mass(mni_subject, hemi=h) test_seed, _, _ = test_stc.center_of_mass(mni_subject, hemi=h) class_mni = mne.vertex_to_mni(class_seed, h, mni_subject)[0] test_mni = mne.vertex_to_mni(test_seed, h, mni_subject)[0] exch = False if np.max(class_pow) < np.max(test_pow): exch = True # Compute the centroids distance if np.linalg.norm(class_mni - test_mni) < min_dist: if exch == True: os.remove(class_list[i]) class_list[i] = test_fn class_list = _sortlist(class_list, stc, src) elif exch == False: os.remove(test_fn) belong = True i = i + 1 if belong is False: class_list.append(test_fn) class_list = _sortlist(class_list, stc, src) return len(class_list)
def get_label_distances(subject, subjects_dir, parc='aparc'): """Get Euclidean distance between label center of masses. Get the Euclidean distance between label center of mass and return the distance matrix. The distance are computed between vertices in the MNI coordinates in the subject source space. Parameters: ----------- subject: str Name of the subject. subjects_dir: str The subjects directory. parc: str Name of the parcellation. Default 'aparc'. Return: ------- rounded_com: ndarray | (N, N) The distance between center of masses of different labels coords_all: ndarray | (N, ) The MNI coordinates of the vertices in the source space. coms_lh, coms_rh: list | (N, ) The centre of masses of labels in left and right hemispheres. """ import itertools from scipy import linalg # get the labels aparc = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir, parc=parc) # get rid of the unknown label aparc = [apa for apa in aparc if apa.name.find('unknown') == -1] N = len(aparc) # get the number of labels # get the center of mass of each of the labels and coords_all, coms_lh, coms_rh = [], [], [] for mylab in aparc: # now, split between hemispheres if mylab.name.endswith('-lh'): com_lh = mylab.center_of_mass(subject, subjects_dir=subjects_dir) coords_ = mne.vertex_to_mni(com_lh, hemis=0, subject=subject, subjects_dir=subjects_dir) coms_lh.append(com_lh) else: com_rh = mylab.center_of_mass(subject, subjects_dir=subjects_dir) coords_ = mne.vertex_to_mni(com_rh, hemis=1, subject=subject, subjects_dir=subjects_dir) coms_rh.append(com_rh) coords_all.append(coords_) # compute the distances com_distances = np.zeros((N, N)) for (i, j) in itertools.combinations(list(range(N)), 2): com_distances[i, j] = linalg.norm(coords_all[i] - coords_all[j]) # only one half matrix is created above, make it full com_distances += com_distances.T rounded_com = np.round(com_distances, 0) # return the distance matrix rounded to nearest integer return rounded_com, np.array(coords_all), coms_lh, coms_rh
subject = 'fsaverage' # Plot brain in 3D with PySurfer if available brain = new_stc.plot(subject, hemi='lh', subjects_dir=subjects_dir, backend='mayavi') brain.show_view('lateral') # use peak getter to move vizualization to the time point of the peak vertno_max, time_idx = new_stc.get_peak(hemi='lh', time_as_index=True) brain.set_data_time_index(time_idx) # draw marker at maximum peaking vertex brain.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue', scale_factor=0.6, map_surface='white') mni_coords = mne.vertex_to_mni(vertno_max, hemis=0, subject=subject, subjects_dir=subjects_dir) print('The MNI coords are ', mni_coords) # my_trans = mne.read_trans(?) # src_pts = apply_trans(trans, some_tgt_pts) utils.coord_to_label(subject, mni_coords, label='mycoord', hemi='lh', n_steps=25, map_surface="white") brain.add_label('mycoord-lh.label', color="darkseagreen", alpha=.8) # if the new mni_coords are computed brain.add_foci(mni_coords, coords_as_verts=False, hemi='lh', color='red', map_surface='white', scale_factor=0.6)
def test_scale_mri_xfm(): """Test scale_mri transforms and MRI scaling.""" # scale fsaverage tempdir = _TempDir() os.environ['_MNE_FEW_SURFACES'] = 'true' fake_home = testing.data_path() # add fsaverage create_default_subject(subjects_dir=tempdir, fs_home=fake_home, verbose=True) # add sample (with few files) sample_dir = op.join(tempdir, 'sample') os.mkdir(sample_dir) os.mkdir(op.join(sample_dir, 'bem')) for dirname in ('mri', 'surf'): copytree(op.join(fake_home, 'subjects', 'sample', dirname), op.join(sample_dir, dirname)) subject_to = 'flachkopf' spacing = 'oct2' for subject_from in ('fsaverage', 'sample'): if subject_from == 'fsaverage': scale = 1. # single dim else: scale = [0.9, 2, .8] # separate src_from_fname = op.join(tempdir, subject_from, 'bem', '%s-%s-src.fif' % (subject_from, spacing)) src_from = mne.setup_source_space( subject_from, spacing, subjects_dir=tempdir, add_dist=False) write_source_spaces(src_from_fname, src_from) print(src_from_fname) vertices_from = np.concatenate([s['vertno'] for s in src_from]) assert len(vertices_from) == 36 hemis = ([0] * len(src_from[0]['vertno']) + [1] * len(src_from[0]['vertno'])) mni_from = mne.vertex_to_mni(vertices_from, hemis, subject_from, subjects_dir=tempdir) if subject_from == 'fsaverage': # identity transform source_rr = np.concatenate([s['rr'][s['vertno']] for s in src_from]) * 1e3 assert_allclose(mni_from, source_rr) if subject_from == 'fsaverage': overwrite = skip_fiducials = False else: with pytest.raises(IOError, match='No fiducials file'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir) skip_fiducials = True with pytest.raises(IOError, match='already exists'): scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, skip_fiducials=skip_fiducials) overwrite = True scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir, verbose='debug', overwrite=overwrite, skip_fiducials=skip_fiducials) if subject_from == 'fsaverage': assert _is_mri_subject(subject_to, tempdir), "Scaling failed" src_to_fname = op.join(tempdir, subject_to, 'bem', '%s-%s-src.fif' % (subject_to, spacing)) assert op.exists(src_to_fname), "Source space was not scaled" # Check MRI scaling fname_mri = op.join(tempdir, subject_to, 'mri', 'T1.mgz') assert op.exists(fname_mri), "MRI was not scaled" # Check MNI transform src = mne.read_source_spaces(src_to_fname) vertices = np.concatenate([s['vertno'] for s in src]) assert_array_equal(vertices, vertices_from) mni = mne.vertex_to_mni(vertices, hemis, subject_to, subjects_dir=tempdir) assert_allclose(mni, mni_from, atol=1e-3) # 0.001 mm del os.environ['_MNE_FEW_SURFACES']
doMorph = True subjectDir = os.environ['SUBJECTS_DIR'] modelSubj = 'fsaverage' # Distance from fMRI-based central point to include in hand motor label labelRadii = [10] subject_set = [str(subj) for subj in subj_nums_hcp] # Load list of labels and pull out pre-central gyrus labelList = mne.read_labels_from_annot(subject=modelSubj, parc='aparc.a2009s', hemi='both') primaryMotor = [l for l in labelList if 'G_precentral-' in l.name] # Get MNI coords for vertices in L/R hemis primaryMotorMNI_pos = [mne.vertex_to_mni(primaryMotor[0].vertices, 0, modelSubj), mne.vertex_to_mni(primaryMotor[1].vertices, 1, modelSubj)] # Find closest point in fsaverage brain space according to # Witt 2008, Functional neuroimaging correlates of finger-tapping task # variations coords in Talairach space # list is [left hemi, right hemi] hand_knob_pos = [np.atleast_2d(np.array([-38, -26, 50])), np.atleast_2d(np.array([36, -22, 54]))] SMA = [-4, -8, 52] dists = [] for orig_label, label_pos, knob_pos in zip(primaryMotor, primaryMotorMNI_pos, hand_knob_pos): # Find dist between MNI point and all vertices dists.append(np.squeeze(cdist(knob_pos, label_pos, 'euclidean'))) # Find min dist and index
persistent = [line.rstrip() for line in pfid] remitted = [line.rstrip() for line in rfid] sx = np.recfromcsv(sx_fname) hi = [rec[2] for s in subjs for rec in sx if rec[0]==s] inatt = [rec[1] for s in subjs for rec in sx if rec[0]==s] # find closest source to seed if seed[0] < 0: hemis = 0 # LH else: hemis = 1 # RH # important to do this by source, because not every vertex has a source fname = data_dir + 'morphed-lcmv-%dto%d-'%(bands[0][0],bands[0][1]) + subjs[0] stc = mne.read_source_estimate(fname) # this is what we get when we read in the fsaverage subject coord = mne.vertex_to_mni(vertices=stc.vertno[hemis],hemis=hemis,subject='fsaverage') dist = np.sqrt((coord[:,0] - seed[0])**2 + (coord[:,1] - seed[1])**2 + (coord[:,2] - seed[2])**2) seed_src = np.argmin(dist) + hemis*len(stc.lh_vertno) print 'Distance to seed: %.2fmm'%np.min(dist) # for each band, compute subject-based correlation map for l_freq, h_freq in bands: nv_corrs = [] adhd_corrs = [] per_corrs = [] rem_corrs = [] print 'Band %d to %d Hz'%(l_freq, h_freq) cnt=0 for s in subjs: print cnt+1, '/', len(subjs) fname = data_dir + 'morphed-lcmv-%dto%d-'%(l_freq,h_freq) + s
os.system('3dmaskdump -xyz -o ' + mask_fname + ' ' + roi) a = np.genfromtxt(mask_fname) os.system('rm ' + mask_fname) gv = a[a[:, 6] > 0, 3:6] # separate good voxels in the mask # change AFNI results from RAI to LPI gv[:, 0] = gv[:, 0] * -1 gv[:, 1] = gv[:, 1] * -1 src = mne.setup_source_space(subject='fsaverage_mne', fname=None, spacing='ico5', surface='inflated', n_jobs=2) # get left and right coordinates for all the sources coord0 = mne.vertex_to_mni(vertices=src[0]['vertno'], hemis=0, subject='fsaverage_mne') coord1 = mne.vertex_to_mni(vertices=src[1]['vertno'], hemis=1, subject='fsaverage_mne') coord = np.vstack([coord0, coord1]) # store the index of the sources within min_dist of the mask voxels b = [] for i in range(gv.shape[0]): dist = np.sqrt((coord[:, 0] - gv[i, 0])**2 + (coord[:, 1] - gv[i, 1])**2 + (coord[:, 2] - gv[i, 2])**2) if min(dist) <= min_dist: b.append(np.argmin(dist)) # create a stc with 1s for the near sources d = np.zeros([coord.shape[0], 1])