def create_local_clustering(self, overwrite, r_thresh): """ API for performing any of a variety of clustering routines available through NiLearn. """ import os.path as op from scipy.sparse import save_npz, load_npz from nilearn.regions import connected_regions from pynets.fmri.clustools import make_local_connectivity_tcorr, make_local_connectivity_scorr conn_comps = len(connected_regions(self._clust_mask_corr_img, extract_type='connected_components', min_region_size=1)[1]) if self.clust_type == 'kmeans': if self.k > conn_comps: if conn_comps != 1: raise ValueError('k must be less than or equal to the total number of connected components in ' 'the mask in the case of kmeans clustering.') if self.clust_type == 'complete' or self.clust_type == 'average' or self.clust_type == 'single': if conn_comps > 1: raise ValueError('Complete, Average, and Single linkage agglomerative clustering are unstable in the ' 'case of multiple connected components.') if self.clust_type == 'ward': if self.k < conn_comps: raise ValueError('k must minimally be greater than the total number of connected components in ' 'the mask in the case of agglomerative clustering.') if self.local_corr == 'tcorr' or self.local_corr == 'scorr': self._local_conn_mat_path = "%s%s%s%s" % (self.uatlas.split('.nii')[0], '_', self.local_corr, '_conn.npz') if (not op.isfile(self._local_conn_mat_path)) or (overwrite is True): if self.local_corr == 'tcorr': self._local_conn = make_local_connectivity_tcorr(self._func_img, self._clust_mask_corr_img, thresh=r_thresh) elif self.local_corr == 'scorr': self._local_conn = make_local_connectivity_scorr(self._func_img, self._clust_mask_corr_img, thresh=r_thresh) else: raise ValueError('Local connectivity type not available') print("%s%s" % ('Saving spatially constrained connectivity structure to: ', self._local_conn_mat_path)) save_npz(self._local_conn_mat_path, self._local_conn) elif op.isfile(self._local_conn_mat_path): self._local_conn = load_npz(self._local_conn_mat_path) elif self.local_corr == 'allcorr': self._local_conn = 'auto' else: raise ValueError('Local connectivity method not recognized. Only tcorr, scorr, and auto are currently ' 'supported') else: self._local_conn = 'auto' return
def individual_tcorr_clustering(func_file, clust_mask, ID, k, clust_type, thresh=0.5): import os from pynets import utils from pynets.fmri import clustools nilearn_clust_list = ['kmeans', 'ward', 'complete', 'average'] mask_name = os.path.basename(clust_mask).split('.nii.gz')[0] atlas_select = "%s%s%s%s%s" % (mask_name, '_', clust_type, '_k', str(k)) print("%s%s%s%s%s%s%s" % ('\nCreating atlas using ', clust_type, ' at cluster level ', str(k), ' for ', str(atlas_select), '...\n')) dir_path = utils.do_dir_path(atlas_select, func_file) uatlas_select = "%s%s%s%s%s%s%s%s" % (dir_path, '/', mask_name, '_', clust_type, '_k', str(k), '.nii.gz') if clust_type in nilearn_clust_list: clustools.nil_parcellate(func_file, clust_mask, k, clust_type, ID, dir_path, uatlas_select) elif clust_type == 'ncut': working_dir = "%s%s%s" % (os.path.dirname(func_file), '/', atlas_select) outfile = "%s%s%s%s" % (working_dir, '/rm_tcorr_conn_', str(ID), '.npy') outfile_parc = "%s%s%s" % (working_dir, '/rm_tcorr_indiv_cluster_', str(ID)) binfile = "%s%s%s%s%s%s" % (working_dir, '/rm_tcorr_indiv_cluster_', str(ID), '_', str(k), '.npy') clustools.make_local_connectivity_tcorr(func_file, clust_mask, outfile, thresh) clustools.binfile_parcellate(outfile, outfile_parc, int(k)) clustools.make_image_from_bin_renum(uatlas_select, binfile, clust_mask) clustering = True return uatlas_select, atlas_select, clustering, clust_mask, k, clust_type
def test_make_local_connectivity_tcorr(): """ Test for make_local_connectivity_tcorr functionality """ print("testing make_local_connectivity_tcorr") base_dir = str(Path(__file__).parent / "examples") dir_path = base_dir + '/002/fmri' mask_file = base_dir + '/triple_net_ICA_overlap_3_sig_bin.nii.gz' image_file = dir_path + '/002.nii.gz' func_img = nib.load(image_file) mask_img = nib.load(mask_file) W = clustools.make_local_connectivity_tcorr(func_img, mask_img, thresh=0.50) assert W is not None
def test_make_local_connectivity_tcorr(): """ Test for make_local_connectivity_tcorr functionality """ print("testing make_local_connectivity_tcorr") base_dir = str(Path(__file__).parent/"examples") mask_file = f"{base_dir}/miscellaneous/triple_net_ICA_overlap_3_sig_bin.nii.gz" func_file = f"{base_dir}/BIDS/sub-25659/ses-1/func/sub-25659_ses-1_task-rest_space-MNI152NLin6Asym_desc-" \ f"smoothAROMAnonaggr_bold_short.nii.gz" func_img = nib.load(func_file) mask_img = nib.load(mask_file) W = clustools.make_local_connectivity_tcorr(func_img, mask_img, thresh=0.50) assert W is not None out_img = clustools.parcellate_ncut(W, 200, mask_img) assert isinstance(out_img, nib.Nifti1Image)
def create_local_clustering(self, overwrite, r_thresh, min_region_size=80): """ API for performing any of a variety of clustering routines available through NiLearn. """ import os.path as op from scipy.sparse import save_npz, load_npz from nilearn.regions import connected_regions try: conn_comps = connected_regions( self._clust_mask_corr_img, extract_type="connected_components", min_region_size=min_region_size, ) self._conn_comps = conn_comps[0] self.num_conn_comps = len(conn_comps[1]) except BaseException: raise ValueError("Clustering mask is empty!") if not self._conn_comps: if np.sum(np.asarray(self._clust_mask_corr_img.dataobj)) == 0: raise ValueError("Clustering mask is empty!") else: self._conn_comps = self._clust_mask_corr_img self.num_conn_comps = 1 print( f"Detected {self.num_conn_comps} connected components in " f"clustering mask with a mininimum region " f"size of {min_region_size}") if ( self.clust_type == "complete" or self.clust_type == "average" or self.clust_type == "single" ): if self.num_conn_comps > 1: raise ValueError( "Clustering method unstable with spatial constrainsts " "applied to multiple connected components.") if ( self.clust_type == "ward" and self.num_conn_comps > 1 ) or self.clust_type == "ncut": if self.k < self.num_conn_comps: raise ValueError( "k must minimally be greater than the total number of " "connected components in " "the mask in the case of agglomerative clustering.") if self.local_corr == "tcorr" or self.local_corr == "scorr": self._local_conn_mat_path = ( f"{self.uatlas.split('.nii')[0]}_" f"{self.local_corr}_conn.npz" ) if (not op.isfile(self._local_conn_mat_path)) or ( overwrite is True): from pynets.fmri.clustools import ( make_local_connectivity_tcorr, make_local_connectivity_scorr, ) if self.local_corr == "tcorr": self._local_conn = make_local_connectivity_tcorr( self._func_img, self._clust_mask_corr_img, thresh=r_thresh) elif self.local_corr == "scorr": self._local_conn = make_local_connectivity_scorr( self._func_img, self._clust_mask_corr_img, thresh=r_thresh) else: raise ValueError( "Local connectivity type not available") print( f"Saving spatially constrained connectivity structure" f" to: {self._local_conn_mat_path}" ) save_npz(self._local_conn_mat_path, self._local_conn) elif op.isfile(self._local_conn_mat_path): self._local_conn = load_npz(self._local_conn_mat_path) elif self.local_corr == "allcorr": if self.clust_type == "ncut": raise ValueError( "Must select either `tcorr` or `scorr` local " "connectivity option if you are using " "`ncut` clustering method") self._local_conn = "auto" else: raise ValueError( "Local connectivity method not recognized. Only tcorr," " scorr, and auto are currently " "supported") else: self._local_conn = "auto" return
def create_local_clustering(self, overwrite, r_thresh, min_region_size=80): """ API for performing any of a variety of clustering routines available through NiLearn. """ import os.path as op from scipy.sparse import save_npz, load_npz from nilearn.regions import connected_regions try: conn_comps = connected_regions(self._clust_mask_corr_img, extract_type='connected_components', min_region_size=min_region_size) self._conn_comps = conn_comps[0] self.num_conn_comps = len(conn_comps[1]) except: raise ValueError('Clustering mask is empty!') if not self._conn_comps: if np.sum(np.asarray(self._clust_mask_corr_img.dataobj)) == 0: raise ValueError('Clustering mask is empty!') else: self._conn_comps = self._clust_mask_corr_img self.num_conn_comps = 1 print( f"Detected {self.num_conn_comps} connected components in clustering mask with a mininimum region " f"size of {min_region_size}") if self.clust_type == 'complete' or self.clust_type == 'average' or self.clust_type == 'single': if self.num_conn_comps > 1: raise ValueError( 'Clustering method unstable with spatial constrainsts applied to multiple ' 'connected components.') if (self.clust_type == 'ward' and self.num_conn_comps > 1) or self.clust_type == 'ncut': if self.k < self.num_conn_comps: raise ValueError( 'k must minimally be greater than the total number of connected components in ' 'the mask in the case of agglomerative clustering.') if self.local_corr == 'tcorr' or self.local_corr == 'scorr': self._local_conn_mat_path = f"{self.uatlas.split('.nii')[0]}_{self.local_corr}_conn.npz" if (not op.isfile( self._local_conn_mat_path)) or (overwrite is True): from pynets.fmri.clustools import make_local_connectivity_tcorr, make_local_connectivity_scorr if self.local_corr == 'tcorr': self._local_conn = make_local_connectivity_tcorr( self._func_img, self._clust_mask_corr_img, thresh=r_thresh) elif self.local_corr == 'scorr': self._local_conn = make_local_connectivity_scorr( self._func_img, self._clust_mask_corr_img, thresh=r_thresh) else: raise ValueError( 'Local connectivity type not available') print( f"Saving spatially constrained connectivity structure to: {self._local_conn_mat_path}" ) save_npz(self._local_conn_mat_path, self._local_conn) elif op.isfile(self._local_conn_mat_path): self._local_conn = load_npz(self._local_conn_mat_path) elif self.local_corr == 'allcorr': if self.clust_type == 'ncut': raise ValueError( 'Must select either `tcorr` or `scorr` local connectivity option if you are using ' '`ncut` clustering method') self._local_conn = 'auto' else: raise ValueError( 'Local connectivity method not recognized. Only tcorr, scorr, and auto are currently ' 'supported') else: self._local_conn = 'auto' return