示例#1
0
def test_reconst_ivim():

    with TemporaryDirectory() as out_dir:
        bvals = np.array([
            0., 10., 20., 30., 40., 60., 80., 100., 120., 140., 160., 180.,
            200., 300., 400., 500., 600., 700., 800., 900., 1000.
        ])
        N = len(bvals)
        bvecs = generate_bvecs(N)
        temp_bval_path = pjoin(out_dir, "temp.bval")
        np.savetxt(temp_bval_path, bvals)
        temp_bvec_path = pjoin(out_dir, "temp.bvec")
        np.savetxt(temp_bvec_path, bvecs)

        gtab = gradient_table(bvals, bvecs)

        S0, f, D_star, D = 1000.0, 0.132, 0.00885, 0.000921

        mevals = np.array(([D_star, D_star, D_star], [D, D, D]))
        # This gives an isotropic signal.
        data = multi_tensor(gtab,
                            mevals,
                            snr=None,
                            S0=S0,
                            fractions=[f * 100, 100 * (1 - f)])
        # Single voxel data
        data_single = data[0]
        temp_affine = np.eye(4)

        data_multi = np.zeros((2, 2, 1, len(gtab.bvals)), dtype=int)
        data_multi[0, 0, 0] = data_multi[0, 1, 0] = data_multi[
            1, 0, 0] = data_multi[1, 1, 0] = data_single
        data_path = pjoin(out_dir, 'tmp_data.nii.gz')
        save_nifti(data_path, data_multi, temp_affine)

        mask = np.ones_like(data_multi[..., 0], dtype=np.uint8)
        mask_path = pjoin(out_dir, 'tmp_mask.nii.gz')
        save_nifti(mask_path, mask, temp_affine)

        ivim_flow = ReconstIvimFlow()

        args = [data_path, temp_bval_path, temp_bvec_path, mask_path]

        ivim_flow.run(*args, out_dir=out_dir)

        S0_path = ivim_flow.last_generated_outputs['out_S0_predicted']
        S0_data = load_nifti_data(S0_path)
        assert_equal(S0_data.shape, data_multi.shape[:-1])

        f_path = ivim_flow.last_generated_outputs['out_perfusion_fraction']
        f_data = load_nifti_data(f_path)
        assert_equal(f_data.shape, data_multi.shape[:-1])

        D_star_path = ivim_flow.last_generated_outputs['out_D_star']
        D_star_data = load_nifti_data(D_star_path)
        assert_equal(D_star_data.shape, data_multi.shape[:-1])

        D_path = ivim_flow.last_generated_outputs['out_D']
        D_data = load_nifti_data(D_path)
        assert_equal(D_data.shape, data_multi.shape[:-1])
示例#2
0
def test_motion_correction():
    data_path, fbvals_path, fbvecs_path = get_fnames('small_64D')
    volume = load_nifti_data(data_path)

    with TemporaryDirectory() as out_dir:
        # Use an abbreviated data-set:
        img = nib.load(data_path)
        data = img.get_fdata()[..., :10]
        nib.save(nib.Nifti1Image(data, img.affine),
                 os.path.join(out_dir, 'data.nii.gz'))
        # Save a subset:
        bvals = np.loadtxt(fbvals_path)
        bvecs = np.loadtxt(fbvecs_path)
        np.savetxt(os.path.join(out_dir, 'bvals.txt'), bvals[:10])
        np.savetxt(os.path.join(out_dir, 'bvecs.txt'), bvecs[:10])

        motion_correction_flow = MotionCorrectionFlow()

        motion_correction_flow._force_overwrite = True
        motion_correction_flow.run(os.path.join(out_dir, 'data.nii.gz'),
                                   os.path.join(out_dir, 'bvals.txt'),
                                   os.path.join(out_dir, 'bvecs.txt'),
                                   out_dir=out_dir)
        out_path = motion_correction_flow.last_generated_outputs['out_moved']
        corrected = load_nifti_data(out_path)

        npt.assert_equal(corrected.shape, data.shape)
        npt.assert_equal(corrected.min(), data.min())
        npt.assert_equal(corrected.max(), data.max())
示例#3
0
    def _cmc_sc(self):
        from dipy.tracking.stopping_criterion import CmcStoppingCriterion

        f_pve_csf, f_pve_gm, f_pve_wm = load_pve_files(self.subj_folder,
                                                       self.pve_file_name)[:3]
        pve_csf_data = load_nifti_data(f_pve_csf)
        pve_gm_data = load_nifti_data(f_pve_gm)
        pve_wm_data = load_nifti_data(f_pve_wm)
        cmc_criterion = CmcStoppingCriterion.from_pve(
            pve_wm_data,
            pve_gm_data,
            pve_csf_data,
            step_size=self.parameters_dict['step_size'],
            average_voxel_size=self.parameters_dict['voxel_size'])
        self.classifier = cmc_criterion
示例#4
0
def test_response_from_mask():
    fdata, fbvals, fbvecs = get_fnames('small_64D')
    bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
    data = load_nifti_data(fdata)

    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)
示例#5
0
def test_reslice():

    with TemporaryDirectory() as out_dir:
        data_path, _, _ = get_fnames('small_25')
        volume = load_nifti_data(data_path)

        reslice_flow = ResliceFlow()
        reslice_flow.run(data_path, [1.5, 1.5, 1.5], out_dir=out_dir)

        out_path = reslice_flow.last_generated_outputs['out_resliced']
        resliced = load_nifti_data(out_path)

        npt.assert_equal(resliced.shape[0] > volume.shape[0], True)
        npt.assert_equal(resliced.shape[1] > volume.shape[1], True)
        npt.assert_equal(resliced.shape[2] > volume.shape[2], True)
        npt.assert_equal(resliced.shape[-1], volume.shape[-1])
示例#6
0
def test_dti_xval():
    data = load_nifti_data(fdata)
    gtab = gt.gradient_table(fbval, fbvec)
    dm = dti.TensorModel(gtab, 'LS')
    # The data has 102 directions, so will not divide neatly into 10 bits
    npt.assert_raises(ValueError, xval.kfold_xval, dm, data, 10)

    # In simulation with no noise, COD should be perfect:
    psphere = dpd.get_sphere('symmetric362')
    bvecs = np.concatenate(([[0, 0, 0]], psphere.vertices))
    bvals = np.zeros(len(bvecs)) + 1000
    bvals[0] = 0
    gtab = gt.gradient_table(bvals, bvecs)
    mevals = np.array(([0.0015, 0.0003, 0.0001], [0.0015, 0.0003, 0.0003]))
    mevecs = [
        np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]),
        np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
    ]
    S = sims.single_tensor(gtab, 100, mevals[0], mevecs[0], snr=None)

    dm = dti.TensorModel(gtab, 'LS')
    kf_xval = xval.kfold_xval(dm, S, 2)
    cod = xval.coeff_of_determination(S, kf_xval)
    npt.assert_array_almost_equal(cod, np.ones(kf_xval.shape[:-1]) * 100)

    # Test with 2D data for use of a mask
    S = np.array([[S, S], [S, S]])
    mask = np.ones(S.shape[:-1], dtype=bool)
    mask[1, 1] = 0
    kf_xval = xval.kfold_xval(dm, S, 2, mask=mask)
    cod2d = xval.coeff_of_determination(S, kf_xval)
    npt.assert_array_almost_equal(np.round(cod2d[0, 0]), cod)
示例#7
0
def test_exponential_iso():
    fdata, fbvals, fbvecs = dpd.get_fnames()
    data_dti = load_nifti_data(fdata)
    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()
        sffit1.odf(sphere)
        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)
示例#8
0
def test_mppca_flow():
    with TemporaryDirectory() as out_dir:
        S0 = 100 + 2 * np.random.standard_normal((22, 23, 30, 20))
        data_path = os.path.join(out_dir, "random_noise.nii.gz")
        save_nifti(data_path, S0, np.eye(4))

        mppca_flow = MPPCAFlow()
        mppca_flow.run(data_path, out_dir=out_dir)
        assert_true(os.path.isfile(
                mppca_flow.last_generated_outputs['out_denoised']))
        assert_false(os.path.isfile(
                mppca_flow.last_generated_outputs['out_sigma']))

        mppca_flow._force_overwrite = True
        mppca_flow.run(data_path, return_sigma=True, pca_method='svd',
                       out_dir=out_dir)
        assert_true(os.path.isfile(
                mppca_flow.last_generated_outputs['out_denoised']))
        assert_true(os.path.isfile(
                mppca_flow.last_generated_outputs['out_sigma']))

        denoised_path = mppca_flow.last_generated_outputs['out_denoised']
        denoised_data = load_nifti_data(denoised_path)
        assert_greater(denoised_data.min(), S0.min())
        assert_less(denoised_data.max(), S0.max())
        npt.assert_equal(np.round(denoised_data.mean()), 100)
示例#9
0
def test_FiberFit():
    data_file, bval_file, bvec_file = dpd.get_fnames('small_64D')
    data = load_nifti_data(data_file)
    bvals, bvecs = read_bvals_bvecs(bval_file, bvec_file)
    gtab = grad.gradient_table(bvals, bvecs)
    FM = life.FiberModel(gtab)
    evals = [0.0015, 0.0005, 0.0005]

    streamline = [[[1, 2, 3], [4, 5, 3], [5, 6, 3], [6, 7, 3]],
                  [[1, 2, 3], [4, 5, 3], [5, 6, 3]]]

    fiber_matrix, vox_coords = FM.setup(streamline, np.eye(4), evals)

    w = np.array([0.5, 0.5])
    sig = opt.spdot(fiber_matrix, w) + 1.0  # Add some isotropic stuff
    S0 = data[..., gtab.b0s_mask]
    this_data = np.zeros((10, 10, 10, 64))
    this_data[vox_coords[:, 0], vox_coords[:, 1], vox_coords[:, 2]] =\
        (sig.reshape((4, 64)) *
         S0[vox_coords[:, 0], vox_coords[:, 1], vox_coords[:, 2]])

    # Grab some realistic S0 values:
    this_data = np.concatenate([data[..., gtab.b0s_mask], this_data], -1)

    fit = FM.fit(this_data, streamline, np.eye(4))
    npt.assert_almost_equal(fit.predict()[1], fit.data[1], decimal=-1)

    # Predict with an input GradientTable
    npt.assert_almost_equal(fit.predict(gtab)[1], fit.data[1], decimal=-1)

    npt.assert_almost_equal(
        this_data[vox_coords[:, 0], vox_coords[:, 1], vox_coords[:, 2]],
        fit.data)
示例#10
0
文件: test_sfm.py 项目: mvgolub/dipy
def test_sfm_stick():
    fdata, fbvals, fbvecs = dpd.get_fnames()
    data = load_nifti_data(fdata)
    gtab = grad.gradient_table(fbvals, fbvecs)
    sfmodel = sfm.SparseFascicleModel(gtab,
                                      solver='NNLS',
                                      response=[0.001, 0, 0])
    sffit1 = sfmodel.fit(data[0, 0, 0])
    sphere = dpd.get_sphere()
    sffit1.odf(sphere)
    sffit1.predict(gtab)

    SNR = 1000
    S0 = 100
    mevals = np.array(([0.001, 0, 0], [0.001, 0, 0]))
    angles = [(0, 0), (60, 0)]
    S, sticks = sims.multi_tensor(gtab,
                                  mevals,
                                  S0,
                                  angles=angles,
                                  fractions=[50, 50],
                                  snr=SNR)

    sfmodel = sfm.SparseFascicleModel(gtab,
                                      solver='NNLS',
                                      response=[0.001, 0, 0])
    sffit = sfmodel.fit(S)
    pred = sffit.predict()
    npt.assert_(xval.coeff_of_determination(pred, S) > 96)
示例#11
0
文件: test_sfm.py 项目: mvgolub/dipy
def test_sfm():
    fdata, fbvals, fbvecs = dpd.get_fnames()
    data = load_nifti_data(fdata)
    gtab = grad.gradient_table(fbvals, fbvecs)
    for iso in [sfm.ExponentialIsotropicModel, None]:
        sfmodel = sfm.SparseFascicleModel(gtab, isotropic=iso)
        sffit1 = sfmodel.fit(data[0, 0, 0])
        sphere = dpd.get_sphere()
        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 do_segmentation(self,src_path,dst_path):
    """
    
    This function is used to segment the input image into a segmented image based on grey matter, white matter and csf. These are the features used to
    detect the stage of AD 

    Variables & its function:
    nclass => value is initialized as 3 inorder to divide to 3 classes-GM,WM,CSF
    beta => The smoothness factor of segmentation
    t0 => Stores the time before segmentation
    hmrf => Create an instance of class TissueClassifierHMRF
    t1 => Store the time after segmentation
    total_time => Calculate the total time taken for segmentation
    brain => Reconstructing the segmented brain image as a 3D file which is then saved to the destination

    """
    #To get only the image data array
    t1 = load_nifti_data(src_path)
    print('t1.shape (%d, %d, %d)' % t1.shape)
    #To load the entire nifti file
    t2 = nib.load(src_path)
    nclass = 3
    beta = 0.1
    t0 = time.time()
    hmrf = TissueClassifierHMRF()
    #Perform segmentation
    initial_segmentation, final_segmentation, PVE = hmrf.classify(t1, nclass, beta)
    t1 = time.time()
    total_time = t1-t0
    print('Total time:' + str(total_time))
    print(final_segmentation.shape)
    brain = nib.Nifti1Image(final_segmentation,t2.affine)
    print('Segmentation performed successfully')
    nib.save(brain, os.path.join(dst_path))
示例#13
0
def test_median_otsu():
    fname = get_fnames('S0_10')
    data = load_nifti_data(fname)
    data = np.squeeze(data.astype('f8'))
    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_almost_equal(mask.sum(), mask2.sum())

    _, 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)

    # For 4D volumes, can't call without vol_idx input:
    assert_raises(ValueError, median_otsu, data2)
示例#14
0
文件: eval.py 项目: geyunxiang/mmdps
def eval_method(name=None, method=None, track_path=None, data_path=None):

    if track_path == None:
        track_path = './Result/Track/tractogram_' + method + '_' + name + '.trk'
    if data_path == None:
        data_path = './data/DWI/' + name + '/'

    if not op.exists(track_path):
        print('no tracking')
        return 0

    else:

        from dipy.io.gradients import read_bvals_bvecs
        from dipy.io.image import load_nifti_data, load_nifti
        from dipy.core.gradients import gradient_table

        data, affine, hardi_img = load_nifti(data_path + 'norm.nii.gz',
                                             return_img=True)
        print(data.shape)
        labels = load_nifti_data(data_path + 'seg.nii.gz')
        # t1_data = load_nifti_data('./data/tanenci_20170601/b0.nii.gz')
        bvals, bvecs = read_bvals_bvecs(data_path + 'DWI.bval',
                                        data_path + 'DWI.bvec')
        gtab = gradient_table(bvals, bvecs)


# Read the candidates from file in voxel space:
    candidate_sl_sft = load_trk(track_path, 'same', bbox_valid_check=False)
    candidate_sl_sft.to_vox()
    candidate_sl = candidate_sl_sft.streamlines

    print('loading finished, begin weighting')

    fiber_model = life.FiberModel(gtab)
    inv_affine = np.linalg.inv(hardi_img.affine)
    fiber_fit = fiber_model.fit(data,
                                reduct(candidate_sl, data[:, :, :, 0]),
                                affine=np.eye(4))

    print('weighting finished, begin prediction')

    beta_baseline = np.zeros(fiber_fit.beta.shape[0])
    pred_weighted = np.reshape(
        opt.spdot(fiber_fit.life_matrix, beta_baseline),
        (fiber_fit.vox_coords.shape[0], np.sum(~gtab.b0s_mask)))

    model_predict = fiber_fit.predict()
    model_error = model_predict - fiber_fit.data
    model_rmse = np.sqrt(np.mean(model_error[:, 10:]**2, -1))
    #print('model_rmse:', model_rmse.shape)

    vol_model = np.zeros(data.shape[:3]) * np.nan
    vol_model[fiber_fit.vox_coords[:, 0], fiber_fit.vox_coords[:, 1],
              fiber_fit.vox_coords[:, 2]] = model_rmse

    #print('error:', np.sum(vol_model) / model_rmse.shape[0])

    return np.sum(model_rmse) / model_rmse.shape[0], vol_model, affine
示例#15
0
def create_cmc_classifier(folder_name):
    from dipy.tracking.stopping_criterion import CmcStoppingCriterion

    f_pve_csf, f_pve_gm, f_pve_wm = load_pve_files(folder_name)
    pve_csf_data = load_nifti_data(f_pve_csf)
    pve_gm_data = load_nifti_data(f_pve_gm)
    pve_wm_data, _, voxel_size = load_nifti(f_pve_wm, return_voxsize=True)
    voxel_size = np.average(voxel_size[1:4])
    step_size = 0.2
    cmc_criterion = CmcStoppingCriterion.from_pve(
        pve_wm_data,
        pve_gm_data,
        pve_csf_data,
        step_size=step_size,
        average_voxel_size=voxel_size)

    return cmc_criterion, step_size
示例#16
0
def read_cenir_multib(bvals=None):
    """Read CENIR multi b-value data.

    Parameters
    ----------
    bvals : list or int
        The b-values to read from file (200, 400, 1000, 2000, 3000).

    Returns
    -------
    gtab : a GradientTable class instance
    img : nibabel.Nifti1Image

    """
    files, folder = fetch_cenir_multib(with_raw=False)
    if bvals is None:
        bvals = [200, 400, 1000, 2000, 3000]
    if isinstance(bvals, int):
        bvals = [bvals]
    file_dict = {
        200: {
            'DWI': pjoin(folder, '4D_dwi_eddycor_B200.nii.gz'),
            'bvals': pjoin(folder, 'dwi_bvals_B200'),
            'bvecs': pjoin(folder, 'dwi_bvecs_B200')
        },
        400: {
            'DWI': pjoin(folder, '4D_dwieddycor_B400.nii.gz'),
            'bvals': pjoin(folder, 'bvals_B400'),
            'bvecs': pjoin(folder, 'bvecs_B400')
        },
        1000: {
            'DWI': pjoin(folder, '4D_dwieddycor_B1000.nii.gz'),
            'bvals': pjoin(folder, 'bvals_B1000'),
            'bvecs': pjoin(folder, 'bvecs_B1000')
        },
        2000: {
            'DWI': pjoin(folder, '4D_dwieddycor_B2000.nii.gz'),
            'bvals': pjoin(folder, 'bvals_B2000'),
            'bvecs': pjoin(folder, 'bvecs_B2000')
        },
        3000: {
            'DWI': pjoin(folder, '4D_dwieddycor_B3000.nii.gz'),
            'bvals': pjoin(folder, 'bvals_B3000'),
            'bvecs': pjoin(folder, 'bvecs_B3000')
        }
    }
    data = []
    bval_list = []
    bvec_list = []
    for bval in bvals:
        data.append(load_nifti_data(file_dict[bval]['DWI']))
        bval_list.extend(np.loadtxt(file_dict[bval]['bvals']))
        bvec_list.append(np.loadtxt(file_dict[bval]['bvecs']))

    # All affines are the same, so grab the last one:
    aff = nib.load(file_dict[bval]['DWI']).affine
    return (nib.Nifti1Image(np.concatenate(data, -1), aff),
            gradient_table(bval_list, np.concatenate(bvec_list, -1)))
示例#17
0
文件: test_sfm.py 项目: mvgolub/dipy
def test_sfm_background():
    fdata, fbvals, fbvecs = dpd.get_fnames()
    data = load_nifti_data(fdata)
    gtab = grad.gradient_table(fbvals, fbvecs)
    to_fit = data[0, 0, 0]
    to_fit[gtab.b0s_mask] = 0
    sfmodel = sfm.SparseFascicleModel(gtab, solver='NNLS')
    sffit = sfmodel.fit(to_fit)
    npt.assert_equal(sffit.beta, np.zeros_like(sffit.beta))
示例#18
0
def test_odf_with_zeros():
    fdata, fbval, fbvec = get_fnames('small_25')
    gtab = grad.gradient_table(fbval, fbvec)
    data = load_nifti_data(fdata)
    dm = dti.TensorModel(gtab)
    df = dm.fit(data)
    df.evals[0, 0, 0] = np.array([0, 0, 0])
    sphere = create_unit_sphere(4)
    odf = df.odf(sphere)
    npt.assert_equal(odf[0, 0, 0], np.zeros(sphere.vertices.shape[0]))
示例#19
0
def reconst_mmri_core(flow, lap, pos):
    with TemporaryDirectory() as out_dir:
        data_path, bval_path, bvec_path = get_fnames('small_25')
        volume = load_nifti_data(data_path)

        mmri_flow = flow()
        mmri_flow.run(data_files=data_path,
                      bvals_files=bval_path,
                      bvecs_files=bvec_path,
                      small_delta=0.0129,
                      big_delta=0.0218,
                      laplacian=lap,
                      positivity=pos,
                      out_dir=out_dir)

        for out_name in [
                'out_rtop', 'out_lapnorm', 'out_msd', 'out_qiv', 'out_rtap',
                'out_rtpp', 'out_ng', 'out_parng', 'out_perng'
        ]:
            out_path = mmri_flow.last_generated_outputs[out_name]
            out_data = load_nifti_data(out_path)
            npt.assert_equal(out_data.shape, volume.shape[:-1])

        bvals, bvecs = read_bvals_bvecs(bval_path, bvec_path)
        bvals[0] = 5.
        bvecs = generate_bvecs(len(bvals))
        tmp_bval_path = pjoin(out_dir, "tmp.bval")
        tmp_bvec_path = pjoin(out_dir, "tmp.bvec")
        np.savetxt(tmp_bval_path, bvals)
        np.savetxt(tmp_bvec_path, bvecs.T)
        mmri_flow._force_overwrite = True
        with npt.assert_raises(BaseException):
            npt.assert_warns(UserWarning,
                             mmri_flow.run,
                             data_path,
                             tmp_bval_path,
                             tmp_bvec_path,
                             small_delta=0.0129,
                             big_delta=0.0218,
                             laplacian=lap,
                             positivity=pos,
                             out_dir=out_dir)
示例#20
0
def get_data(name=None,
             data_path=None,
             pft=False,
             norm='norm.nii.gz',
             bval='DWI.bval',
             bvec='DWI.bvec',
             seg='seg.nii.gz',
             FA=None,
             mask='norm_mask.nii.gz'):
    if name != None:
        root = './data/DWI/' + name
    else:
        root = data_path
    DWI = root + '/' + norm
    bvals_path = root + '/' + bval
    bvecs_path = root + '/' + bvec

    mask_path = root + '/' + mask

    data, affine, img = load_nifti(DWI, return_img=True)
    if seg == None:
        labels = None
    else:
        seg_path = root + '/' + seg
        labels = load_nifti_data(seg_path)

    bvals, bvecs = read_bvals_bvecs(bvals_path, bvecs_path)
    gtab = gradient_table(bvals, bvecs)
    head_mask = load_nifti_data(mask_path)

    if not pft:
        return data, affine, img, labels, gtab, head_mask
    else:
        f_pve_csf = root + './pve_2.nii.gz'
        f_pve_gm = root + './pve_0.nii.gz'
        f_pve_wm = root + './pve_1.nii.gz'
        pve_csf_data = load_nifti_data(f_pve_csf)
        pve_gm_data = load_nifti_data(f_pve_gm)
        pve_wm_data, _, voxel_size = load_nifti(f_pve_wm, return_voxsize=True)

        return data, affine, img, labels, gtab, head_mask, \
               pve_csf_data, pve_gm_data, pve_wm_data, voxel_size
示例#21
0
def test_min_signal_alone():
    fdata, fbvals, fbvecs = get_fnames()
    data = load_nifti_data(fdata)
    gtab = grad.gradient_table(fbvals, fbvecs)

    idx = tuple(np.array(np.where(data == np.min(data)))[:-1, 0])
    ten_model = dti.TensorModel(gtab)
    fit_alone = ten_model.fit(data[idx])
    fit_together = ten_model.fit(data)
    npt.assert_array_almost_equal(fit_together.model_params[idx],
                                  fit_alone.model_params, decimal=12)
示例#22
0
文件: bench_csd.py 项目: mvgolub/dipy
def bench_csdeconv(center=(50, 40, 40), width=12):
    img, gtab, labels_img = read_stanford_labels()
    data = load_nifti_data(img)

    labels = load_nifti_data(labels_img)
    shape = labels.shape
    mask = np.in1d(labels, [1, 2])
    mask.shape = shape

    a, b, c = center
    hw = width // 2
    idx = (slice(a - hw, a + hw), slice(b - hw, b + hw), slice(c - hw, c + hw))

    data_small = data[idx].copy()
    mask_small = mask[idx].copy()
    voxels = mask_small.sum()

    cmd = "model.fit(data_small, mask_small)"
    print("== Benchmarking CSD fit on %d voxels ==" % voxels)
    msg = "SH order - %d, gradient directons - %d :: %g sec"

    # Basic case
    sh_order = 8
    ConstrainedSphericalDeconvModel(gtab, None, sh_order=sh_order)
    time = npt.measure(cmd)
    print(msg % (sh_order, num_grad(gtab), time))

    # Smaller data set
    # data_small = data_small[..., :75].copy()
    gtab = GradientTable(gtab.gradients[:75])
    ConstrainedSphericalDeconvModel(gtab, None, sh_order=sh_order)
    time = npt.measure(cmd)
    print(msg % (sh_order, num_grad(gtab), time))

    # Super resolution
    sh_order = 12
    ConstrainedSphericalDeconvModel(gtab, None, sh_order=sh_order)
    time = npt.measure(cmd)
    print(msg % (sh_order, num_grad(gtab), time))
示例#23
0
def test_median_otsu():
    fname = get_fnames('S0_10')
    data = load_nifti_data(fname)
    data = cp.asarray(np.squeeze(data.astype('f8')))
    dummy_mask = data > data.mean()
    data_masked, mask = median_otsu(
        data,
        median_radius=3,
        numpass=2,
        autocrop=False,
        vol_idx=None,
        dilate=None,
    )
    assert mask.sum() < dummy_mask.sum()
    data2 = cp.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 mask.sum() == mask2.sum()

    _, mask3 = median_otsu(
        data2,
        median_radius=3,
        numpass=2,
        autocrop=False,
        vol_idx=[0, 1],
        dilate=1,
    )
    assert mask2.sum() < mask3.sum()

    _, mask4 = median_otsu(
        data2,
        median_radius=3,
        numpass=2,
        autocrop=False,
        vol_idx=[0, 1],
        dilate=2,
    )
    assert mask3.sum() < mask4.sum()

    # For 4D volumes, can't call without vol_idx input:
    with pytest.raises(ValueError):
        median_otsu(data2)
示例#24
0
def test_csd_xval():
    # First, let's see that it works with some data:
    data = load_nifti_data(fdata)[1:3, 1:3, 1:3]  # Make it *small*
    gtab = gt.gradient_table(fbval, fbvec)
    S0 = np.mean(data[..., gtab.b0s_mask])
    response = ([0.0015, 0.0003, 0.0001], S0)

    # In simulation, it should work rather well (high COD):
    psphere = dpd.get_sphere('symmetric362')
    bvecs = np.concatenate(([[0, 0, 0]], psphere.vertices))
    bvals = np.zeros(len(bvecs)) + 1000
    bvals[0] = 0
    gtab = gt.gradient_table(bvals, bvecs)
    mevals = np.array(([0.0015, 0.0003, 0.0001], [0.0015, 0.0003, 0.0003]))
    mevecs = [
        np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]),
        np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
    ]
    S0 = 100
    S = sims.single_tensor(gtab, S0, mevals[0], mevecs[0], snr=None)
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                message=descoteaux07_legacy_msg,
                                category=PendingDeprecationWarning)
        sm = csd.ConstrainedSphericalDeconvModel(gtab, response)
    np.random.seed(12345)
    response = ([0.0015, 0.0003, 0.0001], S0)
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                message=descoteaux07_legacy_msg,
                                category=PendingDeprecationWarning)
        kf_xval = xval.kfold_xval(sm, S, 2, response, sh_order=2)
    # Because of the regularization, COD is not going to be perfect here:
    cod = xval.coeff_of_determination(S, kf_xval)
    # We'll just test for regressions:
    csd_cod = 97  # pre-computed by hand for this random seed

    # We're going to be really lenient here:
    npt.assert_array_almost_equal(np.round(cod), csd_cod)
    # Test for sD data with more than one voxel for use of a mask:
    S = np.array([[S, S], [S, S]])
    mask = np.ones(S.shape[:-1], dtype=bool)
    mask[1, 1] = 0
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                message=descoteaux07_legacy_msg,
                                category=PendingDeprecationWarning)
        kf_xval = xval.kfold_xval(sm, S, 2, response, sh_order=2, mask=mask)

    cod = xval.coeff_of_determination(S, kf_xval)
    npt.assert_array_almost_equal(np.round(cod[0]), csd_cod)
示例#25
0
def test_median_otsu_flow():
    with TemporaryDirectory() as out_dir:
        data_path, _, _ = get_fnames('small_25')
        volume = load_nifti_data(data_path)
        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,
                                   vol_idx=vol_idx,
                                   median_radius=median_radius,
                                   numpass=numpass,
                                   autocrop=autocrop,
                                   dilate=dilate)

        result_mask_data = load_nifti_data(join(out_dir, mask_name))
        npt.assert_array_equal(result_mask_data.astype(np.uint8), mask)

        result_masked = nib.load(join(out_dir, masked_name))
        result_masked_data = np.asanyarray(result_masked.dataobj)

        npt.assert_array_equal(np.round(result_masked_data), masked)
示例#26
0
def reconst_flow_core(flow, extra_args=[], extra_kwargs={}):
    with TemporaryDirectory() as out_dir:
        data_path, bval_path, bvec_path = get_fnames('small_25')
        volume, affine = load_nifti(data_path)
        mask = np.ones_like(volume[:, :, :, 0], dtype=np.uint8)
        mask_path = join(out_dir, 'tmp_mask.nii.gz')
        save_nifti(mask_path, mask, affine)

        dti_flow = flow()

        args = [data_path, bval_path, bvec_path, mask_path]
        args.extend(extra_args)
        kwargs = dict(out_dir=out_dir)
        kwargs.update(extra_kwargs)

        dti_flow.run(*args, **kwargs)

        fa_path = dti_flow.last_generated_outputs['out_fa']
        fa_data = load_nifti_data(fa_path)
        assert_equal(fa_data.shape, volume.shape[:-1])

        tensor_path = dti_flow.last_generated_outputs['out_tensor']
        tensor_data = load_nifti_data(tensor_path)
        # Per default, tensor data is 5D, with six tensor elements on the last
        # dimension, except if nifti_tensor is set to False:
        if extra_kwargs.get('nifti_tensor', True):
            assert_equal(tensor_data.shape[-1], 6)
            assert_equal(tensor_data.shape[:-2], volume.shape[:-1])
        else:
            assert_equal(tensor_data.shape[-1], 6)
            assert_equal(tensor_data.shape[:-1], volume.shape[:-1])

        for out_name in ['out_ga', 'out_md', 'out_ad', 'out_rd', 'out_mode']:
            out_path = dti_flow.last_generated_outputs[out_name]
            out_data = load_nifti_data(out_path)
            assert_equal(out_data.shape, volume.shape[:-1])

        rgb_path = dti_flow.last_generated_outputs['out_rgb']
        rgb_data = load_nifti_data(rgb_path)
        assert_equal(rgb_data.shape[-1], 3)
        assert_equal(rgb_data.shape[:-1], volume.shape[:-1])

        evecs_path = dti_flow.last_generated_outputs['out_evec']
        evecs_data = load_nifti_data(evecs_path)
        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 = load_nifti_data(evals_path)
        assert_equal(evals_data.shape[-1], 3)
        assert_equal(evals_data.shape[:-1], volume.shape[:-1])
示例#27
0
def test_auto_response():
    fdata, fbvals, fbvecs = get_fnames('small_64D')
    bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
    data = load_nifti_data(fdata)

    gtab = gradient_table(bvals, bvecs)
    radius = 3

    def test_fa_superior(FA, fa_thr):
        return FA > fa_thr

    def test_fa_inferior(FA, fa_thr):
        return FA < fa_thr

    predefined_functions = [fa_superior, fa_inferior]
    defined_functions = [test_fa_superior, test_fa_inferior]

    for fa_thr in np.arange(0.1, 1, 0.1):
        for predefined, defined in \
          zip(predefined_functions, defined_functions):
            response_predefined, ratio_predefined, nvoxels_predefined = \
                auto_response(gtab,
                              data,
                              roi_center=None,
                              roi_radius=radius,
                              fa_callable=predefined,
                              fa_thr=fa_thr,
                              return_number_of_voxels=True)

            response_defined, ratio_defined, nvoxels_defined = \
                auto_response(gtab,
                              data,
                              roi_center=None,
                              roi_radius=radius,
                              fa_callable=defined,
                              fa_thr=fa_thr,
                              return_number_of_voxels=True)

            assert_equal(nvoxels_predefined, nvoxels_defined)
            assert_array_almost_equal(response_predefined[0],
                                      response_defined[0])
            assert_almost_equal(response_predefined[1], response_defined[1])
            assert_almost_equal(ratio_predefined, ratio_defined)
示例#28
0
def test_no_predict():
    # Test that if you try to do this with a model that doesn't have a `predict`
    # method, you get something reasonable.
    class NoPredictModel(base.ReconstModel):
        def __init__(self, gtab):
            base.ReconstModel.__init__(self, gtab)

        def fit(self, data, mask=None):
            return NoPredictFit(self, data, mask=mask)

    class NoPredictFit(base.ReconstFit):
        def __init__(self, model, data, mask=None):
            base.ReconstFit.__init__(self, model, data)

    gtab = gt.gradient_table(fbval, fbvec)
    my_model = NoPredictModel(gtab)
    data = load_nifti_data(fdata)[1:3, 1:3, 1:3]  # Whatever

    npt.assert_raises(ValueError, xval.kfold_xval, my_model, data, 2)
示例#29
0
from dipy.reconst.csdeconv import (ConstrainedSphericalDeconvModel,
                                   auto_response)
from dipy.tracking import utils
from dipy.tracking.local_tracking import LocalTracking
from dipy.tracking.streamline import Streamlines
from dipy.tracking.stopping_criterion import ThresholdStoppingCriterion
from dipy.viz import window, actor, colormap, has_fury

# Enables/disables interactive visualization
interactive = False

hardi_fname, hardi_bval_fname, hardi_bvec_fname = get_fnames('stanford_hardi')
label_fname = get_fnames('stanford_labels')

data, affine, hardi_img = load_nifti(hardi_fname, return_img=True)
labels = load_nifti_data(label_fname)
bvals, bvecs = read_bvals_bvecs(hardi_bval_fname, hardi_bvec_fname)
gtab = gradient_table(bvals, bvecs)

seed_mask = (labels == 2)
white_matter = (labels == 1) | (labels == 2)
seeds = utils.seeds_from_mask(seed_mask, affine, density=1)

response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
csd_fit = csd_model.fit(data, mask=white_matter)
"""
We use the GFA of the CSA model to build a stopping criterion.
"""

from dipy.reconst.shm import CsaOdfModel
示例#30
0
def load_TOM(fn):
    data = load_nifti_data(fn)
    return data