Example #1
0
def generate_fmri_data_for_subject(subject):
    """
	Input : Take as input each fmri file. One file = One block
	Load all fmri data and apply a global mask mak on it. The global mask is computed using the mask from each fmri run (block). 
	Applying a global mask for a subject uniformize the data. 
	Output: Output fmri_runs for a subject, corrected using a global mask
	"""
    fmri_filenames = sorted(
        glob.glob(
            os.path.join(paths.rootpath, "fmri-data/en", "sub-%03d" % subject,
                         "func", "resample*.nii")))

    masks_filenames = sorted(
        glob.glob(
            os.path.join(paths.path2Data, "en/fmri_data/masks",
                         "sub_{}".format(subject), "resample*.pkl")))
    masks = []
    for file in masks_filenames:
        with open(file, 'rb') as f:
            mask = pickle.load(f)
            masks.append(mask)

    global_mask = math_img('img>0.5', img=mean_img(masks))
    masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True)
    masker.fit()
    fmri_runs = [masker.transform(f) for f in tqdm(fmri_filenames)]
    print(fmri_runs[0].shape)

    return fmri_runs
Example #2
0
def glass_brain(r2_voxels, subject, current_ROI, ROI_name, name):
    """
	Input : Masked results of r2score
	Take masked data and project it again in a 3D space
	Ouput : 3D glassbrain of r2score 
	"""

    # Get one mask and fit it to the corresponding ROI
    if current_ROI != -1 and current_ROI <= 5:
        masks_ROIs_filenames = sorted(
            glob.glob(os.path.join(paths.path2Data, "en/ROIs_masks/",
                                   "*.nii")))
        ROI_mask = masks_ROIs_filenames[current_ROI]
        ROI_mask = NiftiMasker(ROI_mask, detrend=True, standardize=True)
        ROI_mask.fit()
        unmasked_data = ROI_mask.inverse_transform(r2_voxels)

    # Get masks and fit a global mask
    else:
        masks = []
        masks_filenames = sorted(
            glob.glob(
                os.path.join(paths.path2Data, "en/fmri_data/masks",
                             "sub_{}".format(subject), "resample*.pkl")))
        for file in masks_filenames:
            with open(file, 'rb') as f:
                mask = pickle.load(f)
                masks.append(mask)

        global_mask = math_img('img>0.5', img=mean_img(masks))
        masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True)
        masker.fit()
        unmasked_data = masker.inverse_transform(r2_voxels)

    display = plot_glass_brain(unmasked_data,
                               display_mode='lzry',
                               threshold='auto',
                               colorbar=True,
                               title='Sub_{}'.format(subject))
    if not os.path.exists(
            os.path.join(paths.path2Figures, 'glass_brain',
                         'Sub_{}'.format(subject), ROI_name)):
        os.makedirs(
            os.path.join(paths.path2Figures, 'glass_brain',
                         'Sub_{}'.format(subject), ROI_name))

    display.savefig(
        os.path.join(paths.path2Figures, 'glass_brain',
                     'Sub_{}'.format(subject), ROI_name,
                     'R_squared_test_{}.png'.format(name)))
    print(
        'Figure Path : ',
        os.path.join(paths.path2Figures, 'glass_brain',
                     'Sub_{}'.format(subject), ROI_name,
                     'R_squared_test_{}.png'.format(name)))
    display.close()
Example #3
0
def compute_global_masker(rootdir, subjects):
    # masks = [compute_epi_mask(glob.glob(op.join(rootdir, "fmri-data/en", "sub-%03d" % s, "func","*.nii"))) for s in subjects]
    # global_mask = math_img('img>0.5', img=mean_img(masks))
    # masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True, memory='/volatile/tmp')
    masker = MultiNiftiMasker(mask_img=op.join(
        rootdir, "lpp-scripts3/inputs/ROIs/mask_ICV.nii"),
                              detrend=True,
                              standardize=True)
    masker.fit()
    return masker
def compute_all_subjects_mask():
    """ Computes the mask of all the subjects and the sesssions
    """
    masker = MultiNiftiMasker(mask_strategy='epi', memory=CACHE_DIR,
                              memory_level=2, n_jobs=10, verbose=5)
               
    imgs = dataset.func1 + dataset.func2
    masker.fit(imgs)
    masker.mask_img_.to_filename('all_subjects.nii.gz')
    plot_roi(masker.mask_img_)
Example #5
0
def compute_global_masker(files):  # [[path, path2], [path3, path4]]
    # return a MultiNiftiMasker object
    masks = [compute_epi_mask(f) for f in files]
    global_mask = math_img(
        'img>0.5',
        img=mean_img(masks))  # take the average mask and threshold at 0.5
    masker = MultiNiftiMasker(
        global_mask, detrend=True, standardize=True
    )  # return a object that transforms a 4D barin into a 2D matrix of voxel-time and can do the reverse action
    masker.fit()
    return masker
def compute_global_masker(rootdir, subjects):
    masks = [
        compute_epi_mask(
            glob.glob(
                os.path.join(rootdir, "fmri-data/en", "sub-%03d" % s, "func",
                             "*.nii"))) for s in subjects
    ]
    global_mask = math_img('img>0.5', img=mean_img(masks))
    masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True)
    masker.fit()
    return masker
def compute_global_masker(rootdir):
    '''Define the mask that will be applied onto data'''
    mask = op.join(rootdir, 'spm12/tpm/mask_ICV.nii')
    global_mask = math_img('img>0', img=mask)
    masker = MultiNiftiMasker(global_mask,
                              smoothing_fwhm=1.5,
                              high_pass=1 / 128,
                              t_r=2,
                              detrend=True,
                              standardize=True)
    masker.fit()
    return masker
def compute_all_subjects_mask():
    """ Computes the mask of all the subjects and the sesssions
    """
    masker = MultiNiftiMasker(mask_strategy='epi',
                              memory=CACHE_DIR,
                              memory_level=2,
                              n_jobs=10,
                              verbose=5)

    imgs = dataset.func1 + dataset.func2
    masker.fit(imgs)
    masker.mask_img_.to_filename('all_subjects.nii.gz')
    plot_roi(masker.mask_img_)
Example #9
0
def generate_fmri_data_for_subject(subject, current_ROI):
	"""
	Input : Take as input each fmri file. One file = One block
	Load all fmri data and apply a global mask mak on it. The global mask is computed using the mask from each fmri run (block). 
	Applying a global mask for a subject uniformize the data. 
	Output: Output fmri_runs for a subject, corrected using a global mask
	"""

	# Get all paths for fmri data
	fmri_filenames = sorted(glob.glob(os.path.join(paths.rootpath, 
												"fmri-data/en",
												"sub-%03d" % subject, 
												"func", 
												"resampled*.nii")))
	
	# Process for All brain
	if current_ROI == -1:
		# Get paths for masks
		masks_filenames = sorted(glob.glob(os.path.join(paths.path2Data,
												"en/fmri_data/masks",
												"sub_{}".format(subject),  
												"resample*.pkl")))
		masks = []
		for file in masks_filenames:
			with open(file, 'rb') as f:
				mask = pickle.load(f)
				masks.append(mask)

		# Compute a global mask for all subject. This way the data will be uniform
		global_mask = math_img('img>0.5', img=mean_img(masks))
		masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True)
		masker.fit()

		# Apply the mask to each fmri run (block)
		fmri_runs = [masker.transform(f) for f in tqdm(fmri_filenames)]
	
	# Process for a  specific ROI
	else:
		# get paths of ROIs masks
		masks_ROIs_filenames = sorted(glob.glob(os.path.join(paths.path2Data, 
												"en/ROIs_masks/",
												"*.nii")))
		# Choose the mask 
		ROI_mask = masks_ROIs_filenames[current_ROI]
		ROI_mask = NiftiMasker(ROI_mask, detrend=True, standardize=True)
		ROI_mask.fit()

		# Apply the mask to each fmri run (block)
		fmri_runs = [ROI_mask.transform(f) for f in fmri_filenames]
		
	return fmri_runs
Example #10
0
def fetch_masker(masker_path,
                 language,
                 path_to_fmridata,
                 path_to_input,
                 smoothing_fwhm=None,
                 logger=None):
    """ Fetch or compute if needed a global masker from all subjects of a
    given language.
    Arguments:
        - masker_path: str
        - language: str
        - path_to_input: str
        - path_to_fmridata: str
        - smoothing_fwhm: int
        - logger: Logger
    """
    if os.path.exists(masker_path + '.nii.gz') and os.path.exists(masker_path +
                                                                  '.yml'):
        logger.report_state(" loading existing masker...")
        params = read_yaml(masker_path + '.yml')
        mask_img = nib.load(masker_path + '.nii.gz')
        masker = MultiNiftiMasker()
        masker.set_params(**params)
        masker.fit([mask_img])
    else:
        logger.report_state(" recomputing masker...")
        fmri_runs = {}
        subjects = [
            get_subject_name(id) for id in possible_subjects_id(language)
        ]
        for subject in subjects:
            _, fmri_paths = fetch_data(path_to_fmridata, path_to_input,
                                       subject, language)
            fmri_runs[subject] = fmri_paths
        masker = compute_global_masker(list(fmri_runs.values()),
                                       smoothing_fwhm=smoothing_fwhm)
        params = masker.get_params()
        params = {
            key: params[key]
            for key in [
                'detrend', 'dtype', 'high_pass', 'low_pass', 'mask_strategy',
                'memory_level', 'n_jobs', 'smoothing_fwhm', 'standardize',
                't_r', 'verbose'
            ]
        }
        nib.save(masker.mask_img_, masker_path + '.nii.gz')
        save_yaml(params, masker_path + '.yml')
    return masker
def run(root_dir="/", dump_dir=None, data_set=None, n_jobs=1):
    from nilearn.input_data import MultiNiftiMasker, NiftiMapsMasker
    from joblib import Memory, Parallel, delayed
    import nibabel
    from tempfile import mkdtemp

    if dump_dir is None:
        dump_dir = mkdtemp(os.path.join(root_dir, 'tmp'))
    mem = Memory(cachedir=os.path.join(root_dir, dump_dir))
    print "Loading all paths and variables into memory"
    df = get_all_paths(root_dir=root_dir, data_set=data_set)
    target_affine_ = nibabel.load(df["func"][0]).get_affine()
    target_shape_ = nibabel.load(df["func"][0]).shape[:-1]
    print "preparing and running MultiNiftiMasker"
    mnm = MultiNiftiMasker(mask_strategy="epi", memory=mem, n_jobs=n_jobs,
                           verbose=10, target_affine=target_affine_,
                           target_shape=target_shape_)
    mask_img = mnm.fit(list(df["func"])).mask_img_
    print "preparing and running NiftiMapsMasker"
    nmm = NiftiMapsMasker(
        maps_img=os.path.join("/usr/share/fsl/data/atlases/HarvardOxford/",
                              "HarvardOxford-cortl-prob-2mm.nii.gz"),
        mask_img=mask_img, detrend=True, smoothing_fwhm=5, standardize=True,
        low_pass=None, high_pass=None, memory=mem, verbose=10)
    region_ts = Parallel(n_jobs=n_jobs)(
        delayed(_data_fitting)(niimg, nmm, n_hv_confounds=5)
        for niimg in list(df["func"]))
#   joblib.dump(region_ts,
#               os.path.join(dump_dir, "results.pkl"))
#   region_signals = DataFrame({"region_signals": region_ts}, index=df.index)
#   df.join(region_signals)
#   return df
    return region_ts
Example #12
0
def compute_global_masker(files,
                          smoothing_fwhm=None
                          ):  # [[path, path2], [path3, path4]]
    """Returns a MultiNiftiMasker object from list (of list) of files.
    Arguments:
        - files: list (of list of str)
    Returns:
        - masker: MultiNiftiMasker
    """
    masks = [compute_epi_mask(f) for f in files]
    global_mask = math_img(
        'img>0.5',
        img=mean_img(masks))  # take the average mask and threshold at 0.5
    masker = MultiNiftiMasker(global_mask,
                              detrend=True,
                              standardize=True,
                              smoothing_fwhm=smoothing_fwhm)
    masker.fit()
    return masker
Example #13
0
def test_check_embedded_nifti_masker():
    owner = OwningClass()
    masker = check_embedded_nifti_masker(owner)
    assert type(masker) is MultiNiftiMasker

    for mask, multi_subject in ((MultiNiftiMasker(), True), (NiftiMasker(),
                                                             False)):
        owner = OwningClass(mask=mask)
        masker = check_embedded_nifti_masker(owner,
                                             multi_subject=multi_subject)
        assert type(masker) == type(mask)
        for param_key in masker.get_params():
            if param_key not in [
                    'memory', 'memory_level', 'n_jobs', 'verbose'
            ]:
                assert (getattr(masker, param_key) == getattr(mask, param_key))
            else:
                assert (getattr(masker,
                                param_key) == getattr(owner, param_key))

    # Check use of mask as mask_img
    shape = (6, 8, 10, 5)
    affine = np.eye(4)
    mask = nibabel.Nifti1Image(np.ones(shape[:3], dtype=np.int8), affine)
    owner = OwningClass(mask=mask)
    masker = check_embedded_nifti_masker(owner)
    assert masker.mask_img is mask

    # Check attribute forwarding
    data = np.zeros((9, 9, 9))
    data[2:-2, 2:-2, 2:-2] = 10
    imgs = nibabel.Nifti1Image(data, np.eye(4))
    mask = MultiNiftiMasker()
    mask.fit([[imgs]])
    owner = OwningClass(mask=mask)
    masker = check_embedded_nifti_masker(owner)
    assert masker.mask_img is mask.mask_img_

    # Check conflict warning
    mask = NiftiMasker(mask_strategy='epi')
    owner = OwningClass(mask=mask)
    with pytest.warns(UserWarning):
        check_embedded_nifti_masker(owner)
def test_check_embedded_nifti_masker():
    owner = OwningClass()
    masker = check_embedded_nifti_masker(owner)
    assert_true(type(masker) is MultiNiftiMasker)

    for mask, multi_subject in (
            (MultiNiftiMasker(), True), (NiftiMasker(), False)):
        owner = OwningClass(mask=mask)
        masker = check_embedded_nifti_masker(owner,
                                             multi_subject=multi_subject)
        assert_equal(type(masker), type(mask))
        for param_key in masker.get_params():
            if param_key not in ['memory', 'memory_level', 'n_jobs',
                                 'verbose']:
                assert_equal(getattr(masker, param_key),
                            getattr(mask, param_key))
            else:
                assert_equal(getattr(masker, param_key),
                            getattr(owner, param_key))

    # Check use of mask as mask_img
    shape = (6, 8, 10, 5)
    affine = np.eye(4)
    mask = nibabel.Nifti1Image(np.ones(shape[:3], dtype=np.int8), affine)
    owner = OwningClass(mask=mask)
    masker = check_embedded_nifti_masker(owner)
    assert_true(masker.mask_img is mask)

    # Check attribute forwarding
    data = np.zeros((9, 9, 9))
    data[2:-2, 2:-2, 2:-2] = 10
    imgs = nibabel.Nifti1Image(data, np.eye(4))
    mask = MultiNiftiMasker()
    mask.fit([[imgs]])
    owner = OwningClass(mask=mask)
    masker = check_embedded_nifti_masker(owner)
    assert_true(masker.mask_img is mask.mask_img_)

    # Check conflict warning
    mask = NiftiMasker(mask_strategy='epi')
    owner = OwningClass(mask=mask)
    assert_warns(UserWarning, check_embedded_nifti_masker, owner)
def compute_global_masker(files):  # [[path, path2], [path3, path4]]
    # return a MultiNiftiMasker object

    #spm_dir = '/neurospin/unicog/protocols/IRMf/Meyniel_MarkovGuess_2014'
    #mask = join(spm_dir, 'spm12/tpm/mask_ICV.nii')
    #global_mask = math_img('img>0', img=mask)
    #masker = MultiNiftiMasker(mask_img=global_mask)
    #masker.fit()

    masks = [compute_epi_mask(f) for f in files]
    global_mask = math_img(
        'img>0.5',
        img=mean_img(masks))  # take the average mask and threshold at 0.5
    masker = MultiNiftiMasker(
        global_mask,
        detrend=params.pref.detrend,
        standardize=params.pref.standardize
    )  # return a object that transforms a 4D barin into a 2D matrix of voxel-time and can do the reverse action
    masker.fit()
    return masker
sys.stderr.write(" Done (%.2fs).\n" % (time.time() - t0))

############################################################################
# Then we prepare and mask the data
# ----------------------------------
import numpy as np
from nilearn.input_data import MultiNiftiMasker

sys.stderr.write("Preprocessing data...")
t0 = time.time()

# Load and mask fMRI data
masker = MultiNiftiMasker(mask_img=miyawaki_dataset.mask,
                          detrend=True,
                          standardize=False)
masker.fit()
X_train = masker.transform(X_random_filenames)
X_test = masker.transform(X_figure_filenames)

# We load the visual stimuli from csv files
y_train = []
for y in y_random_filenames:
    y_train.append(
        np.reshape(np.loadtxt(y, dtype=np.int, delimiter=','),
                   (-1, ) + y_shape,
                   order='F'))

y_test = []
for y in y_figure_filenames:
    y_test.append(
        np.reshape(np.loadtxt(y, dtype=np.int, delimiter=','),
def create_raw_rest_data(imgs_list,
                         root,
                         raw_dir,
                         masker_params=None,
                         n_jobs=1,
                         mock=False,
                         memory=Memory(cachedir=None),
                         overwrite=False):
    """

    Parameters
    ----------
    memory
    imgs_list: DataFrame with columns filename, confounds
    root
    raw_dir
    masker_params
    n_jobs
    mock

    Returns
    -------

    """
    if masker_params is None:
        masker_params = {}
    masker = MultiNiftiMasker(verbose=1,
                              memory=memory,
                              memory_level=1,
                              **masker_params)
    if masker.mask_img is None:
        masker.fit(imgs_list['filename'])
    else:
        masker.fit()

    if 'confounds' in imgs_list.columns:
        confounds = imgs_list['confounds']
        imgs_list.rename(columns={'confounds': 'orig_confounds'})
    else:
        confounds = repeat(None)

    if not os.path.exists(raw_dir):
        os.makedirs(raw_dir)
    filenames = Parallel(n_jobs=n_jobs)(delayed(_unmask_single_img)(
        masker, imgs, confounds, root, raw_dir, mock=mock, overwrite=overwrite)
                                        for imgs, confounds in zip(
                                            imgs_list['filename'], confounds))
    imgs_list = imgs_list.rename(columns={'filename': 'orig_filename'})
    imgs_list = imgs_list.assign(filename=filenames)
    imgs_list = imgs_list.assign(confounds=None)
    if not mock:
        imgs_list.to_csv(os.path.join(raw_dir, 'data.csv'), mode='w+')
        mask_img_file = os.path.join(raw_dir, 'mask_img.nii.gz')
        masker.mask_img_.to_filename(mask_img_file)
        params = masker.get_params()
        params.pop('memory')
        params.pop('memory_level')
        params.pop('n_jobs')
        params.pop('verbose')
        params['mask_img'] = mask_img_file
        json.dump(params, open(os.path.join(raw_dir, 'masker.json'), 'w+'))
class MultiCovariance(BaseEstimator):

    def __init__(self, estimator, smoothing_fwhm=None, mask=None,
                 detrend=None, standardize=None,
                 target_affine=None, target_shape=None,
                 low_pass=None, high_pass=None, t_r=None,
                 memory=Memory(cachedir=None), memory_level=0,
                 n_jobs=1, verbose=0):
        self.estimator = estimator
        self.mask = mask
        self.memory = memory
        self.memory_level = memory_level
        self.n_jobs = n_jobs
        self.verbose = verbose
        self.low_pass = low_pass
        self.high_pass = high_pass
        self.t_r = t_r
        self.smoothing_fwhm = smoothing_fwhm
        self.target_affine = target_affine
        self.target_shape = target_shape
        self.standardize = standardize
        self.detrend = detrend

    def fit(self, niimgs=None, y=None, confounds=None, connectivity=None):
        """Compute the mask and the components

        Parameters
        ----------
        niimgs: list of filenames or NiImages
            Data on which the PCA must be calculated. If this is a list,
            the affine is considered the same for all.
        """
        # Hack to support single-subject data:
        if isinstance(niimgs, (basestring, nibabel.Nifti1Image)):
            niimgs = [niimgs]
            # This is a very incomplete hack, as it won't work right for
            # single-subject list of 3D filenames
        # First, learn the mask
        if not isinstance(self.mask, MultiNiftiMasker):
            self.masker_ = MultiNiftiMasker(mask=self.mask,
                                            smoothing_fwhm=self.smoothing_fwhm,
                                            target_affine=self.target_affine,
                                            target_shape=self.target_shape,
                                            low_pass=self.low_pass,
                                            high_pass=self.high_pass,
                                            t_r=self.t_r,
                                            memory=self.memory,
                                            memory_level=self.memory_level)
        else:
            try:
                self.masker_ = clone(self.mask)
            except TypeError as e:
                # Workaround for a joblib bug: in joblib 0.6, a Memory object
                # with cachedir = None cannot be cloned.
                masker_memory = self.mask.memory
                if masker_memory.cachedir is None:
                    self.mask.memory = None
                    self.masker_ = clone(self.mask)
                    self.mask.memory = masker_memory
                    self.masker_.memory = Memory(cachedir=None)
                else:
                    # The error was raised for another reason
                    raise e

            for param_name in ['target_affine', 'target_shape',
                               'smoothing_fwhm', 'low_pass', 'high_pass',
                               't_r', 'memory', 'memory_level']:
                if getattr(self.masker_, param_name) is not None:
                    warnings.warn('Parameter %s of the masker overriden'
                                  % param_name)
                setattr(self.masker_, param_name,
                        getattr(self, param_name))
        if self.masker_.mask is None:
            self.masker_.fit(niimgs)
        else:
            self.masker_.fit()
        self.mask_img_ = self.masker_.mask_img_

        parameters = get_params(MultiNiftiMasker, self)

        # Now compute the covariances

        self.covariances_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
            delayed(subject_covariance)(
                self.estimator,
                niimg,
                self.masker_.mask_img_,
                parameters,
                memory=self.memory,
                ref_memory_level=self.memory_level,
                confounds=confounds,
                connectivity=connectivity,
                verbose=self.verbose
            )
            for niimg in niimgs)
        return self
Example #19
0
import nibabel
import os
import pylab as pl
import numpy as np
import time

# CanICA
from nilearn.decomposition.canica import CanICA
from nilearn.input_data import MultiNiftiMasker

# Masker:

masker = MultiNiftiMasker(smoothing_fwhm=6.,
                          memory="nilearn_cache",
                          memory_level=1)
masker.fit(dataset.func)
affine = masker.mask_img_.get_affine()

if not os.path.exists('canica.nii.gz'):
    t0 = time.time()
    canica = CanICA(n_components=n_components, mask=masker,
                    smoothing_fwhm=6.,
                    memory="nilearn_cache", memory_level=1,
                    threshold=None,
                    random_state=1)
    canica.fit(dataset.func)
    print('Canica: %f' % (time.time() - t0))
    canica_components = masker.inverse_transform(canica.components_)
    nibabel.save(canica_components, 'canica.nii.gz')

if not os.path.exists('canica.pdf'):
Example #20
0
import nibabel
import os
import pylab as pl
import numpy as np
import time

# CanICA
from nilearn.decomposition.canica import CanICA
from nilearn.input_data import MultiNiftiMasker

# Masker:

masker = MultiNiftiMasker(smoothing_fwhm=6.,
                          memory="nilearn_cache",
                          memory_level=1)
masker.fit(dataset.func)
affine = masker.mask_img_.get_affine()

if not os.path.exists('canica.nii.gz'):
    t0 = time.time()
    canica = CanICA(n_components=n_components,
                    mask=masker,
                    smoothing_fwhm=6.,
                    memory="nilearn_cache",
                    memory_level=1,
                    threshold=None,
                    random_state=1)
    canica.fit(dataset.func)
    print('Canica: %f' % (time.time() - t0))
    canica_components = masker.inverse_transform(canica.components_)
    nibabel.save(canica_components, 'canica.nii.gz')
y_figure_filenames = miyawaki_dataset.label[:12]
y_shape = (10, 10)

sys.stderr.write(" Done (%.2fs).\n" % (time.time() - t0))

### Preprocess and mask #######################################################
import numpy as np
from nilearn.input_data import MultiNiftiMasker

sys.stderr.write("Preprocessing data...")
t0 = time.time()

# Load and mask fMRI data
masker = MultiNiftiMasker(mask_img=miyawaki_dataset.mask, detrend=True,
                          standardize=False)
masker.fit()
X_train = masker.transform(X_random_filenames)
X_test = masker.transform(X_figure_filenames)

# Load visual stimuli from csv files
y_train = []
for y in y_random_filenames:
    y_train.append(np.reshape(np.loadtxt(y, dtype=np.int, delimiter=','),
                              (-1,) + y_shape, order='F'))

y_test = []
for y in y_figure_filenames:
    y_test.append(np.reshape(np.loadtxt(y, dtype=np.int, delimiter=','),
                             (-1,) + y_shape, order='F'))

X_train = np.vstack([x[2:] for x in X_train])
Example #22
0
CACHE_DIR = '/home/mr234268/data'

dataset = datasets.fetch_adni_rs_fmri()
func_files = dataset['func']
dx_group = dataset['dx_group']

n_sample = 140
idx = np.random.randint(len(func_files), size=n_sample)
func_files_sample = np.array(func_files)[idx]

multi_masker = MultiNiftiMasker(mask_strategy='epi',
                                memory=CACHE_DIR,
                                n_jobs=1,
                                memory_level=2)
multi_masker.fit(func_files_sample)
plot_img(multi_masker.mask_img_)

n_components = 40
canica = CanICA(mask=multi_masker,
                n_components=n_components,
                smoothing_fwhm=6.,
                memory=CACHE_DIR,
                memory_level=5,
                threshold=3.,
                verbose=10,
                random_state=0)
canica.fit(func_files_sample)

# Retrieve the independent components in brain space
components_img = canica.masker_.inverse_transform(canica.components_)
Example #23
0

# We first create a masker, giving it the options that we care
# about. Here we use standardizing of the data, as it is often important
# for decoding
mask_filename = os.getcwd() + "/dataset/train/Patient_01/GT.nii.gz"
scan_filename = os.getcwd() + "/dataset/train/Patient_01/Patient_01.nii.gz"

masker = MultiNiftiMasker(mask_img=mask_filename, standardize=True)
print(masker)


# We give the masker a filename and retrieve a 2D array ready
# for machine learning with scikit-learn

masker.fit(scan_filename)
#masker.transform(scan_filename)
scan_masked = masker.fit_transform(scan_filename)

# calculate mean image for the background
mean_func_img = mean_img(scan_filename)
'''
plot_roi(masker.mask_img_, mean_func_img, display_mode='y', cut_coords=4, title="Mask")
show()
'''
# maxes = np.max(labelArray, axis=0)
# calculate mean image for the background
# mean_func_img = mean_img(filename)

# plot_roi(mask_img, mean_func_img, display_mode='y', cut_coords=4, title="Mask")
    import joblib
    from sklearn.base import clone
    import nibabel

    root_dir = "/media/Elements/volatile/new/salma"

    mem = Memory(cachedir=os.path.join(root_dir,
                                       ("storage/workspace/brainpedia"
                                       "/preproc/henson2010faces/dump/")))
    print "Loading all paths and variables into memory"
    df = get_all_paths(root_dir=root_dir,
                       data_set=["henson2010faces"])
    target_affine_ = nibabel.load(df["func"][0]).get_affine()
    target_shape_ = nibabel.load(df["func"][0]).shape[:-1]
    print "preparing and running MultiNiftiMasker"
    mnm = MultiNiftiMasker(mask_strategy="epi", memory=mem, n_jobs=1,
                           verbose=10, target_affine=target_affine_,
                           target_shape=target_shape_)
    mask_img = mnm.fit(list(df["func"])).mask_img_
    print "preparing and running NiftiMapsMasker"
    nmm = NiftiMapsMasker(
        maps_img=os.path.join("/usr/share/fsl/data/atlases/HarvardOxford/",
                              "HarvardOxford-cortl-prob-2mm.nii.gz"),
        mask_img=mask_img, detrend=True, smoothing_fwhm=5, standardize=True,
        low_pass=None, high_pass=None, memory=mem, verbose=10)
    region_ts = [clone(nmm).fit_transform(niimg, n_hv_confounds=5)
                 for niimg in list(df["func"])]
    joblib.dump(region_ts, "/home/storage/workspace/rphlypo/retreat/results/")
    region_signals = DataFrame({"region_signals": region_ts}, index=df.index)
    df.join(region_signals)