def get_masker_coord(filename): if 'BASC' in filename: basc = datasets.fetch_atlas_basc_multiscale_2015(version='sym')['scale444'] filename=basc nib_basc444 = nib.load(basc) labels_data = nib_basc444.get_data() else: nib_parcel = nib.load(filename) labels_data = nib_parcel.get_data() #fetch all possible label values all_labels = np.unique(labels_data) # remove the 0. value which correspond to voxels out of ROIs all_labels = all_labels[1:] # bari_labels = np.zeros((all_labels.shape[0],3)) # ## go through all labels # for i,curlabel in enumerate(all_labels): # vox_in_label = np.stack(np.argwhere(labels_data == curlabel)) # bari_labels[i] = vox_in_label.mean(axis=0) # allcoords=[] for i,curlabel in enumerate(all_labels): img_curlab = math_img(formula="img==%d"%curlabel,img=filename) allcoords.append(find_xyz_cut_coords(img_curlab)) allcoords=np.array(allcoords) return allcoords
def get_centers(brain, orig_labs): """ Get coordinate centers given a nifti image loaded with nibabel Returns a dictionary of label: coordinate as an [x, y, z] array """ dat = brain.get_data() labs, size = np.unique(dat, return_counts=True) size = dict(zip(labs, size)) # Bit of a clumsy stop-gap for correcting for lost ROIs due to resampling/registration for n in orig_labs: if not size.get(n): size[n] = None coords_connectome = [] for lab in labs: fd_dat = np.asarray(dat == lab).astype('float64') parcel = nb.Nifti1Image(dataobj=fd_dat, header=brain.header, affine=brain.affine) coords_connectome.append(nip.find_xyz_cut_coords(parcel)) return dict(zip(labs, coords_connectome)), size
def plotResultImageWithoutDatamanager(path_seg, path_t1, path_result, savepath, subject, output_type='save'): if output_type == 'save': figure, (axes1, axes2) = plt.subplots(2, 1, figsize=(10, 10)) cut = plotting.find_xyz_cut_coords(path_seg, activation_threshold=0.5) plotting.plot_roi(path_result, path_t1, cut_coords=cut, axes=axes1, title='Result') plotting.plot_roi(path_seg, path_t1, cut_coords=cut, axes=axes2, title='Target') plt.savefig(os.path.join(savepath, 'result_' + subject + '.png')) plt.close() logging.info('Subject ' + str(subject) + ' plotted with image ' + path_t1 + '.') elif output_type == 'show': figure, (axes1, axes2) = plt.subplots(2, 1, figsize=(10, 10)) plotting.plot_roi(path_result, path_t1, axes=axes1, title='Result') plotting.plot_roi(path_seg, path_t1, axes=axes2, title='Target') plt.show() plt.close()
def get_names_and_coords_of_parcels(parlistfile): from nilearn.plotting import find_xyz_cut_coords from nilearn.image import new_img_like try: atlas_select = parlistfile.split('/')[-1].split('.')[0] except: atlas_select = 'User_specified_atlas' bna_img = nib.load(parlistfile) bna_data = np.round(bna_img.get_data(),1) ##Get an array of unique parcels bna_data_for_coords_uniq = np.unique(bna_data) ##Number of parcels: par_max = len(bna_data_for_coords_uniq) - 1 bna_data = bna_data.astype('int16') img_stack = [] for idx in range(1, par_max+1): roi_img = bna_data == bna_data_for_coords_uniq[idx].astype('int16') roi_img = roi_img.astype('int16') img_stack.append(roi_img) img_stack = np.array(img_stack).astype('int16') img_list = [] for idy in range(par_max): roi_img_nifti = new_img_like(bna_img, img_stack[idy]) img_list.append(roi_img_nifti) coords = [] for roiin in img_list: coord = find_xyz_cut_coords(roiin) coords.append(coord) coords = list(tuple(x) for x in np.array(coords)) return(coords, atlas_select, par_max, img_list)
def get_names_and_coords_of_parcels_from_img(bna_img): from nilearn.plotting import find_xyz_cut_coords from nilearn.image import new_img_like bna_data = np.round(bna_img.get_data(), 1) # Get an array of unique parcels bna_data_for_coords_uniq = np.unique(bna_data) # Number of parcels: par_max = len(bna_data_for_coords_uniq) - 1 bna_data = bna_data.astype('int16') img_stack = [] for idx in range(1, par_max + 1): roi_img = bna_data == bna_data_for_coords_uniq[idx].astype('int16') roi_img = roi_img.astype('int16') img_stack.append(roi_img) img_stack = np.array(img_stack).astype('int16') img_list = [] for idy in range(par_max): roi_img_nifti = new_img_like(bna_img, img_stack[idy]) img_list.append(roi_img_nifti) coords = [] for roiin in img_list: coord = find_xyz_cut_coords(roiin) coords.append(coord) coords = list(tuple(x) for x in np.array(coords)) return coords, par_max, img_list
def plotResultImage(datamanager, resultpath, savepath, subject, output_type='save'): basefile = datamanager.getFileName(subject, 't1') segfile = datamanager.getFileName(subject, 'seg') if output_type == 'save': figure, (axes1, axes2) = plt.subplots(2, 1, figsize=(10, 10)) cut = plotting.find_xyz_cut_coords(segfile, activation_threshold=0.5) plotting.plot_roi(resultpath, basefile, cut_coords=cut, axes=axes1, title='Result') plotting.plot_roi(segfile, basefile, cut_coords=cut, axes=axes2, title='Target') plt.savefig(os.path.join(savepath, 'result_' + subject + '.png')) plt.close() logging.info('Subject ' + str(subject) + ' plotted with image ' + basefile + '.') elif output_type == 'show': figure, (axes1, axes2) = plt.subplots(2, 1, figsize=(10, 10)) plotting.plot_roi(savepath, basefile, axes=axes1, title='Result') plotting.plot_roi(segfile, basefile, axes=axes2, title='Target') plt.show() plt.close()
def plot(self, downsample=1, out_base="."): out_path = os.path.join(out_base, self.subject, self.name, self.task) os.makedirs(out_path, exist_ok=True) raw = nib.load(self.path) M = np.max(raw.get_data()) n = raw.shape[3] mean = nimage.mean_img(raw) xyzcuts = nilplot.find_xyz_cut_coords(mean) xcuts = nilplot.find_cut_slices(mean, "x") ycuts = nilplot.find_cut_slices(mean, "y") zcuts = nilplot.find_cut_slices(mean, "z") del raw nrange = range(0, n, downsample) for i, img in enumerate(nimage.iter_img(self.path)): if i in nrange: nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img), colorbar=False, output_file="%s/orth_epi%0d.png" % (out_path, i), annotate=True, cut_coords=xyzcuts, cmap="gist_heat") nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img), colorbar=False, output_file="%s/x_epi%0d.png" % (out_path, i), annotate=True, display_mode="x", cut_coords=xcuts, cmap="gist_heat") nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img), colorbar=False, output_file="%s/y_epi%0d.png" % (out_path, i), annotate=True, display_mode="y", cut_coords=ycuts, cmap="gist_heat") nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img), colorbar=False, output_file="%s/z_epi%0d.png" % (out_path, i), annotate=True, display_mode="z", cut_coords=zcuts, cmap="gist_heat") slice_names = ["orth_epi", "x_epi", "y_epi", "z_epi"] for slic in slice_names: filenames = ["%s/%s%0d.png" % (out_path, slic, i) for i in nrange] with imageio.get_writer('%s/%s.gif' % (out_path, slic), mode='I') as writer: for i, filename in zip(nrange, filenames): image = Image.open(filename) draw = ImageDraw.Draw(image) fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 16) draw.text((2, 2), str(i), font=fnt, fill=(255, 0, 0, 255)) image.save(filename, "PNG") image = imageio.imread(filename) writer.append_data(image)
def _save_results(annotated_names, maps_img, dimension): maps_img = nibabel.load(maps_img) for i, img in enumerate(image.iter_img(maps_img)): cut_coords = plotting.find_xyz_cut_coords(img) if annotated_names is not None: annotated_name = annotated_names.iloc[i].Difumo_names else: annotated_name = None _plot_dl_maps(img, cut_coords, annotated_name, i, dimension) return
def run_mini_pipeline(): atlas = datasets.fetch_atlas_msdl() atlas_img = atlas['maps'] labels = pd.read_csv(atlas['labels'])['name'] masker = NiftiMapsMasker(maps_img=atlas_img, standardize=True, memory='/tmp/nilearn', verbose=0) data = datasets.fetch_adhd(number_subjects) figures_folder = '../figures/' count=0 for func_file, confound_file in zip(data.func, data.confounds): # fit the data to the atlas mask, regress out confounds time_series = masker.fit_transform(func_file, confounds=confound_file) correlation = np.corrcoef(time_series.T) #plotting starts here plt.figure(figsize=(10, 10)) plt.imshow(correlation, interpolation="nearest") x_ticks = plt.xticks(range(len(labels)), labels, rotation=90) y_ticks = plt.yticks(range(len(labels)), labels) corr_file = figures_folder+'subject_number_' + str(count) + '_correlation.pdf' plt.savefig(corr_file) atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in image.iter_img(atlas_img)] threshold = 0.6 plotting.plot_connectome(correlation, atlas_region_coords, edge_threshold=threshold) connectome_file = figures_folder+'subject_number_' + str(count) + '_connectome.pdf' plt.savefig(connectome_file) #graph setup #binarize correlation matrix correlation[correlation<threshold] = 0 correlation[correlation != 0] = 1 graph = nx.from_numpy_matrix(correlation) partition=louvain.best_partition(graph) values = [partition.get(node) for node in graph.nodes()] plt.figure() nx.draw_spring(graph, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=True) graph_file = figures_folder+'subject_number_' + str(count) + '_community.pdf' plt.savefig(graph_file) count += 1 plt.close('all')
def plot_map(single_map, title, i): fig = plt.figure() vmax = np.max(np.abs(single_map.get_data())) cut_coords = find_xyz_cut_coords(single_map, activation_threshold=0.33 * vmax) plot_stat_map(single_map, title=str(title), figure=fig, cut_coords=cut_coords, threshold=0.) plt.savefig(join(analysis_dir, '%s.png' % title)) plt.close(fig)
def save_info(info, dimension): """Save found records Parameters ---------- info : dict Contains meta-data assigned to each atlas name such as overlap proportion, etc Each atlas dict contains following attributes: 'intersection' : sparse matrix dot product between DiFuMo regions and regions in target atlas (existing pre-defined) 'target_size' : np.ndarray Size of each region estimated in target atlas 'overlap_proportion' : list of pd.Series Each list contains the proportion of overlap estimated between this region and all region in target sizes. Sorted according to most strong hit in the overlap. 'overlap_size' : list Each list contain overlap in estimated sizes for all regions in target atlas. dimension : int DiFuMo atlas dimension Returns ------- data : pd.DataFrame """ html = "https://parietal-inria.github.io/DiFuMo/{0}/html/{1}.html" table = set_difumo_storage() maps_img = nibabel.load(fetch_difumo(dimension=dimension).maps) for i, img in enumerate(image.iter_img(maps_img)): cut_coords = plotting.find_xyz_cut_coords(img) for n in [64, 128, 256, 512, 1024]: labels = fetch_difumo(dimension=n).labels['Difumo_names'].to_list() # Proportion of overlap with each index of difumo component this_img_info = info[n]['overlap_proportion'][i] identified_components = this_img_info.index[1:6] if len(identified_components) != 0: # grabbing the top five from the overlapped list for identified_component in identified_components: table['dimension'].append(dimension) table['component'].append(i + 1) table['overlap_against'].append(n) table['identified'].append(identified_component + 1) table['label'].append(labels[identified_component]) return pd.DataFrame(table)
def plot_dictionary(components, idx, write_dir): """ Plot a dictionary element acorss subjects """ mean_val = components[:, :, idx].mean(0) mean_img = masker.inverse_transform(mean_val) fig = plt.figure(figsize=(14, 5), facecolor='k') # colorbar_ax = fig.add_axes([.98, 0.05, .02, .9], axis_bgcolor='k') # vmax = np.max(np.abs(mean_val)) # _draw_colorbar(colorbar_ax, vmax=vmax, offset = vmax/2) cut_coords = plotting.find_xyz_cut_coords(mean_img) for i, subject in enumerate(subject_list): anat = db[db.contrast == 't1'][db.subject == subject].path.values[-1] img = masker.inverse_transform(components[i, :, idx]) axes = plt.axes([.00 + .13 * np.mod(i, 3), .245 * (i / 3), .13, .245]) plotting.plot_stat_map( img, bg_img=anat, axes=axes, display_mode='x', cut_coords=cut_coords[0:1], dim=0, threshold=3.0, black_bg=True, vmax=8, # title=subject, colorbar=False) axes = plt.axes([.4, .3, .57, .4]) colors = plt.cm.hsv(np.linspace(0, 255 / n_contrasts, 255)) plt.bar(range(n_contrasts), dictionary[idx], color=colors) plt.xticks(np.linspace(1., n_contrasts + .8, num=n_contrasts + 1), labels_bottom, rotation=75, ha='right', fontsize=9, color='w') for nc in range(n_contrasts): plt.text(nc, dictionary[idx].max() + .001, labels_top[nc], rotation=75, ha='left', va='bottom', color='w', fontsize=9) # plt.axis('tight') plt.subplots_adjust(bottom=.3, top=.7) fig.savefig(os.path.join(write_dir, 'snapshot_%02d.png' % idx), facecolor='k') plt.close(fig)
def plotResultImage(datamanager, resultpath, savepath, subject, output_type='save'): try: basefile = datamanager.getFileName(subject, 't1') except: try: basefile = datamanager.getFileName(subject, 'ct') except: basefile = datamanager.getFileName(subject, 't1t2') segfile = datamanager.getFileName(subject, 'seg') if output_type == 'save': figure, (axes1, axes2) = plt.subplots(2, 1, figsize=(10, 10)) cut = plotting.find_xyz_cut_coords(segfile, activation_threshold=0.5) # change cut to none if it appears to be an empty array try: if cut == []: cut = None plotting.plot_roi(resultpath, basefile, cut_coords=cut, axes=axes1, title='Result') plotting.plot_roi(segfile, basefile, cut_coords=cut, axes=axes2, title='Target') plt.savefig(os.path.join(savepath, 'result_' + subject + '.png')) plt.close() except: logging.info('Subject ' + str(subject) + ' couldnt be plotted as a result of an absent ROI') logging.info('Subject ' + str(subject) + ' plotted with image ' + basefile + '.') elif output_type == 'show': figure, (axes1, axes2) = plt.subplots(2, 1, figsize=(10, 10)) plotting.plot_roi(savepath, basefile, axes=axes1, title='Result') plotting.plot_roi(segfile, basefile, axes=axes2, title='Target') plt.show() plt.close()
def get_centers(brain): """ Get coordinate centers given a nifti image loaded with nibabel Returns a dictionary of label: coordinate as an [x, y, z] array """ dat = brain.get_data() labs = np.unique(dat) labs = labs[labs != 0] # Line below throwing memory error. I will likely calculate each layer one at a time # and find the center fd_dat = np.stack( [np.asarray(dat == lab).astype('float64') for lab in labs], axis=3) parcels = nb.Nifti1Image(dataobj=fd_dat, header=brain.header, affine=brain.affine) regions_imgs = image.iter_img(parcels) # compute the centers of mass for each ROI coords_connectome = [nip.find_xyz_cut_coords(img) for img in regions_imgs] return dict(zip(labs, coords_connectome))
def plot_single(img, name, output_dir, view_types=['stat_map'], color=None, threshold=0): from nilearn.plotting import plot_stat_map, find_xyz_cut_coords, plot_glass_brain if color is not None: cmap = make_cmap(color, rotation=.5) cmap_white = make_cmap(color, rotation=.5, white=True) else: cmap = 'cold_hot' cmap_white = 'cold_white_hot' srcs = [] vmax = np.abs(img.get_data()).max() threshold = vmax / 8 for view_type in view_types: src = join(output_dir, '%s_%s.png' % (name, view_type)) cut_coords = find_xyz_cut_coords(img, activation_threshold=vmax / 3) if view_type == 'stat_map': plot_stat_map(img, threshold=threshold, cut_coords=cut_coords, vmax=vmax, colorbar=True, output_file=src, # cmap=cmap ) elif view_type == 'glass_brain': plot_glass_brain(img, threshold=threshold, vmax=vmax, plot_abs=False, output_file=src, colorbar=True, # cmap=cmap_white ) else: raise ValueError('Wrong view type in `view_types`: got %s' % view_type) srcs.append(src) return srcs, name
def get_masker_coord(atlasname): """ Get coordinates of parcellation (3D) from a brain atlas image defined by labels (integers) Parameters: --------- atlasname : string - pathway of the atlas OR is atlas is BASC tuple or list as filename[0]='BASC' filename[1]='sym' or 'asym' filename[2]= str of nb of parcel (version): '444' """ if 'BASC' in atlasname: basc = datasets.fetch_atlas_basc_multiscale_2015( version=atlasname[1])['scale' + atlasname[2]] atlasname = basc nib_parcel = nib.load(atlasname) labels_data = nib_parcel.get_data() #fetch all possible label values all_labels = np.unique(labels_data) # remove the 0. value which correspond to voxels out of ROIs all_labels = all_labels[1:] # bari_labels = np.zeros((all_labels.shape[0],3)) # ## go through all labels # for i,curlabel in enumerate(all_labels): # vox_in_label = np.stack(np.argwhere(labels_data == curlabel)) # bari_labels[i] = vox_in_label.mean(axis=0) # allcoords = [] for i, curlabel in enumerate(all_labels): img_curlab = math_img(formula="img==%d" % curlabel, img=atlasname) allcoords.append(find_xyz_cut_coords(img_curlab)) allcoords = np.array(allcoords) return allcoords
verbose=10, random_state=0) canica.fit(all_images) components_img = canica.masker_.inverse_transform(canica.components_) nibabel.save(components_img, 'components_img_cuts.nii') ### Visualize the results ##################################################### # Show some interesting components import matplotlib.pyplot as plt from nilearn.plotting import plot_roi, plot_stat_map, plot_glass_brain, find_xyz_cut_coords fh = plt.figure(facecolor='w', figsize=(18, 10)) nrows = int(np.floor(np.sqrt(0.75 * n_components))) # 4:3 aspect ncols = int(np.ceil(n_components / float(nrows))) all_cut_coords = [find_xyz_cut_coords(img) for img in iter_img(components_img)] sort_idx = np.argsort(np.array(all_cut_coords)[:, 2]) for ci in range(n_components): ax = fh.add_subplot(nrows, ncols, ci + 1) ic_idx = sort_idx[ci] cut_coords = all_cut_coords[ic_idx] var_explained = canica.variance_[ic_idx] plot_stat_map(index_img(components_img, ic_idx), title="IC%02d (v=%.1f)" % (ic_idx, var_explained), axes=ax, colorbar=False, display_mode="z", cut_coords=(cut_coords[2], )) plt.show()
rois = labels['name'].T n_r = len(rois) l=360./n_r#roi label size in figures visu = atlas_filename all_ntwks = range(n_r) networks = {'Auditory': [0,1],'striate' : [2],'DMN': [3,4,5,6],'Occ post' :[7], 'Motor': [8],'Attentional' : [9,10,11,12,14,15,16,17,18], 'Basal' : [13],'Visual secondary' : [19,20,21], 'Salience':[22,23,24], 'Temporal(STS)':[25,26],'Langage':[27,28,29,30,31],'Cereb':[32], 'Dors PCC': [33],'cing ins' :[34,35,36],'Ant IPS': [37,38],'All ROIs':all_ntwks} coords = [] #chose regions representative coordinates, other wise it s computed with find_xyz_cut_coords #coords = np.vstack((labels['x'], labels['y'], labels['z'])).T if not coords: coords =[plotting.find_xyz_cut_coords(roi) for roi in image.iter_img(atlas_filename)] root='/neurospin/grip/protocols/MRI/AVCnn_Dhaif_2016/AVCnn/AVCnn_data/' #fichier reg et conca pret pour analyse func_type_list = [ 'controlRSc','patientsRSc_LD', 'patientsRSc_LG']# #name of each group's directory for functional images reg_dirs = [ root+'rgt']#name of each group's directory for regressors (regressor have to be .txt files) reg_prefix = 'art_mv_fmv_wm_vent_ext_hv_' #art_mv_fmv_wm_vent_ext_hv_regressor prefix (regressors must have corresponding functional file name after prefix: swars_ab_123456.nii and reg1_reg2_swars_ab_123456.txt) common = 4 #initial differing character between regressors and functional file names #choose report directory and name (default location is in root, default name is atlas_naabsolute main_title ='AVCnn_Cont_LG_LD_'+MC_correction # save_dir = root + 'reports_test/' try: os.makedirs(save_dir) except: print('Warning could not make dir '+save_dir) pass
extraction.fit() regions_img = extraction.regions_img_ ################################################################################ # Visualization # Show region extraction results by importing image & plotting utilities from nilearn import plotting from nilearn.image import index_img from nilearn.plotting import find_xyz_cut_coords # Showing region extraction results using 4D maps visualization tool plotting.plot_prob_atlas(regions_img, display_mode='z', cut_coords=1, view_type='contours', title="Regions extracted.") # To reduce the complexity, we choose to display all the regions # extracted from network 3 import numpy as np DMN_network = index_img(atlas_networks, 3) plotting.plot_stat_map(DMN_network, display_mode='z', cut_coords=1, title='Network 3', colorbar=False) regions_indices_network3 = np.where(np.array(extraction.index_) == 3) for index in regions_indices_network3[0]: cur_img = index_img(extraction.regions_img_, index) coords = find_xyz_cut_coords(cur_img) plotting.plot_stat_map(cur_img, display_mode='z', cut_coords=coords[2:3], title="Blob of network3", colorbar=False) plotting.show()
def plot_spm( zmaps, roi_dict, bg_img=None, z_threshold=0, f=None, axes=None, # brain_mask='../Templates/mni_icbm152_nlin_asym_09c_nifti/mni_icbm152_nlin_asym_09c.nii.gz', roi_to_plot=('PreSMA', 'M1', 'ACC', 'rIFG', 'STR', 'GPe', 'GPi', 'STN'), cut_coords=[None, None, None, None, None, None, None, None], contrasts=('failed_stop - go_trial', 'successful_stop - go_trial', 'failed_stop - successful_stop'), plot_columns=(0, 1, 3, 4, 6, 7), empty_plots=False, skip_all_but_last=False, **kwargs): if f is None: gridspec = dict(hspace=0.0, wspace=0.0, width_ratios=[1, 1, 0.05, 1, 1, .05, 1, 1, .1]) f, axes = plt.subplots( len(roi_to_plot), len(zmaps) + 3, gridspec_kw=gridspec ) # add 3 columns: 2 interspace, 1 on the right for the colorbar if empty_plots: f.set_size_inches(len(zmaps) * 4, len(roi_to_plot) * 4) return f, axes all_cut_coords = [] all_disps = [] for row_n, roi in enumerate(roi_to_plot): # for debugging if skip_all_but_last: if row_n < (len(roi_to_plot) - 1): continue # get cut coordinates based on 1 hemisphere (if applicable) if roi in ['STR', 'STN', 'PreSMA', 'GPe', 'GPi']: roi_map = roi_dict['l' + roi] else: roi_map = roi_dict[roi] # roi_map = make_conjunction_mask(roi_map['fn'], brain_mask) if roi == 'rIFG': ## saggital if cut_coords[row_n] is None: this_cut_coords = plotting.find_xyz_cut_coords( roi_map['fn'])[0:1] else: this_cut_coords = cut_coords[row_n] display_mode = 'x' plot_rois = ['rIFG'] #, 'M1', 'rPreSMA'] elif roi == 'STR': ## axial view if cut_coords[row_n] is None: this_cut_coords = plotting.find_xyz_cut_coords( roi_map['fn'])[2:3] else: this_cut_coords = cut_coords[row_n] display_mode = 'z' plot_rois = [ 'rIFG', 'M1', 'lSTR', 'lGPe', 'lGPi', 'lSTN', 'rSTR', 'rGPe', 'rGPi', 'rSTN' ] elif roi == 'STN': ## plot coronal view if cut_coords[row_n] is None: this_cut_coords = plotting.find_xyz_cut_coords( roi_map['fn'])[1:2] else: this_cut_coords = cut_coords[row_n] display_mode = 'y' plot_rois = [ 'rIFG', 'M1', 'lSTR', 'lGPe', 'lGPi', 'lSTN', 'rSTR', 'rGPe', 'rGPi', 'rSTN' ] all_cut_coords.append({display_mode: this_cut_coords[0]}) # loop over contrasts for columns for col_n, map_n in zip(plot_columns, np.arange(len(zmaps))): zmap = zmaps[map_n] if skip_all_but_last: if col_n < (len(zmaps) - 1): continue if row_n == (len(roi_to_plot) - 1) and col_n == (len(zmaps) - 1): # plot colobar in the last plot cbar = False else: cbar = False # # do not plot in column 2 or 5 # plot_col = col_n # if col_n > 1: # plot_col = col_n + 1 # if col_n > 3: # plot_col = col_n + 2 if isinstance(z_threshold, list): this_threshold = z_threshold[map_n] else: this_threshold = z_threshold ax = axes[row_n, col_n] # print(cbar) disp = plotting.plot_stat_map(zmap, bg_img=bg_img, threshold=this_threshold, cut_coords=this_cut_coords, display_mode=display_mode, axes=ax, colorbar=cbar, **kwargs) # just plot *all* contours, always for roi_ in plot_rois: roi_map = roi_dict[roi_] # for roi_, roi_map in roi_dict.items(): # print(roi_map) add_contours(disp, roi=roi_map['fn'], thr=roi_map['threshold'], color=roi_map['color']) # determine limits (xlim/ylim) based on first column, and apply to all others this_key = list([x for x in disp.axes.keys()])[0] # Determine new xlim/ylim based on first column if col_n == plot_columns[0]: # extract old/current limits cur_xlim = disp.axes[this_key].ax.get_xlim() cur_ylim = disp.axes[this_key].ax.get_ylim() if display_mode == 'x': new_xlim = get_prop_limits([0, 1], cur_xlim) new_ylim = get_prop_limits([0, 1], cur_ylim) elif display_mode == 'z' and 'STN' in roi: new_xlim = get_prop_limits([.25, .75], cur_xlim) new_ylim = get_prop_limits([.40, .90], cur_ylim) elif display_mode == 'z' and 'STR' in roi: new_xlim = get_prop_limits([0, 1], cur_xlim) new_ylim = get_prop_limits([0.3, 1], cur_ylim) elif display_mode == 'y': new_xlim = get_prop_limits([.26, .74], cur_xlim) new_ylim = get_prop_limits([.25, .75], cur_ylim) # Change axes limits disp.axes[this_key].ax.set_xlim(new_xlim[0], new_xlim[1]) disp.axes[this_key].ax.set_ylim(new_ylim[0], new_ylim[1]) all_disps.append(disp) # # set new xlimits if necessary (ie zoom for STN view) # if 'STN' in roi and display_mode == 'z': # this_key = [x for x in disp.axes.keys()] # this_key = this_key[0] # cur_xlim = disp.axes[this_key].ax.get_xlim() # cur_ylim = disp.axes[this_key].ax.get_ylim() # new_xlim = get_prop_limits([.25, .75], cur_xlim) # new_ylim = get_prop_limits([.40, .90], cur_ylim) # disp.axes[this_key].ax.set_xlim(new_xlim[0], new_xlim[1]) # disp.axes[this_key].ax.set_ylim(new_ylim[0], new_ylim[1]) # elif 'STN' in roi and display_mode == 'y': # this_key = [x for x in disp.axes.keys()] # this_key = this_key[0] # cur_xlim = disp.axes[this_key].ax.get_xlim() # cur_ylim = disp.axes[this_key].ax.get_ylim() # new_xlim = get_prop_limits([.25, .75], cur_xlim) # new_ylim = get_prop_limits([.25, .75], cur_ylim) # disp.axes[this_key].ax.set_xlim(new_xlim[0], new_xlim[1]) # disp.axes[this_key].ax.set_ylim(new_ylim[0], new_ylim[1]) # elif 'STR' in roi and display_mode == 'z': # this_key = [x for x in disp.axes.keys()] # this_key = this_key[0] # cur_xlim = disp.axes[this_key].ax.get_xlim() # cur_ylim = disp.axes[this_key].ax.get_ylim() # new_xlim = get_prop_limits([0, 1], cur_xlim) # new_ylim = get_prop_limits([.3, 1], cur_ylim) # disp.axes[this_key].ax.set_xlim(new_xlim[0], new_xlim[1]) # disp.axes[this_key].ax.set_ylim(new_ylim[0], new_ylim[1]) # all_disps.append(disp) # add labels if not skip_all_but_last: for row_n, ax in enumerate(axes[:, 0]): cc = all_cut_coords[row_n] disp_mode = [x for x in cc.keys()][0] coord = cc[disp_mode] ax.annotate('%s = %d' % (disp_mode, int(coord)), xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - 0.5, 0), xycoords=ax.yaxis.label, textcoords='offset points', rotation=90, ha='right', va='center') f.set_size_inches(len(zmaps) * 4, len(roi_to_plot) * 4) return f, axes, all_disps
def _reporting(self): """ Returns ------- displays : list A list of all displays to be rendered. """ from nilearn.reporting.html_report import _embed_img from nilearn import plotting if self._reporting_data is not None: maps_image = self._reporting_data['maps_image'] else: maps_image = None if maps_image is not None: n_maps = image.get_data(maps_image).shape[-1] maps_to_be_displayed = range(n_maps) if isinstance(self.displayed_maps, int): if n_maps < self.displayed_maps: msg = ("`generate_report()` received " f"{self.displayed_maps} to be displayed. " f"But masker only has {n_maps} maps." f"Setting number of displayed maps to {n_maps}.") warnings.warn(category=UserWarning, message=msg) self.displayed_maps = n_maps maps_to_be_displayed = range(self.displayed_maps) elif isinstance(self.displayed_maps, (list, np.ndarray)): if max(self.displayed_maps) > n_maps: raise ValueError("Report cannot display the " "following maps " f"{self.displayed_maps} because " f"masker only has {n_maps} maps.") maps_to_be_displayed = self.displayed_maps self._report_content['report_id'] = self.report_id self._report_content['number_of_maps'] = n_maps self._report_content['displayed_maps'] = list(maps_to_be_displayed) img = self._reporting_data['img'] embeded_images = [] if img is not None: dim = image.load_img(img).shape if len(dim) == 4: # compute middle image from 4D series for plotting img = image.index_img(img, dim[-1] // 2) # Find the cut coordinates cut_coords = [ plotting.find_xyz_cut_coords(image.index_img( maps_image, i)) for i in maps_to_be_displayed ] for idx, component in enumerate(maps_to_be_displayed): display = plotting.plot_img(img, cut_coords=cut_coords[idx], black_bg=False, cmap='CMRmap_r') display.add_overlay(image.index_img(maps_image, idx), cmap=plotting.cm.black_blue) embeded_images.append(_embed_img(display)) display.close() return embeded_images else: msg = ("No image provided to fit in NiftiMapsMasker. " "Plotting only spatial maps for reporting.") warnings.warn(msg) self._report_content['warning_message'] = msg for component in maps_to_be_displayed: display = plotting.plot_stat_map( image.index_img(maps_image, component)) embeded_images.append(_embed_img(display)) display.close() return embeded_images else: return [None]
# is not implemented. See Note section above for details. components_img = estimator.components_img_ components_img.to_filename('%s_resting_state.nii.gz' % names[estimator]) components_imgs.append(components_img) ############################################################################### # Visualize the results # ---------------------- from nilearn.plotting import (plot_prob_atlas, find_xyz_cut_coords, show, plot_stat_map) from nilearn.image import index_img # Selecting specific maps to display: maps were manually chosen to be similar indices = {dict_learning: 25, canica: 33} # We select relevant cut coordinates for displaying cut_component = index_img(components_imgs[0], indices[dict_learning]) cut_coords = find_xyz_cut_coords(cut_component) for estimator, components in zip(estimators, components_imgs): # 4D plotting plot_prob_atlas(components, view_type="filled_contours", title="%s" % names[estimator], cut_coords=cut_coords, colorbar=False) # 3D plotting plot_stat_map(index_img(components, indices[estimator]), title="%s" % names[estimator], cut_coords=cut_coords, colorbar=False) show()
subject_time_series.append(region_ts) ############################################################################## # Computing group-sparse precision matrices from nilearn.connectome import GroupSparseCovarianceCV gsc = GroupSparseCovarianceCV(verbose=2) gsc.fit(subject_time_series) from sklearn import covariance gl = covariance.GraphLassoCV(verbose=2) gl.fit(np.concatenate(subject_time_series)) ############################################################################## # Displaying results atlas_imgs = image.iter_img(msdl_atlas_dataset.maps) atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in atlas_imgs] plotting.plot_connectome(gl.covariance_, atlas_region_coords, edge_threshold='90%', title="Covariance", display_mode="lzr") plotting.plot_connectome(-gl.precision_, atlas_region_coords, edge_threshold='90%', title="Sparse inverse covariance (GraphLasso)", display_mode="lzr", edge_vmax=.5, edge_vmin=-.5) plot_matrices(gl.covariance_, gl.precision_, "GraphLasso")
def plot_overlaps(info, atlas_names, dimension, output_dir=None, cmap=plt.cm.gist_rainbow, proposed_labels=None): """Plot the regions overlapped from existing anatomical atlases Parameters ---------- info : pd.DataFrame Data frame contains ovelap information of specific dimension with regards to : ['harvard_oxford', 'destrieux', 'diedrichsen', 'jhu', 'juelich', 'mist', 'yeo_networks7', 'yeo_networks17', 'component', 'cut_coords'] The info columns atlas_names : str or list of str Grab atlas from web given the name. Few are shipped with FSL and Nilearn. Valid options: ['harvard_oxford', 'destrieux', 'diedrichsen', 'juelich', 'jhu', 'mist', 'yeo_networks7', 'yeo_networks17'] dimension : int DiFuMo atlas dimension cmap : instance of matplotlib cmap or str, default='gist_rainbow' Look at these link https://nilearn.github.io/auto_examples/01_plotting/plot_colormaps.html#sphx-glr-auto-examples-01-plotting-plot-colormaps-py output_dir : str Path to save the plots proposed_labels : pd.DataFrame, optional DiFuMo proposed labels useful for comparisons. """ atlases = fetch_atlases(atlas_names) cmap = plt.cm.get_cmap(cmap) color_list = cmap(np.linspace(0, 1, dimension)) difumo = fetch_difumo(dimension=dimension) maps_img = nibabel.load(difumo.maps) if proposed_labels is None: proposed_labels = difumo.labels for comp_idx, (img, color) in enumerate(zip(image.iter_img(maps_img), color_list)): cut_coords = plotting.find_xyz_cut_coords(img) this_data = info[info['component'] == comp_idx] masked_data = _mask_background(this_data) columns = _remove_columns(masked_data) fig, axes = plt.subplots(ncols=2, nrows=len(columns) + 1, figsize=(10, 22), facecolor='k') proposed_label = proposed_labels.iloc[comp_idx].Difumo_names # plot difumo component-wise axbig = _simplify_grid(fig, axes, 0) _plot_difumo(img, axbig, proposed_label, cut_coords, dimension) # plot overlapped references - backbone for naming DiFuMo for atlas_idx, atlas in enumerate(columns): labels_img, labels = atlases[atlas].maps, atlases[atlas].labels # this atlas match for component index match_found = masked_data[atlas].values[0] _plot_references(match_found, labels_img, labels, atlas, atlas_idx, fig, axes, cut_coords, color) if not os.path.exists(output_dir): os.makedirs(output_dir) plt.savefig(join(output_dir, '{0}.jpg'.format(comp_idx + 1)), facecolor='k', bbox_inches='tight') plt.close() return
isinstance(name, str) for name in groups if name == group_name_2) # Load all masks into a list masks_1 = [] masks_2 = [] for i, sub in enumerate(subjects): if groups[i] == group_name_1: masks_1.append(ni.load(os.path.join(data_dir, sub, 'mrs', mask_file))) if groups[i] == group_name_2: masks_2.append(ni.load(os.path.join(data_dir, sub, 'mrs', mask_file))) # Calculate the coordinates of the centroids centres_1 = np.zeros((n_subs_1, 3)) centres_2 = np.zeros((n_subs_2, 3)) for i in range(n_subs_1): centres_1[i, :] = plotting.find_xyz_cut_coords(masks_1[i]) for i in range(n_subs_2): centres_2[i, :] = plotting.find_xyz_cut_coords(masks_2[i]) # Create a dummy adjacency matrix adjacency_matrix_1 = np.zeros((n_subs_1, n_subs_1)) adjacency_matrix_2 = np.zeros((n_subs_2, n_subs_2)) # Plot the figure fig = plt.figure() fig.set_size_inches(5, 3) axes1 = plt.subplot(111) plotting.plot_connectome(adjacency_matrix=adjacency_matrix_1, node_coords=centres_1, node_size=50, node_color=node_colour_1, display_mode='xz',
doc = xmltodict.parse(xml.text)["atlas"]["data"][ "label"] # convert to a superior data structure :) # We will store region voxel value, name, and a center coordinate regions = pandas.DataFrame(columns=["value", "name", "x", "y", "z"]) count = 0 for region in doc: regions.loc[count, "value"] = int(region["index"]) regions.loc[count, "name"] = region["name"] count += 1 # USE NILEARN TO FIND REGION COORDINATES (the center of the largest activation connected component) for region in regions.iterrows(): label = region[1]["value"] roi = numpy.zeros(aal4mm.shape) roi[aal4mm.get_data() == label] = 1 nii = nibabel.Nifti1Image(roi, affine=aal4mm.get_affine()) x, y, z = [int(x) for x in find_xyz_cut_coords(nii)] regions.loc[region[0], ["x", "y", "z"]] = [x, y, z] # Save data to file for application regions.to_csv("../data/aal_4mm_region_coords.tsv", sep="\t") # We will also flatten the brain-masked imaging data into a vector, # so we can select a region x,y,z based on the name region_lookup = pandas.DataFrame(columns=["aal"]) region_lookup["aal"] = aal4mm.get_data()[img4mm.get_data() != 0] region_lookup.to_pickle("../data/aal_4mm_region_lookup.pkl")
def run_mini_pipeline(): atlas = datasets.fetch_atlas_msdl() atlas_img = atlas['maps'] labels = pd.read_csv(atlas['labels'])['name'] masker = NiftiMapsMasker(maps_img=atlas_img, standardize=True, memory='/tmp/nilearn', verbose=0) data = datasets.fetch_adhd(number_subjects) figures_folder = '../figures/' count = 0 for func_file, confound_file in zip(data.func, data.confounds): # fit the data to the atlas mask, regress out confounds time_series = masker.fit_transform(func_file, confounds=confound_file) correlation = np.corrcoef(time_series.T) #plotting starts here plt.figure(figsize=(10, 10)) plt.imshow(correlation, interpolation="nearest") x_ticks = plt.xticks(range(len(labels)), labels, rotation=90) y_ticks = plt.yticks(range(len(labels)), labels) corr_file = figures_folder + 'subject_number_' + str( count) + '_correlation.pdf' plt.savefig(corr_file) atlas_region_coords = [ plotting.find_xyz_cut_coords(img) for img in image.iter_img(atlas_img) ] threshold = 0.6 plotting.plot_connectome(correlation, atlas_region_coords, edge_threshold=threshold) connectome_file = figures_folder + 'subject_number_' + str( count) + '_connectome.pdf' plt.savefig(connectome_file) #graph setup #binarize correlation matrix correlation[correlation < threshold] = 0 correlation[correlation != 0] = 1 graph = nx.from_numpy_matrix(correlation) partition = louvain.best_partition(graph) values = [partition.get(node) for node in graph.nodes()] plt.figure() nx.draw_spring(graph, cmap=plt.get_cmap('jet'), node_color=values, node_size=30, with_labels=True) graph_file = figures_folder + 'subject_number_' + str( count) + '_community.pdf' plt.savefig(graph_file) count += 1 plt.close('all')
correlations.append(correlation) # Mean of all correlations import numpy as np mean_correlations = np.mean(correlations, axis=0).reshape(n_regions_extracted, n_regions_extracted) # Visualization # Plotting connectome results import matplotlib.pyplot as plt from nilearn import image regions_imgs = image.iter_img(regions_extracted_img) coords_connectome = [plotting.find_xyz_cut_coords(img) for img in regions_imgs] title = 'Correlation interactions between %d regions' % n_regions_extracted plt.figure() plt.imshow(mean_correlations, interpolation="nearest", vmax=1, vmin=-1, cmap=plt.cm.bwr) plt.colorbar() plt.title(title) plotting.plot_connectome(mean_correlations, coords_connectome, edge_threshold='90%', title=title) ################################################################################
roi_coords = [] for i_roi, roi in enumerate(roi_paths): roi_nii = nib.load(roi) roi_th = nib.Nifti1Image(np.array(roi_nii.get_data() > 0, dtype=np.int16), roi_nii.get_affine(), header=roi_nii.get_header()) rroi = resample_img(roi_th, target_affine=tmp_img.get_affine(), target_shape=tmp_img.shape[:3], interpolation='nearest') cur_roi_img = nib.Nifti1Image(np.array(np.squeeze(rroi.get_data()) > 0, dtype=np.int32), affine=tmp_img.get_affine()) roi_coords.append(plotting.find_xyz_cut_coords(cur_roi_img)) RES_NAME = 'net_pred_combined_clf_' + ROI_DIR WRITE_DIR = op.join(os.getcwd(), RES_NAME) if not op.exists(WRITE_DIR): os.mkdir(WRITE_DIR) ############################################################################## # load+preprocess data ############################################################################## print('Loading ADHD data (1=ADHD)...') rs_files = glob.glob('/Volumes/porsche/adhd_niak/fmri*/*.nii.gz') sub_ids = [int(f.split('_session')[0].split('X_')[-1]) for f in rs_files] fo = open("adhd200_all.tsv", "rw+")
def save_info(info, save_labels, atlas_names, dimension): """Save found records Parameters ---------- info : dict Contains meta-data assigned to each atlas name such as overlap proportion, etc Each atlas dict contains following attributes: 'intersection' : sparse matrix dot product between DiFuMo regions and regions in target atlas (existing pre-defined) 'target_size' : np.ndarray Size of each region estimated in target atlas 'overlap_proportion' : list of pd.Series Each list contains the proportion of overlap estimated between this region and all region in target sizes. Sorted according to most strong hit in the overlap. 'overlap_size' : list Each list contain overlap in estimated sizes for all regions in target atlas. save_labels : dict List of original labels specific to each atlas. Useful for matching the overlap for the visualization of records. atlas_names : str or list of str Grab atlas from web given the name. Few are shipped with FSL and Nilearn. Valid options: ['harvard_oxford', 'destrieux', 'diedrichsen', 'juelich', 'jhu', 'mist', 'yeo_networks7', 'yeo_networks17'] dimension : int DiFuMo atlas dimension Returns ------- data : pd.DataFrame """ table = set_data_storage() maps_img = nibabel.load(fetch_difumo(dimension=dimension).maps) for i, img in enumerate(image.iter_img(maps_img)): cut_coords = plotting.find_xyz_cut_coords(img) table['cut_coords'].append(cut_coords) table['component'].append(i) for atlas in atlas_names: # Proporting of overlap with each index of difumo component this_atlas_info = info[atlas]['overlap_proportion'][i] if atlas in [ 'harvard_oxford', 'diedrichsen', 'juelich', 'jhu', 'mist', 'yeo_networks7', 'yeo_networks17' ]: if len(this_atlas_info.index[:1]) != 0: # grabbing the top one from the overlapped list this_label = save_labels[atlas][ this_atlas_info.index[:1]][0] else: this_label = 'none' if atlas == 'mist': table[atlas].append(this_label[0]) else: table[atlas].append(this_label) else: this_label = save_labels[atlas][ this_atlas_info.index[:1]][0][1] this_label = this_label.decode() table[atlas].append(this_label) return pd.DataFrame(table)
display_atlas = nilearn.plotting.plot_prob_atlas(ref_atlas, anat_img=anat_ref_file[0], title=atlas_name + '_anat', cut_coords=(5, 0, 0), threshold=0.) atlas_ref_labels = '/neurospin/grip/protocols/MRI/Resting_state_Victor_2014/atlases/atlas_fonctionel_control_AVCnn/AVCnn_roi_labels.csv' #'/neurospin/grip/protocols/MRI/Resting_state_Victor_2014/atlases/atlas_fonctionel_control_AVCnn/AVCnn_roi_labels.csv' #'/neurospin/grip/protocols/MRI/Resting_state_Victor_2014/AVCnn/resultats/references/msdl_rois_labels.csv' #atlas_ref_labels = '/neurospin/grip/protocols/MRI/Resting_state_Victor_2014/AVCnn/resultats/references/labels_short.csv' #labels_ref = np.recfromcsv(atlas_ref_labels) labels_ref = open(atlas_ref_labels).read().split() label_colors = np.random.rand(len(labels_ref), 3) coords_ref = [ plotting.find_xyz_cut_coords(roi) for roi in image.iter_img(ref_atlas) ] rois_ref = np.asarray(labels_ref) n_r = len(rois_ref) l = 300. / n_r #roi label size in figures visu_ref = ref_atlas at_check = [plt.gcf()] #figure handle for atlas check # prepare pairs for pairwise comparisons between groups comps = [] for func_index in range(len(func_type_list) - 1): if func_index != len(func_type_list) - func_index: for i in range(func_index, len(func_type_list) - func_index): if i + 1 < len(func_type_list): comps.append(
from nilearn.image import index_img from nilearn.plotting import find_xyz_cut_coords # Showing region extraction results using 4D maps visualization tool plotting.plot_prob_atlas(regions_img, display_mode='z', cut_coords=1, view_type='contours', title="Regions extracted.") # To reduce the complexity, we choose to display all the regions # extracted from network 3 import numpy as np DMN_network = index_img(atlas_networks, 3) plotting.plot_roi(DMN_network, display_mode='z', cut_coords=1, title='Network 3') regions_indices_network3 = np.where(np.array(extraction.index_) == 3) for index in regions_indices_network3[0]: cur_img = index_img(extraction.regions_img_, index) coords = find_xyz_cut_coords(cur_img) plotting.plot_roi(cur_img, display_mode='z', cut_coords=coords[2:3], title="Blob of network3") plotting.show()
coords_connectome = plotting.find_probabilistic_atlas_cut_coords(regions_img) plotting.plot_connectome(mean_correlations, coords_connectome, edge_threshold='90%', title=title) ################################################################################ # Plot regions extracted for only one specific network # ---------------------------------------------------- components_img = atlas_harvard_oxford.maps # First, we plot a network of index=4 without region extraction (left plot) from nilearn import image img = image.index_img(components_img, 1) coords = plotting.find_xyz_cut_coords(img) display = plotting.plot_stat_map(img, cut_coords=coords, colorbar=False, title='Showing one specific network') ################################################################################ # Now, we plot (right side) same network after region extraction to show that # connected regions are nicely seperated. # Each brain extracted region is identified as separate color. # For this, we take the indices of the all regions extracted related to original # network given as 4. regions_indices_of_map3 = np.where(np.array(regions_index) == 1) display = plotting.plot_anat(cut_coords=coords,
# saving each subject correlation to correlations correlations.append(correlation) # Mean of all correlations import numpy as np mean_correlations = np.mean(correlations, axis=0).reshape(n_regions_extracted, n_regions_extracted) ############################################################################### # Plot resulting connectomes # ---------------------------- import matplotlib.pyplot as plt from nilearn import image regions_imgs = image.iter_img(regions_extracted_img) coords_connectome = [plotting.find_xyz_cut_coords(img) for img in regions_imgs] title = 'Correlation interactions between %d regions' % n_regions_extracted plt.figure() plt.imshow(mean_correlations, interpolation="nearest", vmax=1, vmin=-1, cmap=plt.cm.bwr) plt.colorbar() plt.title(title) plotting.plot_connectome(mean_correlations, coords_connectome, edge_threshold='90%', title=title) ################################################################################ # Plot regions extracted for only one specific network # ---------------------------------------------------- # First, we plot a network of index=4 without region extraction (left plot) img = image.index_img(components_img, 4)
xml = requests.get(response["label_description_file"]) doc = xmltodict.parse(xml.text)["atlas"]["data"]["label"] # convert to a superior data structure :) # We will store region voxel value, name, and a center coordinate regions = pandas.DataFrame(columns=["value","name","x","y","z"]) count = 0 for region in doc: regions.loc[count,"value"] = int(region["index"]) regions.loc[count,"name"] = region["name"] count+=1 # USE NILEARN TO FIND REGION COORDINATES (the center of the largest activation connected component) for region in regions.iterrows(): label = region[1]["value"] roi = numpy.zeros(aal4mm.shape) roi[aal4mm.get_data()==label] = 1 nii = nibabel.Nifti1Image(roi,affine=aal4mm.get_affine()) x,y,z = [int(x) for x in find_xyz_cut_coords(nii)] regions.loc[region[0],["x","y","z"]] = [x,y,z] # Save data to file for application regions.to_csv("../data/aal_4mm_region_coords.tsv",sep="\t") # We will also flatten the brain-masked imaging data into a vector, # so we can select a region x,y,z based on the name region_lookup = pandas.DataFrame(columns=["aal"]) region_lookup["aal"] = aal4mm.get_data()[img4mm.get_data()!=0] region_lookup.to_pickle("../data/aal_4mm_region_lookup.pkl")
confound_filename = adhd_dataset.confounds[0] # Computing some confounds hv_confounds = mem.cache(nilearn.image.high_variance_confounds)( fmri_filename) time_series = masker.transform(fmri_filename, confounds=[hv_confounds, confound_filename]) print("-- Computing graph-lasso inverse matrix ...") from sklearn import covariance gl = covariance.GraphLassoCV(verbose=2) gl.fit(time_series) # Displaying results ########################################################## atlas_imgs = image.iter_img(msdl_atlas_dataset.maps) atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in atlas_imgs] title = "GraphLasso" plotting.plot_connectome(-gl.precision_, atlas_region_coords, edge_threshold='90%', title="Sparse inverse covariance") plotting.plot_connectome(gl.covariance_, atlas_region_coords, edge_threshold='90%', title="Covariance") plot_matrices(gl.covariance_, gl.precision_, title) plt.show()
# Then find the center of the regions and plot a connectome regions_img = regions_extracted_img coords_connectome = plotting.find_probabilistic_atlas_cut_coords(regions_img) plotting.plot_connectome(mean_correlations, coords_connectome, edge_threshold='90%', title=title) ################################################################################ # Plot regions extracted for only one specific network # ---------------------------------------------------- # First, we plot a network of index=4 without region extraction (left plot) from nilearn import image img = image.index_img(components_img, 4) coords = plotting.find_xyz_cut_coords(img) display = plotting.plot_stat_map(img, cut_coords=coords, colorbar=False, title='Showing one specific network') ################################################################################ # Now, we plot (right side) same network after region extraction to show that # connected regions are nicely seperated. # Each brain extracted region is identified as separate color. # For this, we take the indices of the all regions extracted related to original # network given as 4. regions_indices_of_map3 = np.where(np.array(regions_index) == 4) display = plotting.plot_anat(cut_coords=coords, title='Regions from this network')
# Grab extracted components umasked back to Nifti image. # Note: For older versions, less than 0.4.1. components_img_ # is not implemented. See Note section above for details. components_img = estimator.components_img_ components_img.to_filename('%s_resting_state.nii.gz' % names[estimator]) components_imgs.append(components_img) ############################################################################### # Visualize the results # ---------------------- from nilearn.plotting import (plot_prob_atlas, find_xyz_cut_coords, show, plot_stat_map) from nilearn.image import index_img # Selecting specific maps to display: maps were manually chosen to be similar indices = {dict_learning: 25, canica: 33} # We select relevant cut coordinates for displaying cut_component = index_img(components_imgs[0], indices[dict_learning]) cut_coords = find_xyz_cut_coords(cut_component) for estimator, components in zip(estimators, components_imgs): # 4D plotting plot_prob_atlas(components, view_type="filled_contours", title="%s" % names[estimator], cut_coords=cut_coords, colorbar=False) # 3D plotting plot_stat_map(index_img(components, indices[estimator]), title="%s" % names[estimator], cut_coords=cut_coords, colorbar=False) show()
node_colour = 'red' # Load in the participant IDs subjects = pd.read_csv(data_dir + 'participants.tsv', delimiter='\t')[ID_header] n_subs = len(subjects) # Load all masks into a list all_masks = [] for i, sub in enumerate(subjects): all_masks.append(ni.load(os.path.join(data_dir, sub, 'mrs', mask_file))) # Calculate the coordinates of the centroids all_centres = np.zeros((n_subs, 3)) for i in range(n_subs): all_centres[i, :] = plotting.find_xyz_cut_coords(all_masks[i]) # Create a dummy adjacency matrix adjacency_matrix = np.zeros((n_subs, n_subs)) # Plot the figure fig = plt.figure() fig.set_size_inches(5, 3) axes1 = plt.subplot(111) plotting.plot_connectome(adjacency_matrix=adjacency_matrix, node_coords=all_centres, node_size=50, node_color=node_colour, display_mode='xz', node_kwargs={'alpha': 0.3}, axes=axes1)