def test_nodemaker_tools_masking_coords_WB(atlas): """ Test nodemaker_tools_masking_coords_WB functionality """ # Set example inputs roi = tempfile.NamedTemporaryFile(mode="w+", suffix=".nii.gz").name data_gen.generate_mni_space_img()[1].to_filename(roi) error = 2 start_time = time.time() [WB_coords, _, _, WB_labels] = nodemaker.fetch_nilearn_atlas_coords(atlas) print("%s%s%s" % ( "fetch_nilearn_atlas_coords (Masking whole-brain " "coords version) --> finished: ", str(np.round(time.time() - start_time, 1)), "s", )) start_time = time.time() [WB_coords_masked, WB_labels_masked] = nodemaker.coords_masker(roi, WB_coords, WB_labels, error) print("%s%s%s" % ( "coords_masker (Masking whole-brain coords version) " "--> finished: ", str(np.round(time.time() - start_time, 1)), "s", )) assert WB_coords is not None assert WB_coords is not None assert WB_coords_masked is not None assert WB_labels is not None assert WB_labels_masked is not None
def test_compute_brain_mask(): img, _ = data_gen.generate_mni_space_img(res=8, random_state=0) brain_mask = compute_brain_mask(img, threshold=.2) gm_mask = compute_brain_mask(img, threshold=.2, mask_type="gm") wm_mask = compute_brain_mask(img, threshold=.2, mask_type="wm") brain_data, gm_data, wm_data = map(get_data, (brain_mask, gm_mask, wm_mask)) # Check that whole-brain mask is non-empty assert (brain_data != 0).any() for subset in gm_data, wm_data: # Test that gm and wm masks are included in the whole-brain mask assert (np.logical_and(brain_data, subset) == subset.astype(bool)).all() # Test that gm and wm masks are non-empty assert (subset != 0).any() # Test that gm and wm masks have empty intersection assert (np.logical_and(gm_data, wm_data) == 0).all() # Check that we get a useful warning for empty masks with pytest.warns(masking.MaskWarning): compute_brain_mask(img, threshold=1) # Check that masks obtained from same FOV are the same img1, _ = data_gen.generate_mni_space_img(res=8, random_state=1) mask_img1 = compute_brain_mask(img1, verbose=1, threshold=.2) assert (brain_data == get_data(mask_img1)).all() # Check that error is raised if mask type is unknown with pytest.raises(ValueError, match='Unknown mask type foo.'): compute_brain_mask(img, verbose=1, mask_type='foo')
def test_nodemaker_tools_masking_coords_RSN(atlas): """ Test nodemaker_tools_masking_coords_RSN functionality """ # Set example inputs template = pkg_resources.resource_filename( "pynets", f"templates/standard/MNI152_T1_brain_2mm.nii.gz") dir_path = str(tempfile.TemporaryDirectory().name) os.makedirs(dir_path, exist_ok=True) roi = tempfile.NamedTemporaryFile(mode="w+", suffix=".nii.gz").name data_gen.generate_mni_space_img()[1].to_filename(roi) subnet = "Default" parc = False parcels_4d_img = None error = 2 start_time = time.time() [coords, _, _, labels] = nodemaker.fetch_nilearn_atlas_coords(atlas) print("%s%s%s" % ( "fetch_nilearn_atlas_coords (Masking subnet version) --> " "finished: ", str(np.round(time.time() - start_time, 1)), "s", )) start_time = time.time() [net_coords, _, net_labels, subnet] = nodemaker.get_node_membership(subnet, template, coords, labels, parc, parcels_4d_img) print("%s%s%s" % ( "get_node_membership (Masking subnet version) --> " "finished: ", str(np.round(time.time() - start_time, 1)), "s", )) start_time = time.time() [net_coords_masked, net_labels_masked] = nodemaker.coords_masker(roi, net_coords, net_labels, error) print("%s%s%s" % ( "coords_masker (Masking subnet version) --> finished: ", str(np.round(time.time() - start_time, 1)), "s", )) assert coords is not None assert net_coords is not None assert net_coords_masked is not None assert net_labels is not None assert net_labels_masked is not None assert subnet is not None
def test_mask_roi(): """ Test mask_roi functionality """ mask = pkg_resources.resource_filename( "pynets", "templates/standard/MNI152_T1_brain_mask_2mm.nii.gz") dir_path = str(tempfile.TemporaryDirectory().name) os.makedirs(dir_path, exist_ok=True) func_file = tempfile.NamedTemporaryFile(mode="w+", suffix=".nii.gz").name data_gen.generate_fake_fmri()[1].to_filename(func_file) roi = tempfile.NamedTemporaryFile(mode="w+", suffix=".nii.gz").name data_gen.generate_mni_space_img()[1].to_filename(roi) roi_masked = nodemaker.mask_roi(dir_path, roi, mask, func_file) assert roi_masked is not None
def random_mni_roi_data(): roi_img = data_gen.generate_mni_space_img(res=2)[1] roi_file_tmp = tempfile.NamedTemporaryFile(mode='w+', suffix='.nii.gz') roi_file = str(roi_file_tmp.name) roi_img.to_filename(roi_file) yield {'roi_file': roi_file} roi_file_tmp.close()
def test_vol_to_surf(kind, n_scans, use_mask): img, mask_img = data_gen.generate_mni_space_img(n_scans) if not use_mask: mask_img = None if n_scans == 1: img = image.new_img_like(img, image.get_data(img).squeeze()) fsaverage = datasets.fetch_surf_fsaverage() mesh = surface.load_surf_mesh(fsaverage["pial_left"]) inner_mesh = surface.load_surf_mesh(fsaverage["white_left"]) center_mesh = np.mean([mesh[0], inner_mesh[0]], axis=0), mesh[1] proj = surface.vol_to_surf( img, mesh, kind="depth", inner_mesh=inner_mesh, mask_img=mask_img) other_proj = surface.vol_to_surf( img, center_mesh, kind=kind, mask_img=mask_img) correlation = pearsonr(proj.ravel(), other_proj.ravel())[0] assert correlation > .99 with pytest.raises(ValueError, match=".*interpolation.*"): surface.vol_to_surf(img, mesh, interpolation="bad")
def test_compute_multi_brain_mask(): pytest.raises(TypeError, compute_multi_brain_mask, []) # Check error raised if images with different shapes are given as input imgs = [data_gen.generate_mni_space_img(res=8, random_state=0)[0], data_gen.generate_mni_space_img(res=12, random_state=0)[0]] pytest.raises(ValueError, compute_multi_brain_mask, imgs) # Check results are the same if affine is the same imgs1 = [data_gen.generate_mni_space_img(res=9, random_state=0)[0], data_gen.generate_mni_space_img(res=9, random_state=1)[0]] imgs2 = [data_gen.generate_mni_space_img(res=9, random_state=2)[0], data_gen.generate_mni_space_img(res=9, random_state=3)[0]] mask1 = compute_multi_brain_mask(imgs1, threshold=.2) mask2 = compute_multi_brain_mask(imgs2, threshold=.2) assert_array_equal(get_data(mask1), get_data(mask2))
def test_depth_ball_sampling(): img, *_ = data_gen.generate_mni_space_img() mesh = surface.load_surf_mesh(datasets.fetch_surf_fsaverage()["pial_left"]) with pytest.raises(ValueError, match=".*does not support.*"): surface.vol_to_surf(img, mesh, kind="ball", depth=[.5])
def test_nodemaker_tools_masking_parlistfile_WB(): """ Test nodemaker_tools_masking_parlistfile_WB functionality """ # Set example inputs parlistfile = pkg_resources.resource_filename( "pynets", "templates/atlases/whole_brain_cluster_labels_PCA200.nii.gz") dir_path = str(tempfile.TemporaryDirectory().name) os.makedirs(dir_path, exist_ok=True) shutil.copy2(parlistfile, f"{dir_path}/{os.path.basename(parlistfile)}") parlistfile = f"{dir_path}/{os.path.basename(parlistfile)}" atlas = "whole_brain_cluster_labels_PCA200" roi = tempfile.NamedTemporaryFile(mode="w+", suffix=".nii.gz").name data_gen.generate_mni_space_img()[1].to_filename(roi) ID = "002" 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_labels = np.arange(len(WB_coords) + 1)[np.arange(len(WB_coords) + 1) != 0].tolist() start_time = time.time() WB_parcel_list = nodemaker.three_to_four_parcellation(parlistfile) start_time = time.time() [ WB_net_parcels_map_nifti_unmasked, WB_coords_unmasked, _, _, _, dir_path, ] = nodemaker.node_gen(WB_coords, WB_parcel_list, WB_labels, dir_path, ID, parc, atlas, parlistfile) print("%s%s%s" % ( "node_gen (Masking whole-brain version) --> finished: ", np.round(time.time() - start_time, 1), "s", )) start_time = time.time() WB_parcel_list = nodemaker.three_to_four_parcellation(parlistfile) [WB_parcels_map_nifti, parcel_list_exp] = nodemaker.create_parcel_atlas(WB_parcel_list) print("%s%s%s" % ( "create_parcel_atlas (Masking whole-brain version) --> finished: ", np.round(time.time() - start_time, 1), "s", )) start_time = time.time() WB_parcel_list = nodemaker.three_to_four_parcellation(parlistfile) [ WB_net_parcels_map_nifti_masked, WB_coords_masked, WB_labels_masked, _, _, _, ] = nodemaker.node_gen_masking( roi, WB_coords, WB_parcel_list, WB_labels, dir_path, ID, parc, atlas, parlistfile, vox_size="2mm", ) WB_parcel_list = nodemaker.three_to_four_parcellation(parlistfile) WB_parcel_list_masked = nodemaker.parcel_masker( roi, WB_coords, WB_parcel_list, WB_labels, dir_path, ID, perc_overlap, vox_size="2mm", )[2] print("%s%s%s" % ( "parcel_masker (Masking whole-brain version) --> " "finished: ", np.round(time.time() - start_time, 1), "s", )) print("%s%s%s" % ( "node_gen_masking (Masking whole-brain version) --> " "finished: ", np.round(time.time() - start_time, 1), "s", )) assert WB_coords is not None assert WB_labels is not None assert WB_parcel_list is not None assert WB_coords_masked is not None assert WB_labels_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(): """ Test nodemaker_tools_masking_parlistfile_RSN functionality """ # Set example inputs template = pkg_resources.resource_filename( "pynets", f"templates/standard/MNI152_T1_brain_2mm.nii.gz") tmp = tempfile.TemporaryDirectory() dir_path = str(tmp.name) os.makedirs(dir_path, exist_ok=True) parlistfile = pkg_resources.resource_filename( "pynets", "templates/atlases/whole_brain_cluster_labels_PCA200.nii.gz") shutil.copy2(parlistfile, f"{dir_path}/{os.path.basename(parlistfile)}") parlistfile = f"{dir_path}/{os.path.basename(parlistfile)}" roi = tempfile.NamedTemporaryFile(mode="w+", suffix=".nii.gz").name data_gen.generate_mni_space_img()[1].to_filename(roi) subnet = "Default" ID = "002" perc_overlap = 0.75 parc = True start_time = time.time() coords = nodemaker.get_names_and_coords_of_parcels(parlistfile)[0] 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() parcels_4d_img = nodemaker.three_to_four_parcellation(parlistfile) [net_coords, net_parcels_4d_img, net_labels, subnet] = \ nodemaker.get_node_membership( subnet, template, coords, labels, parc, parcels_4d_img ) 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_parcels_4d_img_masked, ] = nodemaker.parcel_masker( roi, net_coords, net_parcels_4d_img, net_labels, dir_path, ID, perc_overlap, vox_size="2mm", ) 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_parcels_4d_img_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, subnet, 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_parcels_4d_img is not None assert net_coords_masked is not None assert net_labels_masked is not None assert net_parcels_4d_img_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 subnet is not None tmp.cleanup()