def fit(self, X, Y): """Fit data X and Y and learn transformation to map X to Y Parameters ---------- X: Niimg-like object Source data. Y: Niimg-like object Target data Returns ------- self """ self.masker_ = check_embedded_nifti_masker(self) self.masker_.n_jobs = self.n_jobs if self.masker_.mask_img is None: self.masker_.fit([X]) else: self.masker_.fit() if type(self.clustering) == nib.nifti1.Nifti1Image or os.path.isfile( self.clustering): # check that clustering provided fills the mask, if not, reduce the mask if 0 in self.masker_.transform(self.clustering): reduced_mask = _intersect_clustering_mask( self.clustering, self.masker_.mask_img) self.mask = reduced_mask self.masker_ = check_embedded_nifti_masker(self) self.masker_.n_jobs = self.n_jobs self.masker_.fit() warnings.warn( "Mask used was bigger than clustering provided. " + "Its intersection with the clustering was used instead.") if isinstance(X, (list, np.ndarray)): X_ = concat_imgs(X) else: X_ = load_img(X) if isinstance(X, (list, np.ndarray)): Y_ = concat_imgs(Y) else: Y_ = load_img(Y) self.fit_, self.labels_ = [], [] rs = ShuffleSplit(n_splits=self.n_bags, test_size=.8, random_state=0) outputs = Parallel( n_jobs=self.n_jobs, prefer="threads", verbose=self.verbose)( delayed(fit_one_parcellation) (X_, Y_, self.alignment_method, self.masker_, self.n_pieces, self.clustering, clustering_index, self.n_jobs, self.verbose) for clustering_index, _ in rs.split(range(X_.shape[-1]))) # change split self.labels_ = [output[0] for output in outputs] self.fit_ = [output[1] for output in outputs] return self
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 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 fit(self, X, Y): ''' X and Y must be lists of equal length (number of subjects) Inside each element may lists or a Niimgs (all of the same len / shape) ''' self.masker_ = check_embedded_nifti_masker(self) self.masker_.n_jobs = self.n_jobs if type(self.clustering) == nib.nifti1.Nifti1Image or os.path.isfile(self.clustering): # check that clustering provided fills the mask, if not, reduce the mask if 0 in self.masker_.transform(self.clustering): reduced_mask = _intersect_clustering_mask( self.clustering, self.masker_.mask_img) self.mask = reduced_mask self.masker_ = check_embedded_nifti_masker(self) self.masker_.n_jobs = self.n_jobs self.masker_.fit() warnings.warn( "Mask used was bigger than clustering provided. Its intersection with the clustering was used instead.") # Avoid warning with imgs != None # if masker_ has been provided a mask_img if self.masker_.mask_img is None: self.masker_.fit([X]) else: self.masker_.fit() self.fitted_intra = [] for X_sub, Y_sub in zip(X, Y): intra_align = IntraSubjectAlignment(alignment_method=self.alignment_method, n_pieces=self.n_pieces, clustering=self.clustering, n_bags=self.n_bags, mask=self.masker_, smoothing_fwhm=self.smoothing_fwhm, standardize=self.standardize, detrend=self.detrend, 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, n_jobs=self.n_jobs, verbose=self.verbose) intra_align.fit(X_sub, Y_sub) self.fitted_intra.append(intra_align) self.Y_shape = intra_align.Y_shape return self
def fit(self, X, Y): """Fit data X and Y and learn transformation to map X to Y Almost the same as pairwise align except for commented line Parameters ---------- X: Niimg-like object See http://nilearn.github.io/manipulating_images/input_output.html source data Y: Niimg-like object See http://nilearn.github.io/manipulating_images/input_output.html target data Returns ------- self """ self.masker_ = check_embedded_nifti_masker(self) self.masker_.n_jobs = 1 # self.n_jobs # Avoid warning with imgs != None # if masker_ has been provided a mask_img if self.masker_.mask_img is None: self.masker_.fit([X]) else: self.masker_.fit() # miss concatenation, transpose X_ = self.masker_.transform(X) Y_ = self.masker_.transform(Y) self.Y_shape = Y_.shape self.fit_, self.labels_ = [], [] rs = ShuffleSplit(n_splits=self.n_bags, test_size=.8, random_state=0) outputs = Parallel(n_jobs=self.n_jobs, prefer="threads", verbose=self.verbose)( delayed(fit_one_parcellation_intra)( self.masker_.inverse_transform(X_), self.masker_.inverse_transform( Y_), self.alignment_method, self.masker_, self.n_pieces, self.clustering, clustering_index, self.memory, self.n_jobs, self.verbose) for clustering_index, _ in rs.split(X_)) # split on X_.T X (n_features, n_samples) # call a different fit_one_parcellation function self.labels_ = [output[0] for output in outputs] self.fit_ = [output[1] for output in outputs] return self
def fit(self, imgs): """ Learn a template from source images, using alignment. Parameters ---------- imgs: List of 4D Niimg-like or List of lists of 3D Niimg-like Source subjects data. Each element of the parent list is one subject data, and all must have the same length (n_samples). Returns ------- self Attributes ---------- self.template: 4D Niimg object Length : n_samples """ # Check if the input is a list, if list of lists, concatenate each subjects # data into one unique image. if not isinstance(imgs, (list, np.ndarray)) or len(imgs) < 2: raise InputError( 'The method TemplateAlignment.fit() need a list input. \ Each element of the list (Niimg-like or list of Niimgs) \ is the data for one subject.') else: if isinstance(imgs[0], (list, np.ndarray)): imgs = [concat_imgs(img) for img in imgs] self.masker_ = check_embedded_nifti_masker(self) self.masker_.n_jobs = self.n_jobs # self.n_jobs # if masker_ has been provided a mask_img if self.masker_.mask_img is None: self.masker_.fit(imgs) else: self.masker_.fit() self.template, self.template_history = \ _create_template(imgs, self.n_iter, self.scale_template, self.alignment_method, self.n_pieces, self.clustering, self.n_bags, self.masker_, self.memory, self.memory_level, self.n_jobs, self.verbose) if self.save_template is not None: self.template.to_filename(self.save_template)
def fit(self, X, Y): """Fit data X and Y and learn transformation to map X to Y Parameters ---------- X: Niimg-like object See http://nilearn.github.io/manipulating_images/input_output.html source data Y: Niimg-like object See http://nilearn.github.io/manipulating_images/input_output.html target data Returns ------- self """ self.masker_ = check_embedded_nifti_masker(self) self.masker_.n_jobs = 1 # self.n_jobs # Avoid warning with imgs != None # if masker_ has been provided a mask_img if self.masker_.mask_img is None: self.masker_.fit([X]) else: self.masker_.fit() X_ = load_img(self.masker_, X) Y_ = load_img(self.masker_, Y) self.fit_, self.labels_ = [], [] rs = ShuffleSplit(n_splits=self.n_bags, test_size=.8, random_state=0) outputs = Parallel( n_jobs=self.n_jobs, backend=self.parallel_backend, verbose=self.verbose)(delayed(fit_one_parcellation)( X_, Y_, self.alignment_method, self.masker_.mask_img.get_data( ), self.n_pieces, self.clustering_method, clustering_index, self.memory, self.n_jobs, self.parallel_backend, self.verbose) for clustering_index, _ in rs.split(Y_.T)) self.labels_ = [output[0] for output in outputs] self.fit_ = [output[1] for output in outputs] return self
def fit(self, imgs=None, y=None, confounds=None): if isinstance(imgs, _basestring) or not hasattr(imgs, '__iter__'): # these classes are meant for list of 4D images # (multi-subject), we want it to work also on a single # subject, so we hack it. imgs = [ imgs, ] if len(imgs) == 0: # Common error that arises from a null glob. Capture # it early and raise a helpful message raise ValueError('Need one or more Niimg-like objects as input, ' 'an empty list was given.') self.masker_ = check_embedded_nifti_masker(self) # 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_ return self
def check_embedded_atlas_masker(estimator, atlas_type=None, img=None, multi_subject=True, seeds=None, radius=None, t_r=None, low_pass=None, high_pass=None): """Base function to return masker type and its parameters Accepts all Nilearn masker types but returns only Maps or Labels masker. The idea being that this function returns an object with essential parameters embedded in it such as repetition time, low pass, high pass, standardize, detrend for resting state fMRI data analysis. Mostly useful for pipelined analysis. Parameters ---------- estimator : object, instance of all masker types Accepts any instance masker type from nilearn.input_data img : maps_img or labels_img Used in initialization of instance masker object depending upon the length/type of the image. If maps_img related then used in NiftiMapsMasker instance or labels_img then NiftiLabelsMasker. seeds : List of triplet of coordinates in native space Used in NiftiSpheresMasker initialization. atlas_type : str {'maps', 'labels'} 'maps' implies NiftiMapsMasker 'labels' implies NiftiLabelsMasker multi_subject : bool, optional Indicates whether to return masker of multi subject type. List of subjects. Returns ------- masker : NiftiMapsMasker, NiftiLabelsMasker Depending upon atlas type. params : dict Masker parameters """ if atlas_type is not None: if atlas_type not in ['maps', 'labels', 'spheres', 'auto']: raise ValueError( "You provided unsupported masker type for atlas_type={0} " "selection. Choose one among them ['maps', 'labels', 'spheres']" "for atlas type masker. Otherwise atlas_type=None for general " "Nifti or MultiNifti Maskers.".format(atlas_type)) if not isinstance(estimator, (NiftiMasker, MultiNiftiMasker, NiftiMapsMasker, NiftiLabelsMasker, NiftiSpheresMasker)): raise ValueError("Unsupported 'estimator' instance of masker is " "provided".format(estimator)) if atlas_type == 'spheres' and seeds is None: raise ValueError("'seeds' must be specified for atlas_type='spheres'." "See documentation nilearn.input_data.NiftiSpheresMasker.") if (atlas_type == 'maps' or atlas_type == 'labels') and img is None: raise ValueError("'img' should not be None for atlas_type={0} related " "instance of masker. Atlas related maskers is created " "by provided a valid atlas image. See documenation in " "nilearn.input_data for specific " "masker related either maps or labels".format(atlas_type)) if atlas_type == 'auto' and img is not None: img = check_niimg(img) if len(img.shape) > 3: atlas_type = 'maps' else: atlas_type = 'labels' if atlas_type == 'maps' and img is not None: img = check_niimg_4d(img) if atlas_type == 'labels' and img is not None: img = check_niimg_3d(img) new_masker = check_embedded_nifti_masker(estimator, multi_subject=multi_subject) mask = getattr(new_masker, 'mask_img', None) estimator_mask = getattr(estimator, 'mask_img', None) if mask is None and estimator_mask is not None: new_masker.mask_img = estimator.mask_img if atlas_type is None: return new_masker else: masker_params = new_masker.get_params() new_masker_params = dict() _ignore = set(('mask_strategy', 'mask_args', 'n_jobs', 'target_affine', 'target_shape')) for param in masker_params: if param in _ignore: continue if hasattr(new_masker, param): new_masker_params[param] = getattr(new_masker, param) # Append atlas extraction related parameters if t_r is not None: new_masker_params['t_r'] = t_r if low_pass is not None: new_masker_params['low_pass'] = low_pass if high_pass is not None: new_masker_params['high_pass'] = high_pass if atlas_type is not None: if len(img.shape) > 3 and atlas_type == 'maps': new_masker_params['maps_img'] = img new_masker = NiftiMapsMasker(**new_masker_params) elif len(img.shape) == 3 and atlas_type == 'labels': new_masker_params['labels_img'] = img new_masker = NiftiLabelsMasker(**new_masker_params) return new_masker if seeds is not None and atlas_type == 'spheres': if radius is not None: new_masker_params['radius'] = radius new_masker_params['seeds'] = seeds new_masker = NiftiSpheresMasker(**new_masker_params) return new_masker
def fit(self, *args, **kwargs): self.masker = check_embedded_nifti_masker(self)
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