def test_ascm_accuracy(): test_ascm_data_ref = nib.load(dpd.get_data("ascm_test")).get_data() test_data = nib.load(dpd.get_data("aniso_vox")).get_data() # the test data was constructed in this manner mask = test_data > 50 sigma = estimate_sigma(test_data, N=4) den_small = non_local_means( test_data, sigma=sigma, mask=mask, patch_radius=1, block_radius=1, rician=True) den_large = non_local_means( test_data, sigma=sigma, mask=mask, patch_radius=2, block_radius=1, rician=True) S0n = np.array(adaptive_soft_matching(test_data, den_small, den_large, sigma[0])) assert_array_almost_equal(S0n, test_ascm_data_ref)
def test_dipy_fit_tensor(): with InTemporaryDirectory() as tmp: dwi, bval, bvec = get_data("small_25") # Copy data to tmp directory shutil.copyfile(dwi, "small_25.nii.gz") shutil.copyfile(bval, "small_25.bval") shutil.copyfile(bvec, "small_25.bvec") # Call script cmd = ["dipy_fit_tensor", "--mask=none", "small_25.nii.gz"] out = run_command(" ".join(cmd)) assert_equal(out[0], 0) # Get expected values img = nib.load("small_25.nii.gz") affine = img.get_affine() shape = img.shape[:-1] # Check expected outputs assert_image_shape_affine("small_25_fa.nii.gz", shape, affine) assert_image_shape_affine("small_25_t2di.nii.gz", shape, affine) assert_image_shape_affine("small_25_dirFA.nii.gz", shape, affine) assert_image_shape_affine("small_25_ad.nii.gz", shape, affine) assert_image_shape_affine("small_25_md.nii.gz", shape, affine) assert_image_shape_affine("small_25_rd.nii.gz", shape, affine) with InTemporaryDirectory() as tmp: dwi, bval, bvec = get_data("small_25") # Copy data to tmp directory shutil.copyfile(dwi, "small_25.nii.gz") shutil.copyfile(bval, "small_25.bval") shutil.copyfile(bvec, "small_25.bvec") # Call script cmd = ["dipy_fit_tensor", "--save-tensor", "--mask=none", "small_25.nii.gz"] out = run_command(" ".join(cmd)) assert_equal(out[0], 0) # Get expected values img = nib.load("small_25.nii.gz") affine = img.get_affine() shape = img.shape[:-1] # Check expected outputs assert_image_shape_affine("small_25_fa.nii.gz", shape, affine) assert_image_shape_affine("small_25_t2di.nii.gz", shape, affine) assert_image_shape_affine("small_25_dirFA.nii.gz", shape, affine) assert_image_shape_affine("small_25_ad.nii.gz", shape, affine) assert_image_shape_affine("small_25_md.nii.gz", shape, affine) assert_image_shape_affine("small_25_rd.nii.gz", shape, affine) # small_25_tensor saves the tensor as a symmetric matrix following # the nifti standard. ten_shape = shape + (1, 6) assert_image_shape_affine("small_25_tensor.nii.gz", ten_shape, affine)
def test_fit_dti(): # Let's see whether we can pass a list of files for each one: fdata1, fbval1, fbvec1 = dpd.get_data('small_101D') fdata2, fbval2, fbvec2 = dpd.get_data('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_nlls_fit_tensor(): """ Test the implementation of NLLS and RESTORE """ b0 = 1000. bvecs, bval = read_bvec_file(get_data('55dir_grad.bvec')) gtab = grad.gradient_table(bval, bvecs) B = bval[1] #Scale the eigenvalues and tensor by the B value so the units match D = np.array([1., 1., 1., 0., 0., 1., -np.log(b0) * B]) / B evals = np.array([2., 1., 0.]) / B md = evals.mean() tensor = from_lower_triangular(D) #Design Matrix X = dti.design_matrix(bvecs, bval) #Signals Y = np.exp(np.dot(X,D)) Y.shape = (-1,) + Y.shape #Estimate tensor from test signals and compare against expected result #using non-linear least squares: tensor_model = dti.TensorModel(gtab, fit_method='NLLS') tensor_est = tensor_model.fit(Y) assert_equal(tensor_est.shape, Y.shape[:-1]) assert_array_almost_equal(tensor_est.evals[0], evals) assert_array_almost_equal(tensor_est.quadratic_form[0], tensor) assert_almost_equal(tensor_est.md[0], md) # Using the gmm weighting scheme: tensor_model = dti.TensorModel(gtab, fit_method='NLLS', weighting='gmm') assert_equal(tensor_est.shape, Y.shape[:-1]) assert_array_almost_equal(tensor_est.evals[0], evals) assert_array_almost_equal(tensor_est.quadratic_form[0], tensor) assert_almost_equal(tensor_est.md[0], md) # Use NLLS with some actual 4D data: data, bvals, bvecs = get_data('small_25') gtab = grad.gradient_table(bvals, bvecs) tm1 = dti.TensorModel(gtab, fit_method='NLLS') dd = nib.load(data).get_data() tf1 = tm1.fit(dd) tm2 = dti.TensorModel(gtab) tf2 = tm2.fit(dd) assert_array_almost_equal(tf1.fa, tf2.fa, decimal=1)
def uniform_seed_grid(): #read bvals,gradients and data fimg,fbvals, fbvecs = get_data('small_64D') bvals=np.load(fbvals) gradients=np.load(fbvecs) img =ni.load(fimg) data=img.get_data() x,y,z,g=data.shape M=np.mgrid[.5:x-.5:np.complex(0,x),.5:y-.5:np.complex(0,y),.5:z-.5:np.complex(0,z)] M=M.reshape(3,x*y*z).T print(M.shape) print(M.dtype) for m in M: print(m) gqs = GeneralizedQSampling(data,bvals,gradients) iT=iter(EuDX(gqs.QA,gqs.IN,seeds=M)) T=[] for t in iT: T.append(i) print('lenT',len(T)) assert_equal(len(T), 1221)
def test_eudx_bad_seed(): """Test passing a bad seed to eudx""" fimg, fbvals, fbvecs = get_data('small_101D') img = ni.load(fimg) affine = img.get_affine() data = img.get_data() gtab = gradient_table(fbvals, fbvecs) tensor_model = TensorModel(gtab) ten = tensor_model.fit(data) ind = quantize_evecs(ten.evecs) seed = [1000000., 1000000., 1000000.] eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], a_low=.2) try: track = list(eu) except ValueError as ve: if ve.args[0] == 'Seed outside boundaries': print(ve) print(data.shape) seed = [1., 5., 8.] eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], a_low=.2) track = list(eu) seed = [-1., 1000000., 1000000.] eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], a_low=.2) try: track = list(eu) except ValueError as ve: if ve.args[0] == 'Seed outside boundaries': print(ve)
def test_passing_maskedview(): data = np.ones((2,4,56)) mask = np.array([[True, False, False, True], [True, False, True, False]]) gtab, bval = read_bvec_file(get_data('55dir_grad.bvec')) data = data[mask] mv = MaskedView(mask, data) tensor = dti.Tensor(mv, bval, gtab.T, min_signal=1e-9) assert_equal(tensor.shape, (2,4)) assert_equal(tensor.fa().shape, (2,4)) assert_equal(tensor.evals.shape, (2,4,3)) assert_equal(tensor.evecs.shape, (2,4,3,3)) assert_equal(type(tensor.model_params), MaskedView) assert_array_equal(tensor.mask, mask) tensor = tensor[0] assert_equal(tensor.shape, (4,)) assert_equal(tensor.fa().shape, (4,)) assert_equal(tensor.evals.shape, (4,3)) assert_equal(tensor.evecs.shape, (4,3,3)) assert_equal(type(tensor.model_params), MaskedView) assert_array_equal(tensor.mask, mask[0]) tensor = tensor[0] assert_equal(tensor.shape, tuple()) assert_equal(tensor.fa().shape, tuple()) assert_equal(tensor.evals.shape, (3,)) assert_equal(tensor.evecs.shape, (3,3)) assert_equal(type(tensor.model_params), np.ndarray)
def test_nnls_jacobian_fucn(): b0 = 1000. bvecs, bval = read_bvec_file(get_data('55dir_grad.bvec')) gtab = grad.gradient_table(bval, bvecs) B = bval[1] # Scale the eigenvalues and tensor by the B value so the units match D = np.array([1., 1., 1., 0., 0., 1., -np.log(b0) * B]) / B # Design Matrix X = dti.design_matrix(gtab) # Signals Y = np.exp(np.dot(X, D)) # Test Jacobian at D args = [X, Y] analytical = dti._nlls_jacobian_func(D, *args) for i in range(len(X)): args = [X[i], Y[i]] approx = opt.approx_fprime(D, dti._nlls_err_func, 1e-8, *args) assert_true(np.allclose(approx, analytical[i])) # Test Jacobian at zero D = np.zeros_like(D) args = [X, Y] analytical = dti._nlls_jacobian_func(D, *args) for i in range(len(X)): args = [X[i], Y[i]] approx = opt.approx_fprime(D, dti._nlls_err_func, 1e-8, *args) assert_true(np.allclose(approx, analytical[i]))
def test_masked_array_with_tensor(): data = np.ones((2, 4, 56)) mask = np.array([[True, False, False, True], [True, False, True, False]]) bvec, bval = read_bvec_file(get_data('55dir_grad.bvec')) gtab = grad.gradient_table_from_bvals_bvecs(bval, bvec.T) tensor_model = TensorModel(gtab) tensor = tensor_model.fit(data, mask=mask) assert_equal(tensor.shape, (2, 4)) assert_equal(tensor.fa.shape, (2, 4)) assert_equal(tensor.evals.shape, (2, 4, 3)) assert_equal(tensor.evecs.shape, (2, 4, 3, 3)) tensor = tensor[0] assert_equal(tensor.shape, (4,)) assert_equal(tensor.fa.shape, (4,)) assert_equal(tensor.evals.shape, (4, 3)) assert_equal(tensor.evecs.shape, (4, 3, 3)) tensor = tensor[0] assert_equal(tensor.shape, tuple()) assert_equal(tensor.fa.shape, tuple()) assert_equal(tensor.evals.shape, (3,)) assert_equal(tensor.evecs.shape, (3, 3)) assert_equal(type(tensor.model_params), np.ndarray)
def test_median_otsu_flow(): with TemporaryDirectory() as out_dir: data_path, _, _ = get_data('small_25') volume = nib.load(data_path).get_data() save_masked = True median_radius = 3 numpass = 3 autocrop = False vol_idx = [0] dilate = 0 mo_flow = MedianOtsuFlow() mo_flow.run(data_path, out_dir=out_dir, save_masked=save_masked, median_radius=median_radius, numpass=numpass, autocrop=autocrop, vol_idx=vol_idx, dilate=dilate) mask_name = mo_flow.last_generated_outputs['out_mask'] masked_name = mo_flow.last_generated_outputs['out_masked'] masked, mask = median_otsu(volume, median_radius, numpass, autocrop, vol_idx, dilate) result_mask_data = nib.load(join(out_dir, mask_name)).get_data() npt.assert_array_equal(result_mask_data, mask) result_masked_data = nib.load(join(out_dir, masked_name)).get_data() npt.assert_array_equal(result_masked_data, masked)
def get_synthetic_warped_circle(nslices): #get a subsampled circle fname_cicle = get_data('reg_o') circle = np.load(fname_cicle)[::4,::4].astype(floating) #create a synthetic invertible map and warp the circle d, dinv = vfu.create_harmonic_fields_2d(64, 64, 0.1, 4) d = np.asarray(d, dtype=floating) dinv = np.asarray(dinv, dtype=floating) mapping = DiffeomorphicMap(2, (64, 64)) mapping.forward, mapping.backward = d, dinv wcircle = mapping.transform(circle) if(nslices == 1): return circle, wcircle #normalize and form the 3d by piling slices circle = (circle-circle.min())/(circle.max() - circle.min()) circle_3d = np.ndarray(circle.shape + (nslices,), dtype=floating) circle_3d[...] = circle[...,None] circle_3d[...,0] = 0 circle_3d[...,-1] = 0 #do the same with the warped circle wcircle = (wcircle-wcircle.min())/(wcircle.max() - wcircle.min()) wcircle_3d = np.ndarray(wcircle.shape + (nslices,), dtype=floating) wcircle_3d[...] = wcircle[...,None] wcircle_3d[...,0] = 0 wcircle_3d[...,-1] = 0 return circle_3d, wcircle_3d
def test_sphere_scaling_csdmodel(): """Check that mirroring regularization sphere does not change the result of the model""" _, fbvals, fbvecs = get_data('small_64D') bvals = np.load(fbvals) bvecs = np.load(fbvecs) gtab = gradient_table(bvals, bvecs) mevals = np.array(([0.0015, 0.0003, 0.0003], [0.0015, 0.0003, 0.0003])) angles = [(0, 0), (60, 0)] S, sticks = multi_tensor(gtab, mevals, 100., angles=angles, fractions=[50, 50], snr=None) hemi = small_sphere sphere = hemi.mirror() response = (np.array([0.0015, 0.0003, 0.0003]), 100) model_full = ConstrainedSphericalDeconvModel(gtab, response, reg_sphere=sphere) model_hemi = ConstrainedSphericalDeconvModel(gtab, response, reg_sphere=hemi) csd_fit_full = model_full.fit(S) csd_fit_hemi = model_hemi.fit(S) assert_array_almost_equal(csd_fit_full.shm_coeff, csd_fit_hemi.shm_coeff)
def test_median_otsu(): fname = get_data('S0_10') img = nib.load(fname) data = img.get_data() data = np.squeeze(data) dummy_mask = data > data.mean() data_masked, mask = median_otsu(data, median_radius=3, numpass=2, autocrop=False, vol_idx=None, dilate=None) assert_equal(mask.sum() < dummy_mask.sum(), True) data2 = np.zeros(data.shape + (2,)) data2[..., 0] = data data2[..., 1] = data data2_masked, mask2 = median_otsu(data2, median_radius=3, numpass=2, autocrop=False, vol_idx=[0, 1], dilate=None) assert_equal(mask.sum() == mask2.sum(), True) _, mask3 = median_otsu(data2, median_radius=3, numpass=2, autocrop=False, vol_idx=[0, 1], dilate=1) assert_equal(mask2.sum() < mask3.sum(), True) _, mask4 = median_otsu(data2, median_radius=3, numpass=2, autocrop=False, vol_idx=[0, 1], dilate=2) assert_equal(mask3.sum() < mask4.sum(), True)
def test_eudx_further(): """ Cause we love testin.. ;-) """ fimg, fbvals, fbvecs = get_data("small_101D") img = ni.load(fimg) affine = img.get_affine() bvals = np.loadtxt(fbvals) gradients = np.loadtxt(fbvecs).T data = img.get_data() ten = Tensor(data, bvals, gradients, thresh=50) x, y, z = data.shape[:3] seeds = np.zeros((10 ** 4, 3)) for i in range(10 ** 4): rx = (x - 1) * np.random.rand() ry = (y - 1) * np.random.rand() rz = (z - 1) * np.random.rand() seeds[i] = np.ascontiguousarray(np.array([rx, ry, rz]), dtype=np.float64) # print seeds # """ eu = EuDX(a=ten.fa(), ind=ten.ind(), seeds=seeds, a_low=0.2) T = [e for e in eu] # check that there are no negative elements for t in T: assert_equal(np.sum(t.ravel() < 0), 0) """
def test_eudx(): # read bvals,gradients and data fimg, fbvals, fbvecs = get_data("small_64D") bvals = np.load(fbvals) gradients = np.load(fbvecs) img = ni.load(fimg) data = img.get_data() print(data.shape) gqs = GeneralizedQSampling(data, bvals, gradients) ten = Tensor(data, bvals, gradients, thresh=50) seed_list = np.dot(np.diag(np.arange(10)), np.ones((10, 3))) iT = iter(EuDX(gqs.qa(), gqs.ind(), seeds=seed_list)) T = [] for t in iT: T.append(t) iT2 = iter(EuDX(ten.fa(), ten.ind(), seeds=seed_list)) T2 = [] for t in iT2: T2.append(t) print("length T ", sum([length(t) for t in T])) print("length T2", sum([length(t) for t in T2])) print(gqs.QA[1, 4, 8, 0]) print(gqs.QA.ravel()[ndarray_offset(np.array([1, 4, 8, 0]), np.array(gqs.QA.strides), 4, 8)]) assert_almost_equal( gqs.QA[1, 4, 8, 0], gqs.QA.ravel()[ndarray_offset(np.array([1, 4, 8, 0]), np.array(gqs.QA.strides), 4, 8)] ) assert_almost_equal(sum([length(t) for t in T]), 70.999996185302734, places=3) assert_almost_equal(sum([length(t) for t in T2]), 56.999997615814209, places=3)
def test_r2_term_odf_sharp(): SNR = None S0 = 1 angle = 75 _, fbvals, fbvecs = get_data('small_64D') #get_data('small_64D') bvals = np.load(fbvals) bvecs = np.load(fbvecs) sphere = get_sphere('symmetric724') gtab = gradient_table(bvals, bvecs) mevals = np.array(([0.0015, 0.0003, 0.0003], [0.0015, 0.0003, 0.0003])) S, sticks = multi_tensor(gtab, mevals, S0, angles=[(0, 0), (angle, 0)], fractions=[50, 50], snr=SNR) mevecs = [all_tensor_evecs(sticks[0]).T, all_tensor_evecs(sticks[1]).T] odf_gt = multi_tensor_odf(sphere.vertices, [0.5, 0.5], mevals, mevecs) odfs_sh = sf_to_sh(odf_gt, sphere, sh_order=8, basis_type=None) fodf_sh = odf_sh_to_sharp(odfs_sh, sphere, basis=None, ratio=3 / 15., sh_order=8, lambda_=1., tau=0.1, r2_term=True) fodf = sh_to_sf(fodf_sh, sphere, sh_order=8, basis_type=None) directions_gt, _, _ = peak_directions(odf_gt, sphere) directions, _, _ = peak_directions(fodf, sphere) ang_sim = angular_similarity(directions_gt, directions) assert_equal(ang_sim > 1.9, True) assert_equal(directions.shape[0], 2)
def test_csd_predict(): """ """ SNR = 100 S0 = 1 _, fbvals, fbvecs = get_data('small_64D') bvals = np.load(fbvals) bvecs = np.load(fbvecs) gtab = gradient_table(bvals, bvecs) mevals = np.array(([0.0015, 0.0003, 0.0003], [0.0015, 0.0003, 0.0003])) angles = [(0, 0), (60, 0)] S, sticks = multi_tensor(gtab, mevals, S0, angles=angles, fractions=[50, 50], snr=SNR) sphere = get_sphere('symmetric362') odf_gt = multi_tensor_odf(sphere.vertices, mevals, angles, [50, 50]) response = (np.array([0.0015, 0.0003, 0.0003]), S0) csd = ConstrainedSphericalDeconvModel(gtab, response) csd_fit = csd.fit(S) prediction = csd_predict(csd_fit.shm_coeff, gtab, response=response, S0=S0) npt.assert_equal(prediction.shape[0], S.shape[0]) model_prediction = csd.predict(csd_fit.shm_coeff) assert_array_almost_equal(prediction, model_prediction) # Roundtrip tests (quite inaccurate, because of regularization): assert_array_almost_equal(csd_fit.predict(gtab, S0=S0),S,decimal=1) assert_array_almost_equal(csd.predict(csd_fit.shm_coeff, S0=S0),S,decimal=1)
def test_exponential_iso(): fdata, fbvals, fbvecs = dpd.get_data() data_dti = nib.load(fdata).get_data() gtab_dti = grad.gradient_table(fbvals, fbvecs) data_multi, gtab_multi = dpd.dsi_deconv_voxels() for data, gtab in zip([data_dti, data_multi], [gtab_dti, gtab_multi]): sfmodel = sfm.SparseFascicleModel( gtab, isotropic=sfm.ExponentialIsotropicModel) sffit1 = sfmodel.fit(data[0, 0, 0]) sphere = dpd.get_sphere() odf1 = sffit1.odf(sphere) pred1 = sffit1.predict(gtab) SNR = 1000 S0 = 100 mevals = np.array(([0.0015, 0.0005, 0.0005], [0.0015, 0.0005, 0.0005])) angles = [(0, 0), (60, 0)] S, sticks = sims.multi_tensor(gtab, mevals, S0, angles=angles, fractions=[50, 50], snr=SNR) sffit = sfmodel.fit(S) pred = sffit.predict() npt.assert_(xval.coeff_of_determination(pred, S) > 96)
def test_response_from_mask(): fdata, fbvals, fbvecs = get_data('small_64D') bvals = np.load(fbvals) bvecs = np.load(fbvecs) data = nib.load(fdata).get_data() gtab = gradient_table(bvals, bvecs) ten = TensorModel(gtab) tenfit = ten.fit(data) FA = fractional_anisotropy(tenfit.evals) FA[np.isnan(FA)] = 0 radius = 3 for fa_thr in np.arange(0, 1, 0.1): response_auto, ratio_auto, nvoxels = auto_response(gtab, data, roi_center=None, roi_radius=radius, fa_thr=fa_thr, return_number_of_voxels=True) ci, cj, ck = np.array(data.shape[:3]) / 2 mask = np.zeros(data.shape[:3]) mask[ci - radius: ci + radius, cj - radius: cj + radius, ck - radius: ck + radius] = 1 mask[FA <= fa_thr] = 0 response_mask, ratio_mask = response_from_mask(gtab, data, mask) assert_equal(int(np.sum(mask)), nvoxels) assert_array_almost_equal(response_mask[0], response_auto[0]) assert_almost_equal(response_mask[1], response_auto[1]) assert_almost_equal(ratio_mask, ratio_auto)
def test_eudx_bad_seed(): """Test passing a bad seed to eudx""" fimg, fbvals, fbvecs = get_data('small_101D') img = ni.load(fimg) affine = img.affine data = img.get_data() gtab = gradient_table(fbvals, fbvecs) tensor_model = TensorModel(gtab) ten = tensor_model.fit(data) ind = quantize_evecs(ten.evecs) sphere = get_sphere('symmetric724') seed = [1000000., 1000000., 1000000.] eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], odf_vertices=sphere.vertices, a_low=.2) assert_raises(ValueError, list, eu) print(data.shape) seed = [1., 5., 8.] eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], odf_vertices=sphere.vertices, a_low=.2) track = list(eu) seed = [-1., 1000000., 1000000.] eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], odf_vertices=sphere.vertices, a_low=.2) assert_raises(ValueError, list, eu)
def test_csd_superres(): """ Check the quality of csdfit with high SH order. """ _, fbvals, fbvecs = get_data('small_64D') bvals = np.load(fbvals) bvecs = np.load(fbvecs) gtab = gradient_table(bvals, bvecs) # img, gtab = read_stanford_hardi() evals = np.array([[1.5, .3, .3]]) * [[1.], [1.]] / 1000. S, sticks = multi_tensor(gtab, evals, snr=None, fractions=[55., 45.]) model16 = ConstrainedSphericalDeconvModel(gtab, (evals[0], 3.), sh_order=16) fit16 = model16.fit(S) # print local_maxima(fit16.odf(default_sphere), default_sphere.edges) d, v, ind = peak_directions(fit16.odf(default_sphere), default_sphere, relative_peak_threshold=.2, min_separation_angle=0) # Check that there are two peaks assert_equal(len(d), 2) # Check that peaks line up with sticks cos_sim = abs((d * sticks).sum(1)) ** .5 assert_(all(cos_sim > .99))
def test_sfm(): fdata, fbvals, fbvecs = dpd.get_data() data = nib.load(fdata).get_data() gtab = grad.gradient_table(fbvals, fbvecs) sfmodel = sfm.SparseFascicleModel(gtab) sffit1 = sfmodel.fit(data[0, 0, 0]) sphere = dpd.get_sphere("symmetric642") odf1 = sffit1.odf(sphere) pred1 = sffit1.predict(gtab) mask = np.ones(data.shape[:-1]) sffit2 = sfmodel.fit(data, mask) pred2 = sffit2.predict(gtab) odf2 = sffit2.odf(sphere) sffit3 = sfmodel.fit(data) pred3 = sffit3.predict(gtab) odf3 = sffit3.odf(sphere) npt.assert_almost_equal(pred3, pred2, decimal=2) npt.assert_almost_equal(pred3[0, 0, 0], pred1, decimal=2) npt.assert_almost_equal(odf3[0, 0, 0], odf1, decimal=2) npt.assert_almost_equal(odf3[0, 0, 0], odf2[0, 0, 0], decimal=2) # Fit zeros and you will get back zeros npt.assert_almost_equal( sfmodel.fit(np.zeros(data[0, 0, 0].shape)).beta, np.zeros(sfmodel.design_matrix[0].shape[-1]) )
def test_force_overwrite(): with TemporaryDirectory() as out_dir: data_path, _, _ = get_data('small_25') mo_flow = MedianOtsuFlow(output_strategy='absolute') # Generate the first results mo_flow.run(data_path, out_dir=out_dir) mask_file = mo_flow.last_generated_outputs['out_mask'] first_time = os.path.getmtime(mask_file) # re-run with no force overwrite, modified time should not change mo_flow.run(data_path, out_dir=out_dir) mask_file = mo_flow.last_generated_outputs['out_mask'] second_time = os.path.getmtime(mask_file) assert first_time == second_time # re-run with force overwrite, modified time should change mo_flow = MedianOtsuFlow(output_strategy='absolute', force=True) # Make sure that at least one second elapsed, so that time-stamp is # different (sometimes measured in whole seconds) time.sleep(1) mo_flow.run(data_path, out_dir=out_dir) mask_file = mo_flow.last_generated_outputs['out_mask'] third_time = os.path.getmtime(mask_file) assert third_time != second_time
def test_restore(): """ Test the implementation of the RESTORE algorithm """ b0 = 1000. bvecs, bval = read_bvec_file(get_data('55dir_grad.bvec')) gtab = grad.gradient_table(bval, bvecs) B = bval[1] #Scale the eigenvalues and tensor by the B value so the units match D = np.array([1., 1., 1., 0., 0., 1., -np.log(b0) * B]) / B evals = np.array([2., 1., 0.]) / B md = evals.mean() tensor = from_lower_triangular(D) #Design Matrix X = dti.design_matrix(gtab) #Signals Y = np.exp(np.dot(X,D)) Y.shape = (-1,) + Y.shape for drop_this in range(1, Y.shape[-1]): # RESTORE estimates should be robust to dropping this_y = Y.copy() this_y[:, drop_this] = 1.0 tensor_model = dti.TensorModel(gtab, fit_method='restore', sigma=67.0) tensor_est = tensor_model.fit(this_y) assert_array_almost_equal(tensor_est.evals[0], evals, decimal=3) assert_array_almost_equal(tensor_est.quadratic_form[0], tensor, decimal=3)
def test_qb_commandline(): with InTemporaryDirectory(): tracks_file = get_data('fornix') cmd = ["dipy_quickbundles", tracks_file, '--pkl_file', 'mypickle.pkl', '--out_file', 'tracks300.trk'] out = run_command(cmd) assert_equal(out[0], 0)
def test_dandelion(): fimg,fbvals,fbvecs=get_data('small_101D') bvals=np.loadtxt(fbvals) gradients=np.loadtxt(fbvecs).T data=nib.load(fimg).get_data() print(bvals.shape, gradients.shape, data.shape) sd=SphericalDandelion(data,bvals,gradients) sdf=sd.spherical_diffusivity(data[5,5,5]) XA=sd.xa() np.set_printoptions(2) print XA.min(),XA.max(),XA.mean() print sdf*10**4 """ print(sdf.shape) gq=GeneralizedQSampling(data,bvals,gradients) sodf=gq.odf(data[5,5,5]) vertices, faces = get_sphere('symmetric362') print(faces.shape) peaks,inds=peak_finding(np.squeeze(sdf),faces) print(peaks, inds) peaks2,inds2=peak_finding(np.squeeze(sodf),faces) print(peaks2, inds2) """ '''
def test_all_zeros(): bvecs, bvals = read_bvec_file(get_data('55dir_grad.bvec')) gtab = grad.gradient_table_from_bvals_bvecs(bvals, bvecs.T) fit_methods = ['LS', 'OLS', 'NNLS', 'RESTORE'] for _ in fit_methods: dm = dti.TensorModel(gtab) assert_array_almost_equal(dm.fit(np.zeros(bvals.shape[0])).evals, 0)
def reconst_flow_core(flow, extra_args=[]): with TemporaryDirectory() as out_dir: data_path, bval_path, bvec_path = get_data('small_25') vol_img = nib.load(data_path) volume = vol_img.get_data() mask = np.ones_like(volume[:, :, :, 0]) mask_img = nib.Nifti1Image(mask.astype(np.uint8), vol_img.affine) mask_path = join(out_dir, 'tmp_mask.nii.gz') nib.save(mask_img, mask_path) dti_flow = flow() args = [data_path, bval_path, bvec_path, mask_path] args.extend(extra_args) dti_flow.run(*args, out_dir=out_dir) fa_path = dti_flow.last_generated_outputs['out_fa'] fa_data = nib.load(fa_path).get_data() assert_equal(fa_data.shape, volume.shape[:-1]) tensor_path = dti_flow.last_generated_outputs['out_tensor'] tensor_data = nib.load(tensor_path) assert_equal(tensor_data.shape[-1], 6) assert_equal(tensor_data.shape[:-1], volume.shape[:-1]) ga_path = dti_flow.last_generated_outputs['out_ga'] ga_data = nib.load(ga_path).get_data() assert_equal(ga_data.shape, volume.shape[:-1]) rgb_path = dti_flow.last_generated_outputs['out_rgb'] rgb_data = nib.load(rgb_path) assert_equal(rgb_data.shape[-1], 3) assert_equal(rgb_data.shape[:-1], volume.shape[:-1]) md_path = dti_flow.last_generated_outputs['out_md'] md_data = nib.load(md_path).get_data() assert_equal(md_data.shape, volume.shape[:-1]) ad_path = dti_flow.last_generated_outputs['out_ad'] ad_data = nib.load(ad_path).get_data() assert_equal(ad_data.shape, volume.shape[:-1]) rd_path = dti_flow.last_generated_outputs['out_rd'] rd_data = nib.load(rd_path).get_data() assert_equal(rd_data.shape, volume.shape[:-1]) mode_path = dti_flow.last_generated_outputs['out_mode'] mode_data = nib.load(mode_path).get_data() assert_equal(mode_data.shape, volume.shape[:-1]) evecs_path = dti_flow.last_generated_outputs['out_evec'] evecs_data = nib.load(evecs_path).get_data() assert_equal(evecs_data.shape[-2:], tuple((3, 3))) assert_equal(evecs_data.shape[:-2], volume.shape[:-1]) evals_path = dti_flow.last_generated_outputs['out_eval'] evals_data = nib.load(evals_path).get_data() assert_equal(evals_data.shape[-1], 3) assert_equal(evals_data.shape[:-1], volume.shape[:-1])
def test_btable_prepare(): sq2 = np.sqrt(2) / 2. bvals = 1500 * np.ones(7) bvals[0] = 0 bvecs = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [sq2, sq2, 0], [sq2, 0, sq2], [0, sq2, sq2]]) bt = gradient_table(bvals, bvecs) npt.assert_array_equal(bt.bvecs, bvecs) bt.info fimg, fbvals, fbvecs = get_data('small_64D') bvals = np.load(fbvals) bvecs = np.load(fbvecs) bvecs = np.where(np.isnan(bvecs), 0, bvecs) bt = gradient_table(bvals, bvecs) npt.assert_array_equal(bt.bvecs, bvecs) bt2 = gradient_table(bvals, bvecs.T) npt.assert_array_equal(bt2.bvecs, bvecs) btab = np.concatenate((bvals[:, None], bvecs), axis=1) bt3 = gradient_table(btab) npt.assert_array_equal(bt3.bvecs, bvecs) npt.assert_array_equal(bt3.bvals, bvals) bt4 = gradient_table(btab.T) npt.assert_array_equal(bt4.bvecs, bvecs) npt.assert_array_equal(bt4.bvals, bvals) # Test for proper inputs (expects either bvals/bvecs or 4 by n): assert_raises(ValueError, gradient_table, bvecs)
def test_eudx_further(): """ Cause we love testin.. ;-) """ fimg,fbvals,fbvecs=get_data('small_101D') img=ni.load(fimg) affine=img.get_affine() data=img.get_data() gtab = gradient_table(fbvals, fbvecs) tensor_model = TensorModel(gtab) ten = tensor_model.fit(data) x,y,z=data.shape[:3] seeds=np.zeros((10**4,3)) for i in range(10**4): rx=(x-1)*np.random.rand() ry=(y-1)*np.random.rand() rz=(z-1)*np.random.rand() seeds[i]=np.ascontiguousarray(np.array([rx,ry,rz]),dtype=np.float64) ind = quantize_evecs(ten.evecs) eu=EuDX(a=ten.fa, ind=ind, seeds=seeds, a_low=.2) T=[e for e in eu] #check that there are no negative elements for t in T: assert_equal(np.sum(t.ravel()<0),0)