def test_small_radius(): affine = np.eye(4) shape = (3, 3, 3) data = np.random.random(shape) mask = np.zeros(shape) mask[1, 1, 1] = 1 mask[2, 2, 2] = 1 affine = np.eye(4) * 1.2 seed = (1.4, 1.4, 1.4) masker = NiftiSpheresMasker([seed], radius=0.1, mask_img=nibabel.Nifti1Image(mask, affine)) masker.fit_transform(nibabel.Nifti1Image(data, affine)) # Test if masking is taken into account mask[1, 1, 1] = 0 mask[1, 1, 0] = 1 masker = NiftiSpheresMasker([seed], radius=0.1, mask_img=nibabel.Nifti1Image(mask, affine)) assert_raises_regex(ValueError, 'Sphere around seed #0 is empty', masker.fit_transform, nibabel.Nifti1Image(data, affine)) masker = NiftiSpheresMasker([seed], radius=1.6, mask_img=nibabel.Nifti1Image(mask, affine)) masker.fit_transform(nibabel.Nifti1Image(data, affine))
def test_nifti_spheres_masker_overlap(): # Test resampling in NiftiMapsMasker affine = np.eye(4) shape = (5, 5, 5) data = np.random.RandomState(42).random_sample(shape + (5, )) fmri_img = nibabel.Nifti1Image(data, affine) seeds = [(0, 0, 0), (2, 2, 2)] overlapping_masker = NiftiSpheresMasker(seeds, radius=1, allow_overlap=True) overlapping_masker.fit_transform(fmri_img) overlapping_masker = NiftiSpheresMasker(seeds, radius=2, allow_overlap=True) overlapping_masker.fit_transform(fmri_img) noverlapping_masker = NiftiSpheresMasker(seeds, radius=1, allow_overlap=False) noverlapping_masker.fit_transform(fmri_img) noverlapping_masker = NiftiSpheresMasker(seeds, radius=2, allow_overlap=False) with pytest.raises(ValueError, match='Overlap detected'): noverlapping_masker.fit_transform(fmri_img)
def test_small_radius_inverse(): affine = np.eye(4) shape = (3, 3, 3) data = np.random.RandomState(42).random_sample(shape) mask = np.zeros(shape) mask[1, 1, 1] = 1 mask[2, 2, 2] = 1 affine = np.eye(4) * 1.2 seed = (1.4, 1.4, 1.4) masker = NiftiSpheresMasker([seed], radius=0.1, mask_img=nibabel.Nifti1Image(mask, affine)) spheres_data = masker.fit_transform(nibabel.Nifti1Image(data, affine)) masker.inverse_transform(spheres_data) # Test if masking is taken into account mask[1, 1, 1] = 0 mask[1, 1, 0] = 1 masker = NiftiSpheresMasker([seed], radius=0.1, mask_img=nibabel.Nifti1Image(mask, affine)) masker.fit(nibabel.Nifti1Image(data, affine)) with pytest.raises(ValueError, match='These spheres are empty'): masker.inverse_transform(spheres_data) masker = NiftiSpheresMasker([seed], radius=1.6, mask_img=nibabel.Nifti1Image(mask, affine)) masker.fit(nibabel.Nifti1Image(data, affine)) masker.inverse_transform(spheres_data)
def test_nifti_spheres_masker_overlap(): # Test resampling in NiftiMapsMasker affine = np.eye(4) shape = (5, 5, 5) data = np.random.random(shape + (5, )) fmri_img = nibabel.Nifti1Image(data, affine) seeds = [(0, 0, 0), (2, 2, 2)] overlapping_masker = NiftiSpheresMasker(seeds, radius=1, allow_overlap=True) overlapping_masker.fit_transform(fmri_img) overlapping_masker = NiftiSpheresMasker(seeds, radius=2, allow_overlap=True) overlapping_masker.fit_transform(fmri_img) noverlapping_masker = NiftiSpheresMasker(seeds, radius=1, allow_overlap=False) noverlapping_masker.fit_transform(fmri_img) noverlapping_masker = NiftiSpheresMasker(seeds, radius=2, allow_overlap=False) assert_raises_regex(ValueError, 'Overlap detected', noverlapping_masker.fit_transform, fmri_img)
def extract_timeseries_coords(filename, raw_coords, confounds=None): """Because the power parcellation is given in coordinates and not labels, we dedicate an exclusive function to deal with it. """ coords = np.vstack( (raw_coords.rois['x'], raw_coords.rois['y'], raw_coords.rois['z'])).T spheres_masker = NiftiSpheresMasker(seeds=coords, radius=5., standardize=True) time_series = spheres_masker.fit_transform(filename, confounds=confounds) return time_series
def test_standardization(): data = np.random.RandomState(42).random_sample((3, 3, 3, 5)) img = nibabel.Nifti1Image(data, np.eye(4)) # test zscore masker = NiftiSpheresMasker([(1, 1, 1)], standardize='zscore') # Test the fit s = masker.fit_transform(img) np.testing.assert_almost_equal(s.mean(), 0) np.testing.assert_almost_equal(s.std(), 1) # test psc masker = NiftiSpheresMasker([(1, 1, 1)], standardize='psc') # Test the fit s = masker.fit_transform(img) np.testing.assert_almost_equal(s.mean(), 0) np.testing.assert_almost_equal( s.ravel(), data[1, 1, 1] / data[1, 1, 1].mean() * 100 - 100, )
def signal_extract(data,atlas,t_r=2.2,masker_type='Spheres',saveas='file'): """ Extracts BOLD time-series from regions of interest Parameters ---------- data: Filenames of subjects. atlas: regions or coordinates to extract signals from. masker_type : Type of masker used to extract BOLD signals . types are : 'Spheres','Maps','Labels' saveas : Destination to save and load output (.npz) Returns --------- subject_ts : array-like , 2-D (n_subjects,n_regions) Array of BOLD time-series """ subjects_ts=[] if os.path.exists(saveas): subjects_ts=np.load(saveas)['arr_0'] else: if masker_type== 'Spheres': masker = NiftiSpheresMasker( seeds=atlas, smoothing_fwhm=6, radius=4 ,mask_img=brainmask, detrend=False, standardize=True, low_pass=0.1, high_pass=0.01, t_r=t_r) elif masker_type == 'Maps': masker = NiftiMapsMasker(maps_img=atlas,mask_img=brainmask,standardize=True, high_pass=0.01,low_pass=0.1,detrend=False,t_r=t_r, memory_level=2,smoothing_fwhm=5,resampling_target='data', memory=mem,verbose=5) elif masker_type == 'Labels': masker = NiftiLabelsMasker(labels_img=atlas,mask_img=brainmask,standardize=True, high_pass=0.01,low_pass=0.1,detrend=False,t_r=t_r, memory_level=2,smoothing_fwhm=5,resampling_target='data', memory=mem,verbose=5) else: raise ValueError("Please provide masker type") for func_file in data: time_series = masker.fit_transform(func_file) subjects_ts.append(time_series) np.savez(saveas,subjects_ts) return subjects_ts
def test_is_nifti_spheres_masker_give_nans(): affine = np.eye(4) data_with_nans = np.zeros((10, 10, 10), dtype=np.float32) data_with_nans[:, :, :] = np.nan data_without_nans = np.random.RandomState(42).random_sample((9, 9, 9)) indices = np.nonzero(data_without_nans) # Leaving nans outside of some data data_with_nans[indices] = data_without_nans[indices] img = nibabel.Nifti1Image(data_with_nans, affine) seed = [(7, 7, 7)] # Interaction of seed with nans masker = NiftiSpheresMasker(seeds=seed, radius=2.) assert not np.isnan(np.sum(masker.fit_transform(img))) mask = np.ones((9, 9, 9)) mask_img = nibabel.Nifti1Image(mask, affine) # When mask_img is provided, the seed interacts within the brain, so no nan masker = NiftiSpheresMasker(seeds=seed, radius=2., mask_img=mask_img) assert not np.isnan(np.sum(masker.fit_transform(img)))
def test_is_nifti_spheres_masker_give_nans(): affine = np.eye(4) data_with_nans = np.zeros((10, 10, 10), dtype=np.float32) data_with_nans[:, :, :] = np.nan data_without_nans = np.random.random((9, 9, 9)) indices = np.nonzero(data_without_nans) # Leaving nans outside of some data data_with_nans[indices] = data_without_nans[indices] img = nibabel.Nifti1Image(data_with_nans, affine) seed = [(7, 7, 7)] # Interaction of seed with nans masker = NiftiSpheresMasker(seeds=seed, radius=2.) assert_false(np.isnan(np.sum(masker.fit_transform(img)))) mask = np.ones((9, 9, 9)) mask_img = nibabel.Nifti1Image(mask, affine) # When mask_img is provided, the seed interacts within the brain, so no nan masker = NiftiSpheresMasker(seeds=seed, radius=2., mask_img=mask_img) assert_false(np.isnan(np.sum(masker.fit_transform(img))))
def _fmri_roi_extract_image(data, atlas_path, atlas_type, radius, overlap_ok,mask = None): if 'label' in atlas_type: logging.debug('Labels Extract') label_masker = NiftiLabelsMasker(atlas_path, mask_img=mask) timeseries = label_masker.fit_transform(data) if 'sphere' in atlas_type: atlas_path = np.loadtxt(atlas_path) logging.debug('Sphere Extract') spheres_masker = NiftiSpheresMasker(atlas_path, float(radius),mask_img=mask, allow_overlap = overlap_ok) timeseries = spheres_masker.fit_transform(data) if 'maps' in atlas_type: logging.debug('Maps Extract') maps_masker = NiftiMapsMasker(atlas_path,mask_img=mask, allow_overlap = overlap_ok) timeseries = maps_masker.fit_transform(data) timeseries[timeseries == 0.0] = np.nan return timeseries
def report_flm_adhd_dmn(): # pragma: no cover t_r = 2. slice_time_ref = 0. n_scans = 176 pcc_coords = (0, -53, 26) adhd_dataset = nilearn.datasets.fetch_adhd(n_subjects=1) seed_masker = NiftiSpheresMasker([pcc_coords], radius=10, detrend=True, standardize=True, low_pass=0.1, high_pass=0.01, t_r=2., memory='nilearn_cache', memory_level=1, verbose=0) seed_time_series = seed_masker.fit_transform(adhd_dataset.func[0]) frametimes = np.linspace(0, (n_scans - 1) * t_r, n_scans) design_matrix = make_first_level_design_matrix(frametimes, hrf_model='spm', add_regs=seed_time_series, add_reg_names=["pcc_seed"]) dmn_contrast = np.array([1] + [0] * (design_matrix.shape[1] - 1)) contrasts = {'seed_based_glm': dmn_contrast} first_level_model = FirstLevelModel(t_r=t_r, slice_time_ref=slice_time_ref) first_level_model = first_level_model.fit(run_imgs=adhd_dataset.func[0], design_matrices=design_matrix) report = make_glm_report( first_level_model, contrasts=contrasts, title='ADHD DMN Report', cluster_threshold=15, height_control='bonferroni', min_distance=8., plot_type='glass', report_dims=(1200, 'a'), ) output_filename = 'generated_report_flm_adhd_dmn.html' output_filepath = os.path.join(REPORTS_DIR, output_filename) report.save_as_html(output_filepath) report.get_iframe()
def build_series(brain4d): coords = [ (30, -45, -10), (0, -85, 10), (0, 47, 30), (-35, -20, 50), ] masker = NiftiSpheresMasker( coords, radius=5, detrend=True, standardize=True, low_pass=0.1, high_pass=0.01, t_r=2, ) series = masker.fit_transform(brain4d) return series
def test_nifti_spheres_masker_overlap(): # Test resampling in NiftiMapsMasker affine = np.eye(4) shape = (5, 5, 5) data = np.random.random(shape + (5,)) fmri_img = nibabel.Nifti1Image(data, affine) seeds = [(0, 0, 0), (2, 2, 2)] overlapping_masker = NiftiSpheresMasker(seeds, radius=1, allow_overlap=True) overlapping_masker.fit_transform(fmri_img) overlapping_masker = NiftiSpheresMasker(seeds, radius=2, allow_overlap=True) overlapping_masker.fit_transform(fmri_img) noverlapping_masker = NiftiSpheresMasker(seeds, radius=1, allow_overlap=False) noverlapping_masker.fit_transform(fmri_img) noverlapping_masker = NiftiSpheresMasker(seeds, radius=2, allow_overlap=False) assert_raises_regex(ValueError, 'Overlap detected', noverlapping_masker.fit_transform, fmri_img)
slice_time_ref = 0. n_scans = 176 # Prepare seed pcc_coords = (0, -53, 26) ######################################################################### # Estimate contrasts # ------------------ # Specify the contrasts seed_masker = NiftiSpheresMasker([pcc_coords], radius=10, detrend=True, standardize=True, low_pass=0.1, high_pass=0.01, t_r=2., memory='nilearn_cache', memory_level=1, verbose=0) seed_time_series = seed_masker.fit_transform(adhd_dataset.func[0]) frametimes = np.linspace(0, (n_scans - 1) * t_r, n_scans) design_matrix = make_first_level_design_matrix(frametimes, hrf_model='spm', add_regs=seed_time_series, add_reg_names=["pcc_seed"]) dmn_contrast = np.array([1] + [0]*(design_matrix.shape[1]-1)) contrasts = {'seed_based_glm': dmn_contrast} ######################################################################### # Perform first level analysis # ---------------------------- # Setup and fit GLM first_level_model = FirstLevelModel(t_r=t_r, slice_time_ref=slice_time_ref) first_level_model = first_level_model.fit(run_imgs=adhd_dataset.func[0], design_matrices=design_matrix)
cleaner.fit(run_imgs=fmri_img, design_matrices=design_matrix) dirty_fmri_img = cleaner.results_.predict(design_matrix) print("Clean the data...") fmri_img -= dirty_fmri_img ######################################################################### # Cleaning the data # extract the seed print("Extracting the average seed time serie...") seed_masker = NiftiSpheresMasker([pcc_coords], radius=10, detrend=True, standardize=True, low_pass=0.1, high_pass=0.01, t_r=2., memory='nilearn_cache', memory_level=1, verbose=1) seed_time_series = seed_masker.fit_transform(func_fname) # define the design matrix print("Defining the main design matrix..") frametimes = np.linspace(0, (n_scans - 1) * tr, n_scans) add_reg_names = ["hv_comp_{0}".format(i) for i in range(n_confounds)] add_reg_names.insert(0, "seed") regressors = np.hstack([seed_time_series, hv_comps]) design_matrix = make_design_matrix(frametimes, hrf_model='spm', add_regs=regressors, add_reg_names=add_reg_names) # define contrast print("Defining the seed contrast") dmn_contrast = np.array([1] + [0]*(design_matrix.shape[1]-1)) contrasts = {'seed_based_glm': dmn_contrast}
def signal_extract(func_data=None,confounds=None,atlas_img=None,masker_type='Spheres',smoothing_fwhm=6,high_pass=0.01,low_pass=0.1,t_r=2.2,detrend=False,saveas='file'): """ Extracts BOLD time-series from regions of interest Parameters ---------- func_data: functional images ( Default= None ) confounds: Confounds file used to clean signals ( Default= None ) atlas_img: regions or coordinates to extract signals from ( Default= None ) masker_type : Type of masker used to extract BOLD signals . types are : 'Spheres','Maps','Labels' smoothing_fwhm : Smoothing width applied to signals in mm ( Default= 6 mm ) high_pass, low_pass: Bandpass-Filtering ( Default= 0.01-0.1 Hz ) detrend: Detrending signals ( Default= False ) saveas : Destination to save and load output (.npz) Returns --------- subject_ts : array-like , 2-D (n_subjects,n_regions) Array of BOLD time-series """ subjects_ts=[] if os.path.exists(saveas): subjects_ts=np.load(saveas)['arr_0'] else: if if masker_type== 'Spheres': masker = NiftiSpheresMasker( seeds=atlas_img, smoothing_fwhm=smoothing_fwhm, radius=4 ,mask_img=brainmask, detrend=False, standardize=True, low_pass=low_pass, high_pass=high_pass, t_r=t_r ) elif masker_type == 'Maps': masker = NiftiMapsMasker( maps_img=atlas_img,mask_img=brainmask,standardize=True, low_pass=low_pass, high_pass=high_pass, t_r=t_r, memory_level=2,smoothing_fwhm=smoothing_fwhm,resampling_target='data', memory=mem,verbose=5 ) elif masker_type == 'Labels': masker = NiftiLabelsMasker( labels_img=atlas_img,mask_img=brainmask,standardize=True, high_pass=high_pass,low_pass=low_pass,detrend=False,t_r=t_r, memory_level=2,smoothing_fwhm=smoothing_fwhm,resampling_target='data', memory=mem,verbose=5 ) else: raise ValueError("Please provide masker type") if confounds is not None: for func_file, confound_file in zip(func_data,confounds): time_series = masker.fit_transform(func_file,confounds=confound_file) subjects_ts.append(time_series) np.savez(saveas,subjects_ts) else: for func_file in data: time_series = masker.fit_transform(func_file) subjects_ts.append(time_series) np.savez(saveas,subjects_ts) return subjects_ts
# Find the coordinates of the peak from nibabel.affines import apply_affine values = z_map.get_data() coord_peaks = np.dstack( np.unravel_index(np.argsort(values.ravel()), values.shape))[0, 0, :] coord_mm = apply_affine(z_map.affine, coord_peaks) ############################################################################### # We create a masker for the voxel (allowing us to detrend the signal) # and extract the time course from nilearn.input_data import NiftiSpheresMasker mask = NiftiSpheresMasker([coord_mm], radius=3, detrend=True, standardize=True, high_pass=None, low_pass=None, t_r=7.) sig = mask.fit_transform(fmri_img) ########################################################## # Let's plot the signal and the theoretical response plt.plot(frame_times, sig, label='voxel %d %d %d' % tuple(coord_mm)) plt.plot(design_matrix['active'], color='red', label='model') plt.xlabel('scan') plt.legend() plt.show()
formatted_confounds = formatted_confounds.drop(['Unnamed: 0'], axis=1) # Create masker object to extract average signal within spheres masker = NiftiSpheresMasker(sphere_center, radius=sphere_radius, detrend=True, standardize=True, low_pass=0.1, high_pass=0.01, t_r=1.0, verbose=1, memory="nilearn_cache", memory_level=2) # Extract average signal in spheres with masker object time_series = masker.fit_transform(func_filename, confounds=formatted_confounds.values) connectivity_measure = ConnectivityMeasure(kind='partial correlation') partial_correlation_matrix = connectivity_measure.fit_transform( [time_series])[0] #Save flattened partial correlation matrix with runnum, subnum and seen names flat_partial_correlation_matrix = pd.DataFrame( partial_correlation_matrix).stack().reset_index() flat_partial_correlation_matrix = flat_partial_correlation_matrix.rename( columns={ "level_0": "seed1", "level_1": "seed2", 0: "cor_val" }) flat_partial_correlation_matrix['drop'] = np.where(
#sub_img.to_filename(os.path.join(data_dir,"func.nii")) subject_data = do_subjects_preproc(jobfile, dataset_dir=data_dir)[0] fmri_img = load_img(subject_data.func[0]) ######################################################################### # Seed base correlation analysis corr_output_dir = os.path.join(output_dir, "seed_base_corr") if not os.path.exists(corr_output_dir): os.makedirs(corr_output_dir) seed_masker = NiftiSpheresMasker([pcc_coords], radius=10, detrend=True, standardize=True, low_pass=0.1, high_pass=0.01, t_r=2., memory='nilearn_cache', memory_level=1, verbose=0) seed_time_series = seed_masker.fit_transform(subject_data.func[0]) brain_masker = NiftiMasker(smoothing_fwhm=6, detrend=True, standardize=True, low_pass=0.1, high_pass=0.01, t_r=2., memory='nilearn_cache', memory_level=1, verbose=10) brain_time_series = brain_masker.fit_transform(fmri_img) seed_based_corr = np.dot(brain_time_series.T, seed_time_series) / seed_time_series.shape[0] seed_based_corr_img = brain_masker.inverse_transform(seed_based_corr.T) display = niplt.plot_stat_map(seed_based_corr_img, threshold=0.6, cut_coords=pcc_coords) display.add_markers(marker_coords=[pcc_coords], marker_color='g', marker_size=300) display.savefig(os.path.join(corr_output_dir, 'corr_seed_based.png')) seed_based_corr_img.to_filename(os.path.join(corr_output_dir,
def calc_sc_sphere(in_file, coords, coords_labels, MNI_brain_mask, radius, FWHM): from nilearn.input_data import NiftiMasker, NiftiSpheresMasker import numpy as np import os # MNI mask MNI_brain_mask = MNI_brain_mask # probabilistic seed regions, 4d nifti file & corresponding labels coords = coords coords_labels = coords_labels # extract time series from coords seed_masker = NiftiSpheresMasker(coords, radius=radius, standardize=True, memory='nilearn_cache', memory_level=5, verbose=5) seed_time_series_array = seed_masker.fit_transform(in_file) # extract time series brain-wide brain_masker = NiftiMasker(mask_img=MNI_brain_mask, smoothing_fwhm=FWHM, standardize=True, memory='nilearn_cache', memory_level=5, verbose=2) brain_time_series = brain_masker.fit_transform(in_file) # check if length of coords_labels is equal to number of seed time series # (dependend on number of coordinate sets given with "coords") # break if not equal if len(coords_labels) == seed_time_series_array.shape[1]: icoord = 0 corr_maps_dict = dict.fromkeys(coords_labels) for seed in coords_labels: print("##################################") print(seed) print("##################################") # assign extracted seed time series from seed_time_series_array # at column icoord to seed_time_series & transpose it (because otherwise they have not the right dimensions?) seed_time_series = np.matrix(seed_time_series_array[:, icoord]).T # compute correlation of all voxels with seed regions seed_based_correlations = np.dot(brain_time_series.T, seed_time_series) / \ seed_time_series.shape[0] # increase imask to iterate through columns of seed_time_series_array icoord = icoord + 1 # Fisher-z transform the data to achieve a normal distribution seed_based_correlations_fisher_z = np.arctanh( seed_based_correlations) # transform the 2 dim matrix with the value of each voxel back to a 3 dim image seed_based_correlation_img = brain_masker.inverse_transform( seed_based_correlations_fisher_z.T) print("##################################") # initialize an empty file & "fill" it with the calculated img, necessary becaus nipype needs file types or so... aehm hmm out_file = os.path.abspath('corr_map_' + seed + '_rad5.nii.gz') seed_based_correlation_img.to_filename(out_file) corr_maps_dict[seed] = out_file return corr_maps_dict else: print( "#####################################################################################" ) print( "#####################################################################################" ) print( "Number of labels in prob_masks_labels and volumes in prob_masks does not match!!!!!!!" ) print( "#####################################################################################" ) print( "#####################################################################################" )
def make_parcellation(data_path, parcellation, parc_type=None, parc_params=None): """ Performs a parcellation which reduces voxel space to regions of interest (brain data). Parameters ---------- data_path : str Path to .nii image. parcellation : str Specify which parcellation that you would like to use. For MNI: 'gordon2014_333', 'power2012_264', For TAL: 'shen2013_278'. It is possible to add the OH subcotical atlas on top of a cortical atlas (e.g. gordon) by adding: '+OH' (for oxford harvard subcortical atlas) and '+SUIT' for SUIT cerebellar atlas. e.g.: gordon2014_333+OH+SUIT' parc_type : str Can be 'sphere' or 'region'. If nothing is specified, the default for that parcellation will be used. parc_params : dict **kwargs for nilearn functions Returns ------- data : array Data after the parcellation. NOTE ---- These functions make use of nilearn. Please cite nilearn if used in a publicaiton. """ if isinstance(parcellation, str): parcin = '' if '+' in parcellation: parcin = parcellation parcellation = parcellation.split('+')[0] if '+OH' in parcin: subcortical = True else: subcortical = None if '+SUIT' in parcin: cerebellar = True else: cerebellar = None if not parc_type or not parc_params: path = tenetopath[0] + '/data/parcellation_defaults/defaults.json' with open(path) as data_file: defaults = json.load(data_file) if not parc_type: parc_type = defaults[parcellation]['type'] print('Using default parcellation type') if not parc_params: parc_params = defaults[parcellation]['params'] print('Using default parameters') if parc_type == 'sphere': parcellation = load_parcellation_coords(parcellation) seed = NiftiSpheresMasker(np.array(parcellation), **parc_params) data = seed.fit_transform(data_path) elif parc_type == 'region': path = tenetopath[0] + '/data/parcellation/' + parcellation + '.nii.gz' region = NiftiLabelsMasker(path, **parc_params) data = region.fit_transform(data_path) else: raise ValueError('Unknown parc_type specified') if subcortical: subatlas = fetch_atlas_harvard_oxford('sub-maxprob-thr0-2mm')['maps'] region = NiftiLabelsMasker(subatlas, **parc_params) data_sub = region.fit_transform(data_path) data = np.hstack([data, data_sub]) if cerebellar: path = tenetopath[0] + '/data/parcellation/Cerebellum-SUIT_space-MNI152NLin2009cAsym.nii.gz' region = NiftiLabelsMasker(path, **parc_params) data_cerebellar = region.fit_transform(data_path) data = np.hstack([data, data_cerebellar]) return data
def make_parcellation(data_path, parcellation, parc_type=None, parc_params=None): """ Performs a parcellation which reduces voxel space to regions of interest (brain data). Parameters ---------- data_path : str Path to .nii image. parcellation : str Specify which parcellation that you would like to use. For MNI: 'gordon2014_333', 'power2012_264', For TAL: 'shen2013_278'. It is possible to add the OH subcotical atlas on top of a cortical atlas (e.g. gordon) by adding: '+sub-maxprob-thr0-1mm', '+sub-maxprob-thr0-2mm', 'sub-maxprob-thr25-1mm', 'sub-maxprob-thr25-2mm', '+sub-maxprob-thr50-1mm', '+sub-maxprob-thr50-2mm'. e.g.: gordon2014_333+submaxprob-thr0-2mm' parc_type : str Can be 'sphere' or 'region'. If nothing is specified, the default for that parcellation will be used. parc_params : dict **kwargs for nilearn functions Returns ------- data : array Data after the parcellation. NOTE ---- These functions make use of nilearn. Please cite nilearn if used in a publicaiton. """ if isinstance(parcellation, str): if '+' in parcellation: parcin = parcellation.split('+') parcellation = parcin[0] subcortical = parcin[1] else: subcortical = None if not parc_type or not parc_params: path = teneto.__path__[ 0] + '/data/parcellation_defaults/defaults.json' with open(path) as data_file: defaults = json.load(data_file) if not parc_type: parc_type = defaults[parcellation]['type'] print('Using default parcellation type') if not parc_params: parc_params = defaults[parcellation]['params'] print('Using default parameters') if parc_type == 'sphere': parcellation = teneto.utils.load_parcellation_coords(parcellation) seed = NiftiSpheresMasker(np.array(parcellation), **parc_params) data = seed.fit_transform(data_path) elif parc_type == 'region': path = teneto.__path__[ 0] + '/data/parcellation/' + parcellation + '.nii' region = NiftiLabelsMasker(path, **parc_params) data = region.fit_transform(data_path) else: raise ValueError('Unknown parc_type specified') if subcortical: subatlas = fetch_atlas_harvard_oxford('sub-maxprob-thr0-2mm')['maps'] region = NiftiLabelsMasker(subatlas, **parc_params) data_sub = region.fit_transform(data_path) data = np.hstack([data, data_sub]) return data