def test_syn_registration(): with nbtmp.InTemporaryDirectory() as tmpdir: warped_moving, mapping = syn_registration(subset_b0, subset_t2, moving_affine=hardi_affine, static_affine=MNI_T2_affine, step_length=0.1, metric='CC', dim=3, level_iters=[5, 5, 5], sigma_diff=2.0, radius=1, prealign=None) npt.assert_equal(warped_moving.shape, subset_t2.shape) mapping_fname = op.join(tmpdir, 'mapping.nii.gz') write_mapping(mapping, mapping_fname) file_mapping = read_mapping(mapping_fname, subset_b0_img, subset_t2_img) # Test that it has the same effect on the data: warped_from_file = file_mapping.transform(subset_b0) npt.assert_equal(warped_from_file, warped_moving) # Test that it is, attribute by attribute, identical: for k in mapping.__dict__: npt.assert_((np.all(mapping.__getattribute__(k) == file_mapping.__getattribute__(k))))
def test_read_write_trk(): sl = [ np.array([[0, 0, 0], [0, 0, 0.5], [0, 0, 1], [0, 0, 1.5]]), np.array([[0, 0, 0], [0, 0.5, 0.5], [0, 1, 1]]) ] with nbtmp.InTemporaryDirectory() as tmpdir: fname = op.join(tmpdir, 'sl.trk') aus.write_trk(fname, sl) new_sl = aus.read_trk(fname) npt.assert_equal(list(new_sl), sl) # What happens if this set of streamlines has some funky affine # associated with it? aff = np.eye(4) * np.random.rand() aff[:3, 3] = np.array([1, 2, 3]) aff[3, 3] = 1 # We move the streamlines, and report the inverse of the affine: aus.write_trk(fname, move_streamlines(sl, aff), affine=np.linalg.inv(aff)) # When we read this, we get back what we put in: new_sl = aus.read_trk(fname) # Compare each streamline: for new, old in zip(new_sl, sl): npt.assert_almost_equal(new, old, decimal=5)
def test_predict_dti(): with nbtmp.InTemporaryDirectory() as tmpdir: fbval = op.join(tmpdir, 'dti.bval') fbvec = op.join(tmpdir, 'dti.bvec') fdata = op.join(tmpdir, 'dti.nii.gz') make_dti_data(fbval, fbvec, fdata) file_dict = dti.fit_dti(fdata, fbval, fbvec, out_dir=tmpdir) params_file = file_dict['params'] gtab = dpg.gradient_table(fbval, fbvec) predict_fname = dti.predict(params_file, gtab, S0_file=fdata, out_dir=tmpdir) prediction = nib.load(predict_fname).get_fdata() npt.assert_almost_equal(prediction, nib.load(fdata).get_fdata()) # If you have a mask into the volume, you will predict only that # part of the volume: mask = np.zeros(prediction.shape[:3], dtype=bool) mask[2:4, 2:4, 2:4] = 1 file_dict = dti.fit_dti(fdata, fbval, fbvec, mask=mask, out_dir=tmpdir) params_file = file_dict['params'] predict_fname = dti.predict(params_file, gtab, S0_file=fdata, out_dir=tmpdir) prediction = nib.load(predict_fname).get_fdata() npt.assert_almost_equal(prediction[mask], nib.load(fdata).get_fdata()[mask])
def test_afq_msmt(): tmpdir = nbtmp.InTemporaryDirectory() afd.organize_cfin_data(path=tmpdir.name) myafq = api.AFQ(bids_path=op.join(tmpdir.name, 'cfin_multib'), dmriprep='dipy', tracking_params={"odf_model": "MSMT"}) npt.assert_equal( op.split(myafq.streamlines[0])[-1], "sub-01_ses-01_dwi_space-RASMM_model-MSMT_desc-det_tractography.trk")
def get_temp_hardi(): tmpdir = nbtmp.InTemporaryDirectory() afd.organize_stanford_data(path=tmpdir.name) bids_path = op.join(tmpdir.name, 'stanford_hardi') sub_path = op.join(tmpdir.name, 'stanford_hardi', 'derivatives', 'vistasoft', 'sub-01', 'ses-01', 'dwi') return tmpdir, bids_path, sub_path
def test_DKI_profile(): """ Test using API to profile dki """ tmpdir = nbtmp.InTemporaryDirectory() afd.organize_cfin_data(path=tmpdir.name) myafq = api.AFQ(bids_path=op.join(tmpdir.name, 'cfin_multib'), dmriprep='dipy') myafq.get_dki_fa() myafq.get_dki_md()
def test_bundles_class(): # Example Segmentation results img = nib.Nifti1Image(np.zeros((2, 2, 2)), np.eye(4)) bundles = { 'CST_L': { 'sl': [[[-80.5, -120.5, -60.5], [-80.5, -94.5, -36.5], [-78.5, -68.7, -12.6]], [[-80.5, -120.5, -60.5], [-80.5, -94.5, -36.5], [-78.5, -68.7, -12.6]]], 'idx': [0, 1] }, 'CST_R': { 'sl': [[[-80.5, -120.5, -60.5], [-80.5, -94.5, -36.5], [-78.5, -68.7, -12.6]], [[-80.5, -120.5, -60.5], [-80.5, -94.5, -36.5], [-78.5, -68.7, -12.6]]], 'idx': [0, 1] } } with nbtmp.InTemporaryDirectory() as tmpdir: # save in bundles class for bundles class tests bundles_og = bdl.Bundles(reference=img, bundles_dict=bundles, using_idx=True) bundles_og.save_bundles(file_path=tmpdir) # load bundles again bundles = bdl.Bundles(reference=img) bundle_names = ['CST_L', 'CST_R'] bundles.load_bundles(bundle_names, file_path=tmpdir) # check loaded bundles are same npt.assert_equal(len(bundles.bundles), len(bundles_og.bundles)) npt.assert_equal(len(bundles.bundles['CST_L'].streamlines), len(bundles_og.bundles['CST_L'].streamlines)) npt.assert_equal(len(bundles.bundles['CST_R'].streamlines), len(bundles_og.bundles['CST_R'].streamlines)) npt.assert_equal(bundles.space, bundles_og.space) npt.assert_equal(bundles.bundles['CST_L'].space_attributes, bundles_og.bundles['CST_L'].space_attributes) npt.assert_equal(bundles.origin, bundles_og.origin) npt.assert_array_equal( bundles.bundles['CST_L'].data_per_streamline['idx'], bundles_og.bundles['CST_L'].data_per_streamline['idx']) # test tract profiles profiles = bundles.tract_profiles(np.ones(nib.load(hardi_fdata).shape[:3]), 'test_subject', n_points=1) npt.assert_almost_equal(profiles.Value, np.zeros(2)) # test clean bundles bundles.clean_bundles() npt.assert_equal(len(bundles.bundles), len(bundles_og.bundles))
def test_fit_dti(): # Let's see whether we can pass a list of files for each one: fdata1, fbval1, fbvec1 = dpd.get_fnames('small_101D') fdata2, fbval2, fbvec2 = dpd.get_fnames('small_101D') with nbtmp.InTemporaryDirectory() as tmpdir: file_dict = dti.fit_dti([fdata1, fdata2], [fbval1, fbval2], [fbvec1, fbvec2], out_dir=tmpdir) for f in file_dict.values(): npt.assert_(op.exists(f))
def test_auto_cli(): tmpdir = nbtmp.InTemporaryDirectory() config_file = op.join(tmpdir.name, 'test.toml') arg_dict = afb.func_dict_to_arg_dict() arg_dict['BIDS']['bids_path']['default'] = tmpdir.name afb.generate_config(config_file, arg_dict, False) with pytest.raises( ValueError, match="There must be a dataset_description.json in bids_path"): afb.parse_config_run_afq(config_file, arg_dict, False)
def test_AFQ_no_prealign(): """ Test if API can run without prealign """ tmpdir = nbtmp.InTemporaryDirectory() afd.organize_stanford_data(path=tmpdir.name) myafq = api.AFQ(dmriprep_path=op.join(tmpdir.name, 'stanford_hardi', 'derivatives', 'dmriprep'), sub_prefix='sub', use_prealign=False) myafq.export_rois()
def test_AFQ_data(): """ Test with some actual data """ tmpdir = nbtmp.InTemporaryDirectory() afd.organize_stanford_data(path=tmpdir.name) myafq = api.AFQ(preproc_path=op.join(tmpdir.name, 'stanford_hardi'), sub_prefix='sub') npt.assert_equal(nib.load(myafq.brain_mask[0]).shape, nib.load(myafq['dwi_file'][0]).shape[:3]) npt.assert_equal(nib.load(myafq.brain_mask[0]).shape, nib.load(myafq.dti[0]).shape[:3])
def test_predict_dki(): with nbtmp.InTemporaryDirectory() as tmpdir: fbval = op.join(tmpdir, 'dki.bval') fbvec = op.join(tmpdir, 'dki.bvec') fdata = op.join(tmpdir, 'dki.nii.gz') make_dki_data(fbval, fbvec, fdata) file_dict = dki.fit_dki(fdata, fbval, fbvec, out_dir=tmpdir) params_file = file_dict['params'] gtab = dpg.gradient_table(fbval, fbvec) predict_fname = dki.predict(params_file, gtab, S0_file=fdata, out_dir=tmpdir) prediction = nib.load(predict_fname).get_data() npt.assert_almost_equal(prediction, nib.load(fdata).get_data())
def test_cli_dkimicro(): with nbtmp.InTemporaryDirectory() as tmpdir: fbval = op.join(tmpdir, 'dki.bval') fbvec = op.join(tmpdir, 'dki.bvec') fdata = op.join(tmpdir, 'dki.nii.gz') make_dki_data(fbval, fbvec, fdata) cmd = " ".join( ["pyAFQ_dkimicro", "-d", op.join(tmpdir, "dki.nii.gz"), "-l", op.join(tmpdir, "dki.bval"), "-c", op.join(tmpdir, "dki.bvec")]) out = os.system(cmd) assert out == 0
def test_cli(): with nbtmp.InTemporaryDirectory() as tmpdir: fbval = op.join(tmpdir, 'dti.bval') fbvec = op.join(tmpdir, 'dti.bvec') fdata = op.join(tmpdir, 'dti.nii.gz') make_dti_data(fbval, fbvec, fdata) cmd = " ".join([ "pyAFQ_dti", "-d", op.join(tmpdir, "dti.nii.gz"), "-l", op.join(tmpdir, "dti.bval"), "-c", op.join(tmpdir, "dti.bvec") ]) out = os.system(cmd) assert out == 0 assert op.exists(op.join(tmpdir, 'dti', 'dti_params.nii.gz'))
def test_streamline_registration(): sl1 = [np.array([[0, 0, 0], [0, 0, 0.5], [0, 0, 1], [0, 0, 1.5]]), np.array([[0, 0, 0], [0, 0.5, 0.5], [0, 1, 1]])] affine_mat = np.eye(4) affine_mat[:3, 3] = np.random.randn(3) sl2 = list(transform_tracking_output(sl1, affine_mat)) aligned, matrix = streamline_registration(sl2, sl1) npt.assert_almost_equal(matrix, np.linalg.inv(affine_mat)) npt.assert_almost_equal(aligned[0], sl1[0]) npt.assert_almost_equal(aligned[1], sl1[1]) # We assume the two tracks come from the same space, but it might have # some affine associated with it: base_aff = np.eye(4) * np.random.rand() base_aff[:3, 3] = np.array([1, 2, 3]) base_aff[3, 3] = 1 with nbtmp.InTemporaryDirectory() as tmpdir: for use_aff in [None, base_aff]: fname1 = op.join(tmpdir, 'sl1.trk') fname2 = op.join(tmpdir, 'sl2.trk') if use_aff is not None: img = nib.Nifti1Image(np.zeros((2, 2, 2)), use_aff) # Move the streamlines to this other space, and report it: tgm1 = StatefulTractogram( transform_tracking_output(sl1, np.linalg.inv(use_aff)), img, Space.VOX) save_trk(tgm1, fname1, bbox_valid_check=False) tgm2 = StatefulTractogram( transform_tracking_output(sl2, np.linalg.inv(use_aff)), img, Space.VOX) save_trk(tgm2, fname2, bbox_valid_check=False) else: img = nib.Nifti1Image(np.zeros((2, 2, 2)), np.eye(4)) tgm1 = StatefulTractogram(sl1, img, Space.RASMM) tgm2 = StatefulTractogram(sl2, img, Space.RASMM) save_trk(tgm1, fname1, bbox_valid_check=False) save_trk(tgm2, fname2, bbox_valid_check=False) aligned, matrix = streamline_registration(fname2, fname1) npt.assert_almost_equal(aligned[0], sl1[0], decimal=5) npt.assert_almost_equal(aligned[1], sl1[1], decimal=5)
def test_AFQ_missing_files(): tmpdir = nbtmp.InTemporaryDirectory() bids_path = tmpdir.name with pytest.raises( ValueError, match="There must be a dataset_description.json in bids_path"): api.AFQ(bids_path) afd.to_bids_description(bids_path, **{ "Name": "Missing", "Subjects": ["sub-01"] }) with pytest.raises( ValueError, match=f"No non-json files recognized by pyBIDS in {bids_path}"): api.AFQ(bids_path) subses_folder = op.join(bids_path, "derivatives", "otherDeriv", 'sub-01', 'ses-01') os.makedirs(subses_folder, exist_ok=True) afd.to_bids_description( op.join(bids_path, "derivatives", "otherDeriv"), **{ "Name": "Missing", "PipelineDescription": { "Name": "otherDeriv" } }) touch(op.join(subses_folder, "sub-01_ses-01_dwi.nii.gz")) with pytest.raises(ValueError, match="No non-json files recognized by pyBIDS" + " in the pipeline: missingPipe"): api.AFQ(bids_path, dmriprep="missingPipe") os.mkdir(op.join(bids_path, "missingPipe")) afd.to_bids_description( op.join(bids_path, "missingPipe"), **{ "Name": "Missing", "PipelineDescription": { "Name": "missingPipe" } }) with pytest.raises(ValueError, match="No non-json files recognized by pyBIDS" + " in the pipeline: missingPipe"): api.AFQ(bids_path, dmriprep="missingPipe")
def test_register_dwi(): fdata, fbval, fbvec = dpd.get_fnames('small_64D') with nbtmp.InTemporaryDirectory() as tmpdir: # Use an abbreviated data-set: img = nib.load(fdata) data = img.get_fdata()[..., :10] nib.save(nib.Nifti1Image(data, img.affine), op.join(tmpdir, 'data.nii.gz')) # Save a subset: bvals = np.loadtxt(fbval) bvecs = np.loadtxt(fbvec) np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals[:10]) np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs[:10]) reg_file = register_dwi(op.join(tmpdir, 'data.nii.gz'), op.join(tmpdir, 'bvals.txt'), op.join(tmpdir, 'bvecs.txt')) npt.assert_(op.exists(reg_file))
def test_register_dwi_series(): fdata, fbval, fbvec = dpd.get_fnames('small_64D') with nbtmp.InTemporaryDirectory() as tmpdir: # Use an abbreviated data-set: img = nib.load(fdata) data = img.get_fdata()[..., :10] nib.save(nib.Nifti1Image(data, img.affine), op.join(tmpdir, 'data.nii.gz')) # Save a subset: bvals = np.loadtxt(fbval) bvecs = np.loadtxt(fbvec) np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals[:10]) np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs[:10]) gtab = dpg.gradient_table(op.join(tmpdir, 'bvals.txt'), op.join(tmpdir, 'bvecs.txt')) reg_img, reg_affines = register_dwi_series(data, gtab, img.affine) npt.assert_(isinstance(reg_img, nib.Nifti1Image))
def test_fit_dti(): with nbtmp.InTemporaryDirectory() as tmpdir: fbval = op.join(tmpdir, 'dti.bval') fbvec = op.join(tmpdir, 'dti.bvec') fdata = op.join(tmpdir, 'dti.nii.gz') make_dti_data(fbval, fbvec, fdata) cmd = ["pyAFQ_dti", "-d", fdata, "-l", fbval, "-c", fbvec, "-o", tmpdir, '-b', '0'] out = runner.run_command(cmd) npt.assert_equal(out[0], 0) # Get expected values names = ['FA', 'MD', 'AD', 'RD'] for n in names: fname = op.join(tmpdir, "dti_%s.nii.gz" % n) img = nib.load(fdata) affine = img.affine shape = img.shape[:-1] assert_image_shape_affine(fname, shape, affine)
def test_fit_csd(): fdata, fbval, fbvec = dpd.get_data('small_64D') with nbtmp.InTemporaryDirectory() as tmpdir: # Convert from npy to txt: bvals = np.load(fbval) bvecs = np.load(fbvec) np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals) np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs) for sh_order in [4, 6]: fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'), op.join(tmpdir, 'bvecs.txt'), out_dir=tmpdir, sh_order=sh_order) npt.assert_(op.exists(fname)) sh_coeffs_img = nib.load(fname) npt.assert_equal(sh_order, calculate_max_order(sh_coeffs_img.shape[-1]))
def test_predict_dti(): with nbtmp.InTemporaryDirectory() as tmpdir: fbval = op.join(tmpdir, 'dti.bval') fbvec = op.join(tmpdir, 'dti.bvec') fdata = op.join(tmpdir, 'dti.nii.gz') make_dti_data(fbval, fbvec, fdata) cmd1 = ["pyAFQ_dti", "-d", fdata, "-l", fbval, "-c", fbvec, "-o", tmpdir] out = runner.run_command(cmd1) npt.assert_equal(out[0], 0) # Get expected values fparams = op.join(tmpdir, "dti_params.nii.gz") cmd2 = ["pyAFQ_dti_predict", "-p", fparams, "-l", fbval, "-c", fbvec, "-o", tmpdir, '-b', '0'] out = runner.run_command(cmd2) npt.assert_equal(out[0], 0) pred = nib.load(op.join(tmpdir, "dti_prediction.nii.gz")).get_fdata() data = nib.load(op.join(tmpdir, "dti.nii.gz")).get_fdata() npt.assert_array_almost_equal(pred, data)
def test_slr_registration(): # have to import subject sls file_dict = afd.read_stanford_hardi_tractography() streamlines = file_dict['tractography_subsampled.trk'] # have to import sls atlas afd.fetch_hcp_atlas_16_bundles() atlas_fname = op.join(afd.afq_home, 'hcp_atlas_16_bundles', 'Atlas_in_MNI_Space_16_bundles', 'whole_brain', 'whole_brain_MNI.trk') hcp_atlas = load_tractogram(atlas_fname, 'same', bbox_valid_check=False) with nbtmp.InTemporaryDirectory() as tmpdir: mapping = slr_registration(streamlines, hcp_atlas.streamlines, moving_affine=subset_b0_img.affine, static_affine=subset_t2_img.affine, moving_shape=subset_b0_img.shape, static_shape=subset_t2_img.shape, progressive=False, greater_than=10, rm_small_clusters=1, rng=np.random.RandomState(seed=8)) warped_moving = mapping.transform(subset_b0) npt.assert_equal(warped_moving.shape, subset_t2.shape) mapping_fname = op.join(tmpdir, 'mapping.npy') write_mapping(mapping, mapping_fname) file_mapping = read_mapping(mapping_fname, subset_b0_img, subset_t2_img) # Test that it has the same effect on the data: warped_from_file = file_mapping.transform(subset_b0) npt.assert_equal(warped_from_file, warped_moving) # Test that it is, attribute by attribute, identical: for k in mapping.__dict__: assert (np.all( mapping.__getattribute__(k) == file_mapping.__getattribute__( k)))
def test_streamline_registration(): sl1 = [ np.array([[0, 0, 0], [0, 0, 0.5], [0, 0, 1], [0, 0, 1.5]]), np.array([[0, 0, 0], [0, 0.5, 0.5], [0, 1, 1]]) ] affine = np.eye(4) affine[:3, 3] = np.random.randn(3) sl2 = list(move_streamlines(sl1, affine)) aligned, matrix = streamline_registration(sl2, sl1) npt.assert_almost_equal(matrix, np.linalg.inv(affine)) npt.assert_almost_equal(aligned[0], sl1[0]) npt.assert_almost_equal(aligned[1], sl1[1]) # We assume the two tracks come from the same space, but it might have # some affine associated with it: base_aff = np.eye(4) * np.random.rand() base_aff[:3, 3] = np.array([1, 2, 3]) base_aff[3, 3] = 1 with nbtmp.InTemporaryDirectory() as tmpdir: for use_aff in [None, base_aff]: fname1 = op.join(tmpdir, 'sl1.trk') fname2 = op.join(tmpdir, 'sl2.trk') if use_aff is not None: # Move the streamlines to this other space, and report it: write_trk(fname1, move_streamlines(sl1, np.linalg.inv(use_aff)), use_aff) write_trk(fname2, move_streamlines(sl2, np.linalg.inv(use_aff)), use_aff) else: write_trk(fname1, sl1) write_trk(fname2, sl2) aligned, matrix = streamline_registration(fname2, fname1) npt.assert_almost_equal(aligned[0], sl1[0], decimal=5) npt.assert_almost_equal(aligned[1], sl1[1], decimal=5)
def test_noise_from_b0(): out_shape = (5, 6, 7) with nbtmp.InTemporaryDirectory() as tmpdir: # make artificial dti data fbval = op.join(tmpdir, 'dti.bval') fbvec = op.join(tmpdir, 'dti.bvec') fdata = op.join(tmpdir, 'dti.nii.gz') make_dti_data(fbval, fbvec, fdata, out_shape=out_shape) # make artifical mask mask = np.ones(out_shape) mask[0, 0, :] = 0 # load data and mask bvals, bvecs = read_bvals_bvecs(fbval, fbvec) img, data, gtab, mask = ut.prepare_data(fdata, fbval, fbvec, mask=mask, b0_threshold=50) # test noise_from_b0 noise = dti.noise_from_b0(data, gtab, bvals, mask=mask) npt.assert_almost_equal(noise, 0)
def test_AFQ_data_waypoint(): """ Test with some actual data again, this time for track segmentation """ tmpdir = nbtmp.InTemporaryDirectory() afd.organize_stanford_data(path=tmpdir.name) dmriprep_path = op.join(tmpdir.name, 'stanford_hardi', 'derivatives', 'dmriprep') bundle_names = ["SLF", "ARC", "CST", "FP"] tracking_params = dict(odf_model="DTI") segmentation_params = dict(filter_by_endpoints=False, seg_algo="AFQ", return_idx=True) clean_params = dict(return_idx=True) myafq = api.AFQ(dmriprep_path=dmriprep_path, sub_prefix='sub', bundle_names=bundle_names, scalars=["dti_fa", "dti_md"], tracking_params=tracking_params, segmentation_params=segmentation_params, clean_params=clean_params) # Replace the mapping and streamlines with precomputed: file_dict = afd.read_stanford_hardi_tractography() mapping = file_dict['mapping.nii.gz'] streamlines = file_dict['tractography_subsampled.trk'] streamlines = dts.Streamlines( dtu.transform_tracking_output( [s for s in streamlines if s.shape[0] > 100], np.linalg.inv(myafq.dwi_affine[0]))) sl_file = op.join( myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwi_space-RASMM_model-DTI_desc-det_tractography.trk') sft = StatefulTractogram(streamlines, myafq.data_frame.dwi_file[0], Space.VOX) save_tractogram(sft, sl_file, bbox_valid_check=False) mapping_file = op.join( myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwi_mapping_from-DWI_to_MNI_xfm.nii.gz') nib.save(mapping, mapping_file) reg_prealign_file = op.join( myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwi_prealign_from-DWI_to-MNI_xfm.npy') np.save(reg_prealign_file, np.eye(4)) tgram = load_tractogram(myafq.bundles[0], myafq.dwi_img[0]) bundles = aus.tgram_to_bundles(tgram, myafq.bundle_dict, myafq.dwi_img[0]) npt.assert_(len(bundles['CST_R']) > 0) # Test ROI exporting: myafq.export_rois() assert op.exists(op.join( myafq.data_frame['results_dir'][0], 'ROIs', 'sub-01_sess-01_dwi_desc-ROI-CST_R-1-include.json')) # Test bundles exporting: myafq.export_bundles() assert op.exists(op.join( myafq.data_frame['results_dir'][0], 'bundles', 'sub-01_sess-01_dwi_space-RASMM_model-DTI_desc-det-AFQ-CST_L_tractography.trk')) # noqa # Test creation of file with bundle indices: assert op.exists(op.join( myafq.data_frame['results_dir'][0], 'sub-01_sess-01_dwi_space-RASMM_model-DTI_desc-det-AFQ-clean_tractography_idx.json')) # noqa tract_profiles = pd.read_csv(myafq.tract_profiles[0]) assert tract_profiles.shape == (800, 5) # Before we run the CLI, we'll remove the bundles and ROI folders, to see # that the CLI generates them shutil.rmtree(op.join(myafq.data_frame['results_dir'][0], 'bundles')) shutil.rmtree(op.join(myafq.data_frame['results_dir'][0], 'ROIs')) # Test the CLI: print("Running the CLI:") # Bare bones config only points to the files config = dict(files=dict(dmriprep_path=dmriprep_path)) config_file = op.join(tmpdir.name, "afq_config.toml") with open(config_file, 'w') as ff: toml.dump(config, ff) cmd = "pyAFQ " + config_file out = os.system(cmd) assert out == 0 # The combined tract profiles should already exist from the CLI Run: from_file = pd.read_csv(op.join(myafq.afq_dir, 'tract_profiles.csv')) # And should be identical to what we would get by rerunning this: combined_profiles = myafq.combine_profiles() assert combined_profiles.shape == (800, 7) assert_frame_equal(combined_profiles, from_file) # Make sure the CLI did indeed generate these: myafq.export_rois() assert op.exists(op.join( myafq.data_frame['results_dir'][0], 'ROIs', 'sub-01_sess-01_dwi_desc-ROI-CST_R-1-include.json')) myafq.export_bundles() assert op.exists(op.join( myafq.data_frame['results_dir'][0], 'bundles', 'sub-01_sess-01_dwi_space-RASMM_model-DTI_desc-det-AFQ-CST_L_tractography.trk')) # noqa
def test_AFQ_data_planes(): """ Test with some actual data again, this time for track segmentation """ tmpdir = nbtmp.InTemporaryDirectory() afd.organize_stanford_data(path=tmpdir.name) dmriprep_path = op.join(tmpdir.name, 'stanford_hardi', 'derivatives', 'dmriprep') seg_algo = "planes" bundle_names = ["SLF", "ARC", "CST", "FP"] myafq = api.AFQ(dmriprep_path=dmriprep_path, sub_prefix='sub', seg_algo=seg_algo, bundle_names=bundle_names, odf_model="DTI") # Replace the mapping and streamlines with precomputed: file_dict = afd.read_stanford_hardi_tractography() mapping = file_dict['mapping.nii.gz'] streamlines = file_dict['tractography_subsampled.trk'] streamlines = dts.Streamlines( dtu.move_streamlines([s for s in streamlines if s.shape[0] > 100], np.linalg.inv(myafq.dwi_affine[0]))) sl_file = op.join(myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwiDTI_det_streamlines.trk') aus.write_trk(sl_file, streamlines, affine=myafq.dwi_affine[0]) mapping_file = op.join(myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwi_mapping.nii.gz') nib.save(mapping, mapping_file) reg_prealign_file = op.join(myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwi_reg_prealign.npy') np.save(reg_prealign_file, np.eye(4)) tgram = nib.streamlines.load(myafq.bundles[0]).tractogram bundles = aus.tgram_to_bundles(tgram, myafq.bundle_dict) npt.assert_(len(bundles['CST_L']) > 0) # Test ROI exporting: myafq.export_rois() assert op.exists( op.join(myafq.data_frame['results_dir'][0], 'ROIs', 'CST_R_roi1_include.nii.gz')) # Test bundles exporting: myafq.export_bundles() assert op.exists( op.join(myafq.data_frame['results_dir'][0], 'bundles', 'CST_R.trk')) tract_profiles = pd.read_csv(myafq.tract_profiles[0]) assert tract_profiles.shape == (800, 5) # Before we run the CLI, we'll remove the bundles and ROI folders, to see # that the CLI generates them shutil.rmtree(op.join(myafq.data_frame['results_dir'][0], 'bundles')) shutil.rmtree(op.join(myafq.data_frame['results_dir'][0], 'ROIs')) # Test the CLI: print("Running the CLI:") cmd = "pyAFQ " + dmriprep_path out = os.system(cmd) assert out == 0 # The combined tract profiles should already exist from the CLI Run: from_file = pd.read_csv(op.join(myafq.afq_dir, 'tract_profiles.csv')) # And should be identical to what we would get by rerunning this: combined_profiles = myafq.combine_profiles() assert combined_profiles.shape == (800, 7) assert_frame_equal(combined_profiles, from_file) # Make sure the CLI did indeed generate these: assert op.exists( op.join(myafq.data_frame['results_dir'][0], 'ROIs', 'CST_R_roi1_include.nii.gz')) assert op.exists( op.join(myafq.data_frame['results_dir'][0], 'bundles', 'CST_R.trk')) # def test_AFQ_data_recobundles(): # tmpdir = nbtmp.InTemporaryDirectory() # afd.fetch_hcp(["100206"], hcp_bucket='hcp-openaccess', profile_name="hcp", # path=tmpdir.name) # dmriprep_path = op.join(tmpdir.name, 'HCP', 'derivatives', 'dmriprep') # seg_algo = "recobundles" # bundle_names = ["F", "CST", "AF", "CC_ForcepsMajor"] # myafq = api.AFQ(dmriprep_path=dmriprep_path, # sub_prefix='sub', # seg_algo=seg_algo, # bundle_names=bundle_names, # odf_model="DTI", # b0_threshold=15) # # Replace the streamlines with precomputed: # path_to_trk = dpd.fetcher.fetch_target_tractogram_hcp() # path_to_trk = dpd.fetcher.get_target_tractogram_hcp() # sl_file = op.join(myafq.data_frame.results_dir[0], 'sub-100206_sess-01_dwiDTI_det_streamlines.trk') # shutil.copy(path_to_trk, sl_file) # myafq.data_frame["streamlines_file"] = sl_file # print("here") # tgram = nib.streamlines.load(myafq.bundles[0]).tractogram # print("here") # bundles = aus.tgram_to_bundles(tgram, myafq.bundle_dict) # npt.assert_(len(bundles['CST_L']) > 0)
def test_AFQ_data2(): """ Test with some actual data again, this time for track segmentation """ tmpdir = nbtmp.InTemporaryDirectory() afd.organize_stanford_data(path=tmpdir.name) preafq_path = op.join(tmpdir.name, 'stanford_hardi', 'derivatives', 'preafq') myafq = api.AFQ(preafq_path=preafq_path, sub_prefix='sub', bundle_list=["SLF", "ARC", "CST", "FP"]) # Replace the mapping and streamlines with precomputed: file_dict = afd.read_stanford_hardi_tractography() mapping = file_dict['mapping.nii.gz'] streamlines = file_dict['tractography_subsampled.trk'] streamlines = dts.Streamlines( dtu.move_streamlines([s for s in streamlines if s.shape[0] > 100], np.linalg.inv(myafq.dwi_affine[0]))) sl_file = op.join(myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwiDTI_det_streamlines.trk') aus.write_trk(sl_file, streamlines, affine=myafq.dwi_affine[0]) mapping_file = op.join(myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwi_mapping.nii.gz') nib.save(mapping, mapping_file) reg_prealign_file = op.join(myafq.data_frame.results_dir[0], 'sub-01_sess-01_dwi_reg_prealign.npy') np.save(reg_prealign_file, np.eye(4)) tgram = nib.streamlines.load(myafq.bundles[0]).tractogram bundles = aus.tgram_to_bundles(tgram, myafq.bundle_dict) npt.assert_equal(len(bundles['CST_R']), 2) # Test ROI exporting: myafq.export_rois() assert op.exists(op.join(myafq.data_frame['results_dir'][0], 'ROIs', 'CST_R_roi1_include.nii.gz')) # Test bundles exporting: myafq.export_bundles() assert op.exists(op.join(myafq.data_frame['results_dir'][0], 'bundles', 'CST_R.trk')) tract_profiles = pd.read_csv(myafq.tract_profiles[0]) assert tract_profiles.shape == (800, 5) # Before we run the CLI, we'll remove the bundles and ROI folders, to see # that the CLI generates them shutil.rmtree(op.join(myafq.data_frame['results_dir'][0], 'bundles')) shutil.rmtree(op.join(myafq.data_frame['results_dir'][0], 'ROIs')) # Test the CLI: print("Running the CLI:") cmd = "pyAFQ " + preafq_path out = os.system(cmd) assert out == 0 # The combined tract profiles should already exist from the CLI Run: from_file = pd.read_csv(op.join(myafq.afq_dir, 'tract_profiles.csv')) # And should be identical to what we would get by rerunning this: combined_profiles = myafq.combine_profiles() assert combined_profiles.shape == (800, 7) assert_frame_equal(combined_profiles, from_file) # Make sure the CLI did indeed generate these: assert op.exists(op.join(myafq.data_frame['results_dir'][0], 'ROIs', 'CST_R_roi1_include.nii.gz')) assert op.exists(op.join(myafq.data_frame['results_dir'][0], 'bundles', 'CST_R.trk'))
def test_fit_dki(): fdata, fbval, fbvec = dpd.get_fnames('small_101D') with nbtmp.InTemporaryDirectory() as tmpdir: file_dict = dki.fit_dki(fdata, fbval, fbvec, out_dir=tmpdir) for f in file_dict.values(): op.exists(f)
import os.path as op import numpy as np import numpy.testing as npt import nibabel.tmpdirs as nbtmp from AFQ.csd import fit_csd from AFQ.dti import fit_dti from AFQ.tractography import track from AFQ.utils.testing import make_tracking_data seeds = np.array([[-80., -120., -60.], [-81, -121, -61]]) tmpdir = nbtmp.InTemporaryDirectory() fbval = op.join(tmpdir.name, 'dti.bval') fbvec = op.join(tmpdir.name, 'dti.bvec') fdata = op.join(tmpdir.name, 'dti.nii.gz') make_tracking_data(fbval, fbvec, fdata) def test_csd_tracking(): for sh_order in [4, 8, 10]: fname = fit_csd(fdata, fbval, fbvec, response=((0.0015, 0.0003, 0.0003), 100), sh_order=8, lambda_=1, tau=0.1, mask=None, out_dir=tmpdir.name)