def test_fetch_atlas_yeo_2011(): dataset = datasets.fetch_atlas_yeo_2011(data_dir=tmpdir, verbose=0) assert_true(isinstance(dataset.anat, _basestring)) assert_true(isinstance(dataset.colors_17, _basestring)) assert_true(isinstance(dataset.colors_7, _basestring)) assert_true(isinstance(dataset.thick_17, _basestring)) assert_true(isinstance(dataset.thick_7, _basestring)) assert_true(isinstance(dataset.thin_17, _basestring)) assert_true(isinstance(dataset.thin_7, _basestring)) assert_equal(len(url_request.urls), 1)
def split_yeo(out_path): # take yeo atlas and offset rois in rh +100 atlas_yeo_2011 = datasets.fetch_atlas_yeo_2011() atlas_yeo = atlas_yeo_2011.thick_17 atlas_yeo_img = image.reorder_img(image.image.check_niimg_3d(atlas_yeo)) split_x = 128 offset = np.zeros_like(atlas_yeo_img.dataobj) offset[split_x:, :, :] = 100 offset[atlas_yeo_img.dataobj == 0] = 0 offset_img = image.new_img_like(atlas_yeo_img, offset, copy_header=True, affine=atlas_yeo_img.affine) yeo_splithem_img = image.math_img("im1 + im2", im1=atlas_yeo_img, im2=offset_img) # create updated roi list yeo17_networks_str = StringIO("""roi,roi_name,dmn_subnetwork 1,Visual A, 2,Visual B, 3,SomMot A, 4,SomMot B, 5,DorsAttn A, 6,DorsAttn B, 7,SalVentAttn A, 8,SalVentAttn B, 9,Limbic B, 10,Limbic A, 11,Control C, 12,Control A, 13,Control B, 14,TempPar, 15,Default C,mtl 16,Default A,core 17,Default B,dorsal medial""") df_labels = pd.read_csv(yeo17_networks_str, header=0) df_labels_lh = df_labels.copy() df_labels_rh = df_labels.copy() df_labels_lh["hemi"] = "lh" df_labels_rh["hemi"] = "rh" df_labels_rh["roi"] += 100 df_combined = pd.concat((df_labels_lh, df_labels_rh)) df_combined["full_roi_name"] = (df_combined.hemi + "_" + df_combined.roi_name).str.replace( " ", "_") # output os.makedirs(out_path, exist_ok=True) out_file = os.path.join(out_path, "yeo_2011_thick17_splithemi") yeo_splithem_img.to_filename(out_file + ".nii.gz") df_combined.to_csv(out_file + ".tsv", sep="\t", index=False)
def make_masker(scheme): ''' Parameters ---------- scheme : String The type of parcellation wanted. Returns ------- masker: nilearn.input_data.NiftiLabelsMasker Masker of the chosen scheme. labels: list Labels of all the regions in parcellation. ''' if scheme.lower() == "harvox": # 48 regions dataset = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm') atlas_filename = dataset.maps labels = dataset.labels[1:] # trim off "background" label masker = NiftiLabelsMasker(labels_img=atlas_filename, standardize=True, high_variance_confounds=True, verbose=1) elif scheme.lower() == "yeo": # 17 regions dataset = datasets.fetch_atlas_yeo_2011() masker = NiftiLabelsMasker(labels_img=dataset['thick_17'], standardize=True, high_variance_confounds=True, verbose=1) labels = [ "Visual A", "Visual B", "Somatomotor A", "Somatomotor B", "Dorsal Attention A", "Dorsal Attention B", "Salience/Ventral Attention A", "Salience/Ventral Attention B", "Limbic A", "Limbic B", "Control C", "Control A", "Control B", "Temporal Parietal", "Default C", "Default A", "Default B" ] # list from valerie-jzr elif scheme.lower() == "aal": # 116 regions dataset = datasets.fetch_atlas_aal(version='SPM12') labels = dataset['labels'] masker = NiftiLabelsMasker(labels_img=dataset['maps'], standardize=True, high_variance_confounds=True, verbose=1) elif scheme.lower() == "schaefer": dataset = datasets.fetch_atlas_schaefer_2018(n_rois=100, yeo_networks=17) labels = dataset['labels'] masker = NiftiLabelsMasker(labels_img=dataset['maps'], standardize=True, high_variance_confounds=True, verbose=1) return masker, labels
def setup_(self): nl = fe.NeurolangDL() destrieux_atlas = datasets.fetch_atlas_destrieux_2009() yeo_atlas = datasets.fetch_atlas_yeo_2011() img = nib.load(destrieux_atlas['maps']) aff = img.affine data = img.get_data() rset = [] for label, name in destrieux_atlas['labels']: if label == 0: continue voxels = np.transpose((data == label).nonzero()) if len(voxels) == 0: continue rset.append((name.decode('utf8'), fe.ExplicitVBR(voxels, aff, image_dim=img.shape, prebuild_tree=True))) nl.add_tuple_set(rset, name='destrieux') img = nib.load(yeo_atlas['thick_17']) aff = img.affine data = img.get_data().squeeze() rset = [] for label in range(1, 18): name = str(label) if label == 0: continue voxels = np.transpose((data == label).nonzero()) if len(voxels) == 0: continue rset.append((name, fe.ExplicitVBR(voxels, aff, image_dim=data.shape, prebuild_tree=True))) nl.add_tuple_set(rset, name='yeo') self.nl = nl
The time series of all subjects of the ADHD Dataset are concatenated and given directly to :class:`nilearn.connectome.ConnectivityMeasure` for computing parcel-wise correlation matrices for each atlas across all subjects. Mean correlation matrix is displayed on glass brain on extracted coordinates. # author: Amadeus Kanaan """ #################################################################### # Load atlases # ------------- from nilearn import datasets yeo = datasets.fetch_atlas_yeo_2011() print('Yeo atlas nifti image (3D) with 17 parcels and liberal mask is located ' 'at: %s' % yeo['thick_17']) ######################################################################### # Load functional data # -------------------- data = datasets.fetch_adhd(n_subjects=10) print('Functional nifti images (4D, e.g., one subject) are located at : %r' % data['func'][0]) print('Counfound csv files (of same subject) are located at : %r' % data['confounds'][0]) ########################################################################## # Extract coordinates on Yeo atlas - parcellations
The time series of all subjects of the brain development dataset are concatenated and given directly to :class:`nilearn.connectome.ConnectivityMeasure` for computing parcel-wise correlation matrices for each atlas across all subjects. Mean correlation matrix is displayed on glass brain on extracted coordinates. # author: Amadeus Kanaan """ #################################################################### # Load atlases # ------------- from nilearn import datasets yeo = datasets.fetch_atlas_yeo_2011() print('Yeo atlas nifti image (3D) with 17 parcels and liberal mask is located ' 'at: %s' % yeo['thick_17']) ######################################################################### # Load functional data # -------------------- data = datasets.fetch_development_fmri(n_subjects=10) print('Functional nifti images (4D, e.g., one subject) are located at : %r' % data['func'][0]) print('Counfound csv files (of same subject) are located at : %r' % data['confounds'][0]) ########################################################################## # Extract coordinates on Yeo atlas - parcellations
def _get_roi_info(parc): if parc == "msdl": atlas = datasets.fetch_atlas_msdl() roi_file = atlas['maps'] df_labels = pd.DataFrame({"roi_labels": atlas['labels']}) if isinstance(df_labels["roi_labels"][0], bytes): df_labels["roi_labels"] = df_labels.roi_labels.apply(bytes.decode) roi_names = df_labels["roi_labels"].values roi_type = "maps" elif parc == "gordon": atlas_dir = "/parcs/Gordon/Parcels" roi_file = os.path.join(atlas_dir, "Parcels_MNI_111.nii") labs_df = pd.read_excel(os.path.join(atlas_dir, "Parcels.xlsx")) roi_names = labs_df.ParcelID.values roi_type = "labels" elif parc == "basc197": atlas = datasets.fetch_atlas_basc_multiscale_2015(version='sym') roi_file = atlas['scale197'] roi_names = np.arange(1, 198).astype(int) roi_type = "labels" elif parc == "basc444": atlas = datasets.fetch_atlas_basc_multiscale_2015(version='sym') roi_file = atlas['scale444'] roi_names = np.arange(1, 445).astype(int) roi_type = "labels" elif parc == "schaefer200": atlas_dir = "/parcs/Schaefer" schaefer_cols = "roi community c1 c2 c3 c4".split(" ") roi_file = os.path.join(atlas_dir, "Schaefer2018_200Parcels_17Networks_order_FSLMNI152_1mm.nii.gz") labs_df = pd.read_csv(os.path.join(atlas_dir, "Schaefer2018_200Parcels_17Networks_order.txt"), sep="\t", names=schaefer_cols) roi_names = labs_df.roi roi_type = "labels" elif parc == "schaefer400": atlas_dir = "/parcs/Schaefer" schaefer_cols = "roi community c1 c2 c3 c4".split(" ") roi_file = os.path.join(atlas_dir, "Schaefer2018_400Parcels_17Networks_order_FSLMNI152_1mm.nii.gz") labs_df = pd.read_csv(os.path.join(atlas_dir, "Schaefer2018_400Parcels_17Networks_order.txt"), sep="\t", names=schaefer_cols) roi_names = labs_df.roi roi_type = "labels" elif parc == "yeo17": atlas = datasets.fetch_atlas_yeo_2011() roi_file = atlas['thick_17'] yeo_cols = "roi roi_labels c1 c2 c3 c4".split(" ") df_labels = pd.read_csv(atlas["colors_17"], sep=r"\s*", engine="python", names=yeo_cols, skiprows=1) roi_names = df_labels["roi_labels"].values roi_type = "labels" elif parc == "yeo17thin": atlas = datasets.fetch_atlas_yeo_2011() roi_file = atlas['thin_17'] yeo_cols = "roi roi_labels c1 c2 c3 c4".split(" ") df_labels = pd.read_csv(atlas["colors_17"], sep=r"\s*", engine="python", names=yeo_cols, skiprows=1) roi_names = df_labels["roi_labels"].values roi_type = "labels" elif parc == "yeo17split": atlas_dir = "/parcs/Yeo_splithemi" roi_file = os.path.join(atlas_dir, "yeo_2011_thick17_splithemi.nii.gz") labs_df = pd.read_csv(os.path.join(atlas_dir, "yeo_2011_thick17_splithemi.tsv"), sep="\t") roi_names = labs_df.full_roi_name.values roi_type = "labels" elif parc == "yeo7": atlas = datasets.fetch_atlas_yeo_2011() roi_file = atlas['thick_7'] yeo_cols = "roi roi_labels c1 c2 c3 c4".split(" ") df_labels = pd.read_csv(atlas["colors_7"], sep=r"\s*", engine="python", names=yeo_cols, skiprows=1) roi_names = df_labels["roi_labels"].values roi_type = "labels" else: raise Exception("Parcellation not known {}".format(parc)) return roi_file, roi_names, roi_type
def get_labelled_atlas(query, data_dir=None, return_labels=True): """Parses input query to determine which atlas to fetch and what version of the atlas to use (if applicable). Parameters ---------- query : str Input string in the following format: nilearn:{atlas_name}:{atlas_parameters}. The following can be for `atlas_name`: 'destrieux', 'yeo', 'aal', 'talairach', and 'schaefer'. `atlas_parameters` is not available for the `destrieux` atlas. data_dir : str, optional Directory in which to save atlas data. By default None, which creates a ~/nilearn_data/ directory as per nilearn. return_labels : bool, optional Whether to return atlas labels. Default is True. Not available for the 'basc' atlas. Returns ------- str, list or None The atlas image and the accompanying labels (if provided) Raises ------ ValueError Raised when the query does is not formatted correctly or if the no match found. """ # extract parameters params = query.split(':') if len(params) == 3: _, atlas_name, sub_param = params elif len(params) == 2: _, atlas_name = params sub_param = None else: raise ValueError('Incorrect atlas query string provided') # get atlas if atlas_name == 'destrieux': atlas = fetch_atlas_destrieux_2009(lateralized=True, data_dir=data_dir) img = atlas['maps'] labels = atlas['labels'] elif atlas_name == 'yeo': atlas = fetch_atlas_yeo_2011(data_dir=data_dir) img = atlas[sub_param] if '17' in sub_param: labels = pd.read_csv(atlas['colors_17'], sep=r'\s+')['NONE'].tolist() elif atlas_name == 'aal': version = 'SPM12' if sub_param is None else sub_param atlas = fetch_atlas_aal(version=version, data_dir=data_dir) img = atlas['maps'] labels = atlas['labels'] elif atlas_name == 'basc': version, scale = sub_param.split('-') atlas = fetch_atlas_basc_multiscale_2015(version=version, data_dir=data_dir) img = atlas['scale{}'.format(scale.zfill(3))] labels = None elif atlas_name == 'talairach': atlas = fetch_atlas_talairach(level_name=sub_param, data_dir=data_dir) img = atlas['maps'] labels = atlas['labels'] elif atlas_name == 'schaefer': n_rois, networks, resolution = sub_param.split('-') # corrected version of schaefer labels until fixed in nilearn correct_url = ('https://raw.githubusercontent.com/ThomasYeoLab/CBIG/' 'v0.14.3-Update_Yeo2011_Schaefer2018_labelname/' 'stable_projects/brain_parcellation/' 'Schaefer2018_LocalGlobal/Parcellations/MNI/') atlas = fetch_atlas_schaefer_2018(n_rois=int(n_rois), yeo_networks=int(networks), resolution_mm=int(resolution), data_dir=data_dir, base_url=correct_url) img = atlas['maps'] labels = atlas['labels'] else: raise ValueError('No atlas detected. Check query string') if not return_labels: labels = None else: labels = labels.astype(str).tolist() return img, labels
def fetch_yeo(network_name): """Return atlas and networks names of Yeo et al. 2011 Parameters ---------- network_name : str Valid names are 'yeo_networks7', 'yeo_networks17' Returns ------- maps : str Path to Yeo et al. 2011 atlas specified by network name labels : list of str Network names are manually annotated. NOTES ----- Problem: map "networks number" from original yeo et al. 2011 to "network names" Solution: Is to match/close match between RGB color look up table (tuple) associated to each network number in https://github.com/ThomasYeoLab/CBIG/blob/master/stable_projects/brain_parcellation/Schaefer2018_LocalGlobal/Parcellations/MNI/Schaefer2018_1000Parcels_17Networks_order.txt Another source discussion on this issue: https://github.com/ThomasYeoLab/CBIG/issues/2 Original Yeo et al 2011 data can be fetched using function datasets.fetch_atlas_yeo_2011 with Nilearn package. ============================================================= # Yeo2011_7Networks_ColorLUT 0 NONE 0 0 0 0 1 7Networks_1 120 18 134 0 2 7Networks_2 70 130 180 0 3 7Networks_3 0 118 14 0 4 7Networks_4 196 58 250 0 5 7Networks_5 220 248 164 0 6 7Networks_6 230 148 34 0 7 7Networks_7 205 62 78 0 ============================================================= # Yeo2011_17Networks_ColorLUT 0 NONE 0 0 0 0 1 17Networks_1 120 18 134 0 2 17Networks_2 255 0 0 0 3 17Networks_3 70 130 180 0 4 17Networks_4 42 204 164 0 5 17Networks_5 74 155 60 0 6 17Networks_6 0 118 14 0 7 17Networks_7 196 58 250 0 8 17Networks_8 255 152 213 0 9 17Networks_9 220 248 164 0 10 17Networks_10 122 135 50 0 11 17Networks_11 119 140 176 0 12 17Networks_12 230 148 34 0 13 17Networks_13 135 50 74 0 14 17Networks_14 12 48 255 0 15 17Networks_15 0 0 130 0 16 17Networks_16 255 255 0 0 17 17Networks_17 205 62 78 0 """ yeo_networks7 = { "0": "Background", "7Networks_1": "VisCent", # VisualCentral "7Networks_2": "SomMotA", # SomatoMotor A "7Networks_3": "DorsAttnB", # DorsalAttention B "7Networks_4": "SalVentAttnA", # SalienceVentralAttention A "7Networks_5": "LimbicA", # Limbic A Temporoporal "7Networks_6": "ContA", # Control A IPS "7Networks_7": "DefaultB" # Default B } yeo_networks17 = { "0": "Background", "17Networks_1": "VisCent", # VisualCentral "17Networks_2": "VisPeri", # VisualPeripheral "17Networks_3": "SomMotA", # SomatoMotor A "17Networks_4": "SomMotB", # SomatoMotor B "17Networks_5": "DorsAttnA", # DorsalAttention A "17Networks_6": "DorsAttnB", # DorsalAttention B "17Networks_7": "SalVentAttnA", # SalienceVentralAttention A "17Networks_8": "SalVentAttnB", # SalienceVentralAttention B "17Networks_9": "LimbicA", # Limbic A Temporoporal "17Networks_10": "LimbicB", # Limbic B OrbitoFrontalC "17Networks_11": "ContC", # Cont C Cingp "17Networks_12": "ContA", # Cont A IPS "17Networks_13": "ContB", # Cont B IPL "17Networks_14": "TempPar", # Temporo Parietal "17Networks_15": "DefaultC", # Default C RSP "17Networks_16": "DefaultA", # Default A pCunPCC "17Networks_17": "DefaultB" # Default B } data = datasets.fetch_atlas_yeo_2011() if network_name == 'yeo_networks7': maps = data.thick_7 labels = list(yeo_networks7.values()) elif network_name == 'yeo_networks17': maps = data.thick_17 labels = list(yeo_networks17.values()) else: raise ValueError("Invalid network name is provided for Yeo thick" " version of parcellations.") return Bunch(maps=maps, labels=labels)
from nilearn import datasets atlas_yeo_2011 = datasets.fetch_atlas_yeo_2011(data_dir = '/Users/loukas/Desktop/Yeo_mapping/Yeo_atlases')
##### Remove the warnings to keep notebook cleaner ##### import warnings warnings.filterwarnings('ignore') ##### Fetching Brain Parcellations ##### #Fetching Schaefer 400-Parcellations from nilearn import datasets work_dir = '/Volumes/Harddrive_CTS/MRI/Placebo_1_Analysis/' schaefer_parcellations = datasets.fetch_atlas_schaefer_2018(n_rois = 400, yeo_networks = 7, data_dir = work_dir) labels_schaefer = schaefer_parcellations.labels atlas_schaefer = schaefer_parcellations.maps print('Schaefer Atlas ROIs are located in nifti image (4D) at: %s' % atlas_schaefer) #Fetching Yeo 7-Network yeo_parcellations = datasets.fetch_atlas_yeo_2011(data_dir = work_dir, verbose = 1) atlas_yeo = yeo_parcellations.thin_7 print('Yeo Atlas ROIs are located in nifti image (4D) at: %s' % atlas_yeo) #Fetching Power 264-parcellations power = nilearn.datasets.fetch_coords_power_2011() print('Power atlas comes with {0}.'.format(power.keys())) #Compute spheres of fixed radius of sequence (x,y,z) import numpy as np power_coords = np.vstack((power.rois['x'], power.rois['y'], power.rois['z'])).T print('Stacked power coordinates in array of shape {0}.'.format(power_coords.shape)) #Plot Atlases %matplotlib gtk import matplotlib.pyplot as plt
def compute_graph(sub_name, spatial_regulation=10): """ Parameters ---------- sub_name : subject name, should correspond to the folder in which ward data is saved spatial_regulation : float, regulation used on the spatial addition in the ward_parcellation. Used to collect the file, as it appears in it (the XX in skward_regXX_parcellation.nii.gz) Output ------ gx : stack of parcel baricentres and yeo-ROI connectivity fingerprint in a graph """ wards = load_img( "/scratch/mmahaut/data/abide/graph_classification/{}/skward_reg{}_parcellation.nii.gz" .format(sub_name, spatial_regulation)) wards_data = wards.get_fdata() A = np.load( "/scratch/mmahaut/data/abide/graph_classification/{}/parcel_adjacency.npy" .format(sub_name)) # create networkx-graph from the n_parcels x n_parcels adjacency matrix A gx = nx.from_numpy_matrix(A) n_parcels = A.shape[0] # for each parcel (which will become a graph node), compute two sets of attributes: X1 = [] X2 = [] yeo = fetch_atlas_yeo_2011() yeo_masker = NiftiLabelsMasker(labels_img=yeo["thick_17"], standardize=True, memory="nilearn_cache") wards_masker = NiftiLabelsMasker(labels_img=wards, standardize=True, memory="nilearn_cache") rsfmri_img = load_img( "/scratch/mmahaut/data/abide/downloaded_preprocessed/NYU_0051091/NYU_0051091_func_preproc.nii.gz" ) wards_timeseries = wards_masker.fit_transform(rsfmri_img) yeo_timeseries = yeo_masker.fit_transform(rsfmri_img) for i in range(len(wards_timeseries.T)): # compute 3D coordinates of the barycenter of the parcel i pos = np.array(np.where(wards_data == i)) x1_i = centeroidnp(pos) X1.append(x1_i) # compute connectivity fingerprint of the parcel i x2_i = connectivity_fingerprint(yeo_timeseries, wards_timeseries[:, i]) X2.append(x2_i) # optional: normalize X1 and X2 (with min & max) X1 = np.array(X1) X2 = np.array(X2) X1_norm = (X1 - X1.min()) / (X1.max() - X1.min()) X2_norm = (X2 - X2.min()) / (X2.max() - X2.min()) # concatenate X1 and X2 to produce the full # set of attributes attr = np.hstack([X1_norm, X2_norm]) print( sub_name, " attr : ", attr.shape ) # here, with 200 parcels, we'd expect a shape of 200 but get something between 199 and 196, probably for mask reasons # construct dict of attributes d = {idx: list(attr[idx, :]) for idx in range(attr.shape[0])} # add attributes to nodes nx.set_node_attributes(gx, d, "attr") return gx
Author: Bertrand Thirion, 2021 """ import os from nilearn.datasets import fetch_atlas_yeo_2011 from nilearn.input_data import NiftiLabelsMasker from nilearn.plotting import plot_roi, plot_img from nilearn.regions import connected_label_regions import matplotlib.pyplot as plt data_dir = '/tmp' # directory where you put your data lesion = os.path.join(data_dir, 'lesion.nii.gz') # here it is assumed that your input lesion image is available at # '/tmp/lesion.nii.gz' # change it to any path you like atlas = fetch_atlas_yeo_2011() thick17 = atlas['thick_17'] # optionally display the atlas # plot_roi(thick17) # separate yeo17 atlas into connected components: # 122 connected components overall separate_thick17 = connected_label_regions(thick17) # display the lesion on top of the atlas display = plot_img(lesion) display.add_overlay(thick17, cmap=plt.cm.hsv) # compute the mean of lesion proportion per network masker = NiftiLabelsMasker(labels_img=thick17).fit() network_lesion = masker.transform(lesion)
import nilearn.datasets as datasets from nilearn.input_data import (NiftiLabelsMasker, NiftiSpheresMasker, NiftiMapsMasker) # Voxels with 0 intensity correspond to the background. YEO_LABELS = [ 'Background', 'Visual', 'Somato-sensor', 'Dorsal Attention', 'Ventral Attention', 'Limbic', 'Frontoparietal', 'Default' ] ATLAS_3D = dict( cortical=( lambda: datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm')), subcortical=( lambda: datasets.fetch_atlas_harvard_oxford('sub-maxprob-thr25-2mm')), yeo7=(lambda: dict(maps=datasets.fetch_atlas_yeo_2011()['thick_7'], labels=YEO_LABELS)), aal=(lambda: _fetch_aal()), # brodmann=(lambda: # datasets.fetch_atlas_talairach('ba')) ) ATLAS_COORDS = dict(power=(lambda: datasets.fetch_coords_power_2011()), ) ATLAS_PROBABILISTIC = dict(msdl=(lambda: _fetch_msdl())) def _fetch_aal(): """ The AAL atlas does not contain a background label. To make the API consistent we fix it here. """