Пример #1
0
def get_template(space='mni152_1mm', mask=None):
    if space == 'mni152_1mm':
        if mask is None:
            img = nib.load(datasets.fetch_icbm152_2009()['t1'])
        elif mask == 'brain':
            img = nib.load(datasets.fetch_icbm152_2009()['mask'])
        elif mask == 'gm':
            img = datasets.fetch_icbm152_brain_gm_mask(threshold=0.2)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    elif space == 'mni152_2mm':
        if mask is None:
            img = datasets.load_mni152_template()
        elif mask == 'brain':
            img = datasets.load_mni152_brain_mask()
        elif mask == 'gm':
            # this approach seems to approximate the 0.2 thresholded
            # GM mask pretty well
            temp_img = datasets.load_mni152_template()
            data = temp_img.get_data()
            data = data * -1
            data[data != 0] += np.abs(np.min(data))
            data = (data > 1200).astype(int)
            img = nib.Nifti1Image(data, temp_img.affine)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    else:
        raise ValueError('Space {0} not supported'.format(space))
    return img
Пример #2
0
def get_template(space='mni152_1mm', mask=None):
    """
    Load template file.

    Parameters
    ----------
    space : {'mni152_1mm', 'mni152_2mm', 'ale_2mm'}, optional
        Template to load. Default is 'mni152_1mm'.
    mask : {None, 'brain', 'gm'}, optional
        Whether to return the raw template (None), a brain mask ('brain'), or
        a gray-matter mask ('gm'). Default is None.

    Returns
    -------
    img : :obj:`nibabel.nifti1.Nifti1Image`
        Template image object.
    """
    if space == 'mni152_1mm':
        if mask is None:
            img = nib.load(datasets.fetch_icbm152_2009()['t1'])
        elif mask == 'brain':
            img = nib.load(datasets.fetch_icbm152_2009()['mask'])
        elif mask == 'gm':
            img = datasets.fetch_icbm152_brain_gm_mask(threshold=0.2)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    elif space == 'mni152_2mm':
        if mask is None:
            img = datasets.load_mni152_template()
        elif mask == 'brain':
            img = datasets.load_mni152_brain_mask()
        elif mask == 'gm':
            # this approach seems to approximate the 0.2 thresholded
            # GM mask pretty well
            temp_img = datasets.load_mni152_template()
            data = temp_img.get_data()
            data = data * -1
            data[data != 0] += np.abs(np.min(data))
            data = (data > 1200).astype(int)
            img = nib.Nifti1Image(data, temp_img.affine)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    elif space == 'ale_2mm':
        if mask is None:
            img = datasets.load_mni152_template()
        else:
            # Not the same as the nilearn brain mask, but should correspond to
            # the default "more conservative" MNI152 mask in GingerALE.
            img = nib.load(
                op.join(get_resource_path(),
                        'templates/MNI152_2x2x2_brainmask.nii.gz'))
    else:
        raise ValueError('Space {0} not supported'.format(space))
    return img
Пример #3
0
def test_fetch_icbm152_2009():
    dataset = datasets.fetch_icbm152_2009(data_dir=tmpdir, verbose=0)
    assert_true(isinstance(dataset.csf, _basestring))
    assert_true(isinstance(dataset.eye_mask, _basestring))
    assert_true(isinstance(dataset.face_mask, _basestring))
    assert_true(isinstance(dataset.gm, _basestring))
    assert_true(isinstance(dataset.mask, _basestring))
    assert_true(isinstance(dataset.pd, _basestring))
    assert_true(isinstance(dataset.t1, _basestring))
    assert_true(isinstance(dataset.t2, _basestring))
    assert_true(isinstance(dataset.t2_relax, _basestring))
    assert_true(isinstance(dataset.wm, _basestring))
    assert_equal(len(url_request.urls), 1)
Пример #4
0
def test_fetch_icbm152_2009():
    dataset = datasets.fetch_icbm152_2009(data_dir=tmpdir, verbose=0)
    assert_true(isinstance(dataset.csf, _basestring))
    assert_true(isinstance(dataset.eye_mask, _basestring))
    assert_true(isinstance(dataset.face_mask, _basestring))
    assert_true(isinstance(dataset.gm, _basestring))
    assert_true(isinstance(dataset.mask, _basestring))
    assert_true(isinstance(dataset.pd, _basestring))
    assert_true(isinstance(dataset.t1, _basestring))
    assert_true(isinstance(dataset.t2, _basestring))
    assert_true(isinstance(dataset.t2_relax, _basestring))
    assert_true(isinstance(dataset.wm, _basestring))
    assert_equal(len(url_request.urls), 1)
Пример #5
0
plotting.plot_stat_map(
    z_map, threshold=threshold, colorbar=True,
    title='sex effect on grey matter density (FDR = .05)')

###########################################################################
# Note that there does not seem to be any significant effect of sex on
# grey matter density on that dataset.

###########################################################################
# Generating a report
# -------------------
# It can be useful to quickly generate a
# portable, ready-to-view report with most of the pertinent information.
# This is easy to do if you have a fitted model and the list of contrasts,
# which we do here.

from nilearn.reporting import make_glm_report

icbm152_2009 = datasets.fetch_icbm152_2009()
report = make_glm_report(model=second_level_model,
                         contrasts=['age', 'sex'],
                         bg_img=icbm152_2009['t1'],
                         )

#########################################################################
# We have several ways to access the report:

# report  # This report can be viewed in a notebook
# report.save_as_html('report.html')
# report.open_in_browser()
Пример #6
0
from scipy import stats
import matplotlib
matplotlib.use('Agg')
# pylint: disable= wrong-import-position, too-many-lines
import matplotlib.pyplot as plt  # noqa
import matplotlib.cm as cm  # noqa

os.environ['FSLOUTPUTTYPE'] = 'NIFTI_GZ'

LOGGER = logging.getLogger("NeuroReg")

TEMP_FOLDER_PATH = ""
DATA_FOLDER = ""
DB_PATH = ""

TEMPLATE_VOLUME = datasets.fetch_icbm152_2009(data_dir="./").get("t1")
TEMPLATE_MASK = datasets.fetch_icbm152_2009(data_dir="./").get("mask")
TEMPLATE_MASKED_VOLUME = ""


def setup(temp_path, data="glioma"):
    """setup for current computer """
    # pylint: disable= global-statement
    LOGGER.setLevel(logging.INFO)

    file_handler = logging.handlers.RotatingFileHandler('log.txt',
                                                        maxBytes=5 * 10000000,
                                                        backupCount=5)
    file_handler.set_name('log.txt')
    file_handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s -  %(levelname)s - %(message)s')
Пример #7
0
"""
# 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

atlas_types = {'Harvard_Oxford': harvard_oxford.maps,
               'Harvard_Oxford sub': harvard_oxford_sub.maps,
               'MSDL': msdl.maps, 'Smith 2009 10 RSNs': smith.rsn10,
               'Smith2009 20 RSNs': smith.rsn20,
               'Smith2009 70 RSNs': smith.rsn70,
               'Smith2009 10 Brainmap': smith.bm10,
               'Smith2009 20 Brainmap': smith.bm20,
               'Smith2009 70 Brainmap': smith.bm70,
               'ICBM tissues': (icbm['wm'], icbm['gm'], icbm['csf'])}
import nibabel as nib
import numpy as np
import pandas as pd
from nilearn import datasets, image, plotting

from neurolang import ExplicitVBROverlay, NeurolangPDL

###############################################################################
# Data preparation
# ----------------

###############################################################################
# Load the MNI atlas and resample it to 4mm voxels

mni_t1 = nib.load(datasets.fetch_icbm152_2009()["t1"])
mni_t1_4mm = image.resample_img(mni_t1, np.eye(3) * 4)

###############################################################################
# Load the NeuroSynth database

ns_database_fn, ns_features_fn = datasets.utils._fetch_files(
    "neurolang",
    [
        (
            "database.txt",
            "https://github.com/neurosynth/neurosynth-data/raw/master/current_data.tar.gz",
            {"uncompress": True},
        ),
        (
            "features.txt",
    else:
        os.nice(17)
        path = "MM_TEMP_" + "{:%m_%d_%Y}_BE2".format(
            datetime.datetime.now()) + "/"

    util.setup(path, "MolekylareMarkorer")
    #
    # util.prepare_template(datasets.fetch_icbm152_2009(data_dir="./").get("t2"), util.TEMPLATE_MASK, True)
    # moving_datasets_ids = find_images_from_pid([164])
    # print(moving_datasets_ids, len(moving_datasets_ids))
    # data_transforms = image_registration.get_transforms(moving_datasets_ids,
    #                                                     image_registration.AFFINE,
    #                                                     save_to_db=True)

    util.prepare_template(
        datasets.fetch_icbm152_2009(data_dir="./").get("t2"),
        util.TEMPLATE_MASK, True)
    moving_datasets_ids = find_images_from_pid([125, 2101])
    print(moving_datasets_ids, len(moving_datasets_ids))
    data_transforms = image_registration.get_transforms(
        moving_datasets_ids, image_registration.AFFINE, save_to_db=True)

    # moving_datasets_ids = find_images_from_pid([172])
    # print(moving_datasets_ids, len(moving_datasets_ids))
    # data_transforms = image_registration.get_transforms(moving_datasets_ids,
    #                                                     image_registration.RIGID,
    #                                                     save_to_db=True)

    # print(moving_datasets_ids_affine, len(moving_datasets_ids_affine))
    # data_transforms = image_registration.get_transforms(moving_datasets_ids_affine,
    #                                                     image_registration.RIGID,
import numpy as np
import pandas as pd

logger = logging.getLogger('neurolang.probabilistic')
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stderr))
warnings.filterwarnings("ignore")

###############################################################################
# Data preparation
# ----------------

###############################################################################
# Load the MNI template and resample it to 4mm voxels

mni_t1 = nib.load(datasets.fetch_icbm152_2009()['t1'])
mni_t1_4mm = image.resample_img(mni_t1, np.eye(3) * 4)

###############################################################################
# Load Destrieux's atlas
destrieux_dataset = datasets.fetch_atlas_destrieux_2009()
destrieux = nib.load(destrieux_dataset['maps'])
destrieux_resampled = image.resample_img(destrieux,
                                         mni_t1_4mm.affine,
                                         interpolation='nearest')
destrieux_resampled_data = np.asanyarray(destrieux_resampled.dataobj,
                                         dtype=np.int32)
destrieux_voxels_ijk = destrieux_resampled_data.nonzero()
destrieux_voxels_value = destrieux_resampled_data[destrieux_voxels_ijk]
destrieux_table = pd.DataFrame(np.transpose(destrieux_voxels_ijk),
                               columns=['i', 'j', 'k'])
Пример #11
0
import nipype.interfaces.ants as ants
import nibabel as nib
import numpy as np
import matplotlib
matplotlib.use('Agg')
# pylint: disable= wrong-import-position
import matplotlib.pyplot as plt  # noqa
import matplotlib.cm as cm  # noqa

os.environ['FSLOUTPUTTYPE'] = 'NIFTI'

TEMP_FOLDER_PATH = ""
DATA_FOLDER = ""
DB_PATH = ""

TEMPLATE_VOLUME = datasets.fetch_icbm152_2009(data_dir="./").get("t1")
TEMPLATE_MASK = datasets.fetch_icbm152_2009(data_dir="./").get("mask")
TEMPLATE_MASKED_VOLUME = ""


def setup(temp_path):
    """setup for current computer """
    # pylint: disable= global-statement
    global TEMP_FOLDER_PATH
    TEMP_FOLDER_PATH = temp_path
    mkdir_p(TEMP_FOLDER_PATH)
    setup_paths()
    prepare_template(TEMPLATE_VOLUME, TEMPLATE_MASK)


def setup_paths():
Пример #12
0
######################################################################
# Grid search 'C' for prediction
# ---------------------------------

X_sc = StandardScaler()
estimator = SVC(kernel='linear')
param_grid = {'C': np.logspace(-3., 3., 10)}
# Grid search 'C' in linear SVC
cv = GroupShuffleSplit(n_splits=10, test_size=0.3, random_state=0)

######################################################################
# Predictive model - without reduction
# ------------------------------------

# Standard mask
icbm = fetch_icbm152_2009()
mask = icbm.mask

masker = MultiNiftiMasker(mask_img=mask,
                          target_affine=ref_img.affine,
                          target_shape=ref_img.shape,
                          n_jobs=5,
                          verbose=1)
X = masker.fit_transform(input_images)
X = np.vstack(X)
X = X_sc.fit_transform(X)

grid = GridSearchCV(estimator,
                    param_grid=param_grid,
                    cv=cv.split(X, y, groups),
                    verbose=1,
Пример #13
0
    def fit(self, imgs, confounds=None):
        """
        Compute the mask and the dynamic parcels across datasets.

        Parameters
        ----------
        imgs: list of Niimg-like objects
            See http://nilearn.github.io/manipulating_images/input_output.html
            Data on which the mask is calculated. If this is a list,
            the affine is considered the same for all.

        confounds: list of CSV file paths or 2D matrices
            This parameter is passed to nilearn.signal.clean. Please see the
            related documentation for details. Should match with the list
            of imgs given.

         Returns
         -------
         self: object
            Returns the instance itself. Contains attributes listed
            at the object level.
        """
        self.masker_ = check_embedded_nifti_masker(self)
        imgs, confounds = self._sanitize_imgs(imgs, confounds)

        # Avoid warning with imgs != None
        # if masker_ has been provided a mask_img
        if self.masker_.mask_img is None:
            self.masker_.fit(imgs)
        else:
            self.masker_.fit()
        self.mask_img_ = self.masker_.mask_img_

        # Load grey_matter segmentation
        if self.grey_matter == "MNI":
            mni = datasets.fetch_icbm152_2009()
            self.grey_matter = mni.gm

        if self.grey_matter is not None:
            masker_anat = NiftiMasker(
                mask_img=self.mask_img_, smoothing_fwhm=self.smoothing_fwhm
            )
            masker_anat.fit(self.grey_matter)
            grey_matter = masker_anat.transform(self.grey_matter)
            self.weights_grey_matter_ = (
                1 - grey_matter
            ) + self.std_grey_matter * grey_matter
        else:
            self.weights_grey_matter_ = None

        # Control random number generation
        self.random_state = check_random_state(self.random_state)

        # Check that number of batches is reasonable
        if self.n_batch > len(imgs):
            warnings.warn(
                "{0} batches were requested, but only {1} datasets available. Using one dataset per batch instead.".format(
                    self.n_batch, len(imgs)
                )
            )
            self.n_batch = len(imgs)

        # mask_and_reduce step
        if self.n_batch > 1:
            stab_maps, dwell_time = self._mask_and_reduce_batch(imgs, confounds)
        else:
            stab_maps, dwell_time = self._mask_and_reduce(imgs, confounds)

        # Return components
        self.components_ = stab_maps
        self.dwell_time_ = dwell_time

        # Create embedding
        self.embedding = Embedding(stab_maps.todense())
        return self
Пример #14
0
import seaborn as sns

import os

from pathlib import Path
from scipy import io as sio
from pygsp import graphs
import shutil

# In[2]:

from nilearn.input_data import NiftiLabelsMasker
from nilearn.datasets import fetch_icbm152_2009

mnitemp = fetch_icbm152_2009()

glassermasker = NiftiLabelsMasker(labels_img='Glasser_masker.nii.gz',
                                  mask_img=mnitemp['mask'])
glassermasker.fit()

# In[3]:

import numpy as np
coords = np.load('coords_with_order.npz')['coordinates']

ind_reord = np.load('coords_with_order.npz')['order']

# In[4]:

from nilearn.datasets import fetch_abide_pcp