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_
def run_meta_dict_learning(n_components): for i in xrange(30): dl_dir = mkdir_path(os.path.join(dict_learning_dir, 'ndim_%s'%n_components,'DL_%s'%i)) if not os.path.isfile(os.path.join(dl_dir, 'dl_components.nii.gz')): print 'Running Dictionary Learning Decomposition Number %s' % i func_list = [os.path.join(tourettome_workspace, subject, 'ICA/REST_EDIT_UNI_BRAIN_MNI4mm_n196_fwhm_hp.nii.gz') for subject in meta_lists['meta_list_%s' % i]] print func_list dict_learning = DictLearning(n_components=n_components,mask = mask, memory="nilearn_cache", memory_level=2, n_jobs=2, smoothing_fwhm=0, verbose=1, random_state=0, n_epochs=1) dict_learning.fit(func_list) masker = dict_learning.masker_ components_img = masker.inverse_transform(dict_learning.components_) components_img.to_filename('%s/dl_components.nii.gz'%dl_dir) # run meta dictionary learning dict_learning = DictLearning(n_components=n_components, mask=mask, memory="nilearn_cache", memory_level=2, n_jobs=2, smoothing_fwhm=0, verbose=1, random_state=0, n_epochs=1) dict_learning_all = [os.path.join(dict_learning_dir,'ndim_%s'%n_components, 'DL_%s'%i, 'dl_components.nii.gz') for i in xrange(30)] dict_learning.fit(dict_learning_all) masker = dict_learning.masker_ components_img = masker.inverse_transform(dict_learning.components_) components_img.to_filename('%s/ndim_%s/dict_learning_IC.nii.gz' %(dict_learning_dir, n_components))
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
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)
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[ ]:
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
class CanICAInterface(BaseInterface): """ Nipype Interface to NiLearn methods to perform Canonical Independent Component Analysis. For more information look at: nilearn.decomposition.CanICA """ input_spec = CanICAInputSpec output_spec = CanICAOutputSpec 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 def _list_outputs(self): outputs = self.output_spec().get() masker = self._estimator.masker_ # Drop output maps to a Nifti file components_img = masker.inverse_transform(self._estimator.components_) components_img.to_filename(self._reconstructed_img_file) # save the score array if isinstance(self._score, float): with open(self._score_file, 'w') as f: f.write(str("%.10f" % self._score)) else: np.savetxt(self._score_file, self._score, fmt='%.10f') # save the loadings files self._loading_files = [] for idx, loadings in enumerate(self._loadings): loading_file = self._loading_file.format(self._estimator_name, idx) np.savetxt(loading_file, loadings, fmt='%.10f') self._loading_files.append(loading_file) outputs['components'] = op.abspath(self._reconstructed_img_file) outputs['score'] = op.abspath(self._score_file) outputs['loadings'] = [op.abspath(lf) for lf in self._loading_files] return outputs
# ------------------------------------------------------------------ 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
from nilearn import datasets rest_dataset = datasets.fetch_development_fmri(n_subjects=5) func_filenames = rest_dataset.func # list of 4D nifti files for each subject # print basic information on the dataset print('First functional nifti image (4D) is at: %s' % rest_dataset.func[0]) 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='template') print('[Example] Fitting dicitonary learning model') dict_learning.fit(func_filenames) 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('dict_learning.nii.gz') from nilearn.plotting import plot_prob_atlas plot_prob_atlas(dictlearning_components_img, title='All DictLearning components', output_file="dict_learning_atlas.png")
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
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')
rest_dataset = datasets.fetch_adhd(n_subjects=1) func_filenames = rest_dataset.func # nii_dir = 'C:\\Users\\MIT-DGMIF\\Desktop\\test\\' # files = [file for file in os.listdir(nii_dir)] confounds = rest_dataset.confounds ###################################################################### # 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=8, smoothing_fwhm=4., memory="nilearn_cache", memory_level=1, random_state=0) # Fit to the data dict_learn.fit(func_filenames) dict_learn.fit(rsn) dict_learn.fit(subject_niimg) # 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',
# and usually cleaner than :term:`ICA`. Here, we will compare networks built # with :term:`CanICA` to networks built with :term:`Dictionary learning`. # # * Arthur Mensch et al. `Compressed online dictionary learning for fast resting-state fMRI decomposition # <https://hal.archives-ouvertes.fr/hal-01271033/>`_, # ISBI 2016, Lecture Notes in Computer Science # ############################################################################### # Create a dictionary learning estimator 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='whole-brain-template') print('[Example] Fitting dicitonary learning model') dict_learning.fit(func_filenames) 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') ###############################################################################
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
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')
rest_dataset = datasets.fetch_development_fmri(n_subjects=20) func_filenames = rest_dataset.func confounds = rest_dataset.confounds ################################################################################ # Extract functional 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=8, 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 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')
# ------------------------------------ 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') ###############################################################################
class CanICAInterface(BaseInterface): """ Nipype Interface to NiLearn methods to perform Canonical Independent Component Analysis. For more information look at: nilearn.decomposition.CanICA """ input_spec = CanICAInputSpec output_spec = CanICAOutputSpec 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 def _list_outputs(self): outputs = self.output_spec().get() masker = self._estimator.masker_ # Drop output maps to a Nifti file components_img = masker.inverse_transform(self._estimator.components_) components_img.to_filename(self._reconstructed_img_file) # save the score array if isinstance(self._score, float): with open(self._score_file, 'w') as f: f.write(str("%.10f" % self._score)) else: np.savetxt(self._score_file, self._score, fmt='%.10f') # save the loadings files self._loading_files = [] for idx, loadings in enumerate(self._loadings): loading_file = self._loading_file.format(self._estimator_name, idx) np.savetxt(loading_file, loadings, fmt='%.10f') self._loading_files.append(loading_file) outputs['components'] = op.abspath(self._reconstructed_img_file) outputs['score'] = op.abspath(self._score_file) outputs['loadings'] = [op.abspath(lf) for lf in self._loading_files] return outputs