Beispiel #1
0
    def test_002(self):
        from roistats import collect
        from nilearn import plotting as nip
        from nilearn import image
        from nilearn import datasets
        from roistats import atlases, plotting
        import random
        import numpy as np
        import pandas as pd

        atlas = datasets.load_mni152_brain_mask()
        atlas_fp = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr50-2mm')['maps']
        try:
            labels = atlases.labels('HarvardOxford-Cortical.xml')
        except Exception:
            from nilearn import datasets

            name = 'cort-maxprob-thr50-2mm'
            labels = datasets.fetch_atlas_harvard_oxford(name)['labels']

            # Store them in a dict
            labels = dict(enumerate(labels))
        print(atlas_fp)

        images = []
        for i in range(0, 50):
            d = np.random.rand(*atlas.dataobj.shape) * atlas.dataobj
            im = image.new_img_like(atlas, d)
            im = image.smooth_img(im, 5)
            _, f = tempfile.mkstemp(suffix='.nii.gz')
            im.to_filename(f)
            images.append(f)

        for each in images[:3]:
            nip.plot_roi(atlas_fp, bg_img=each)

        df = collect.roistats_from_maps(images, atlas_fp, subjects=None)
        df = df.rename(columns=labels)

        df['group'] = df.index
        df['age'] = df.apply(lambda row: random.random()*5+50, axis=1)
        df['group'] = df.apply(lambda row: row['group'] < len(df)/2, axis=1)
        df['index'] = df.index

        plotting.boxplot('Temporal Pole', df, covariates=['age'], by='group')

        _ = plotting.lmplot('Temporal Pole', 'age', df, covariates=[],
                            hue='group', palette='default')

        cov = df[['age', 'group']]
        melt = pd.melt(df, id_vars='index', value_vars=labels.values(),
                       var_name='region').set_index('index')
        melt = melt.join(cov)
        plotting.hist(melt, by='group', region_colname='region',
                      covariates=['age'])

        print('Removing images')
        import os
        for e in images:
            os.unlink(e)
Beispiel #2
0
def test_fail_fetch_atlas_harvard_oxford():
    # specify non-existing atlas item
    assert_raises_regex(ValueError, 'Invalid atlas name',
                        datasets.fetch_atlas_harvard_oxford, 'not_inside')

    # specify existing atlas item
    target_atlas = 'cort-maxprob-thr0-1mm'
    target_atlas_fname = 'HarvardOxford-' + target_atlas + '.nii.gz'

    HO_dir = os.path.join(tmpdir, 'fsl', 'data', 'atlases')
    os.makedirs(HO_dir)
    nifti_dir = os.path.join(HO_dir, 'HarvardOxford')
    os.makedirs(nifti_dir)

    target_atlas_nii = os.path.join(nifti_dir, target_atlas_fname)
    datasets.load_mni152_template().to_filename(target_atlas_nii)

    dummy = open(os.path.join(HO_dir, 'HarvardOxford-Cortical.xml'), 'w')
    dummy.write("<?xml version='1.0' encoding='us-ascii'?> "
                "<metadata>"
                "</metadata>")
    dummy.close()

    ho = datasets.fetch_atlas_harvard_oxford(target_atlas, data_dir=tmpdir)

    assert_true(isinstance(nibabel.load(ho.maps), nibabel.Nifti1Image))
    assert_true(isinstance(ho.labels, np.ndarray))
    assert_true(len(ho.labels) > 0)
Beispiel #3
0
    def _run_interface(self, runtime):

        from nilearn import datasets
        from nilearn.input_data import NiftiLabelsMasker
        import numpy as np

        dataset = datasets.fetch_atlas_harvard_oxford(
            self.inputs.atlas_identifier)
        atlas_filename = dataset.maps

        masker = NiftiLabelsMasker(labels_img=atlas_filename,
                                   standardize=True,
                                   detrend=True,
                                   low_pass=0.1,
                                   high_pass=0.01,
                                   t_r=self.inputs.tr,
                                   memory='nilearn_cache',
                                   verbose=0)

        #file_labels = open('/home/brainlab/Desktop/Rudas/Data/Parcellation/AAL from Freesourfer/fs_default.txt', 'r')
        #labels = []
        #for line in file_labels.readlines():
        #labels.append(line)
        #file_labels.close()

        time_series = masker.fit_transform(
            self.inputs.in_file, confounds=self.inputs.confounds_file)

        np.savetxt(self.inputs.time_series_out_file,
                   time_series,
                   fmt='%10.2f',
                   delimiter=',')

        if self.inputs.plot:
            from nilearn import plotting
            from nilearn.connectome import ConnectivityMeasure
            import matplotlib
            import matplotlib.pyplot as plt
            fig, ax = matplotlib.pyplot.subplots()

            font = {'family': 'normal', 'size': 5}

            matplotlib.rc('font', **font)

            correlation_measure = ConnectivityMeasure(kind='correlation')
            correlation_matrix = correlation_measure.fit_transform(
                [time_series])[0]

            # Mask the main diagonal for visualization:
            np.fill_diagonal(correlation_matrix, 0)
            plotting.plot_matrix(correlation_matrix,
                                 figure=fig,
                                 labels=dataset.labels[1:],
                                 vmax=0.8,
                                 vmin=-0.8,
                                 reorder=True)

            fig.savefig(self.inputs.correlation_matrix_out_file, dpi=1200)

        return runtime
Beispiel #4
0
def plot_roi(data, file_name):
    dataset = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm')
    atlas_filename = dataset.maps
    print('Atlas ROIs are located at: %s' % atlas_filename)
    plotting.plot_roi(atlas_filename, title="harvard oxford altas")
    plotting.show()
    return
Beispiel #5
0
def test_fail_fetch_atlas_harvard_oxford():
    # specify non-existing atlas item
    assert_raises_regex(ValueError, 'Invalid atlas name',
                        datasets.fetch_atlas_harvard_oxford, 'not_inside')

    # specify existing atlas item
    target_atlas = 'cort-maxprob-thr0-1mm'
    target_atlas_fname = 'HarvardOxford-' + target_atlas + '.nii.gz'

    HO_dir = os.path.join(tmpdir, 'fsl', 'data', 'atlases')
    os.makedirs(HO_dir)
    nifti_dir = os.path.join(HO_dir, 'HarvardOxford')
    os.makedirs(nifti_dir)

    target_atlas_nii = os.path.join(nifti_dir, target_atlas_fname)
    datasets.load_mni152_template().to_filename(target_atlas_nii)

    dummy = open(os.path.join(HO_dir, 'HarvardOxford-Cortical.xml'), 'w')
    dummy.write("<?xml version='1.0' encoding='us-ascii'?> "
                "<metadata>"
                "</metadata>")
    dummy.close()

    ho = datasets.fetch_atlas_harvard_oxford(target_atlas, data_dir=tmpdir)

    assert_true(isinstance(nibabel.load(ho.maps), nibabel.Nifti1Image))
    assert_true(isinstance(ho.labels, np.ndarray))
    assert_true(len(ho.labels) > 0)
Beispiel #6
0
    def _load_4D_func(self, args):

        if args['atlas'] == 'aal':

            aal = fetch_atlas_aal()
            aal = {'file': aal.maps}
            atlas_filename = aal['file']
        else:
            harvard_oxford = fetch_atlas_harvard_oxford(
                'cort-maxprob-thr25-2mm')
            harvard_oxford = {'file': harvard_oxford.maps}
            atlas_filename = harvard_oxford['file']

        data = Parallel(n_jobs=args['n_cores'])(delayed(
            _parallelize_4D_func_loading)(f, atlas_filename, args['method'])
                                                for f in args['paths'])

        # Load last func for some meta-data
        data = np.concatenate(data, axis=0)

        func = nib.load(args['paths'][0])
        self.voxel_idx.append(np.arange(data.shape[1]))
        self.affine.append(func.affine)
        self.data_shape.append(func.shape)
        feature_ids = np.ones(data.shape[1], dtype=np.uint32) * len(self.X)
        self.featureset_id.append(feature_ids)
        self.X.append(data)
def get_R_roi(ROI, R):
    from nilearn.datasets import fetch_atlas_harvard_oxford
    if ROI == 'Frontal Orbital Cortex':  #Cortical atlas for Frontorbital cortex
        ho_atlas = fetch_atlas_harvard_oxford('cort-maxprob-thr50-2mm')
    else:  #Subortical atlas for left and right accumbens
        ho_atlas = fetch_atlas_harvard_oxford('sub-maxprob-thr50-2mm')

    #Define ROI, incl resampling
    ho_map = nib.load(ho_atlas['maps'])
    f_ROI_indx = ho_atlas['labels'].index(ROI)
    ho_map_resamp = image.resample_to_img(ho_map, R, interpolation='nearest')
    f_ROI_bool = ho_map_resamp.get_fdata() == f_ROI_indx
    f_ROI_roi = nib.Nifti1Image(f_ROI_bool.astype(int),
                                affine=ho_map_resamp.affine)
    R_roi = masking.apply_mask(R, f_ROI_roi)
    return R_roi
Beispiel #8
0
def roi_mean(roi_file,
             data_file,
             roi_labels=[3, 14, 9, 19, 8, 18, 5, 16, 4, 15],
             out_file="mean_tsnr.tsv"):
    """
    Calculate Mean of datafile for given ROI.
    
    Parameters
    ---------
    roi_file: str
        Filename of Atlas/Roi_File (nifti)
    data_file: str
        Filename of data to calculate mean
    roi_labesl: list of int
        Select label of roi_file (default: 1)

    out_file: str
        Filename to write tsv-formatted output to        

    Return
    ------
    float: mean of roi
    float: std of roi
    """
    import pdb
    import numpy as np
    import nibabel as nib
    from os.path import abspath
    from nilearn import datasets
    dataset_cort = datasets.fetch_atlas_harvard_oxford(
        'cort-maxprob-thr25-2mm')

    print("Calculationg Means")
    print(data_file)
    print(roi_file)
    data = nib.load(data_file).get_data()
    roi = nib.load(roi_file).get_data()

    if (data.shape != roi.shape):
        raise ValueError("Image-shapes do not match")

    if roi_labels is None:
        roi_labels = np.unique(roi)

    mean_vals = []
    for roi_label in roi_labels:
        mean_vals.append([
            roi_label,
            np.mean(data[roi == roi_label]),
            np.std(data[roi == roi_label])
        ])

    print(mean_vals)

    fname = abspath(out_file)
    np.savetxt(fname, mean_vals, delimiter='\t')

    return fname
Beispiel #9
0
def coordinate_label(mni_coord, atlas='aal', thresh=None, ret_proba=False):

    if atlas == 'aal':
        atl = datasets.fetch_atlas_aal()
        atl.prob = False
    elif atlas == 'harvard_oxford':
        atl = datasets.fetch_atlas_harvard_oxford('cort-prob-2mm')
        atl.prob = True

    elif atlas == 'destrieux':
        atl = datasets.fetch_atlas_destrieux_2009()
        atl.indices = atl.labels['index']
        atl.labels = atl.labels['name']
        atl.prob = False

    atl_map = load_img(atl.maps)
    atl_aff = atl_map.affine

    if atl.prob == True:
        atl_labels = atl.labels
    if atl.prob == False:
        atl_labels = atl.labels
        atl_indices = atl.indices

    labels_out = list()

    for coord in mni_coord:

        mat_coord = np.asarray(resampling.coord_transform(
            coord[0], coord[1], coord[2], np.linalg.inv(atl_aff)),
                               dtype=int)

        if atl.prob == True and ret_proba == True:

            lab_out = get_prob_atlas_label(atl_map,
                                           atl_labels,
                                           mat_coord,
                                           thresh=thresh)

        elif atl.prob == True and ret_proba == False:

            lab_out, _ = get_prob_atlas_label(atl_map,
                                              atl_labels,
                                              mat_coord,
                                              thresh=thresh)

        elif atl.prob == False:

            lab_out = get_atlas_label(atl_map, atl_labels, atl_indices,
                                      mat_coord)

        labels_out.append(lab_out)

    return labels_out
Beispiel #10
0
    def extract_label_rois(self, nifti_image):
        """Extract the 2D ROIs from 4D BOLD image using atlas labels get from nilearn"""

        atlas = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm')
        # get filename containing atlas info
        atlas_filename = atlas.maps
        # Create a masker object to extract signal on the parcellation
        masker = input_data.NiftiLabelsMasker(labels_img=atlas_filename)
        # Turned the Nifti data to time-series where each column is a ROI
        rois_ts = masker.fit_transform(nifti_image)

        return atlas.labels, rois_ts
Beispiel #11
0
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
Beispiel #12
0
def get_atlas_data(map):
    """
    This function takes a map from the HarvardOxford atlas and turns it into a mask we can apply to the NiFTi volumes
    :param map: the map in the HarvardOxford atlas to use
    :return: (NiftiLabelsMasker) a masker object
    """

    atlas = datasets.fetch_atlas_harvard_oxford(map)  # Retrieve the map from nilearn's datasets module
    map = atlas.maps  # Retrieve the maps from the atlas object

    masker = input_data.NiftiLabelsMasker(labels_img=map, standardize=True,
                                          memory='nilearn_cache')  # Turn it into a mask that we can apply

    return masker  # Return it
Beispiel #13
0
def get_atlas(name):
    if name == "destrieux_2009":
        atlas = datasets.fetch_atlas_destrieux_2009()
        atlas_filename = atlas['maps']
    elif name == "harvard_oxford":
        atlas = datasets.fetch_atlas_harvard_oxford("cort-maxprob-thr25-2mm")
        atlas_filename = atlas['maps']
    elif name == "aal":
        atlas = datasets.fetch_atlas_aal()
        atlas_filename = atlas['maps']
    elif name == "smith_2009":
        atlas = datasets.fetch_atlas_smith_2009()
        atlas_filename = atlas['rsn70']
    else:
        raise ValueError('Atlas name unkown')
    return atlas_filename
Beispiel #14
0
def pcc_mask(tmp_path_factory):
    tmp_path = tmp_path_factory.mktemp(basename="pcc_mask")

    os.chdir(str(tmp_path))

    atlas_img = nib.load(fetch_atlas_harvard_oxford("cort-prob-2mm")["maps"])
    atlas = atlas_img.get_fdata()

    pcc_mask = atlas[..., 29] > 10

    pcc_mask_img = new_img_like(atlas_img, pcc_mask, copy_header=True)

    pcc_mask_fname = Path.cwd() / "pcc.nii.gz"
    nib.save(pcc_mask_img, pcc_mask_fname)

    return pcc_mask_fname
Beispiel #15
0
def get_ROI_labels(coords, tol=cfg.ROITolerance):
    """Argument:
    - coords: (N, [x, y, z])

    Returns:
    - ROIs (N)
    """

    # load atlas
    from nilearn import datasets, image

    atlas = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm',
                                                symmetric_split=True)

    labels = atlas['labels']
    atlas_map = image.load_img(atlas['maps'])

    affine = atlas_map.affine[:3, :3]
    translation = atlas_map.affine[:3, 3]
    ROIs = []

    for coord in coords:
        data_coords = np.matmul(np.linalg.inv(affine),
                                np.array(coord) - translation)
        a, b, c = np.apply_along_axis(lambda x: np.round(x, 0), 0,
                                      data_coords).astype(int)
        index = atlas_map.get_data()[a, b, c]
        roi = ''.join([s[0] for s in labels[index].split()
                       if s[0].isalnum()])  # label acronyms
        ROIs.append(roi)

    ROIs = np.array(ROIs)
    if tol > 0:
        j = np.where(ROIs != 'B')[0]
        distances = distance_matrix(coords, coords)
        np.fill_diagonal(distances, distances.max())
        mfnd = np.median(
            distances.min(axis=-1))  # median first neightbor distance
        for i in np.where(ROIs == 'B')[0]:
            fn = distances[
                i, j].argmin()  # first neighbor in known region (idexed wrt j)
            if distances[i, j[fn]] < tol * mfnd: ROIs[i] = ROIs[j[fn]]

    ROIs = [cfg.replacements.get(x, x) for x in ROIs]

    return ROIs
def get_atlas(atlas_name, verbose=False):
    """
    Get atlas from nilearn.
    Atlases are currently only HarvardOxford and AAL
    """

    if atlas_name == "HarvardOxford":
        dataset = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm')
    elif atlas_name == "AAL":
        dataset = datasets.fetch_atlas_aal()

    atlas_filename = dataset.maps
    labels = dataset.labels

    if verbose:
        print('Atlas ROIs are located in nifti image (4D) at: %s' %
              atlas_filename)  # 4D data

    return ((atlas_filename, labels))
Beispiel #17
0
 def __init__(self,
              atlas_name="enumerate(('cort-maxprob-thr0-1mm', \
                                           'cort-maxprob-thr0-2mm', \
                                           'cort-maxprob-thr25-1mm', \
                                           'cort-maxprob-thr25-2mm', \
                                           'cort-maxprob-thr50-1mm', \
                                           'cort-maxprob-thr50-2mm', \
                                           'sub-maxprob-thr0-1mm', \
                                           'sub-maxprob-thr0-2mm', \
                                           'sub-maxprob-thr25-1mm', \
                                           'sub-maxprob-thr25-2mm', \
                                           'sub-maxprob-thr50-1mm', \
                                           'sub-maxprob-thr50-2mm', \
                                           'cort-prob-1mm', \
                                           'cort-prob-2mm', \
                                           'sub-prob-1mm', \
                                           'sub-prob-2mm'))",
              **options):
     from nilearn import datasets
     self.dataset = datasets.fetch_atlas_harvard_oxford(
         atlas_name, **options)
def get_established_parcellation(parcellation="Harvard_Oxford",
                                 target_img=None,
                                 parcellation_dir=None):
    if parcellation == "Harvard_Oxford":
        name = "Harvard_Oxford_cort-prob-2mm"
        data = datasets.fetch_atlas_harvard_oxford('cort-prob-2mm',
                                                   data_dir=parcellation_dir)
        parcel = nibabel.load(data['maps'])
        labels = data['labels'][1:]  # first label is background
        atlas_threshold = 25
    elif parcellation == "smith":
        name = "smith_rsn70"
        data = datasets.fetch_atlas_smith_2009(
            data_dir=parcellation_dir)['rsn70']
        parcel = nibabel.load(data)
        labels = range(parcel.shape[-1])
        atlas_threshold = 4
    elif parcellation == "glasser":
        glasser_dir = path.join(parcellation_dir, 'glasser')
        data = image.load_img(
            path.join(glasser_dir, 'HCP-MMP1_on_MNI152_ICBM2009a_nlin.nii.gz'))
        parcel = image.new_img_like(data, (data.get_fdata() + .01).astype(int))
        labels = list(
            np.genfromtxt(path.join(glasser_dir,
                                    'HCP-MMP1_on_MNI152_ICBM2009a_nlin.txt'),
                          dtype=str,
                          usecols=1))
        name = 'glasser'
        atlas_threshold = None
        # split down midline into lateralized ROIs
        data_coords = np.where(parcel.get_data())
        right_coords = *(i[data_coords[0] > parcel.shape[0] // 2]
                         for i in data_coords),  # tuple comprehension
        parcel.get_data()[right_coords] += len(labels)
        labels = labels + [l.replace('L_', 'R_') for l in labels]
    if target_img:
        parcel = image.resample_to_img(parcel,
                                       target_img,
                                       interpolation='nearest')
    return parcel, labels, name, atlas_threshold
Beispiel #19
0
def fetch_atlases(atlas_names):
    """Fetch atlases provided by name(s)

    Parameters
    ----------
    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']

    Returns
    -------
    data : dict
        Bunch of atlases
    """
    data = {}
    atlas_names = _check_atlases(atlas_names)
    for atlas_name in atlas_names:
        if atlas_name == 'harvard_oxford':
            name = 'cort-maxprob-thr25-2mm'
            data[atlas_name] = datasets.fetch_atlas_harvard_oxford(name)
        elif atlas_name == 'destrieux':
            data[atlas_name] = datasets.fetch_atlas_destrieux_2009()
        elif atlas_name == 'diedrichsen':
            data[atlas_name] = _fetch_atlas_diedrichsen('maxprob-thr25-2mm')
        elif atlas_name == 'juelich':
            data[atlas_name] = _fetch_atlas_juelich('maxprob-thr25-2mm')
        elif atlas_name == 'jhu':
            data[atlas_name] = _fetch_atlas_jhu('labels-2mm')
        elif atlas_name == 'mist':
            data[atlas_name] = fetch_mist()
        elif atlas_name in ['yeo_networks7', 'yeo_networks17']:
            data[atlas_name] = fetch_yeo(atlas_name)
        else:
            raise ValueError("Not a valid atlas. Given atlas is exhausted")
    return data
Beispiel #20
0
from nimare.meta.cbma.ale import SCALE
from nimare.meta.cbma.mkda import MKDAChi2

###############################################################################
# Load Dataset
# -----------------------------------------------------------------------------
# We will assume that the Neurosynth database has already been downloaded and
# converted to a NiMARE dataset.
dset_file = "neurosynth_nimare_with_abstracts.pkl.gz"
dset = Dataset.load(dset_file)

###############################################################################
# Define a region of interest
# -----------------------------------------------------------------------------
# We'll use the right amygdala from the Harvard-Oxford atlas
atlas = datasets.fetch_atlas_harvard_oxford("sub-maxprob-thr50-2mm")
img = nib.load(atlas["maps"])

roi_idx = atlas["labels"].index("Right Amygdala")
img_vals = np.unique(img.get_fdata())
roi_val = img_vals[roi_idx]
roi_img = image.math_img(f"img1 == {roi_val}", img1=img)

###############################################################################
# Select studies with a reported coordinate in the ROI
# -----------------------------------------------------------------------------
roi_ids = dset.get_studies_by_mask(roi_img)
dset_sel = dset.slice(roi_ids)
print(f"{len(roi_ids)}/{len(dset.ids)} studies report at least one coordinate in the ROI")

###############################################################################
Beispiel #21
0
    print(np.shape(bold[task_name]))
    # Convert nans into zeros
    bold[task_name][np.isnan(bold[task_name])] = 0
    # compute the group assignment label
    n_subjs_this_task = np.shape(bold[task_name])[-1]
    n_subjs[task_name] = np.shape(bold[task_name])[-1]
    print('Data loaded: {} \t shape: {}'.format(task_name,
                                                np.shape(bold[task_name])))

# In[6]:

# parcels
from nilearn import image
from nilearn.image.image import mean_img
from nilearn.image import resample_to_img
atlas = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm',
                                            symmetric_split=True)
i = np.eye(3) * 3
atlas.maps = image.resample_img(atlas.maps,
                                target_affine=i,
                                interpolation='nearest')
if ipynby == 1:
    plotting.plot_roi(atlas.maps, title='the harvard-oxford parcel')
nP = len(atlas.labels) - 1  # rm background region
print('number of parcels:\t {}'.format(nP))
masker_ho = NiftiLabelsMasker(labels_img=atlas.maps)
index = masker_ho.labels_img.dataobj
parcels = atlas.labels
parcels[51] = 'Left Juxtapositional Lobule Cortex'
parcels[52] = 'Right Juxtapositional Lobule Cortex'
template = load_mni152_template()
template = image.resample_img(template,
""" A simple example to show how this function works.
"""

####################################################################
# Grab atlas from Nilearn

from nilearn import datasets

atlas_name = 'cort-maxprob-thr0-1mm'
harvard = datasets.fetch_atlas_harvard_oxford(atlas_name=atlas_name)

#####################################################################
# Required inputs for function find_region_names_using_cut_coords

dmn_coords = [(0, -52, 18), (-46, -68, 32), (46, -68, 32), (1, 50, -5)]
atlas_img = harvard.maps
labels = harvard.labels

######################################################################
# Grab function

from nilearn_utils import find_region_names_using_cut_coords

l, n = find_region_names_using_cut_coords(dmn_coords, atlas_img,
                                          labels=labels)

# where 'l' indicates new labels generated according to given atlas labels and
# coordinates
new_labels = l

# where 'n' indicates brain regions names labelled, generated according to given
Beispiel #23
0
from nilearn.datasets import fetch_atlas_harvard_oxford
from nilearn_sandbox.plotting.papaya import papaya_viewer


papaya_viewer(fetch_atlas_harvard_oxford('cort-prob-2mm').maps)
Beispiel #24
0
2. "filled_contours", maps are shown as contours same as above but with \
    fillings inside the contours.

3. "continuous", maps are shown as just color overlays.

The :func:`nilearn.plotting.plot_prob_atlas` function displays each map
with each different color which are picked randomly from the colormap
which is already defined.

See :ref:`plotting` for more information to know how to tune the parameters.
"""
# Load 4D probabilistic atlases
from nilearn import datasets

# Harvard Oxford Atlas
harvard_oxford = datasets.fetch_atlas_harvard_oxford('cort-prob-2mm')
harvard_oxford_sub = datasets.fetch_atlas_harvard_oxford('sub-prob-2mm')

# Multi Subject Dictionary Learning Atlas
msdl = datasets.fetch_atlas_msdl()

# Smith ICA Atlas and Brain Maps 2009
smith = datasets.fetch_atlas_smith_2009()

# ICBM tissue probability
icbm = datasets.fetch_icbm152_2009()

# Visualization
import matplotlib.pyplot as plt
from nilearn import plotting
Beispiel #25
0
weighted_stouffers_results = meta.fit(img_dset)

meta = nimare.meta.ibma.Fishers()
fishers_results = meta.fit(img_dset)

meta = nimare.meta.ibma.PermutedOLS()
ols_results = meta.fit(img_dset)

meta = nimare.meta.ibma.WeightedLeastSquares()
wls_results = meta.fit(img_dset)

meta = nimare.meta.ibma.Hedges()
hedges_results = meta.fit(img_dset)

# Use atlas for likelihood-based estimators
atlas = datasets.fetch_atlas_harvard_oxford("cort-maxprob-thr25-2mm")

# nilearn's NiftiLabelsMasker cannot handle NaNs at the moment,
# and some of the NIDM-Results packs' beta images have NaNs at the edge of the
# brain.
# So, we will create a reduced version of the atlas for this analysis.
nan_mask = image.math_img("~np.any(np.isnan(img), axis=3)",
                          img=img_dset.images["beta"].tolist())
nanmasked_atlas = image.math_img(
    "mask * atlas",
    mask=nan_mask,
    atlas=atlas["maps"],
)
masker = input_data.NiftiLabelsMasker(nanmasked_atlas)

meta = nimare.meta.ibma.VarianceBasedLikelihood(method="reml", mask=masker)
Beispiel #26
0
def get_atlas_rois(atlas, roi_idx, hemisphere, res=None, path=None):
    """
    Extract ROIs from a given atlas.

    Parameters
    ----------
    atlas : str
        Atlas dataset to be downloaded through nilearn's dataset_fetch_atlas functionality.
    roi_idx: list
        List of int of the ROI(s) you want to extract from the atlas. If not sure, use get_atlas_info.
    hemisphere: list
        List of str, that is hemispheres of the ROI(s) you want to extract. Can be ['left'], ['right'] or ['left', 'right'].
    res: str
        Specific version of atlas to be downloaded. Only necessary for Harvard-Oxford and Talairach.
        Please check nilearns respective documentation at
        https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_atlas_harvard_oxford.html or
        https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_atlas_talairach.html
    path: str
        Path to where the extracted ROI(s) will be saved to. If None, ROI(s) will be saved in the current
        working directory.

    Returns
    -------
    list_rois: list
        A list of the extracted ROIs.

    Examples
    --------
    >>> get_atlas_rois('aal', [1, 2, 3], ['left', 'right'], path='/home/urial/Desktop')
    list_rois
    """

    if atlas == 'aal':
        atl_ds = datasets.fetch_atlas_aal()

    elif atlas == 'harvard_oxford':
        if res is None:
            print(
                'Please provide the specific version of the Harvard-Oxford atlas you would like to use.'
            )
        else:
            atl_ds = datasets.fetch_atlas_harvard_oxford(res)

    elif atlas == 'destriuex':
        atl_ds = datasets.fetch_atlas_destrieux_2009()

    elif atlas == 'msdl':
        atl_ds = datasets.fetch_atlas_msdl()

    elif atlas == 'talairach':
        if res is None:
            print(
                'Please provide the level of the Talairach atlas you would like to use.'
            )
        else:
            atl_ds = datasets.fetch_atlas_talairach(level_name=res)

    elif atlas == 'pauli_2017':
        atl_ds = datasets.fetch_atlas_pauli_2017()

    if roi_idx is None:
        print('Please provide the indices of the ROIs you want to extract.')
    elif hemisphere is None:
        print(
            'Please provide the hemisphere(s) from which you want to extract ROIs.'
        )

    for label in roi_idx:
        for hemi in hemisphere:
            roi_ex = Node(PickAtlas(), name='roi_ex')
            roi_ex.inputs.atlas = atl_ds.maps
            roi_ex.inputs.labels = label
            roi_ex.inputs.hemi = hemi
            if path is None:
                roi_ex.inputs.output_file = '%s_%s_%s.nii.gz' % (
                    atlas, str(label), hemi)
                roi_ex.run()
                list_rois = glob('%s_*.nii.gz' % atlas)
            elif path:
                roi_ex.inputs.output_file = opj(
                    path, '%s_%s_%s.nii.gz' % (atlas, str(label), hemi))
                roi_ex.run()
                list_rois = glob(opj(path, '%s_*.nii.gz' % atlas))

    print('The following ROIs were extracted: ')
    print('\n'.join(map(str, list_rois)))

    return list_rois
Beispiel #27
0
def get_atlas_info(atlas, res=None):
    """
    Gather all information from a specified atlas, including the path to the atlas maps, as well as labels
    and their indexes.

    Parameters
    ----------
    atlas : str
        Atlas dataset to be downloaded through nilearn's dataset_fetch_atlas functionality.
    res: str
        Specific version of atlas to be downloaded. Only necessary for Harvard-Oxford and Talairach.
        Please check nilearns respective documentation at
        https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_atlas_harvard_oxford.html or
        https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_atlas_talairach.html

    Returns
    -------
    atlas_info_df : pandas dataframe
        A pandas dataframe containing information about the ROIs and their indexes included in a given atlas.
    atl_ds.maps : str
        Path to the atlas maps.

    Examples
    --------
    >>> get_atlas_info('aal')
    atlas_info_df
    atl_ds.maps
    """

    if atlas == 'aal':
        atl_ds = datasets.fetch_atlas_aal()

    elif atlas == 'harvard_oxford':
        if res is None:
            print(
                'Please provide the specific version of the Harvard-Oxford atlas you would like to use.'
            )
        else:
            atl_ds = datasets.fetch_atlas_harvard_oxford(res)

    elif atlas == 'destriuex':
        atl_ds = datasets.fetch_atlas_destrieux_2009()

    elif atlas == 'msdl':
        atl_ds = datasets.fetch_atlas_msdl()

    elif atlas == 'talairach':
        if res is None:
            print(
                'Please provide the level of the Talairach atlas you would like to use.'
            )
        else:
            atl_ds = datasets.fetch_atlas_talairach(level_name=res)

    elif atlas == 'pauli_2017':
        atl_ds = datasets.fetch_atlas_pauli_2017()

    index = []
    labels = []

    for ind, label in enumerate(atl_ds.labels):
        index.append(ind)
        if atlas == 'destriuex':
            labels.append(label[1])
        else:
            labels.append(label)

    atlas_info_df = pd.DataFrame({'index': index, 'label': labels})

    return atlas_info_df, atl_ds.maps
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

ho = nidatasets.fetch_atlas_harvard_oxford(atlas_name='cort-maxprob-thr25-2mm',
                                           symmetric_split=True)

atlas_img = ho.maps

# Define atlases for LearnBrainRegions object as dict()
atlases = dict()
atlases['harvard_oxford'] = atlas_img
###########################################################################
# Masker
# ------
# Masking the data

from nilearn import datasets

# Fetch grey matter mask from nilearn shipped with ICBM templates
gm_mask = datasets.fetch_icbm152_brain_gm_mask(threshold=0.2)
def load_atlas(name='cort-prob-2mm'):
    atlas = datasets.fetch_atlas_harvard_oxford(name)
    labels = atlas['labels']
    maps = nilearn.image.load_img(atlas['maps'])
    return maps, labels
Beispiel #30
0
def make_parcellation(data_path,
                      parcellation,
                      parc_type=None,
                      parc_params=None):
    """
    Performs a parcellation which reduces voxel space to regions of interest (brain data).

    Parameters
    ----------

    data_path : str
        Path to .nii image.
    parcellation : str
        Specify which parcellation that you would like to use. For MNI: 'gordon2014_333', 'power2012_264', For TAL: 'shen2013_278'.
        It is possible to add the OH subcotical atlas on top of a cortical atlas (e.g. gordon) by adding:
            '+sub-maxprob-thr0-1mm', '+sub-maxprob-thr0-2mm', 'sub-maxprob-thr25-1mm', 'sub-maxprob-thr25-2mm',
            '+sub-maxprob-thr50-1mm', '+sub-maxprob-thr50-2mm'.
            e.g.: gordon2014_333+submaxprob-thr0-2mm'
    parc_type : str
        Can be 'sphere' or 'region'. If nothing is specified, the default for that parcellation will be used.
    parc_params : dict
        **kwargs for nilearn functions

    Returns
    -------

    data : array
        Data after the parcellation.

    NOTE
    ----
    These functions make use of nilearn. Please cite nilearn if used in a publicaiton.
    """

    if isinstance(parcellation, str):

        if '+' in parcellation:
            parcin = parcellation.split('+')
            parcellation = parcin[0]
            subcortical = parcin[1]
        else:
            subcortical = None

        if not parc_type or not parc_params:
            path = teneto.__path__[
                0] + '/data/parcellation_defaults/defaults.json'
            with open(path) as data_file:
                defaults = json.load(data_file)
        if not parc_type:
            parc_type = defaults[parcellation]['type']
            print('Using default parcellation type')
        if not parc_params:
            parc_params = defaults[parcellation]['params']
            print('Using default parameters')

    if parc_type == 'sphere':
        parcellation = teneto.utils.load_parcellation_coords(parcellation)
        seed = NiftiSpheresMasker(np.array(parcellation), **parc_params)
        data = seed.fit_transform(data_path)
    elif parc_type == 'region':
        path = teneto.__path__[
            0] + '/data/parcellation/' + parcellation + '.nii'
        region = NiftiLabelsMasker(path, **parc_params)
        data = region.fit_transform(data_path)
    else:
        raise ValueError('Unknown parc_type specified')

    if subcortical:
        subatlas = fetch_atlas_harvard_oxford('sub-maxprob-thr0-2mm')['maps']
        region = NiftiLabelsMasker(subatlas, **parc_params)
        data_sub = region.fit_transform(data_path)
        data = np.hstack([data, data_sub])

    return data

######################################################################
# Atlases
# =======

destrieux = datasets.fetch_atlas_destrieux_2009()
plotting.view_img(destrieux['maps'],
                  resampling_interpolation='nearest',
                  cmap='gist_ncar', symmetric_cmap=False, colorbar=False)
plotting.plot_roi(destrieux['maps'])


######################################################################
# Harvard-Oxford probabilistic (4D) atlas
harvard_oxford = datasets.fetch_atlas_harvard_oxford('cort-prob-2mm')
plotting.plot_prob_atlas(harvard_oxford['maps'])


######################################################################
surf_destrieux = datasets.fetch_atlas_surf_destrieux()
fsaverage = datasets.fetch_surf_fsaverage()
plotting.view_surf(fsaverage['pial_left'], surf_destrieux['map_left'],
                   cmap='gist_ncar', colorbar=False)


######################################################################

# not needed with master
from nilearn import surface
fsaverage['sulc_left'] = surface.load_surf_data(fsaverage['sulc_left'])
def DownloadAAL3(PATH):
    import os
    from nilearn import datasets

    if os.path.isfile(PATH + '/AAL3_for_SPM12.tar.gz'):
        print('The atlas AAL3 has already been downloaded')
    else:
        os.system('wget https://www.oxcns.org/AAL3_for_SPM12.tar.gz -P ' +
                  PATH)

    if os.path.exists(PATH + '/AAL3'):
        print('The atlas AAL3 has already been unzipped')
    else:
        os.system('tar -zxvf ' + PATH + '/AAL3_for_SPM12.tar.gz -C ' + PATH)

    if os.path.exists(PATH + '/AAL3/AAL3.mat'):
        print('The atlas labels AAL have already been downloaded')
    else:
        os.system(
            'wget https://www.dropbox.com/s/eeullhxfv8tk6fg/AAL3.mat?dl=1 -P '
            + PATH + '/AAL3')
        os.system('mv ' + PATH + '/AAL3/AAL3.mat?dl=1 ' + PATH +
                  '/AAL3/AAL3.mat')

    ###################
    A_HOx = '/home/lxmera/nilearn_data/fsl/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr25-2mm.nii.gz'
    if os.path.isfile(A_HOx):
        print('The atlas Harvard-Oxford has already been downloaded')
    else:
        ###############################
        if os.path.exists('/home/lxmera'):
            datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm')
        else:
            print('####################################')
            print('#                                  #')
            print('#       CAMBIA EL USUARIO          #')
            print('#                                  #')
            print('####################################')

    mat2 = A_HOx[:A_HOx.rfind('/')] + '/labelsHof.mat'
    if os.path.isfile(mat2):
        print('The atlas labels Harvard-Oxford have already been downloaded')
    else:
        os.system(
            'wget https://www.dropbox.com/s/t0keqsapcbdl10b/labelsHof.mat?dl=1 -P '
            + A_HOx[:A_HOx.rfind('/')])
        os.system('mv ' + A_HOx[:A_HOx.rfind('/')] + '/labelsHof.mat?dl=1 ' +
                  A_HOx[:A_HOx.rfind('/')] + '/labelsHof.mat')

    A_MSDL = '/home/lxmera/nilearn_data/msdl_atlas/MSDL_rois/msdl_rois.nii'
    if os.path.isfile(A_MSDL):
        print('The atlas MSDL has already been downloaded')
    else:
        ###############################
        if os.path.exists('/home/lxmera'):
            datasets.fetch_atlas_msdl()
        else:
            print('####################################')
            print('#                                  #')
            print('#       CAMBIA EL USUARIO          #')
            print('#                                  #')
            print('####################################')

    mat3 = A_MSDL[:A_MSDL.rfind('/')] + '/labelsMSDL.mat'
    if os.path.isfile(mat3):
        print('The atlas labels MSDL have already been downloaded')
    else:
        os.system(
            'wget https://www.dropbox.com/s/j18tleliudcx2yn/labelsMSDL.mat?dl=1 -P '
            + A_MSDL[:A_MSDL.rfind('/')])
        os.system('mv ' + A_MSDL[:A_MSDL.rfind('/')] +
                  '/labelsMSDL.mat?dl=1 ' + A_MSDL[:A_MSDL.rfind('/')] +
                  '/labelsMSDL.mat')

    atlas = PATH + '/AAL3/AAL3.nii.gz'
    mat = PATH + '/AAL3/AAL3.mat'
    return atlas, mat, A_HOx, mat2, A_MSDL, mat3
Beispiel #33
0
    subjects = analysis_parameters['subjects']
    source = analysis_parameters['source']
    language = analysis_parameters['language']

    i = 0

    #paths.path2derivatives = '/Users/alexpsq/Code/NeuroSpin/LePetitPrince/derivatives' # to delete
    #paths.path2data = '/Users/alexpsq/Code/NeuroSpin/LePetitPrince/data'

    ###########################################################################
    ############################## Scatter plots ##############################
    ###########################################################################

    if 'scatter_plots' in args.analysis[0]:
        # retrieve default atlas  (= set of ROI)
        atlas = datasets.fetch_atlas_harvard_oxford(params.atlas)
        labels = atlas['labels']
        maps = nilearn.image.load_img(atlas['maps'])

        # extract data
        for index_mask in range(len(labels) - 1):
            mask = math_img('img > 50', img=index_img(maps, index_mask))
            masker = NiftiMasker(mask_img=mask,
                                 memory='nilearn_cache',
                                 verbose=5)
            masker.fit()
            for analysis in analysis_parameters['scatter_plots']:
                for subject in subjects:
                    subject = Subjects().get_subject(int(subject))
                    model1 = [
                        os.path.join(
Beispiel #34
0
from nilearn import datasets
from nilearn import image
ho = datasets.fetch_atlas_harvard_oxford('sub-prob-2mm',
                                         data_dir=None,
                                         symmetric_split=False,
                                         resume=True,
                                         verbose=1)

lables = [
    'Left Caudate', 'Right Caudate', 'Left Putamen', 'Right Putamen',
    'Left Thalamus', 'Right Thalamus', 'Left Accumbens', 'Right Accumbens',
    'Left Pallidum', 'Right Pallidum'
]

indexs = [ho.labels.index(i) - 1 for i in lables]

import nibabel as nib
img = nib.load(ho.maps)

ho_prob = img.get_fdata()

affine = img.affine
header = img.header

import numpy as np
at = np.zeros([91, 109, 91])

for i in indexs:
    tt = ho_prob[:, :, :, i]
    at[tt > 33] = i + 1
Beispiel #35
0
"""
Basic Atlas plotting
=======================

Plot the regions of a reference atlas (here the Harvard-Oxford atlas).
"""

##########################################################################
# Retrieving the atlas data
# -------------------------

from nilearn import datasets

dataset = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm')
atlas_filename = dataset.maps

print('Atlas ROIs are located at: %s' % atlas_filename)

###########################################################################
# Visualizing the Harvard-Oxford atlas
# ------------------------------------

from nilearn import plotting

plotting.plot_roi(atlas_filename, title="Harvard Oxford atlas")
plotting.show()
Beispiel #36
0
def make_parcellation(data_path, parcellation, parc_type=None, parc_params=None):
    """
    Performs a parcellation which reduces voxel space to regions of interest (brain data).

    Parameters
    ----------

    data_path : str
        Path to .nii image.
    parcellation : str
        Specify which parcellation that you would like to use. For MNI: 'gordon2014_333', 'power2012_264', For TAL: 'shen2013_278'.
        It is possible to add the OH subcotical atlas on top of a cortical atlas (e.g. gordon) by adding:
            '+OH' (for oxford harvard subcortical atlas) and '+SUIT' for SUIT cerebellar atlas.
            e.g.: gordon2014_333+OH+SUIT'
    parc_type : str
        Can be 'sphere' or 'region'. If nothing is specified, the default for that parcellation will be used.
    parc_params : dict
        **kwargs for nilearn functions

    Returns
    -------

    data : array
        Data after the parcellation.

    NOTE
    ----
    These functions make use of nilearn. Please cite nilearn if used in a publicaiton.
    """

    if isinstance(parcellation, str):
        parcin = ''
        if '+' in parcellation:
            parcin = parcellation
            parcellation = parcellation.split('+')[0]
        if '+OH' in parcin:
            subcortical = True
        else:
            subcortical = None
        if '+SUIT' in parcin:
            cerebellar = True
        else:
            cerebellar = None

        if not parc_type or not parc_params:
            path = tenetopath[0] + '/data/parcellation_defaults/defaults.json'
            with open(path) as data_file:
                defaults = json.load(data_file)
        if not parc_type:
            parc_type = defaults[parcellation]['type']
            print('Using default parcellation type')
        if not parc_params:
            parc_params = defaults[parcellation]['params']
            print('Using default parameters')

    if parc_type == 'sphere':
        parcellation = load_parcellation_coords(parcellation)
        seed = NiftiSpheresMasker(np.array(parcellation), **parc_params)
        data = seed.fit_transform(data_path)
    elif parc_type == 'region':
        path = tenetopath[0] + '/data/parcellation/' + parcellation + '.nii.gz'
        region = NiftiLabelsMasker(path, **parc_params)
        data = region.fit_transform(data_path)
    else:
        raise ValueError('Unknown parc_type specified')

    if subcortical:
        subatlas = fetch_atlas_harvard_oxford('sub-maxprob-thr0-2mm')['maps']
        region = NiftiLabelsMasker(subatlas, **parc_params)
        data_sub = region.fit_transform(data_path)
        data = np.hstack([data, data_sub])

    if cerebellar:
        path = tenetopath[0] + '/data/parcellation/Cerebellum-SUIT_space-MNI152NLin2009cAsym.nii.gz'
        region = NiftiLabelsMasker(path, **parc_params)
        data_cerebellar = region.fit_transform(data_path)
        data = np.hstack([data, data_cerebellar])

    return data