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  
Ejemplo n.º 2
0
def participant_level(args, subjects_to_analyze):
    # The subject level analysis: extract time-series per subject
    # Retrieve the atlas
    atlas_data = datasets.fetch_atlas_basc_multiscale_2015()
    atlas_filename = atlas_data.scale122

    # find all RS scans and extract time-series on them
    for subject_label in subjects_to_analyze:
        for fmri_file in glob(
                os.path.join(args.bids_dir, "derivatives",
                             "sub-%s" % subject_label, "func",
                             "*_hmc_mni.nii.gz")):
            masker = input_data.NiftiLabelsMasker(labels_img=atlas_filename,
                                                  standardize=True,
                                                  detrend=True,
                                                  verbose=3)
            time_series = masker.fit_transform(fmri_file)
            out_file = os.path.split(fmri_file)[-1].replace(
                "_hmc_mni.nii.gz", "_time_series.tsv")
            out_file = os.path.join(args.output_dir, out_file)
            np.savetxt(out_file, time_series, delimiter='\t')

            estimator = covariance.LedoitWolf(store_precision=True)
            estimator.fit(time_series)
            out_file = os.path.split(fmri_file)[-1].replace(
                "_hmc_mni.nii.gz", "_connectome.tsv")
            out_file = os.path.join(args.output_dir, out_file)
            np.savetxt(out_file, estimator.precision_, delimiter='\t')
Ejemplo n.º 3
0
def plot_atlas():

    ###############################################################################
    # Retrieving multiscale group brain parcellations
    # -----------------------------------------------
    from nilearn.datasets import MNI152_FILE_PATH
    print('Path to MNI152 template: %r' % MNI152_FILE_PATH)

    parcellations = datasets.fetch_atlas_basc_multiscale_2015(version='sym')

    # We show here networks of 64, 197, 444
    networks_64 = parcellations['scale064']
    networks_197 = parcellations['scale197']
    networks_444 = parcellations['scale444']

    ###############################################################################
    # Visualizing brain parcellations
    # -------------------------------

    # The coordinates of all plots are selected automatically by itself
    # We manually change the colormap of our choice
    plotting.plot_roi(networks_64, cmap=plotting.cm.bwr,
                      title='64 regions of brain clusters')

    plotting.plot_roi(networks_197, cmap=plotting.cm.bwr,
                      title='197 regions of brain clusters')

    plotting.plot_roi(networks_444, cmap=plotting.cm.bwr_r,
                      title='444 regions of brain clusters')

    plotting.show()
Ejemplo n.º 4
0
def fetch_basc_vascular_atlas(n_scales='scale007',
                              target_affine=np.diag((5, 5, 5))):
    """ Fetch the BASC brain atlas given its resolution.

    Parameters
    ----------
    hrf_atlas: str, BASC dataset name possible values are: 'scale007',
        'scale012', 'scale036', 'scale064', 'scale122', 'scale197', 'scale325',
        'scale444'

    target_affine : np.array, (default=np.diag((5, 5, 5))), affine matrix for
        the produced Nifti images

    Return
    ------
    mask_full_brain : Nifti Image, full mask brain
    atlas_rois : Nifti Image, ROIs atlas
    """
    if n_scales not in valid_scales:
        raise ValueError(f"n_scales should be in {valid_scales}, "
                         f"got '{n_scales}'")

    basc_dataset = datasets.fetch_atlas_basc_multiscale_2015(version='sym')
    atlas_rois_fname = basc_dataset[n_scales]
    atlas_to_return = image.load_img(atlas_rois_fname)

    atlas_to_return = image.resample_img(atlas_to_return,
                                         target_affine,
                                         interpolation='nearest')

    brain_mask = image_nilearn.binarize_img(atlas_to_return, threshold=0)

    return brain_mask, atlas_to_return
def make_masker(atlas, dim, mask):
    mem = Memory(location=expanduser('cache'))
    masker_params = dict(
        mask_img=mask,
        smoothing_fwhm=5,
        memory=mem,
        memory_level=1,
        standardize=True,
        detrend=True,
        t_r=2,
        low_pass=0.01,
        high_pass=None,
        verbose=0,
    )
    if atlas in ['difumo']:
        if atlas == 'difumo':
            maps_img = fetch_difumo(dimension=dim).maps
        masker = OurNiftiMasker(maps_img=maps_img,
                                reduction='maps',
                                **masker_params)
    elif atlas in ['basc']:
        if atlas == 'basc':
            basc = fetch_atlas_basc_multiscale_2015()
            this_labels_img = basc[f'scale{dim:03.0f}']
        masker = OurNiftiMasker(label_img=this_labels_img,
                                reduction='labels',
                                **masker_params)
    elif atlas == 'none':
        masker = OurNiftiMasker(reduction=None, **masker_params)
    else:
        raise ValueError('Wrong atlas argument')
    masker.fit()
    masker_geom = NiftiMasker(mask_img=mask).fit()
    return masker, masker_geom
Ejemplo n.º 6
0
def fetch_atlas_basc_2015(n_scales='scale007'):
    """ Fetch the BASC brain atlas given its resolution.

    Parameters
    ----------
    hrf_atlas: str, BASC dataset name possible values are: 'scale007',
        'scale012', 'scale036', 'scale064', 'scale122'

    Return
    ------
    mask_full_brain : Nifti Image, full mask brain
    atlas_rois : Nifti Image, ROIs atlas
    """
    if n_scales not in ['scale007', 'scale012', 'scale036', 'scale064',
                        'scale122']:
        raise ValueError("n_scales should be in ['scale007', 'scale012', "
                         "'scale036', 'scale064', 'scale122'], "
                         "got '{}'".format(n_scales))

    basc_dataset = datasets.fetch_atlas_basc_multiscale_2015(version='sym')
    atlas_rois_fname = basc_dataset[n_scales]
    atlas_to_return = image.load_img(atlas_rois_fname)

    # compute the full brain mask (0/1 Nifti object)
    brain_mask = np.ones_like(atlas_to_return.get_fdata())
    brain_mask[atlas_to_return.get_fdata() == 0] = 0

    return image.new_img_like(atlas_to_return, brain_mask), atlas_to_return
def load_atlas(atlas_location=None, download_path=DEFAULT_DOWNLOAD_PATH):
    """Loading a provided atlas
    
    Keyword Arguments:
        atlas_location {str} -- path or url to the atlas (default: {None})
        download_path {[type]} -- download path for the atlas(default: {'./downloaded_atlas.nii.gz'})
    
    Returns:
        {Nibabel Image} -- Atlas's path
    """
    print(f'{bcolors.OKBLUE}Loading atlas{bcolors.ENDC}')
    atlas_filename = ''

    if not atlas_location:
        atlas = datasets.fetch_atlas_msdl()
        atlas_filename = atlas['maps']

    else:
        if is_url(atlas_location):
            print(
                f'{bcolors.OKBLUE}Beginning atlas download with urllib2...{bcolors.ENDC}'
            )
            urllib.request.urlretrieve(atlas_location, download_path)

            atlas_filename = download_path
        elif 'MIST' in atlas_location:
            print(f'{bcolors.OKBLUE}Getting MIST atlases...{bcolors.ENDC}')

            atlas = datasets.fetch_atlas_basc_multiscale_2015(version='sym')
            atlas_filename = atlas['scale{}'.format(
                atlas_location.split('_')[1].zfill(3))]
        else:
            atlas_filename = atlas_location

    return atlas_filename
Ejemplo n.º 8
0
def fetch_atlas_basc_multiscale_2015(args):
    ds = datasets.fetch_atlas_basc_multiscale_2015(**args)
    scales = [7, 12, 20, 36, 64, 122, 197, 325, 444]
    files = []
    for scale in scales:
        files.append(ds['scale{:03d}'.format(scale)])
    df = pd.DataFrame({'scale': scales, 'path':files})
    return df
Ejemplo n.º 9
0
def prepare_data(data_dir, output_dir, pipeline = "cpac", quality_checked = True):
    # get dataset
    print("Loading dataset...")
    abide = datasets.fetch_abide_pcp(data_dir = data_dir,
                                     pipeline = pipeline,
                                     quality_checked = quality_checked)
    # make list of filenames
    fmri_filenames = abide.func_preproc

    # load atlas
    multiscale = datasets.fetch_atlas_basc_multiscale_2015()
    atlas_filename = multiscale.scale064

    # initialize masker object
    masker = NiftiLabelsMasker(labels_img=atlas_filename,
                               standardize=True,
                               memory='nilearn_cache',
                               verbose=0)

    # initialize correlation measure
    correlation_measure = ConnectivityMeasure(kind='correlation', vectorize=True,
                                             discard_diagonal=True)

    try: # check if feature file already exists
        # load features
        feat_file = os.path.join(output_dir, 'ABIDE_BASC064_features.npz')
        X_features = np.load(feat_file)['a']
        print("Feature file found.")

    except: # if not, extract features
        X_features = [] # To contain upper half of matrix as 1d array
        print("No feature file found. Extracting features...")

        for i,sub in enumerate(fmri_filenames):
            # extract the timeseries from the ROIs in the atlas
            time_series = masker.fit_transform(sub)
            # create a region x region correlation matrix
            correlation_matrix = correlation_measure.fit_transform([time_series])[0]
            # add to our container
            X_features.append(correlation_matrix)
            # keep track of status
            print('finished extracting %s of %s'%(i+1,len(fmri_filenames)))
        # Save features
        np.savez_compressed(os.path.join(output_dir, 'ABIDE_BASC064_features'),
                                         a = X_features)

    # Dimensionality reduction of features with PCA
    print("Running PCA...")
    pca = PCA(0.99).fit(X_features) # keeping 99% of variance
    X_features_pca = pca.transform(X_features)

    # Transform phenotypic data into dataframe
    abide_pheno = pd.DataFrame(abide.phenotypic)

    # Get the target vector
    y_target = abide_pheno['DX_GROUP']

    return(X_features_pca, y_target)
def test_make_masker_from_atlas():
    atlas = fetch_atlas_basc_multiscale_2015().scale007
    masker = make_masker_from_atlas(atlas)
    assert_true(isinstance(masker, NiftiLabelsMasker))
    assert_equal(masker.labels_img.shape, (53, 64, 52))

    atlas = fetch_atlas_msdl().maps
    masker = make_masker_from_atlas(atlas)
    assert_true(isinstance(masker, NiftiMapsMasker))
    assert_equal(masker.maps_img.shape, (40, 48, 35, 39))
Ejemplo n.º 11
0
def extract_timeseries(func,
                       atlas=fetch_atlas_basc_multiscale_2015().scale064,
                       confounds=None,
                       memory=None,
                       memory_level=1,
                       duration=None):
    """Extract time series for a list of functional volume.

    Parameters
    ----------
    func : str,
        Path of Nifti volumes.

    atlas : str or 3D/4D Niimg-like object, (default=BASC64)
        The atlas to use to create the masker. If string, it should corresponds
        to the path of a Nifti image.

    confounds : str,
        Path containing the confounds.

    memory : instance of joblib.Memory or string, (default=None)
        Used to cache the masking process. By default, no caching is done. If a
        string is given, it is the path to the caching directory.

    memory_level : integer, optional (default=1)
        Rough estimator of the amount of memory used by caching. Higher value
        means more memory for caching.

    duration : float
        The duration of timeseries to be extracted, measured in seconds.

    """
    TR = 1.992  # s
    masker = make_masker_from_atlas(atlas,
                                    memory=memory,
                                    memory_level=memory_level)
    masker.fit()

    if confounds is not None:
        confounds_ = np.loadtxt(confounds)
    else:
        confounds_ = None

    func_img = nib.load(func)

    if duration is not None:
        # how many slices to keep
        n_slices = int(duration / TR)
        func_img = func_img.slicer[:, :, :, :n_slices]

        if confounds_ is not None:
            confounds_ = confounds_[:n_slices, :]

    return masker.transform(func_img, confounds=confounds_)
Ejemplo n.º 12
0
def extract_timeseries(func,
                       atlas=fetch_atlas_basc_multiscale_2015().scale064,
                       confounds=None,
                       memory=None,
                       memory_level=1):
    """Extract time series for a list of functional volume.

    Parameters
    ----------
    func : str,
        Path of Nifti volumes.

    atlas : str or 3D/4D Niimg-like object, (default=BASC64)
        The atlas to use to create the masker. If string, it should corresponds
        to the path of a Nifti image.

    confounds : str,
        Path containing the confounds.

    memory : instance of joblib.Memory or string, (default=None)
        Used to cache the masking process. By default, no caching is done. If a
        string is given, it is the path to the caching directory.

    memory_level : integer, optional (default=1)
        Rough estimator of the amount of memory used by caching. Higher value
        means more memory for caching.

    n_jobs : integer, optional (default=1)
        Used to process several patients in parallel.
        If -1, then the number of jobs is set to the number of
        cores.

    """

    masker = make_masker_from_atlas(atlas,
                                    memory=memory,
                                    memory_level=memory_level)
    masker.fit()

    if confounds is not None:
        confounds_ = np.loadtxt(confounds)
    else:
        confounds_ = None

    return masker.transform(func, confounds=confounds_)
Ejemplo n.º 13
0
def parcelation(filename):
    from nilearn import plotting
    from nilearn import datasets
    parcellations = datasets.fetch_atlas_basc_multiscale_2015(version='sym')
    networks_64 = parcellations['scale064']
    networks_197 = parcellations['scale197']
    networks_444 = parcellations['scale444']
    x0, y0 = 580, 300
    img = nib.load(filename)
    data_orig = img.get_fdata()[..., 1]  #misc.face()
    print(data_orig.shape)
    fig, axes = plt.subplots(1, 2)
    axes[0].imshow(data_orig)
    axes[0].scatter(x0, y0, c="r")
    axes[0].set_title("original")
    data_rot, (x1, y1) = rot(data_orig, np.array([x0, y0]), 66)
    axes.flatten()[1].imshow(data_rot)
    axes.flatten()[1].scatter(x1, y1, c="r")
    axes.flatten()[1].set_title("Rotation: {}deg".format(66))
    plt.show()
    plotting.plot_roi(img, cmap=plotting.cm.bwr_r, title='yale imaging')
    plotting.show()
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
def fetch_resample_basc(mask, scale="444"):
    from nilearn.datasets import fetch_atlas_basc_multiscale_2015
    from nilearn.image import resample_to_img
    basc = fetch_atlas_basc_multiscale_2015()['scale{}'.format(scale)]
    resampled_basc = resample_to_img(basc, mask, interpolation='nearest')
    return resampled_basc
from nilearn.datasets import fetch_atlas_basc_multiscale_2015

import joblib
from joblib import Parallel, delayed, Memory

# path to the Cam-CAN data set
STORAGE_HOME = '/storage/tompouce/okozynet/camcan'
CAMCAN_PREPROCESSED = '/storage/data/camcan/camcan_preproc'
CAMCAN_PATIENTS_EXCLUDED = join(STORAGE_HOME, 'excluded_patients.csv')
CAMCAN_TIMESERIES = join(STORAGE_HOME, 'timeseries')
# path to the atlases
# modl atlas from task-fMRI was used
ATLASES = [
    '/storage/store/derivatives/OpenNeuro/modl/256/0.0001/maps.nii.gz',
    fetch_atlas_basc_multiscale_2015().scale197
]
ATLASES_DESCR = ['modl256', 'basc197']
# path for the caching
CACHE_TIMESERIES = join(STORAGE_HOME, 'cache/timeseries')
if not os.path.exists(CACHE_TIMESERIES):
    os.makedirs(CACHE_TIMESERIES)
MEMORY = Memory(CACHE_TIMESERIES)

N_JOBS = 10

dataset = load_camcan_rest(data_dir=CAMCAN_PREPROCESSED,
                           patients_excluded=CAMCAN_PATIENTS_EXCLUDED)
for atlas, atlas_descr in zip(ATLASES, ATLASES_DESCR):

    time_series = Parallel(n_jobs=N_JOBS, verbose=1)(
Ejemplo n.º 17
0
from nilearn import datasets
from nilearn import image
import nibabel as nib
import nympy as np
import pickle as pkl


basc = datasets.fetch_atlas_basc_multiscale_2015()
basc444 = nib.load(basc.scale444)

yeo = datasets.fetch_atlas_yeo_2011()
yeo7 = nib.load(yeo.thick_7)

template = datasets.load_mni152_template()
basc_re = image.resample_to_img(basc444, template, interpolation='nearest')
yeo_re = image.resample_to_img(yeo7, template, interpolation='nearest')


yeo_data = yeo_re.get_fdata()[:,:,:,0]
basc_data = basc_re.get_fdata()




inde = []
for i in range(1,445):
    li = list(np.unique(yeo_data[basc_data == i]))
    nu = [len(np.argwhere(yeo_data[basc_data == i] == j)) for j in li]
    inde.append(li[nu.index(max(nu))])

inde = np.array(inde)
Ejemplo n.º 18
0
import os.path
import scipy.io as sio 

suj=89
meas=20

# Load Conditions file
eventname='F:/sim/event_sim.csv'
label=np.array(np.recfromcsv(eventname,names='s'))['s']
# Create session file
rest_mask = label == b'Rest'


# Prepare masker & Correct affine
template = load_mni152_template()
basc = datasets.fetch_atlas_basc_multiscale_2015(version='sym')['scale444']
orig_filename='F:/sim/template/restbaseline.nii.gz'
orig_img= image.load_img(orig_filename)
brainmask = load_mni152_brain_mask()
mem = Memory('nilearn_cache')
masker = NiftiLabelsMasker(labels_img = basc, mask_img = brainmask, 
                           memory=mem, memory_level=1, verbose=0,
                           detrend=False, standardize=False,  
                           high_pass=0.01,t_r=2,
                           resampling_target='labels')
masker.fit()

# Prep Classification
   
for s in np.arange(84,89):#range(suj):#
    for n in range(meas):
Ejemplo n.º 19
0
def copy_atlas():
    if not os.path.exists(ATLAS_DIR):
        os.makedirs(ATLAS_DIR)
    atlas_filename = datasets.fetch_atlas_basc_multiscale_2015().scale122
    shutil.copy(atlas_filename, os.path.join(ATLAS_DIR, ATLAS_FILENAME))
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
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
func_imgs = data_store[name].func
phenotypic = data_store[name].phenotypic
motion_confounds = data_store[name].motion_param
connectome_regress_confounds = None

from utils import data_info

shape, affine, _ = data_info(func_imgs[0])

###########################################################################
# Predefined Atlases
# ------------------
# Fetch the atlas
from nilearn import datasets as nidatasets

basc = nidatasets.fetch_atlas_basc_multiscale_2015()

# Define atlases for LearnBrainRegions object as dict()
atlases = dict()

from region_extractor import connected_label_regions
relabelled_basc_36 = connected_label_regions(basc['scale036'],
                                             min_size=1500)
atlases['basc'] = relabelled_basc_36
###########################################################################
# Masker
# ------
# Masking the data

from nilearn import datasets
This example shows how to download and fetch brain parcellations of
multiple networks using :func:`nilearn.datasets.fetch_atlas_basc_multiscale_2015`
and visualize them using plotting function :func:`nilearn.plotting.plot_roi`.

We show here only three different networks of 'symmetric' version. For more
details about different versions and different networks, please refer to its
documentation.
"""

###############################################################################
# Fetching multiscale group brain parcellations

# import datasets module and use `fetch_atlas_basc_multiscale_2015` function
from nilearn import datasets

parcellations = datasets.fetch_atlas_basc_multiscale_2015(version='sym')

# We show here networks of 64, 197, 444
networks_64 = parcellations['scale064']
networks_197 = parcellations['scale197']
networks_444 = parcellations['scale444']

###############################################################################
# Visualizing brain parcellations

# import plotting module and use `plot_roi` function, since the maps are in 3D
from nilearn import plotting

# The coordinates of all plots are selected automatically by itself
# We manually change the colormap of our choice
plotting.plot_roi(networks_64, cmap=plotting.cm.bwr,
from nilearn.datasets import (fetch_atlas_basc_multiscale_2015,
                              fetch_atlas_msdl)

import joblib
from joblib import Parallel, delayed, Memory

# path to the Cam-CAN data set
CAMCAN_PREPROCESSED = '/home/mehdi/data/camcan/camcan_preproc'
CAMCAN_PATIENTS_EXCLUDED = '/home/mehdi/data/camcan/camcan_preproc/'\
                           'excluded_subjects.csv'
CAMCAN_TIMESERIES = '/home/mehdi/data/camcan/camcan_timeseries'
# path to the atlases
ATLASES = [
    fetch_atlas_msdl().maps,
    fetch_atlas_basc_multiscale_2015().scale064,
    fetch_atlas_basc_multiscale_2015().scale122,
    fetch_atlas_basc_multiscale_2015().scale197
]
ATLASES_DESCR = ['msdl', 'basc064', 'basc122', 'basc197']
# path for the caching
CACHE_TIMESERIES = '/home/mehdi/data/camcan/cache/timeseries'
if not os.path.exists(CACHE_TIMESERIES):
    os.makedirs(CACHE_TIMESERIES)
MEMORY = Memory(CACHE_TIMESERIES)

N_JOBS = 20

dataset = load_camcan_rest(data_dir=CAMCAN_PREPROCESSED,
                           patients_excluded=CAMCAN_PATIENTS_EXCLUDED)
for atlas, atlas_descr in zip(ATLASES, ATLASES_DESCR):
Ejemplo n.º 25
0
# documentation.
# 
# 

# Retrieving multiscale group brain parcellations
# -----------------------------------------------
# 
# 

# In[2]:


# import datasets module and use `fetch_atlas_basc_multiscale_2015` function
from nilearn import datasets

parcellations = datasets.fetch_atlas_basc_multiscale_2015(version='sym')

# We show here networks of 64, 122, 197
networks_64 = parcellations['scale064']
networks_122 = parcellations['scale122']
networks_197 = parcellations['scale197']


# Visualizing brain parcellations
# -------------------------------
# 
# 

# In[3]:

    groups=np.append(groups,np.ones(len(y_foot))*i)
    
# CROSS MODAL CLASSIFICATION (cross-validated)
#n_p=0
#result_cv_tr_foot,permutation_scores_tr_foot, p_foot=permutation_score(pipeline,roi_foot_all,roi_hand_all,y_foot_all,groups,logo,n_p) 
#print('Train FOOT - IMAG VS STIM',np.array(result_cv_tr_foot).mean(),p_foot)
#result_cv_tr_hand,permutation_scores_tr_hand, p_hand=permutation_score(pipeline,roi_hand_all,roi_foot_all,y_hand_all,groups,logo,n_p)
#print('Train HAND - IMAG VS STIM',np.array(result_cv_tr_hand).mean(),p_hand)
#result_cv_tr_imag,permutation_scores_tr_imag, p_imag=permutation_score(pipeline,roi_imag_all,roi_stim_all,y_imag_all,groups,logo,n_p)   
#print('Train IMAG - HAND VS FOOT',np.array(result_cv_tr_imag).mean(),p_imag)
#result_cv_tr_stim,permutation_scores_tr_stim, p_stim=permutation_score(pipeline,roi_stim_all,roi_imag_all,y_stim_all,groups,logo,n_p)
#print('Train STIM - HAND VS FOOT',np.array(result_cv_tr_stim).mean(),p_stim)


# Prepare ploting
basc = datasets.fetch_atlas_basc_multiscale_2015(version='asym')['scale444']
brainmask = load_mni152_brain_mask()
masker = NiftiLabelsMasker(labels_img = basc, mask_img = brainmask, 
                           memory_level=1, verbose=0,
                           detrend=True, standardize=False,  
                           high_pass=0.01,t_r=2.28,
                           resampling_target='labels'
                           )
masker.fit()

pipeline.fit(roi_foot_all,y_foot_all)
coef_foot = pipeline.named_steps['svm'].coef_
weight_f = masker.inverse_transform(coef_foot)
plot_stat_map(weight_f, title='Train Imp',display_mode='z',cmap='bwr',threshold=0.4)