def node_gen(coords, parcel_list, label_names, dir_path, ID, parc, atlas_select, uatlas_select, node_size=None): try: import cPickle as pickle except ImportError: import _pickle as pickle from pynets import nodemaker pick_dump = False if parc is True: [net_parcels_map_nifti, _] = nodemaker.create_parcel_atlas(parcel_list) else: net_parcels_map_nifti = None print('No additional roi masking...') coords = list(tuple(x) for x in coords) if pick_dump is True: # Save coords to pickle coords_path = "%s%s" % (dir_path, '/atlas_coords_wb.pkl') with open(coords_path, 'wb') as f: pickle.dump(coords, f, protocol=2) # Save labels to pickle labels_path = "%s%s" % (dir_path, '/atlas_labelnames_wb.pkl') with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) return net_parcels_map_nifti, coords, label_names, atlas_select, uatlas_select, node_size
def node_gen(coords, parcel_list, label_names, dir_path, ID, parc, atlas_select, uatlas_select): try: import cPickle as pickle except ImportError: import _pickle as pickle from pynets import nodemaker pick_dump = False if parc is True: [net_parcels_map_nifti, _] = nodemaker.create_parcel_atlas(parcel_list) vox_list = [] for i in range(len(parcel_list)): vox_list.append(np.count_nonzero(parcel_list[i].get_data())) vox_array = np.array(vox_list).astype('float64') else: net_parcels_map_nifti = None vox_array = None print('No additional masking...') coords = list(tuple(x) for x in coords) if pick_dump is True: # Save coords to pickle coord_path = "%s%s" % (dir_path, '/atlas_coords_wb.pkl') with open(coord_path, 'wb') as f: pickle.dump(coords, f, protocol=2) # Save labels to pickle labels_path = "%s%s" % (dir_path, '/atlas_labelnames_wb.pkl') with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) return net_parcels_map_nifti, coords, label_names, atlas_select, uatlas_select, vox_array
def test_nodemaker_tools_parlistfile_WB(): # Set example inputs base_dir = str(Path(__file__).parent / "examples") #base_dir = '/Users/rxh180012/PyNets-development/tests/examples' parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' start_time = time.time() [WB_coords, _, _] = nodemaker.get_names_and_coords_of_parcels(parlistfile) print("%s%s%s" % ( 'get_names_and_coords_of_parcels (User-atlas whole-brain version) --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) WB_label_names = np.arange(len(WB_coords) + 1)[np.arange(len(WB_coords) + 1) != 0].tolist() start_time = time.time() WB_parcel_list = nodemaker.gen_img_list(parlistfile) [WB_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(WB_parcel_list) print( "%s%s%s" % ('create_parcel_atlas (User-atlas whole-brain version) --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) assert WB_coords is not None assert WB_label_names is not None assert WB_parcel_list is not None assert WB_parcels_map_nifti is not None assert parcel_list_exp is not None
def test_nodemaker_tools_parlistfile_RSN(): ##Set example inputs## base_dir = str(Path(__file__).parent / "examples") #base_dir = '/Users/PSYC-dap3463/Applications/PyNets/tests/examples' dir_path = base_dir + '/997' func_file = dir_path + '/sub-997_ses-01_task-REST_run-01_bold_space-MNI152NLin2009cAsym_preproc_masked.nii.gz' parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' network = 'Default' parc = True atlas_select = 'whole_brain_cluster_labels_PCA200' [coords, atlas_select, par_max, parcel_list] = nodemaker.get_names_and_coords_of_parcels(parlistfile) label_names = np.arange(len(coords) + 1)[np.arange(len(coords) + 1) != 0].tolist() [net_coords, net_parcel_list, net_label_names, network] = nodemaker.get_node_membership(network, func_file, coords, label_names, parc, parcel_list) [net_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(net_parcel_list) out_path = nodemaker.gen_network_parcels(parlistfile, network, net_label_names, dir_path) assert coords is not None assert net_coords is not None assert net_label_names is not None assert net_parcel_list is not None assert out_path is not None assert net_parcels_map_nifti is not None assert parcel_list_exp is not None assert network is not None
def node_gen(coords, parcel_list, label_names, dir_path, ID, parc): try: import cPickle as pickle except ImportError: import _pickle as pickle from pynets import nodemaker pick_dump = False if parc == True: [net_parcels_map_nifti, parcel_list_adj] = nodemaker.create_parcel_atlas(parcel_list) else: net_parcels_map_nifti = None print('No additional masking...') if pick_dump == True: ##Save coords to pickle coord_path = "%s%s" % (dir_path, '/whole_brain_atlas_coords_wb.pkl') with open(coord_path, 'wb') as f: pickle.dump(coords, f, protocol=2) ##Save labels to pickle labels_path = "%s%s" % (dir_path, '/whole_brain_atlas_labelnames_wb.pkl') with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) return (net_parcels_map_nifti, coords, label_names)
def node_gen_masking(mask, coords, parcel_list, label_names, dir_path, ID, parc): from pynets import nodemaker try: import cPickle as pickle except ImportError: import _pickle as pickle ##Mask Parcels if parc == True: [coords, label_names, parcel_list_masked ] = nodemaker.parcel_masker(mask, coords, parcel_list, label_names, dir_path, ID) [net_parcels_map_nifti, parcel_list_adj] = nodemaker.create_parcel_atlas(parcel_list_masked) ##Mask Coordinates elif parc == False: [coords, label_names] = nodemaker.coord_masker(mask, coords, label_names) ##Save coords to pickle coord_path = "%s%s%s%s" % (dir_path, '/whole_brain_atlas_coords_', os.path.basename(mask).split('.')[0], '.pkl') with open(coord_path, 'wb') as f: pickle.dump(coords, f, protocol=2) net_parcels_map_nifti = None ##Save labels to pickle labels_path = "%s%s%s%s" % (dir_path, '/whole_brain_atlas_labelnames_', os.path.basename(mask).split('.')[0], '.pkl') with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) return (net_parcels_map_nifti, coords, label_names)
def test_nodemaker_tools_masking_parlistfile_RSN(): # Set example inputs base_dir = str(Path(__file__).parent / "examples") #base_dir = '/Users/rxh180012/PyNets-development/tests/examples' dir_path = base_dir + '/997' func_file = dir_path + '/sub-997_ses-01_task-REST_run-01_bold_space-MNI152NLin2009cAsym_preproc_masked.nii.gz' parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' mask = dir_path + '/pDMN_3_bin.nii.gz' network = 'Default' ID = '997' perc_overlap = 0.10 parc = True start_time = time.time() [coords, _, _] = nodemaker.get_names_and_coords_of_parcels(parlistfile) print("%s%s%s" % ('get_names_and_coords_of_parcels --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) label_names = np.arange(len(coords) + 1)[np.arange(len(coords) + 1) != 0].tolist() start_time = time.time() parcel_list = nodemaker.gen_img_list(parlistfile) [net_coords, net_parcel_list, net_label_names, network] = nodemaker.get_node_membership(network, func_file, coords, label_names, parc, parcel_list) print("%s%s%s" % ('get_node_membership --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [net_coords_masked, net_label_names_masked, net_parcel_list_masked ] = nodemaker.parcel_masker(mask, net_coords, net_parcel_list, net_label_names, dir_path, ID, perc_overlap) print("%s%s%s" % ('parcel_masker --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [net_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(net_parcel_list_masked) print("%s%s%s" % ('create_parcel_atlas --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() out_path = nodemaker.gen_network_parcels(parlistfile, network, net_label_names_masked, dir_path) print("%s%s%s" % ('gen_network_parcels --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) assert coords is not None assert net_coords is not None assert net_label_names is not None assert net_parcel_list is not None assert net_coords_masked is not None assert net_label_names_masked is not None assert net_parcel_list_masked is not None assert out_path is not None assert net_parcels_map_nifti is not None assert parcel_list_exp is not None assert network is not None
def test_nodemaker_tools_masking_parlistfile_WB(): # Set example inputs base_dir = str(Path(__file__).parent/"examples") #base_dir = '/Users/rxh180012/PyNets-development/tests/examples' dir_path = base_dir + '/997' parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' atlas_select = 'whole_brain_cluster_labels_PCA200' roi = dir_path + '/pDMN_3_bin.nii.gz' mask = None ID = '997' parc = True perc_overlap = 0.10 start_time = time.time() [WB_coords, _, _] = nodemaker.get_names_and_coords_of_parcels(parlistfile) print("%s%s%s" % ('get_names_and_coords_of_parcels (Masking whole-brain version) --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) WB_label_names = np.arange(len(WB_coords) + 1)[np.arange(len(WB_coords) + 1) != 0].tolist() start_time = time.time() WB_parcel_list = nodemaker.gen_img_list(parlistfile) [_, _, WB_parcel_list_masked] = nodemaker.parcel_masker(roi, WB_coords, WB_parcel_list, WB_label_names, dir_path, ID, mask, perc_overlap) print("%s%s%s" % ('parcel_masker (Masking whole-brain version) --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [WB_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(WB_parcel_list_masked) print("%s%s%s" % ('create_parcel_atlas (Masking whole-brain version) --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [WB_net_parcels_map_nifti_unmasked, WB_coords_unmasked, _, WB_atlas_select, WB_uatlas_select] = nodemaker.node_gen(WB_coords, WB_parcel_list, WB_label_names, dir_path, ID, parc, atlas_select, parlistfile) print("%s%s%s" % ('node_gen (Masking whole-brain version) --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [WB_net_parcels_map_nifti_masked, WB_coords_masked, WB_label_names_masked, WB_atlas_select, WB_uatlas_select] = nodemaker.node_gen_masking(roi, WB_coords, WB_parcel_list, WB_label_names, dir_path, ID, parc, atlas_select, parlistfile, mask) print("%s%s%s" % ('node_gen_masking (Masking whole-brain version) --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) assert WB_coords is not None assert WB_label_names is not None assert WB_parcel_list is not None assert WB_coords_masked is not None assert WB_label_names_masked is not None assert WB_parcel_list_masked is not None assert WB_parcels_map_nifti is not None assert parcel_list_exp is not None assert WB_net_parcels_map_nifti_unmasked is not None assert WB_coords_unmasked is not None assert WB_net_parcels_map_nifti_masked is not None assert WB_coords_masked is not None
def test_nodemaker_tools_masking_parlistfile_RSN(): # Set example inputs base_dir = str(Path(__file__).parent / "examples") dir_path = base_dir + '/002/fmri' func_file = dir_path + '/002.nii.gz' parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' roi = base_dir + '/pDMN_3_bin.nii.gz' network = 'Default' ID = '002' perc_overlap = 0.10 parc = True start_time = time.time() [coords, _, _] = nodemaker.get_names_and_coords_of_parcels(parlistfile) print("%s%s%s" % ('get_names_and_coords_of_parcels --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) labels = np.arange(len(coords) + 1)[np.arange(len(coords) + 1) != 0].tolist() start_time = time.time() parcel_list = nodemaker.gen_img_list(parlistfile) [net_coords, net_parcel_list, net_labels, network] = nodemaker.get_node_membership(network, func_file, coords, labels, parc, parcel_list) print("%s%s%s" % ('get_node_membership --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [net_coords_masked, net_labels_masked, net_parcel_list_masked ] = nodemaker.parcel_masker(roi, net_coords, net_parcel_list, net_labels, dir_path, ID, perc_overlap) print("%s%s%s" % ('parcel_masker --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [net_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(net_parcel_list_masked) print("%s%s%s" % ('create_parcel_atlas --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() out_path = nodemaker.gen_network_parcels(parlistfile, network, net_labels_masked, dir_path) print("%s%s%s" % ('gen_network_parcels --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) assert coords is not None assert net_coords is not None assert net_labels is not None assert net_parcel_list is not None assert net_coords_masked is not None assert net_labels_masked is not None assert net_parcel_list_masked is not None assert out_path is not None assert net_parcels_map_nifti is not None assert parcel_list_exp is not None assert network is not None
def parcel_masker(mask, coords, parcel_list, label_names, dir_path, ID): from pynets import nodemaker from nilearn.image import resample_img from nilearn import masking ##For parcel masking, specify overlap thresh and error cushion in mm voxels perc_overlap = 0.75 ##Default is >=90% overlap mask_img = nib.load(mask) mask_data, _ = masking._load_mask_img(mask) i = 0 indices = [] for parcel in parcel_list: parcel_vol = np.zeros(mask_data.shape, dtype=bool) parcel_data_reshaped = resample_img(parcel, target_affine=mask_img.affine, target_shape=mask_data.shape).get_data() parcel_vol[parcel_data_reshaped==1] = 1 ##Count number of unique voxels where overlap of parcel and mask occurs overlap_count = len(np.unique(np.where((mask_data.astype('uint8')==1) & (parcel_vol.astype('uint8')==1)))) ##Count number of total unique voxels within the parcel total_count = len(np.unique(np.where(((parcel_vol.astype('uint8')==1))))) ##Calculate % overlap try: overlap = float(overlap_count/total_count) except: overlap = float(0) if overlap >= perc_overlap: print(str(round(100*overlap,1)) + '% of parcel ' + str(label_names[i]) + ' falls within mask...') else: indices.append(i) i = i + 1 label_names_adj=list(label_names) coords_adj = list(tuple(x) for x in coords) parcel_list_adj = parcel_list for ix in sorted(indices, reverse=True): print('Removing: ' + str(label_names_adj[ix]) + ' at ' + str(coords_adj[ix])) label_names_adj.pop(ix) coords_adj.pop(ix) parcel_list_adj.pop(ix) ##Create a resampled 3D atlas that can be viewed alongside mask img for QA resampled_parcels_nii_path = dir_path + '/' + ID + '_parcels_resampled2mask_' + str(os.path.basename(mask).split('.')[0]) + '.nii.gz' resampled_parcels_atlas, _ = nodemaker.create_parcel_atlas(parcel_list_adj) resampled_parcels_map_nifti = resample_img(resampled_parcels_atlas, target_affine=mask_img.affine, target_shape=mask_data.shape) nib.save(resampled_parcels_map_nifti, resampled_parcels_nii_path) return(coords_adj, label_names_adj, parcel_list_adj)
def node_gen_masking(mask, coords, parcel_list, label_names, dir_path, ID, parc, atlas_select, uatlas_select): from pynets import nodemaker try: import cPickle as pickle except ImportError: import _pickle as pickle # Mask Parcels if parc is True: # For parcel masking, specify overlap thresh and error cushion in mm voxels if 'bedpostX' in dir_path: perc_overlap = 0.01 else: perc_overlap = 0.75 [coords, label_names, parcel_list_masked ] = nodemaker.parcel_masker(mask, coords, parcel_list, label_names, dir_path, ID, perc_overlap) [net_parcels_map_nifti, _] = nodemaker.create_parcel_atlas(parcel_list_masked) vox_list = [] for i in range(len(parcel_list)): vox_list.append(np.count_nonzero(parcel_list[i].get_data())) vox_array = np.array(vox_list).astype('float64') # Mask Coordinates else: if 'bedpostX' in dir_path: error = 60 else: error = 2 [coords, label_names] = nodemaker.coord_masker(mask, coords, label_names, error) # Save coords to pickle coord_path = "%s%s%s%s" % (dir_path, '/atlas_coords_', os.path.basename(mask).split('.')[0], '.pkl') with open(coord_path, 'wb') as f: pickle.dump(coords, f, protocol=2) net_parcels_map_nifti = None vox_array = None # Save labels to pickle labels_path = "%s%s%s%s" % (dir_path, '/atlas_labelnames_', os.path.basename(mask).split('.')[0], '.pkl') with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) return net_parcels_map_nifti, coords, label_names, atlas_select, uatlas_select, vox_array
def test_nodemaker_tools_parlistfile_RSN(): # Set example inputs base_dir = str(Path(__file__).parent / "examples") #base_dir = '/Users/PSYC-dap3463/Applications/PyNets/tests/examples' dir_path = base_dir + '/997' func_file = dir_path + '/sub-997_ses-01_task-REST_run-01_bold_space-MNI152NLin2009cAsym_preproc_masked.nii.gz' parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' network = 'Default' parc = True start_time = time.time() [coords, _, _, parcel_list] = nodemaker.get_names_and_coords_of_parcels(parlistfile) print("%s%s%s" % ('get_names_and_coords_of_parcels --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) label_names = np.arange(len(coords) + 1)[np.arange(len(coords) + 1) != 0].tolist() start_time = time.time() [net_coords, net_parcel_list, net_label_names, network] = nodemaker.get_node_membership(network, func_file, coords, label_names, parc, parcel_list) print("%s%s%s" % ('get_node_membership --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() [net_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(net_parcel_list) print("%s%s%s" % ('create_parcel_atlas --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) start_time = time.time() out_path = nodemaker.gen_network_parcels(parlistfile, network, net_label_names, dir_path) print("%s%s%s" % ('gen_network_parcels --> finished: ', str(np.round(time.time() - start_time, 1)), 's')) assert coords is not None assert net_coords is not None assert net_label_names is not None assert net_parcel_list is not None assert out_path is not None assert net_parcels_map_nifti is not None assert parcel_list_exp is not None assert network is not None
def node_gen_masking(roi, coords, parcel_list, label_names, dir_path, ID, parc, atlas_select, uatlas_select, mask, node_size=None): from pynets import nodemaker import os.path as op try: import cPickle as pickle except ImportError: import _pickle as pickle # Mask Parcels if parc is True: # For parcel masking, specify overlap thresh and error cushion in mm voxels perc_overlap = 0.75 [coords, label_names, parcel_list_masked ] = nodemaker.parcel_masker(roi, coords, parcel_list, label_names, dir_path, ID, mask, perc_overlap) [net_parcels_map_nifti, _] = nodemaker.create_parcel_atlas(parcel_list_masked) # Mask Coordinates else: error = 2 [coords, label_names] = nodemaker.coords_masker(roi, coords, label_names, mask, error) # Save coords to pickle coords_path = "%s%s%s%s" % (dir_path, '/atlas_coords_', op.basename(roi).split('.')[0], '.pkl') with open(coords_path, 'wb') as f: pickle.dump(coords, f, protocol=2) net_parcels_map_nifti = None # Save labels to pickle labels_path = "%s%s%s%s" % (dir_path, '/atlas_labelnames_', op.basename(roi).split('.')[0], '.pkl') with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) return net_parcels_map_nifti, coords, label_names, atlas_select, uatlas_select, node_size
def test_nodemaker_tools_masking_parlistfile_WB(): ##Set example inputs## base_dir = str(Path(__file__).parent / "examples") dir_path = base_dir + '/997' parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' mask = dir_path + '/pDMN_3_bin.nii.gz' ID = '997' atlas_select = 'whole_brain_cluster_labels_PCA200' parc = True [WB_coords, atlas_select, par_max, WB_parcel_list] = nodemaker.get_names_and_coords_of_parcels(parlistfile) WB_label_names = np.arange(len(WB_coords) + 1)[np.arange(len(WB_coords) + 1) != 0].tolist() [WB_coords_masked, WB_label_names_masked, WB_parcel_list_masked ] = nodemaker.parcel_masker(mask, WB_coords, WB_parcel_list, WB_label_names, dir_path, ID) [WB_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(WB_parcel_list_masked) [ WB_net_parcels_map_nifti_unmasked, WB_coords_unmasked, WB_label_names_unmasked ] = nodemaker.node_gen(WB_coords, WB_parcel_list, WB_label_names, dir_path, ID, parc) [WB_net_parcels_map_nifti_masked, WB_coords_masked, WB_label_names_masked ] = nodemaker.node_gen_masking(mask, WB_coords, WB_parcel_list, WB_label_names, dir_path, ID, parc) assert WB_coords is not None assert WB_label_names is not None assert WB_parcel_list is not None assert WB_coords_masked is not None assert WB_label_names_masked is not None assert WB_parcel_list_masked is not None assert WB_parcels_map_nifti is not None assert parcel_list_exp is not None assert WB_net_parcels_map_nifti_unmasked is not None assert WB_coords_unmasked is not None assert WB_net_parcels_map_nifti_masked is not None assert WB_coords_masked is not None
def test_nodemaker_tools_parlistfile_WB(): ##Set example inputs## base_dir = str(Path(__file__).parent / "examples") parlistfile = base_dir + '/whole_brain_cluster_labels_PCA200.nii.gz' atlas_select = 'whole_brain_cluster_labels_PCA200' [WB_coords, atlas_select, par_max, WB_parcel_list] = nodemaker.get_names_and_coords_of_parcels(parlistfile) WB_label_names = np.arange(len(WB_coords) + 1)[np.arange(len(WB_coords) + 1) != 0].tolist() [WB_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(WB_parcel_list) assert WB_coords is not None assert WB_label_names is not None assert WB_parcel_list is not None assert WB_parcels_map_nifti is not None assert parcel_list_exp is not None
def node_gen_masking(mask, coords, parcel_list, label_names, dir_path, ID, parc): from pynets import nodemaker try: import cPickle as pickle except ImportError: import _pickle as pickle # Mask Parcels if parc is True: # For parcel masking, specify overlap thresh and error cushion in mm voxels if 'bedpostX' in dir_path: perc_overlap = 0.01 else: perc_overlap = 0.75 [coords, label_names, parcel_list_masked ] = nodemaker.parcel_masker(mask, coords, parcel_list, label_names, dir_path, ID, perc_overlap) [net_parcels_map_nifti, _] = nodemaker.create_parcel_atlas(parcel_list_masked) # Mask Coordinates elif parc is False: if 'bedpostX' in dir_path: error = 60 else: error = 2 [coords, label_names] = nodemaker.coord_masker(mask, coords, label_names, error) # Save coords to pickle coord_path = "%s%s%s%s" % (dir_path, '/whole_brain_atlas_coords_', os.path.basename(mask).split('.')[0], '.pkl') with open(coord_path, 'wb') as f: pickle.dump(coords, f, protocol=2) net_parcels_map_nifti = None # Save labels to pickle labels_path = "%s%s%s%s" % (dir_path, '/whole_brain_atlas_labelnames_', os.path.basename(mask).split('.')[0], '.pkl') with open(labels_path, 'wb') as f: pickle.dump(label_names, f, protocol=2) return net_parcels_map_nifti, coords, label_names
def node_gen_masking(roi, coords, parcel_list, labels, dir_path, ID, parc, atlas, uatlas, perc_overlap=0.75, error=4): """ In the case that masking was applied, this function generate nodes based on atlas definitions established by fetch_nodes_and_labels. Parameters ---------- roi : str File path to binarized/boolean region-of-interest Nifti1Image file. coords : list List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node. parcel_list : list List of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks. labels : list List of string labels corresponding to ROI nodes. dir_path : str Path to directory containing subject derivative data for given run. ID : str A subject id or other unique identifier. parc : bool Indicates whether to use parcels instead of coordinates as ROI nodes. atlas : str Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn's datasets.atlas module for more detailed reference. uatlas : str File path to atlas parcellation Nifti1Image in MNI template space. perc_overlap : float Value 0-1 indicating a threshold of spatial overlap to use as a spatial error cushion in the case of evaluating mask/RSN membership from a given list of parcel masks. Default is 0.75. error : int Rounded euclidean distance, in units of voxel number, to use as a spatial error cushion in the case of evaluating mask/RSN membership from a given list of coordinates. Default is 4. Returns ------- net_parcels_map_nifti : Nifti1Image A nibabel-based nifti image consisting of a 3D array with integer voxel intensities corresponding to ROI membership. coords : list List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node. labels : list List of string labels corresponding to ROI nodes. atlas : str Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn's datasets.atlas module for more detailed reference. uatlas : str File path to atlas parcellation Nifti1Image in MNI template space. """ from pynets import nodemaker import os.path as op try: import cPickle as pickle except ImportError: import _pickle as pickle # Mask Parcels if parc is True: # For parcel masking, specify overlap thresh and error cushion in mm voxels [coords, labels, parcel_list_masked ] = nodemaker.parcel_masker(roi, coords, parcel_list, labels, dir_path, ID, perc_overlap) [net_parcels_map_nifti, _] = nodemaker.create_parcel_atlas(parcel_list_masked) # Mask Coordinates else: [coords, labels] = nodemaker.coords_masker(roi, coords, labels, error) # Save coords to pickle coords_path = "%s%s%s%s" % (dir_path, '/atlas_coords_', op.basename(roi).split('.')[0], '.pkl') with open(coords_path, 'wb') as f: pickle.dump(coords, f, protocol=2) net_parcels_map_nifti = None # Save labels to pickle labels_path = "%s%s%s%s" % (dir_path, '/atlas_labelnames_', op.basename(roi).split('.')[0], '.pkl') with open(labels_path, 'wb') as f: pickle.dump(labels, f, protocol=2) return net_parcels_map_nifti, coords, labels, atlas, uatlas
def parcel_masker(roi, coords, parcel_list, label_names, dir_path, ID, mask, perc_overlap): from pynets import nodemaker from nilearn.image import resample_img from nilearn import masking import os.path as op if mask and roi == mask: perc_overlap = 0.9 mask_img = nib.load(roi) mask_data, _ = masking._load_mask_img(roi) i = 0 indices = [] for parcel in parcel_list: parcel_vol = np.zeros(mask_data.shape, dtype=bool) parcel_data_reshaped = resample_img( parcel, target_affine=mask_img.affine, target_shape=mask_data.shape).get_fdata() parcel_vol[parcel_data_reshaped == 1] = 1 # Count number of unique voxels where overlap of parcel and mask occurs overlap_count = len( np.unique( np.where((mask_data.astype('uint8') == 1) & (parcel_vol.astype('uint8') == 1)))) # Count number of total unique voxels within the parcel total_count = len( np.unique(np.where((parcel_vol.astype('uint8') == 1)))) # Calculate % overlap try: overlap = float(overlap_count / total_count) except RuntimeWarning: print('\nWarning: No overlap with roi mask!\n') overlap = float(0) if overlap >= perc_overlap: print("%.2f%s%s%s" % (100 * overlap, '% of parcel ', label_names[i], ' falls within roi mask...')) else: indices.append(i) i = i + 1 label_names_adj = list(label_names) coords_adj = list(tuple(x) for x in coords) parcel_list_adj = parcel_list try: for ix in sorted(indices, reverse=True): print("%s%s%s%s" % ('Removing: ', label_names_adj[ix], ' at ', coords_adj[ix])) label_names_adj.pop(ix) coords_adj.pop(ix) parcel_list_adj.pop(ix) except RuntimeError: print( 'ERROR: Restrictive masking. No parcels remain after masking with brain mask/roi...' ) # Create a resampled 3D atlas that can be viewed alongside mask img for QA resampled_parcels_nii_path = "%s%s%s%s%s%s" % ( dir_path, '/', ID, '_parcels_resampled2roimask_', op.basename(roi).split('.')[0], '.nii.gz') resampled_parcels_atlas, _ = nodemaker.create_parcel_atlas(parcel_list_adj) resampled_parcels_map_nifti = resample_img(resampled_parcels_atlas, target_affine=mask_img.affine, target_shape=mask_data.shape) nib.save(resampled_parcels_map_nifti, resampled_parcels_nii_path) mask_img.uncache() resampled_parcels_map_nifti.uncache() if not coords_adj: raise ValueError( '\nERROR: ROI mask was likely too restrictive and yielded < 2 remaining parcels' ) return coords_adj, label_names_adj, parcel_list_adj
def node_gen(coords, parcel_list, labels, dir_path, ID, parc, atlas, uatlas): """ In the case that masking was not applied, this function generate nodes based on atlas definitions established by fetch_nodes_and_labels. Parameters ---------- coords : list List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node. parcel_list : list List of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks. labels : list List of string labels corresponding to ROI nodes. dir_path : str Path to directory containing subject derivative data for given run. ID : str A subject id or other unique identifier. parc : bool Indicates whether to use parcels instead of coordinates as ROI nodes. atlas : str Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn's datasets.atlas module for more detailed reference. uatlas : str File path to atlas parcellation Nifti1Image in MNI template space. Returns ------- net_parcels_map_nifti : Nifti1Image A nibabel-based nifti image consisting of a 3D array with integer voxel intensities corresponding to ROI membership. coords : list List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node. labels : list List of string labels corresponding to ROI nodes. atlas : str Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn's datasets.atlas module for more detailed reference. uatlas : str File path to atlas parcellation Nifti1Image in MNI template space. """ try: import cPickle as pickle except ImportError: import _pickle as pickle from pynets import nodemaker pick_dump = False if parc is True: [net_parcels_map_nifti, _] = nodemaker.create_parcel_atlas(parcel_list) else: net_parcels_map_nifti = None print('No additional roi masking...') coords = list(tuple(x) for x in coords) if pick_dump is True: # Save coords to pickle coords_path = "%s%s" % (dir_path, '/atlas_coords_wb.pkl') with open(coords_path, 'wb') as f: pickle.dump(coords, f, protocol=2) # Save labels to pickle labels_path = "%s%s" % (dir_path, '/atlas_labelnames_wb.pkl') with open(labels_path, 'wb') as f: pickle.dump(labels, f, protocol=2) return net_parcels_map_nifti, coords, labels, atlas, uatlas
def parcel_masker(mask, coords, parcel_list, label_names, dir_path, ID, perc_overlap): from pynets import nodemaker from nilearn.image import resample_img from nilearn import masking mask_img = nib.load(mask) mask_data, _ = masking._load_mask_img(mask) i = 0 indices = [] for parcel in parcel_list: parcel_vol = np.zeros(mask_data.shape, dtype=bool) parcel_data_reshaped = resample_img( parcel, target_affine=mask_img.affine, target_shape=mask_data.shape).get_data() parcel_vol[parcel_data_reshaped == 1] = 1 # Count number of unique voxels where overlap of parcel and mask occurs overlap_count = len( np.unique( np.where((mask_data.astype('uint8') == 1) & (parcel_vol.astype('uint8') == 1)))) # Count number of total unique voxels within the parcel total_count = len( np.unique(np.where((parcel_vol.astype('uint8') == 1)))) # Calculate % overlap try: overlap = float(overlap_count / total_count) except RuntimeWarning: print('\nWarning: No overlap with mask!\n') overlap = float(0) if overlap >= perc_overlap: print("%.2f%s%s%s" % (100 * overlap, '% of parcel ', label_names[i], ' falls within mask...')) else: indices.append(i) i = i + 1 label_names_adj = list(label_names) coords_adj = list(tuple(x) for x in coords) parcel_list_adj = parcel_list for ix in sorted(indices, reverse=True): print("%s%s%s%s" % ('Removing: ', label_names_adj[ix], ' at ', coords_adj[ix])) label_names_adj.pop(ix) coords_adj.pop(ix) parcel_list_adj.pop(ix) # Create a resampled 3D atlas that can be viewed alongside mask img for QA resampled_parcels_nii_path = "%s%s%s%s%s%s" % ( dir_path, '/', ID, '_parcels_resampled2mask_', os.path.basename(mask).split('.')[0], '.nii.gz') resampled_parcels_atlas, _ = nodemaker.create_parcel_atlas(parcel_list_adj) resampled_parcels_map_nifti = resample_img(resampled_parcels_atlas, target_affine=mask_img.affine, target_shape=mask_data.shape) nib.save(resampled_parcels_map_nifti, resampled_parcels_nii_path) return coords_adj, label_names_adj, parcel_list_adj
def parcel_masker(roi, coords, parcel_list, labels, dir_path, ID, perc_overlap): """ Evaluate the affinity of any arbitrary list of parcel nodes for a user-specified ROI mask. Parameters ---------- roi : str File path to binarized/boolean region-of-interest Nifti1Image file. coords : list List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node. parcel_list : list List of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks. labels : list List of string labels corresponding to ROI nodes. dir_path : str Path to directory containing subject derivative data for given run. ID : str A subject id or other unique identifier. perc_overlap : float Value 0-1 indicating a threshold of spatial overlap to use as a spatial error cushion in the case of evaluating ROI-mask membership from a given list of parcel masks. Returns ------- coords_adj : list Filtered list of (x, y, z) tuples in mm-space with a spatial affinity for the specified ROI mask. labels_adj : list Filtered list of string labels corresponding to ROI nodes with a spatial affinity for the specified ROI mask. parcel_list_adj : list Filtered list of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks with a spatial affinity to the specified ROI mask. """ from pynets import nodemaker from nilearn.image import resample_img from nilearn import masking import os.path as op import warnings warnings.filterwarnings("ignore") mask_img = nib.load(roi) mask_data, _ = masking._load_mask_img(roi) i = 0 indices = [] for parcel in parcel_list: parcel_vol = np.zeros(mask_data.shape, dtype=bool) parcel_data_reshaped = resample_img( parcel, target_affine=mask_img.affine, target_shape=mask_data.shape).get_fdata() parcel_vol[parcel_data_reshaped == 1] = 1 # Count number of unique voxels where overlap of parcel and mask occurs overlap_count = len( np.unique( np.where((mask_data.astype('uint8') == 1) & (parcel_vol.astype('uint8') == 1)))) # Count number of total unique voxels within the parcel total_count = len( np.unique(np.where((parcel_vol.astype('uint8') == 1)))) # Calculate % overlap try: overlap = float(overlap_count / total_count) except: print("%s%s%s" % ('\nWarning: No overlap of parcel', labels[i], 'with roi mask!\n')) overlap = float(0) if overlap >= perc_overlap: print("%.2f%s%s%s" % (100 * overlap, '% of parcel ', labels[i], ' falls within mask...')) else: indices.append(i) i = i + 1 labels_adj = list(labels) coords_adj = list(tuple(x) for x in coords) parcel_list_adj = parcel_list try: for ix in sorted(indices, reverse=True): print("%s%s%s%s" % ('Removing: ', labels_adj[ix], ' at ', coords_adj[ix])) labels_adj.pop(ix) coords_adj.pop(ix) parcel_list_adj.pop(ix) except RuntimeError: print( 'ERROR: Restrictive masking. No parcels remain after masking with brain mask/roi...' ) # Create a resampled 3D atlas that can be viewed alongside mask img for QA resampled_parcels_nii_path = "%s%s%s%s%s%s" % ( dir_path, '/', ID, '_parcels_resampled2roimask_', op.basename(roi).split('.')[0], '.nii.gz') resampled_parcels_atlas, _ = nodemaker.create_parcel_atlas(parcel_list_adj) resampled_parcels_map_nifti = resample_img(resampled_parcels_atlas, target_affine=mask_img.affine, target_shape=mask_data.shape) nib.save(resampled_parcels_map_nifti, resampled_parcels_nii_path) mask_img.uncache() resampled_parcels_map_nifti.uncache() if not coords_adj: raise ValueError( '\nERROR: ROI mask was likely too restrictive and yielded < 2 remaining parcels' ) return coords_adj, labels_adj, parcel_list_adj