예제 #1
0
def make_dictionary(rs_fmri, n_components, cache, mask, n_jobs=1):
    dict_learning = DictLearning(n_components=n_components,
                                 memory=cache, memory_level=2,
                                 verbose=1, random_state=0, n_epochs=1,
                                 mask=mask, n_jobs=n_jobs)
    dict_learning.fit(rs_fmri)
    return dict_learning.components_img_, dict_learning.components_
예제 #2
0
def fit_DictLearning(imgs, params):
    """Interface of DictLearning."""
    defaults = {
        'n_components': 10,
        'memory': "nilearn_cache",
        'memory_level': 2,
        'verbose': 1,
        'random_state': 0,
        'n_epochs': 1,
        'mask_strategy': 'template',
        'n_jobs': -2
    }
    context = dict(defaults, **params)

    return DictLearning(**context).fit(imgs)
예제 #3
0
    def _estimate_atlas_weights(self, images, params):

        nii_images, nii_mask = convert_images_nifti(images)
        bg_offset = 1 if params.get('force_bg', False) else 1

        dict_learn = DictLearning(mask=nii_mask,
                                  n_components=params.get('nb_labels') - bg_offset,
                                  mask_strategy='background',
                                  # method='lars',
                                  n_epochs=10,
                                  n_jobs=1,
                                  verbose=0)
        dict_learn.fit(nii_images)
        components = np.argmax(dict_learn.components_, axis=0) + bg_offset
        atlas = components.reshape(images[0].shape)

        # atlas = segmentation.relabel_sequential(atlas)[0]

        weights = [weights_image_atlas_overlap_major(img, atlas) for img in self._images]
        weights = np.array(weights)

        return atlas, weights, None
예제 #4
0
# ------------------------------------
from nilearn.decomposition import DictLearning, CanICA

n_components = 40

###############################################################################
# Dictionary learning
# --------------------
#
# We use as "template" as a strategy to compute the mask, as this leads
# to slightly faster and more reproducible results. However, the images
# need to be in MNI template space
dict_learning = DictLearning(n_components=n_components,
                             memory="nilearn_cache",
                             memory_level=2,
                             verbose=1,
                             random_state=0,
                             n_epochs=1,
                             mask_strategy='template')
###############################################################################
# CanICA
# ------
canica = CanICA(n_components=n_components,
                memory="nilearn_cache",
                memory_level=2,
                threshold=3.,
                n_init=1,
                verbose=1,
                mask_strategy='template')

###############################################################################
adhd_dataset = datasets.fetch_adhd(n_subjects=20)
func_filenames = adhd_dataset.func
confounds = adhd_dataset.confounds

################################################################################
# Extracting resting-state networks with DictionaryLearning

# Import dictionary learning algorithm from decomposition module and call the
# object and fit the model to the functional datasets
from nilearn.decomposition import DictLearning

# Initialize DictLearning object
dict_learn = DictLearning(n_components=5,
                          smoothing_fwhm=6.,
                          memory="nilearn_cache",
                          memory_level=2,
                          random_state=0)
# Fit to the data
dict_learn.fit(func_filenames)
# Resting state networks/maps
components_img = dict_learn.masker_.inverse_transform(dict_learn.components_)

# Visualization of resting state networks
# Show networks using plotting utilities
from nilearn import plotting

plotting.plot_prob_atlas(components_img,
                         view_type='filled_contours',
                         title='Dictionary Learning maps')
예제 #6
0
from nilearn.image import iter_img
from nilearn.plotting import plot_stat_map, show

for i, cur_img in enumerate(iter_img(components)):
    plot_stat_map(cur_img, display_mode="z", title="IC %d" % i,
                  cut_coords=1, colorbar=False)


# In[ ]:


from nilearn.decomposition import DictLearning

dict_learning = DictLearning(n_components=20,
                             memory="nilearn_cache", memory_level=2,
                             verbose=1,
                             random_state=0,
                             n_epochs=1,
                             mask_strategy='background')

print('[Example] Fitting dicitonary learning model')
dict_learning.fit(func)
print('[Example] Saving results')
# Grab extracted components umasked back to Nifti image.
# Note: For older versions, less than 0.4.1. components_img_
# is not implemented. See Note section above for details.
dictlearning_components_img = dict_learning.components_img_
dictlearning_components_img.to_filename('dictionary_learning_resting_state.nii.gz')


# In[ ]:
예제 #7
0
    def _run_interface(self, runtime):
        algorithm = get_trait_value(self.inputs, 'algorithm', default='canica')
        mask = get_trait_value(self.inputs, 'mask')
        n_components = get_trait_value(self.inputs, 'n_components')
        do_cca = get_trait_value(self.inputs, 'do_cca')
        smoothing_fwhm = get_trait_value(self.inputs,
                                         'smoothing_fwhm',
                                         default=None)
        standardize = get_trait_value(self.inputs, 'standardize', default=None)
        threshold = get_trait_value(self.inputs, 'threshold', default=None)
        random_state = get_trait_value(self.inputs,
                                       'random_state',
                                       default=None)
        n_init = get_trait_value(self.inputs, 'n_init')
        n_jobs = get_trait_value(self.inputs, 'n_jobs')
        n_epochs = get_trait_value(self.inputs, 'n_epochs')
        alpha = get_trait_value(self.inputs, 'alpha')
        memory = get_trait_value(self.inputs, 'memory')
        memory_level = get_trait_value(self.inputs, 'memory_level')
        confounds = get_trait_value(self.inputs, 'confounds')

        # init the estimator
        if algorithm == 'canica':
            self._estimator = CanICA(
                mask=mask,
                n_components=n_components,
                threshold=threshold,
                random_state=random_state,
                standardize=standardize,
                smoothing_fwhm=smoothing_fwhm,
                do_cca=do_cca,
                verbose=1,
                n_init=n_init,
                memory=memory,
                memory_level=memory_level,
                n_jobs=n_jobs,
            )

        elif algorithm == 'dictlearning':
            self._estimator = DictLearning(
                mask=mask,
                n_components=n_components,
                random_state=random_state,
                standardize=standardize,
                smoothing_fwhm=smoothing_fwhm,
                verbose=1,
                n_epochs=n_epochs,
                alpha=alpha,
                memory=memory,
                memory_level=memory_level,
                n_jobs=n_jobs,
            )

        # set output file names
        self._estimator_name = algorithm
        self._confounds = confounds

        self._reconstructed_img_file = '{}_resting_state.nii.gz'.format(
            self._estimator_name)
        self._score_file = '{}_score.txt'.format(self._estimator_name)
        self._loading_file = '{}_{}_loading.txt'

        # fit and transform
        self._estimator.fit(self.inputs.in_files, confounds=self._confounds)
        self._score = self._estimator.score(self.inputs.in_files,
                                            confounds=self._confounds)
        self._loadings = self._estimator.transform(self.inputs.in_files,
                                                   confounds=self._confounds)

        return runtime
예제 #8
0
# ------------------------------------------------------------------
if (args.dictlearn):
    # Extract resting-state networks with DictionaryLearning

    # Import dictionary learning algorithm from decomposition module and call the
    # object and fit the model to the functional datasets
    from nilearn.decomposition import DictLearning
    logger.info("Dict Learning algorithm starting...")

    # Initialize DictLearning object
    dict_learn = DictLearning(n_components=args.n_components,
                              verbose=args.verbose,
                              smoothing_fwhm=args.fwhm,
                              t_r=TR,
                              alpha=10,
                              memory_level=2,
                              random_state=0,
                              n_jobs=args.n_jobs,
                              standardize=args.standarize,
                              high_pass=args.highpass,
                              low_pass=args.lowpass)
    # Fit to the data
    dict_learn.fit(func_filenames, confounds=confounds_components)
    # Resting state networks/maps
    components_img_dic = dict_learn.masker_.inverse_transform(
        dict_learn.components_)

    dict_dir = data_dir + '/' + split + '/' + 'dict'
    create_dir(dict_dir)
    filename = dict_dir + '/' + fwhm + '_resting_state_all.nii.gz'
    # save components image
mean_func_image = 'D:\ROI Schizo\ROIs\Schizo-Healthy\single_subj_T1.nii'
plotting.plot_roi(kmeans_labels_img,
                  mean_func_image,
                  title="KMeans parcellation",
                  display_mode='xz')

kmeans_labels_img.to_filename('roi1_parcellation.nii')

# Import dictionary learning algorithm from decomposition module and call the
# object and fit the model to the functional datasets
from nilearn.decomposition import DictLearning

# Initialize DictLearning object
dict_learn = DictLearning(n_components=2,
                          mask=atlas_harvard_oxford.maps,
                          random_state=0)
# Fit to the data
dict_learn.fit(func[0][0])
# Resting state networks/maps in attribute `components_img_`
# Note that this attribute is implemented from version 0.4.1.
# For older versions, see the note section above for details.
components_img = dict_learn.components_img_

# Visualization of functional networks
# Show networks using plotting utilities
from nilearn import plotting

plotting.plot_prob_atlas(components_img,
                         view_type='filled_contours',
                         title='Dictionary Learning maps')
예제 #10
0
    def _run_interface(self, runtime):

        from nilearn.decomposition import CanICA, DictLearning
        from nilearn.plotting import plot_stat_map, plot_prob_atlas
        from nilearn.image import iter_img
        from nilearn.input_data import NiftiMapsMasker
        import numpy as np

        canica = CanICA(n_components=self.inputs.n_components,
                        smoothing_fwhm=None,
                        low_pass=self.inputs.low_pass,
                        high_pass=self.inputs.high_pass,
                        t_r=self.inputs.tr,
                        do_cca=True,
                        detrend=True,
                        standardize=True,
                        threshold='auto',
                        random_state=0,
                        n_jobs=2,
                        memory_level=2,
                        memory="nilearn_cache")

        canica.fit(self.inputs.in_file, confounds=self.inputs.confounds_file)
        # canica.fit(self.inputs.in_file)

        components_img = canica.components_img_
        components_img.to_filename('descomposition_canica.nii.gz')

        # plot_prob_atlas(components_img, title='All ICA components')


        masker = NiftiMapsMasker(maps_img=components_img, standardize=True, memory='nilearn_cache', verbose=5)
        time_series_ica = masker.fit_transform(self.inputs.in_file)

        np.savetxt('time_series_ica.csv', np.asarray(time_series_ica), delimiter=',')

        for i, cur_img in enumerate(iter_img(components_img)):
            display = plot_stat_map(cur_img, display_mode="ortho", colorbar=True)
            display.savefig('ica_ic_' + str(i + 1) + '.png')
            display.close()

        dict_learning = DictLearning(n_components=self.inputs.n_components,
                                     smoothing_fwhm=None,
                                     low_pass=self.inputs.low_pass,
                                     high_pass=self.inputs.high_pass,
                                     t_r=self.inputs.tr,
                                     detrend=True,
                                     standardize=True,
                                     random_state=0,
                                     n_jobs=-2,
                                     memory_level=2,
                                     memory="nilearn_cache",
                                     mask_strategy = 'template')

        dict_learning.fit(self.inputs.in_file, confounds=self.inputs.confounds_file)

        components_img = dict_learning.components_img_
        components_img.to_filename('descomposition_dict.nii.gz')

        for i, cur_img in enumerate(iter_img(components_img)):
            display = plot_stat_map(cur_img, display_mode="ortho", colorbar=True)
            display.savefig('dic_ic_' + str(i + 1) + '.png')
            display.close()

        return runtime