Exemplo n.º 1
0
def test_shore_fitting_constrain_e0():
    asm = ShoreModel(data.gtab, radial_order=data.radial_order,
                     zeta=data.zeta, lambdaN=data.lambdaN,
                     lambdaL=data.lambdaL,
                     constrain_e0=True)
    asmfit = asm.fit(data.S)
    npt.assert_almost_equal(compute_e0(asmfit), 1)
Exemplo n.º 2
0
def test_shore_fitting_constrain_e0():
    asm = ShoreModel(data.gtab, radial_order=data.radial_order,
                     zeta=data.zeta, lambdaN=data.lambdaN,
                     lambdaL=data.lambdaL,
                     constrain_e0=True)
    asmfit = asm.fit(data.S)
    assert_almost_equal(compute_e0(asmfit), 1)
Exemplo n.º 3
0
def test_shore_fitting_e0():
    gtab = get_gtab_taiwan_dsi()
    mevals = np.array(([0.0015, 0.0003, 0.0003],
                       [0.0015, 0.0003, 0.0003]))
    angl = [(0, 0), (60, 0)]
    S, sticks = MultiTensor(gtab, mevals, S0=100.0, angles=angl,
                            fractions=[50, 50], snr=None)

    radial_order = 8
    zeta = 700
    lambdaN = 1e-12
    lambdaL = 1e-12

    asm = ShoreModel(gtab, radial_order=radial_order,
                     zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)
    asmfit = asm.fit(S)

    assert_almost_equal(compute_e0(asmfit), 1)

    asm = ShoreModel(gtab, radial_order=radial_order,
                     zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL,
                     constrain_e0=True)
    asmfit = asm.fit(S)

    assert_almost_equal(compute_e0(asmfit), 1.)
def shore_odf(gtab, data, affine, mask, sphere):
    radial_order = 6
    zeta = 700
    lambdaN = 1e-8
    lambdaL = 1e-8
    model = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)
    return model.fit(data).odf(sphere)
def dMRI2ODF_DTI(PATH):
    '''
    Input the dMRI data
    return the ODF
    '''
    print(PATH)
    if os.path.exists(PATH + 'processed_data.npz'):
        return None
    dMRI_path = PATH + 'data.nii.gz'
    mask_path = PATH + 'nodif_brain_mask.nii.gz'
    dMRI_img = nib.load(dMRI_path)
    dMRI_data = dMRI_img.get_fdata()
    mask_img = nib.load(mask_path)
    mask = mask_img.get_fdata()

    ########## subsample ##########
    # in the main paper, to train the full 3D brain
    # We downsample the data into around 32x32x32
    # If not downsample, it can process the full-size brain image
    # but cannot fit into GPU memory
    dMRI_data = dMRI_data[::4, ::4, ::4, ...]
    mask = mask[::4, ::4, ::4, ...]

    bval = PATH + "bvals"
    bvec = PATH + "bvecs"

    radial_order = 6
    zeta = 700
    lambdaN = 1e-8
    lambdaL = 1e-8

    ###### process the ODF data ######
    # size is 32x32x32x(362)
    gtab = gradient_table(bvals=bval, bvecs=bvec)
    asm = ShoreModel(gtab,
                     radial_order=radial_order,
                     zeta=zeta,
                     lambdaN=lambdaN,
                     lambdaL=lambdaL)
    asmfit = asm.fit(dMRI_data, mask=mask)
    sphere = get_sphere('symmetric362')
    dMRI_odf = asmfit.odf(sphere)
    dMRI_odf[dMRI_odf <= 0] = 0  # remove the numerical issue

    ###### process the DTI data ######
    # size is 32x32x32x(3x3)
    tenmodel = dti.TensorModel(gtab)
    dMRI_dti = tenmodel.fit(dMRI_data, mask)
    dMRI_dti = dMRI_dti.quadratic_form

    name = PATH.split('/')[2]  # here, might be affected by the path
    # change the [2] here for the correct index
    np.savez(PATH + 'processed_data.npz',
             DTI=dMRI_dti,
             ODF=dMRI_odf,
             mask=mask,
             name=name)

    return None
Exemplo n.º 6
0
def test_multivox_shore():    
    gtab = get_3shell_gtab()

    data = np.random.random([20, 30, 1, gtab.gradients.shape[0]])
    radial_order = 4
    zeta = 700
    asm = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=1e-8, lambdaL=1e-8)
    asmfit = asm.fit(data)
    c_shore=asmfit.shore_coeff
    assert_equal(c_shore.shape[0:3], data.shape[0:3])
    assert_equal(np.alltrue(np.isreal(c_shore)), True)
Exemplo n.º 7
0
def test_shore_fitting_no_constrain_e0():
    asm = ShoreModel(data.gtab,
                     radial_order=data.radial_order,
                     zeta=data.zeta,
                     lambdaN=data.lambdaN,
                     lambdaL=data.lambdaL)
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                message=descoteaux07_legacy_msg,
                                category=PendingDeprecationWarning)
        asmfit = asm.fit(data.S)
    npt.assert_almost_equal(compute_e0(asmfit), 1)
Exemplo n.º 8
0
def test_shore_odf():
    gtab = get_isbi2013_2shell_gtab()

    # load repulsion 724 sphere
    sphere = default_sphere

    # load icosahedron sphere
    sphere2 = create_unit_sphere(5)
    data, golden_directions = sticks_and_ball(gtab,
                                              d=0.0015,
                                              S0=100,
                                              angles=[(0, 0), (90, 0)],
                                              fractions=[50, 50],
                                              snr=None)
    asm = ShoreModel(gtab,
                     radial_order=6,
                     zeta=700,
                     lambdaN=1e-8,
                     lambdaL=1e-8)
    # repulsion724
    asmfit = asm.fit(data)
    odf = asmfit.odf(sphere)
    odf_sh = asmfit.odf_sh()
    odf_from_sh = sh_to_sf(odf_sh, sphere, 6, basis_type=None, legacy=True)
    npt.assert_almost_equal(odf, odf_from_sh, 10)

    expected_phi = shore_matrix(radial_order=6, zeta=700, gtab=gtab)
    npt.assert_array_almost_equal(np.dot(expected_phi, asmfit.shore_coeff),
                                  asmfit.fitted_signal())

    directions, _, _ = peak_directions(odf, sphere, .35, 25)
    npt.assert_equal(len(directions), 2)
    npt.assert_almost_equal(angular_similarity(directions, golden_directions),
                            2, 1)

    # 5 subdivisions
    odf = asmfit.odf(sphere2)
    directions, _, _ = peak_directions(odf, sphere2, .35, 25)
    npt.assert_equal(len(directions), 2)
    npt.assert_almost_equal(angular_similarity(directions, golden_directions),
                            2, 1)

    sb_dummies = sticks_and_ball_dummies(gtab)
    for sbd in sb_dummies:
        data, golden_directions = sb_dummies[sbd]
        asmfit = asm.fit(data)
        odf = asmfit.odf(sphere2)
        directions, _, _ = peak_directions(odf, sphere2, .35, 25)
        if len(directions) <= 3:
            npt.assert_equal(len(directions), len(golden_directions))
        if len(directions) > 3:
            npt.assert_equal(gfa(odf) < 0.1, True)
Exemplo n.º 9
0
def shore_scalarmaps(data, gtab, outpath_fig, verbose=None):

    #bvecs[1:] = (bvecs[1:] /
    #             np.sqrt(np.sum(bvecs[1:] * bvecs[1:], axis=1))[:, None])
    #gtab = gradient_table(bvals, bvecs)
    if verbose:
        print('data.shape (%d, %d, %d, %d)' % data.shape)
    asm = ShoreModel(gtab)
    #Let’s just use only one slice only from the data.

    dataslice = data[30:70, 20:80, data.shape[2] // 2]
    #Fit the signal with the model and calculate the SHORE coefficients.

    asmfit = asm.fit(dataslice)
    #Calculate the analytical RTOP on the signal that corresponds to the integral of the signal.
    if verbose:
        print('Calculating... rtop_signal')
    rtop_signal = asmfit.rtop_signal()
    #Now we calculate the analytical RTOP on the propagator, that corresponds to its central value.

    if verbose:
        print('Calculating... rtop_pdf')
    rtop_pdf = asmfit.rtop_pdf()
    #In theory, these two measures must be equal, to show that we calculate the mean square error on this two measures.

    mse = np.sum((rtop_signal - rtop_pdf)**2) / rtop_signal.size
    if verbose:
        print("MSE = %f" % mse)
    MSE = 0.000000

    #Let’s calculate the analytical mean square displacement on the propagator.
    if verbose:
        print('Calculating... msd')
    msd = asmfit.msd()
    #Show the maps and save them to a file.

    fig = plt.figure(figsize=(6, 6))
    ax1 = fig.add_subplot(2, 2, 1, title='rtop_signal')
    ax1.set_axis_off()
    ind = ax1.imshow(rtop_signal.T, interpolation='nearest', origin='lower')
    plt.colorbar(ind)
    ax2 = fig.add_subplot(2, 2, 2, title='rtop_pdf')
    ax2.set_axis_off()
    ind = ax2.imshow(rtop_pdf.T, interpolation='nearest', origin='lower')
    plt.colorbar(ind)
    ax3 = fig.add_subplot(2, 2, 3, title='msd')
    ax3.set_axis_off()
    ind = ax3.imshow(msd.T, interpolation='nearest', origin='lower', vmin=0)
    plt.colorbar(ind)
    print("about to save")
    plt.savefig(outpath_fig)
    print("save done")
Exemplo n.º 10
0
def test_shore_positive_constrain():
    asm = ShoreModel(data.gtab,
                     radial_order=data.radial_order,
                     zeta=data.zeta,
                     lambdaN=data.lambdaN,
                     lambdaL=data.lambdaL,
                     constrain_e0=True,
                     positive_constraint=True,
                     pos_grid=11,
                     pos_radius=20e-03)
    asmfit = asm.fit(data.S)
    eap = asmfit.pdf_grid(11, 20e-03)
    assert_almost_equal(eap[eap < 0].sum(), 0, 3)
Exemplo n.º 11
0
def test_shore_positive_constrain():
    asm = ShoreModel(data.gtab,
                     radial_order=data.radial_order,
                     zeta=data.zeta,
                     lambdaN=data.lambdaN,
                     lambdaL=data.lambdaL,
                     constrain_e0=True,
                     positive_constraint=True,
                     pos_grid=11,
                     pos_radius=20e-03)
    asmfit = asm.fit(data.S)
    eap = asmfit.pdf_grid(11, 20e-03)
    assert_almost_equal(eap[eap < 0].sum(), 0, 3)
Exemplo n.º 12
0
def test_shore_odf():
    gtab = get_isbi2013_2shell_gtab()

    # load symmetric 724 sphere
    sphere = get_sphere('symmetric724')

    # load icosahedron sphere
    sphere2 = create_unit_sphere(5)
    data, golden_directions = SticksAndBall(gtab,
                                            d=0.0015,
                                            S0=100,
                                            angles=[(0, 0), (90, 0)],
                                            fractions=[50, 50],
                                            snr=None)
    asm = ShoreModel(gtab,
                     radial_order=6,
                     zeta=700,
                     lambdaN=1e-8,
                     lambdaL=1e-8)
    # symmetric724
    asmfit = asm.fit(data)
    odf = asmfit.odf(sphere)
    odf_sh = asmfit.odf_sh()
    odf_from_sh = sh_to_sf(odf_sh, sphere, 6, basis_type=None)
    assert_almost_equal(odf, odf_from_sh, 10)

    directions, _, _ = peak_directions(odf, sphere, .35, 25)
    assert_equal(len(directions), 2)
    assert_almost_equal(angular_similarity(directions, golden_directions), 2,
                        1)

    # 5 subdivisions
    odf = asmfit.odf(sphere2)
    directions, _, _ = peak_directions(odf, sphere2, .35, 25)
    assert_equal(len(directions), 2)
    assert_almost_equal(angular_similarity(directions, golden_directions), 2,
                        1)

    sb_dummies = sticks_and_ball_dummies(gtab)
    for sbd in sb_dummies:
        data, golden_directions = sb_dummies[sbd]
        asmfit = asm.fit(data)
        odf = asmfit.odf(sphere2)
        directions, _, _ = peak_directions(odf, sphere2, .35, 25)
        if len(directions) <= 3:
            assert_equal(len(directions), len(golden_directions))
        if len(directions) > 3:
            assert_equal(gfa(odf) < 0.1, True)
Exemplo n.º 13
0
def reconstruct_shore_fodf(bval_path,
                           bvec_path,
                           data_path,
                           data_var,
                           zeta_val=700.0):

    bval_path = os.path.normpath(bval_path)
    bvec_path = os.path.normpath(bvec_path)
    data_path = os.path.normpath(data_path)

    bvals, bvecs = read_bvals_bvecs(bval_path, bvec_path)
    gtab = gradient_table(bvals, bvecs)

    data = loadmat(data_path)
    data = data[data_var]

    shore_model = ShoreModel(gtab, radial_order=6, zeta=zeta_val)

    shore_peaks = peaks_from_model(shore_model,
                                   data,
                                   default_sphere,
                                   relative_peak_threshold=.1,
                                   min_separation_angle=45)

    print('Debug Here')

    return shore_peaks.shm_coeff
Exemplo n.º 14
0
def test_shore_positive_constrain():
    asm = ShoreModel(data.gtab,
                     radial_order=data.radial_order,
                     zeta=data.zeta,
                     lambdaN=data.lambdaN,
                     lambdaL=data.lambdaL,
                     constrain_e0=True,
                     positive_constraint=True,
                     pos_grid=11,
                     pos_radius=20e-03)
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                message=descoteaux07_legacy_msg,
                                category=PendingDeprecationWarning)
        asmfit = asm.fit(data.S)
        eap = asmfit.pdf_grid(11, 20e-03)
    npt.assert_almost_equal(eap[eap < 0].sum(), 0, 3)
Exemplo n.º 15
0
def test_shore_metrics():
    fetch_taiwan_ntu_dsi()
    img, gtab = read_taiwan_ntu_dsi()

    mevals = np.array(([0.0015, 0.0003, 0.0003],
                       [0.0015, 0.0003, 0.0003]))
    angl = [(0, 0), (60, 0)]
    S, sticks = MultiTensor(gtab, mevals, S0=100, angles=angl,
                            fractions=[50, 50], snr=None)
    S = S / S[0, None].astype(np.float)

    radial_order = 8
    zeta = 800
    lambdaN = 1e-12
    lambdaL = 1e-12
    asm = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)
    asmfit = asm.fit(S)
    c_shore= asmfit.shore_coeff

    cmat = SHOREmatrix(radial_order, zeta, gtab)
    S_reconst = np.dot(cmat, c_shore)
    nmse_signal = np.sqrt(np.sum((S - S_reconst) ** 2)) / (S.sum())
    assert_almost_equal(nmse_signal, 0.0, 4)

    mevecs2 = np.zeros((2, 3, 3))
    angl = np.array(angl)
    for i in range(2):
        mevecs2[i] = all_tensor_evecs(sticks[i]).T

    sphere = get_sphere('symmetric724')
    v = sphere.vertices
    radius = 10e-3
    pdf_shore = asmfit.pdf(v * radius)
    pdf_mt = multi_tensor_pdf(v * radius, [.5, .5], mevals=mevals, mevecs=mevecs2)
    nmse_pdf = np.sqrt(np.sum((pdf_mt - pdf_shore) ** 2)) / (pdf_mt.sum())
    assert_almost_equal(nmse_pdf, 0.0, 2)

    rtop_shore_signal = asmfit.rtop_signal()
    rtop_shore_pdf = asmfit.rtop_pdf()
    assert_almost_equal(rtop_shore_signal, rtop_shore_pdf, 9)
    rtop_mt = multi_tensor_rtop([.5, .5], mevals=mevals)
    assert_equal(rtop_mt/rtop_shore_signal < 1.12 and rtop_mt/rtop_shore_signal > 0.9 , True)
    
    msd_mt = multi_tensor_msd([.5, .5], mevals=mevals)
    msd_shore = asmfit.msd()
    assert_equal(msd_mt/msd_shore < 1.05 and msd_mt/msd_shore > 0.95 , True)
Exemplo n.º 16
0
def fit_data(data, bvals, bvecs, model_type='3D-SHORE', calculate_peak_image=False):
    """ Fits the defined model to the input dMRI and returns an MITK compliant ODF image.
    """

    # create dipy Sphere
    sphere = get_mitk_sphere()
    odf = None
    model = None
    gtab = gradient_table(bvals, bvecs)

    # fit selected model
    if model_type == '3D-SHORE':
        print('Fitting 3D-SHORE')
        radial_order = 6
        zeta = 700
        lambdaN = 1e-8
        lambdaL = 1e-8
        model = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)
        asmfit = model.fit(data)
        odf = asmfit.odf(sphere)
    elif model_type == 'CSA-QBALL':
        print('Fitting CSA-QBALL')
        model = CsaOdfModel(gtab, 4)
        odf = model.fit(data).odf(sphere)
        odf = np.clip(odf, 0, np.max(odf, -1)[..., None])
    elif model_type == 'SFM':
        print('Fitting SFM')
        response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
        model = sfm.SparseFascicleModel(gtab, sphere=sphere,
                                        l1_ratio=0.5, alpha=0.001,
                                        response=response[0])
        odf = model.fit(data).odf(sphere)
    elif model_type == 'CSD':
        print('Fitting CSD')
        response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
        model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
        odf = model.fit(data).odf(sphere)
    else:
        raise ValueError('Model type not supported. Available models: 3D-SHORE, CSA-QBALL, SFM, CSD')

    print('Preparing ODF image')
    # swap axes to obtain MITK compliant format.
    # odf = odf.swapaxes(3, 2)
    # odf = odf.swapaxes(2, 1)
    # odf = odf.swapaxes(1, 0)

    odf_image = sitk.Image([data.shape[2], data.shape[1], data.shape[0]], sitk.sitkVectorFloat32, len(sphere.vertices))
    for x in range(data.shape[2]):
        for y in range(data.shape[1]):
            for z in range(data.shape[0]):
                odf_image.SetPixel(x,y,z, odf[z,y,x,:])

    # if not calculate_peak_image:
    return odf_image, None
Exemplo n.º 17
0
def test_multivox_shore():
    gtab = get_3shell_gtab()

    data = np.random.random([20, 30, 1, gtab.gradients.shape[0]])
    radial_order = 4
    zeta = 700
    asm = ShoreModel(gtab,
                     radial_order=radial_order,
                     zeta=zeta,
                     lambdaN=1e-8,
                     lambdaL=1e-8)
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                message=descoteaux07_legacy_msg,
                                category=PendingDeprecationWarning)
        asmfit = asm.fit(data)
    c_shore = asmfit.shore_coeff
    npt.assert_equal(c_shore.shape[0:3], data.shape[0:3])
    npt.assert_equal(np.alltrue(np.isreal(c_shore)), True)
Exemplo n.º 18
0
def test_shore_odf():
    gtab = get_isbi2013_2shell_gtab()

    # load symmetric 724 sphere
    sphere = get_sphere('symmetric724')

    # load icosahedron sphere
    sphere2 = create_unit_sphere(5)
    data, golden_directions = SticksAndBall(gtab, d=0.0015,
                                            S0=100, angles=[(0, 0), (90, 0)],
                                            fractions=[50, 50], snr=None)
    asm = ShoreModel(gtab, radial_order=6,
                     zeta=700, lambdaN=1e-8, lambdaL=1e-8)
    # symmetric724
    asmfit = asm.fit(data)
    odf = asmfit.odf(sphere)
    odf_sh = asmfit.odf_sh()
    odf_from_sh = sh_to_sf(odf_sh, sphere, 6, basis_type=None)
    assert_almost_equal(odf, odf_from_sh, 10)


    directions, _ , _ = peak_directions(odf, sphere, .35, 25)
    assert_equal(len(directions), 2)
    assert_almost_equal(
        angular_similarity(directions, golden_directions), 2, 1)

    # 5 subdivisions
    odf = asmfit.odf(sphere2)
    directions, _ , _ = peak_directions(odf, sphere2, .35, 25)
    assert_equal(len(directions), 2)
    assert_almost_equal(
        angular_similarity(directions, golden_directions), 2, 1)

    sb_dummies = sticks_and_ball_dummies(gtab)
    for sbd in sb_dummies:
        data, golden_directions = sb_dummies[sbd]
        asmfit = asm.fit(data)
        odf = asmfit.odf(sphere2)
        directions, _ , _ = peak_directions(odf, sphere2, .35, 25)
        if len(directions) <= 3:
            assert_equal(len(directions), len(golden_directions))
        if len(directions) > 3:
            assert_equal(gfa(odf) < 0.1, True)
Exemplo n.º 19
0
def test_shore_positive_constrain():
    gtab = get_gtab_taiwan_dsi()
    mevals = np.array(([0.0015, 0.0003, 0.0003],
                       [0.0015, 0.0003, 0.0003]))
    angl = [(0, 0), (60, 0)]
    S, sticks = MultiTensor(gtab, mevals, S0=100.0, angles=angl,
                            fractions=[50, 50], snr=None)

    radial_order = 6
    zeta = 700
    lambdaN = 1e-12
    lambdaL = 1e-12

    asm = ShoreModel(gtab, radial_order=radial_order,
                     zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL,
                     constrain_e0=True, positive_constraint=True, pos_grid=11, pos_radius=20e-03)

    asmfit = asm.fit(S)
    eap = asmfit.pdf_grid(11, 20e-03)
    assert_equal(eap[eap<0].sum(),0)
Exemplo n.º 20
0
def dodata(f_name, data_path):
    dipy_home = pjoin(os.path.expanduser('~'), 'dipy_data')
    folder = pjoin(dipy_home, data_path)
    fraw = pjoin(folder, f_name + '.nii.gz')
    fbval = pjoin(folder, f_name + '.bval')
    fbvec = pjoin(folder, f_name + '.bvec')
    flabels = pjoin(folder, f_name + '.nii-label.nii.gz')

    bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
    gtab = gradient_table(bvals, bvecs)

    img = nib.load(fraw)
    data = img.get_data()
    affine = img.get_affine()

    label_img = nib.load(flabels)
    labels = label_img.get_data()
    lap = through_label_sl.label_position(labels, labelValue=1)
    dataslice = data[40:80, 20:80, lap[2][2] / 2]
    #print lap[2][2]/2

    #get_csd_gfa(f_name,data,gtab,dataslice)

    maskdata, mask = median_otsu(data,
                                 2,
                                 1,
                                 False,
                                 vol_idx=range(10, 50),
                                 dilate=2)  #不去背景
    """ get fa and tensor evecs and ODF"""
    from dipy.reconst.dti import TensorModel, mean_diffusivity
    tenmodel = TensorModel(gtab)
    tenfit = tenmodel.fit(data, mask)

    sphere = get_sphere('symmetric724')

    FA = fractional_anisotropy(tenfit.evals)
    FA[np.isnan(FA)] = 0

    np.save(os.getcwd() + '\zhibiao' + f_name + '_FA.npy', FA)
    fa_img = nib.Nifti1Image(FA.astype(np.float32), affine)
    nib.save(fa_img, os.getcwd() + '\zhibiao' + f_name + '_FA.nii.gz')
    print('Saving "DTI_tensor_fa.nii.gz" sucessful.')
    evecs_img = nib.Nifti1Image(tenfit.evecs.astype(np.float32), affine)
    nib.save(evecs_img,
             os.getcwd() + '\zhibiao' + f_name + '_DTI_tensor_evecs.nii.gz')
    print('Saving "DTI_tensor_evecs.nii.gz" sucessful.')
    MD1 = mean_diffusivity(tenfit.evals)
    nib.save(nib.Nifti1Image(MD1.astype(np.float32), img.get_affine()),
             os.getcwd() + '\zhibiao' + f_name + '_MD.nii.gz')

    #tensor_odfs = tenmodel.fit(data[20:50, 55:85, 38:39]).odf(sphere)
    #from dipy.reconst.odf import gfa
    #dti_gfa=gfa(tensor_odfs)

    wm_mask = (np.logical_or(FA >= 0.4,
                             (np.logical_and(FA >= 0.15, MD >= 0.0011))))

    response = recursive_response(gtab,
                                  data,
                                  mask=wm_mask,
                                  sh_order=8,
                                  peak_thr=0.01,
                                  init_fa=0.08,
                                  init_trace=0.0021,
                                  iter=8,
                                  convergence=0.001,
                                  parallel=False)
    from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
    csd_model = ConstrainedSphericalDeconvModel(gtab, response)

    #csd_fit = csd_model.fit(data)

    from dipy.direction import peaks_from_model

    csd_peaks = peaks_from_model(model=csd_model,
                                 data=data,
                                 sphere=sphere,
                                 relative_peak_threshold=.5,
                                 min_separation_angle=25,
                                 parallel=False)

    GFA = csd_peaks.gfa

    nib.save(GFA, os.getcwd() + '\zhibiao' + f_name + '_MSD.nii.gz')
    print('Saving "GFA.nii.gz" sucessful.')

    from dipy.reconst.shore import ShoreModel
    asm = ShoreModel(gtab)
    print('Calculating...SHORE msd')
    asmfit = asm.fit(data, mask)
    msd = asmfit.msd()
    msd[np.isnan(msd)] = 0

    #print GFA[:,:,slice].T
    print('Saving msd_img.png')
    nib.save(msd, os.getcwd() + '\zhibiao' + f_name + '_GFA.nii.gz')
Exemplo n.º 21
0
radial_order is the radial order of the SHORE basis.

zeta is the scale factor of the SHORE basis.

lambdaN and lambdaN are the radial and angular regularization constants, respectively.

For details regarding these four parameters see (Cheng J. et al, MICCAI workshop 2011) and 
(Merlet S. et al, Medical Image Analysis 2013).
"""

radial_order = 6
zeta = 700
lambdaN=1e-8
lambdaL=1e-8
asm = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)

"""
Fit the SHORE model to the data
"""

asmfit = asm.fit(data_small)

"""
Load an odf reconstruction sphere
"""

sphere = get_sphere('symmetric724')

"""
Compute the ODF  
def dMRI2ODF_DTI(PATH):
    '''
    Input the dMRI data
    return the ODF
    '''
    dMRI_path = PATH + 'data.nii.gz'
    mask_path = PATH + 'nodif_brain_mask.nii.gz'
    dMRI_img = nib.load(dMRI_path)
    dMRI_data = dMRI_img.get_fdata()
    mask_img = nib.load(mask_path)
    mask = mask_img.get_fdata()

    ########## subsample ##########
    # dMRI_data = dMRI_data[45:-48,50:-65,51:-54,...]
    # mask = mask[45:-48,50:-65,51:-54]
    # breakpoint()
    dMRI_data = dMRI_data[:, 87, ...]
    mask = mask[:, 87, ...]

    for cnt in range(10):
        fig = plt.imshow(dMRI_data[:, :, cnt].transpose(1, 0),
                         cmap='Greys',
                         interpolation='nearest')
        plt.axis('off')
        # plt.imshow(dMRI_data[:,15,:,cnt].transpose(1,0),cmap='Greys')
        plt.savefig(str(cnt) + '.png',
                    bbox_inches='tight',
                    dpi=300,
                    transparent=True,
                    pad_inches=0)

    # breakpoint()
    bval = PATH + "bvals"
    bvec = PATH + "bvecs"

    radial_order = 6
    zeta = 700
    lambdaN = 1e-8
    lambdaL = 1e-8

    gtab = gradient_table(bvals=bval, bvecs=bvec)
    asm = ShoreModel(gtab,
                     radial_order=radial_order,
                     zeta=zeta,
                     lambdaN=lambdaN,
                     lambdaL=lambdaL)
    asmfit = asm.fit(dMRI_data, mask=mask)
    sphere = get_sphere('symmetric362')
    dMRI_odf = asmfit.odf(sphere)
    dMRI_odf[dMRI_odf <= 0] = 0

    tenmodel = dti.TensorModel(gtab)
    tenfit = tenmodel.fit(dMRI_data, mask)
    dMRI_dti = tenfit.quadratic_form

    FA = fractional_anisotropy(tenfit.evals)
    FA[np.isnan(FA)] = 0
    FA = np.clip(FA, 0, 1)
    RGB = color_fa(FA, tenfit.evecs)

    evals = tenfit.evals + 1e-20
    evecs = tenfit.evecs
    cfa = RGB + 1e-20
    cfa /= cfa.max()

    evals = np.expand_dims(evals, 2)
    evecs = np.expand_dims(evecs, 2)
    cfa = np.expand_dims(cfa, 2)

    ren = window.Scene()
    sphere = get_sphere('symmetric362')
    ren.add(
        actor.tensor_slicer(evals,
                            evecs,
                            scalar_colors=cfa,
                            sphere=sphere,
                            scale=0.5))
    window.record(ren,
                  n_frames=1,
                  out_path='../data/tensor.png',
                  size=(5000, 5000))

    odf_ = dMRI_odf

    ren = window.Scene()
    sfu = actor.odf_slicer(np.expand_dims(odf_, 2),
                           sphere=sphere,
                           colormap="plasma",
                           scale=0.5)

    ren.add(sfu)
    window.record(ren,
                  n_frames=1,
                  out_path='../data/odfs.png',
                  size=(5000, 5000))

    return None
Exemplo n.º 23
0
print('data.shape (%d, %d)' % b3k_data.shape)

zeta = 100
#scale_val = 0.5
num_vox = 5
odf_stack = np.zeros((num_vox, 1, 1, 724))

for i in range(num_vox):
    radial_order = 6
    lambdaN = 1e-8
    lambdaL = 1e-8
    print('Zeta Value: \n')
    print(zeta)
    asm = ShoreModel(gtab,
                     radial_order=radial_order,
                     zeta=zeta,
                     lambdaN=lambdaN,
                     lambdaL=lambdaL)

    asmfit = asm.fit(one_vox)

    sphere = get_sphere('symmetric724')

    odf = asmfit.odf(sphere)
    odf = np.reshape(odf, [10, 1, 1, 724])

    odf_stack[i, :, :, :] = odf[0, :, :, :]
    print('odf.shape (%d, %d, %d, %d)' % odf.shape)
    zeta = zeta + 200

# Enables/disables interactive visualization
Exemplo n.º 24
0
def test_shore_metrics():
    gtab = get_gtab_taiwan_dsi()
    mevals = np.array(([0.0015, 0.0003, 0.0003],
                       [0.0015, 0.0003, 0.0003]))
    angl = [(0, 0), (60, 0)]
    S, sticks = MultiTensor(gtab, mevals, S0=100.0, angles=angl,
                            fractions=[50, 50], snr=None)

    # test shore_indices
    n = 7
    l = 6
    m = -4
    radial_order, c = shore_order(n, l, m)
    n2, l2, m2 = shore_indices(radial_order, c)
    assert_equal(n, n2)
    assert_equal(l, l2)
    assert_equal(m, m2)

    radial_order = 6
    c = 41
    n, l, m = shore_indices(radial_order, c)
    radial_order2, c2 = shore_order(n, l, m)
    assert_equal(radial_order, radial_order2)
    assert_equal(c, c2)

    # since we are testing without noise we can use higher order and lower lambdas, with respect to the default.
    radial_order = 8
    zeta = 700
    lambdaN = 1e-12
    lambdaL = 1e-12
    asm = ShoreModel(gtab, radial_order=radial_order,
                     zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)
    asmfit = asm.fit(S)
    c_shore = asmfit.shore_coeff

    cmat = shore_matrix(radial_order, zeta, gtab)
    S_reconst = np.dot(cmat, c_shore)

    # test the signal reconstruction
    S = S / S[0]
    nmse_signal = np.sqrt(np.sum((S - S_reconst) ** 2)) / (S.sum())
    assert_almost_equal(nmse_signal, 0.0, 4)

    # test if the analytical integral of the pdf is equal to one
    integral = 0
    for n in range(int((radial_order)/2 +1)):
        integral += c_shore[n] * (np.pi**(-1.5) * zeta **(-1.5) * genlaguerre(n,0.5)(0)) ** 0.5

    assert_almost_equal(integral, 1.0, 10)

    # test if the integral of the pdf calculated on a discrete grid is equal to one
    pdf_discrete = asmfit.pdf_grid(17, 40e-3)
    integral = pdf_discrete.sum()
    assert_almost_equal(integral, 1.0, 1)

    # compare the shore pdf with the ground truth multi_tensor pdf

    sphere = get_sphere('symmetric724')
    v = sphere.vertices
    radius = 10e-3
    pdf_shore = asmfit.pdf(v * radius)
    pdf_mt = multi_tensor_pdf(v * radius, mevals=mevals,
                              angles=angl, fractions= [50, 50])
    nmse_pdf = np.sqrt(np.sum((pdf_mt - pdf_shore) ** 2)) / (pdf_mt.sum())
    assert_almost_equal(nmse_pdf, 0.0, 2)

    # compare the shore rtop with the ground truth multi_tensor rtop
    rtop_shore_signal = asmfit.rtop_signal()
    rtop_shore_pdf = asmfit.rtop_pdf()
    assert_almost_equal(rtop_shore_signal, rtop_shore_pdf, 9)
    rtop_mt = multi_tensor_rtop([.5, .5], mevals=mevals)
    assert_equal(rtop_mt / rtop_shore_signal <1.10 and rtop_mt / rtop_shore_signal > 0.95, True)

    # compare the shore msd with the ground truth multi_tensor msd
    msd_mt = multi_tensor_msd([.5, .5], mevals=mevals)
    msd_shore = asmfit.msd()
    assert_equal(msd_mt / msd_shore < 1.05 and msd_mt / msd_shore > 0.95, True)
Exemplo n.º 25
0
print('FOD Gradient Table Loaded and Ready for use')

fod_data = loadmat(fod_data_path)
fod_actual_data = fod_data['new_q_fod']

print('Output Data all loaded and ready for use ...')

print('Fitting Shore to both models')

radial_order = 6
zeta = 700
lambdaN = 1e-8
lambdaL = 1e-8
asm = ShoreModel(gtab,
                 radial_order=radial_order,
                 zeta=zeta,
                 lambdaN=lambdaN,
                 lambdaL=lambdaL)

asmfit = asm.fit(actual_data)

print('Shore Model Coeffs Generated ...')

print('Transforming object shape to save to a .mat file')

shore_input_matrix = np.zeros((57267, 50))

for i in range(0, 57267):

    temp_shore_coeffs = asmfit.fit_array[i]._shore_coef
    shore_input_matrix[i, :] = temp_shore_coeffs
Exemplo n.º 26
0
print('Gradient Table Loaded and Ready for use')

data = loadmat(data_path)
actual_data = data['ms_data']

print('Data all loaded and ready for use')

print('data.shape (%d, %d)' % actual_data.shape)

radial_order = 6
zeta = 700
lambdaN = 1e-8
lambdaL = 1e-8
asm = ShoreModel(gtab,
                 radial_order=radial_order,
                 zeta=zeta,
                 lambdaN=lambdaN,
                 lambdaL=lambdaL)

asmfit = asm.fit(actual_data)

print('Shore Model Coeffs Generated ...')

print('Transforming object shape to save to a .mat file')

shore_input_matrix = np.zeros((57267, 50))

for i in range(0, 57267):

    temp_shore_coeffs = asmfit.fit_array[i]._shore_coef
    shore_input_matrix[i, :] = temp_shore_coeffs
Exemplo n.º 27
0
    if mask is not None:
        mask = sitk.GetArrayFromImage(mask)
        print(mask.shape)


    # fit selected model
    sh_coeffs = None
    odf = None
    if model_type == '3D-SHORE':
        print('Fitting 3D-SHORE')
        print("radial_order: ", radial_order)
        print("zeta: ", zeta)
        print("lambdaN: ", lambdaN)
        print("lambdaL: ", lambdaL)
        model = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)
        asmfit = model.fit(data)
        odf = asmfit.odf(sphere)
    elif model_type == 'CSA-QBALL':
        print('Fitting CSA-QBALL')
        print("sh_order: ", sh_order)
        print("smooth: ", smooth)
        model = CsaOdfModel(gtab=gtab, sh_order=sh_order, smooth=smooth)
        sh_coeffs = model.fit(data, mask=mask).shm_coeff
    elif model_type == 'SFM':
        print('Fitting SFM')
        print("fa_thr: ", fa_thr)
        response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=fa_thr)
        model = sfm.SparseFascicleModel(gtab, sphere=sphere,
                                        l1_ratio=0.5, alpha=0.001,
                                        response=response[0])
Exemplo n.º 28
0
axial_middle = nifti_img.shape[2] // 2
#plt.figure('Showing the datasets')
#plt.subplots(1, 2, 1).set_axis_off()
plt.imshow(nifti_img[:, :, axial_middle, 30].T, cmap='gray', origin='lower', vmax=1, vmin=0)
plt.show()
#plt.subplot(1, 2, 2).set_axis_off()
plt.imshow(nifti_img[:, :, axial_middle, 10].T, cmap='gray', origin='lower')
plt.savefig('vishabyte_mid_axial_slices.png', bbox_inches='tight')


print('Working on fitting SHORE to the Data \n')
radial_order = 8
zeta = 700
lambdaN = 1e-8
lambdaL = 1e-8
asm = ShoreModel(gtab, radial_order=radial_order,
                 zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)



bval_path_5shell = r'D:\MASI LAB WORK\Solid_Harmonics\concat_bvals.bval'
bvec_path_5shell = r'D:\MASI LAB WORK\Solid_Harmonics\concat_bvecs.bvec'
nifti_path_5shell = r'D:\MASI LAB WORK\Solid_Harmonics\vishabyte_concat.nii.gz'
bvec_path_5shell = os.path.normpath(bvec_path_5shell)
bval_path_5shell = os.path.normpath(bval_path_5shell)
nifti_path_5shell = os.path.normpath(nifti_path_5shell)

nifti_5 = nib.load(nifti_path_5shell)
nifti_img_5shell = nifti_5.get_data()

bvals_5shell,bvecs_5shell = read_bvals_bvecs(bval_path_5shell, bvec_path_5shell)
gtab_5shell = gradient_table(bvals_5shell, bvecs_5shell)
Exemplo n.º 29
0
def prepare_data(csv_file, label_name):

    Names = []
    labels = []
    Visit_ = []

    # csv_file = 'data/ad_data/adrc-subject-list.csv'
    with open(csv_file, 'rb') as f:
        reader = csv.reader(f)
        count = 0

        for row in reader:
            if count == 0:
                # label_idx = row.index(label_name)  # normal should use this, APOE is different
                label_idx1 = 3
                label_idx2 = 4
                count = count + 1
                continue
            else:
                Names.append(row[0])
                labels.append(row[label_idx1] == '4' or row[label_idx2] == '4')
                # labels.append(1*(row[2]=="Male"))
                count = count + 1
    # Labels = np.zeros([len(labels) , 2])
    # for labelid in range(len(labels)):
    #     Labels[ labelid , labels[labelid] ] = 1
    # pdb.set_trace()

    spd_data_folder = "data/ad_data/data/"
    spd_data_name = "/cor_DTI_SPD.nii"
    dMRI_data_name = "/dMRI.nii.gz"

    track_names = [
        "fmajor_PP.avg33_mni_bbr_track_image.nii.gz",
        "fminor_PP.avg33_mni_bbr_track_image.nii.gz",
        "lh.atr_PP.avg33_mni_bbr_track_image.nii.gz",
        "lh.cab_PP.avg33_mni_bbr_track_image.nii.gz",
        "lh.ccg_PP.avg33_mni_bbr_track_image.nii.gz",
        "lh.cst_AS.avg33_mni_bbr_track_image.nii.gz",
        "lh.ilf_AS.avg33_mni_bbr_track_image.nii.gz",
        "lh.slfp_PP.avg33_mni_bbr_track_image.nii.gz",
        "lh.slft_PP.avg33_mni_bbr_track_image.nii.gz",
        "lh.unc_AS.avg33_mni_bbr_track_image.nii.gz",
        "rh.atr_PP.avg33_mni_bbr_track_image.nii.gz",
        "rh.cab_PP.avg33_mni_bbr_track_image.nii.gz",
        "rh.ccg_PP.avg33_mni_bbr_track_image.nii.gz",
        "rh.cst_AS.avg33_mni_bbr_track_image.nii.gz",
        "rh.ilf_AS.avg33_mni_bbr_track_image.nii.gz",
        "rh.slfp_PP.avg33_mni_bbr_track_image.nii.gz",
        "rh.slft_PP.avg33_mni_bbr_track_image.nii.gz",
        "rh.unc_AS.avg33_mni_bbr_track_image.nii.gz",
    ]

    Traces = [[] for _ in range(len(track_names))]
    Traces_ODF = [[] for _ in range(len(track_names))]
    for pid in range(len(Names)):
        name = Names[pid]
        for vi in ["_v2", "_v3", "_v1", "_v4"]:
            spd_path = spd_data_folder + name + vi + spd_data_name
            if os.path.isfile(spd_path):
                break
        if not os.path.isfile(spd_path):
            print(
                "There's something wrong in this dataset, the data is not v1/v2/v3."
            )
            exit()
        Visit_.append(vi)
        spd_img = nib.load(spd_path)
        spd_data = spd_img.get_data()
        mtx_whole = vec2mtx(spd_data)

        dMRI_path = spd_data_folder + name + vi + dMRI_data_name
        dMRI_img = nib.load(dMRI_path)
        dMRI_data = dMRI_img.get_data()

        ############### ODF
        radial_order = 6
        zeta = 700
        lambdaN = 1e-8
        lambdaL = 1e-8
        bval = "./data/ad_data/Bval_vec/dti_bvals.bval"
        bvec = "./data/ad_data/Bval_vec/" + name + vi + "/bvecs_eddy.rotated.bvecs"
        gtab = gtab = gradient_table(bvals=bval, bvecs=bvec)
        asm = ShoreModel(gtab,
                         radial_order=radial_order,
                         zeta=zeta,
                         lambdaN=lambdaN,
                         lambdaL=lambdaL)

        ############### ODF

        for track_id in range(len(track_names)):
            track_sub_name = track_names[track_id]
            # for vi in ["_v2","_v3","_v1","_v4"]:  ########## \tab for the rest 3 lines
            track_path = spd_data_folder + name + vi + "/" + track_sub_name
            # if os.path.isfile(track_path):
            #     break
            if os.path.isfile(track_path):
                Pos = read_fiber(track_path)
                # pdb.set_trace()
                minx = min(Pos[:, 0])
                maxx = max(Pos[:, 0])
                miny = min(Pos[:, 1])
                maxy = max(Pos[:, 1])
                minz = min(Pos[:, 2])
                maxz = max(Pos[:, 2])
                # pdb.set_trace()
                asmfit = asm.fit(dMRI_data[minx:maxx + 1, miny:maxy + 1,
                                           minz:maxz + 1])
                # pdb.set_trace()
                sphere = get_sphere('symmetric724')
                dMRI_odf = asmfit.odf(sphere)
                # pdb.set_trace()
                Traces_ODF[track_id].append(dMRI_odf[(Pos[:, 0] - minx,
                                                      Pos[:, 1] - miny,
                                                      Pos[:, 2] - minz)])
                Traces[track_id].append(mtx_whole[(Pos[:, 0], Pos[:,
                                                                  1], Pos[:,
                                                                          2])])
            else:
                Traces[track_id].append([])
    Traces = np.asarray(Traces)
    # Traces_ODF = None
    Traces_ODF = np.asarray(Traces_ODF)
    Labels = np.asarray(labels)
    # pdb.set_trace()
    return Traces, Traces_ODF, Labels, track_names, Names, Visit_
Exemplo n.º 30
0
"""
img contains a nibabel Nifti1Image object (data) and gtab contains a GradientTable
object (gradient information e.g. b-values). For example, to read the b-values
it is possible to write print(gtab.bvals).

Load the raw diffusion data and the affine.
"""

data = img.get_data()
affine = img.affine
print('data.shape (%d, %d, %d, %d)' % data.shape)
"""
Instantiate the Model.
"""

asm = ShoreModel(gtab)
"""
Let's just use only one slice only from the data.
"""

dataslice = data[30:70, 20:80, data.shape[2] // 2]
"""
Fit the signal with the model and calculate the SHORE coefficients.
"""

asmfit = asm.fit(dataslice)
"""
Calculate the analytical RTOP on the signal
that corresponds to the integral of the signal.
"""
Exemplo n.º 31
0
                                    data=maskdata,
                                    sphere=sphere,
                                    relative_peak_threshold=.5,
                                    min_separation_angle=25,
                                    mask=mask,
                                    return_odf=False,
                                    normalize_peaks=True)

        GFA = csapeaks.gfa
        GFA_img = nib.Nifti1Image(GFA.astype(np.float32), affine)
        print GFA.shape
        nib.save(GFA_img, os.getcwd() + '/zhibiao/' + f_name + '_GFA.nii.gz')
        print('Saving "GFA.nii.gz" sucessful.')

        from dipy.reconst.shore import ShoreModel
        asm = ShoreModel(gtab)
        print('Calculating...SHORE msd')
        asmfit = asm.fit(data, mask)
        msd = asmfit.msd()
        msd[np.isnan(msd)] = 0

        #print GFA[:,:,slice].T
        print('Saving msd_img.png')
        print msd.shape
        msd_img = nib.Nifti1Image(msd.astype(np.float32), affine)
        nib.save(msd_img, os.getcwd() + '/zhibiao/' + f_name + '_MSD.nii.gz')
        """Rtop """
        print('Calculating... rtop_signal')
        rtop_signal = asmfit.rtop_signal()
        rtop_signal[np.isnan(rtop_signal)] = 0
        #print GFA[:,:,slice].T
Exemplo n.º 32
0
def test_shore_metrics():
    gtab = get_gtab_taiwan_dsi()
    mevals = np.array(([0.0015, 0.0003, 0.0003],
                       [0.0015, 0.0003, 0.0003]))
    angl = [(0, 0), (60, 0)]
    S, _ = multi_tensor(gtab, mevals, S0=100.0, angles=angl,
                        fractions=[50, 50], snr=None)

    # test shore_indices
    n = 7
    l = 6
    m = -4
    radial_order, c = shore_order(n, l, m)
    n2, l2, m2 = shore_indices(radial_order, c)
    npt.assert_equal(n, n2)
    npt.assert_equal(l, l2)
    npt.assert_equal(m, m2)

    radial_order = 6
    c = 41
    n, l, m = shore_indices(radial_order, c)
    radial_order2, c2 = shore_order(n, l, m)
    npt.assert_equal(radial_order, radial_order2)
    npt.assert_equal(c, c2)

    npt.assert_raises(ValueError, shore_indices, 6, 100)
    npt.assert_raises(ValueError, shore_order, m, n, l)
    # since we are testing without noise we can use higher order and lower
    # lambdas, with respect to the default.
    radial_order = 8
    zeta = 700
    lambdaN = 1e-12
    lambdaL = 1e-12
    asm = ShoreModel(gtab, radial_order=radial_order,
                     zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL)
    asmfit = asm.fit(S)
    c_shore = asmfit.shore_coeff

    cmat = shore_matrix(radial_order, zeta, gtab)
    S_reconst = np.dot(cmat, c_shore)

    # test the signal reconstruction
    S = S / S[0]
    nmse_signal = np.sqrt(np.sum((S - S_reconst) ** 2)) / (S.sum())
    npt.assert_almost_equal(nmse_signal, 0.0, 4)

    # test if the analytical integral of the pdf is equal to one
    integral = 0
    for n in range(int((radial_order)/2 + 1)):
        integral += c_shore[n] * (np.pi**(-1.5) * zeta ** (-1.5) *
                                  genlaguerre(n, 0.5)(0)) ** 0.5

    npt.assert_almost_equal(integral, 1.0, 10)

    # test if the integral of the pdf calculated on a discrete grid is
    # equal to one
    pdf_discrete = asmfit.pdf_grid(17, 40e-3)
    integral = pdf_discrete.sum()
    npt.assert_almost_equal(integral, 1.0, 1)

    # compare the shore pdf with the ground truth multi_tensor pdf

    sphere = get_sphere('symmetric724')
    v = sphere.vertices
    radius = 10e-3
    pdf_shore = asmfit.pdf(v * radius)
    pdf_mt = multi_tensor_pdf(v * radius, mevals=mevals,
                              angles=angl, fractions=[50, 50])

    nmse_pdf = np.sqrt(np.sum((pdf_mt - pdf_shore) ** 2)) / (pdf_mt.sum())
    npt.assert_almost_equal(nmse_pdf, 0.0, 2)

    # compare the shore rtop with the ground truth multi_tensor rtop
    rtop_shore_signal = asmfit.rtop_signal()
    rtop_shore_pdf = asmfit.rtop_pdf()
    npt.assert_almost_equal(rtop_shore_signal, rtop_shore_pdf, 9)
    rtop_mt = multi_tensor_rtop([.5, .5], mevals=mevals)
    npt.assert_equal(rtop_mt / rtop_shore_signal < 1.10 and
                     rtop_mt / rtop_shore_signal > 0.95, True)

    # compare the shore msd with the ground truth multi_tensor msd
    msd_mt = multi_tensor_msd([.5, .5], mevals=mevals)
    msd_shore = asmfit.msd()
    npt.assert_equal(msd_mt / msd_shore < 1.05 and msd_mt / msd_shore > 0.95,
                     True)
Exemplo n.º 33
0
img contains a nibabel Nifti1Image object (data) and gtab contains a GradientTable
object (gradient information e.g. b-values). For example, to read the b-values
it is possible to write print(gtab.bvals).

Load the raw diffusion data and the affine.
"""

data = img.get_data()
affine = img.affine
print('data.shape (%d, %d, %d, %d)' % data.shape)

"""
Instantiate the Model.
"""

asm = ShoreModel(gtab)

"""
Let's just use only one slice only from the data.
"""

dataslice = data[30:70, 20:80, data.shape[2] // 2]

"""
Fit the signal with the model and calculate the SHORE coefficients.
"""

asmfit = asm.fit(dataslice)

"""
Calculate the analytical rtop on the signal
Exemplo n.º 34
0
plt.clf()

print('Working on fitting SHORE to the Data \n')

zeta = 150

mse_vol_stack = np.zeros((dims[0], dims[1], dims[2], 5))

for i in range(5):

    radial_order = 6
    lambdaN = 1e-8
    lambdaL = 1e-8
    asm = ShoreModel(gtab,
                     radial_order=radial_order,
                     zeta=zeta,
                     lambdaN=lambdaN,
                     lambdaL=lambdaL)

    asmfit = asm.fit(nifti_img, mask)

    print('Shore Model Coeffs Generated ... \n')

    print('Reconstructing Signal \n')
    signal_recon = asmfit.fitted_signal()

    mse_volume = np.zeros((dims[0], dims[1], dims[2]))

    for x in range(dims[0]):
        for y in range(dims[1]):
            for z in range(dims[2]):
Exemplo n.º 35
0
    if mask is not None:
        mask = sitk.GetArrayFromImage(mask)
        print(mask.shape)

    # fit selected model
    sh_coeffs = None
    odf = None
    if model_type == '3D-SHORE':
        print('Fitting 3D-SHORE')
        print("radial_order: ", radial_order)
        print("zeta: ", zeta)
        print("lambdaN: ", lambdaN)
        print("lambdaL: ", lambdaL)
        model = ShoreModel(gtab,
                           radial_order=radial_order,
                           zeta=zeta,
                           lambdaN=lambdaN,
                           lambdaL=lambdaL)
        asmfit = model.fit(data)
        odf = asmfit.odf(sphere)
    elif model_type == 'CSA-QBALL':
        print('Fitting CSA-QBALL')
        print("sh_order: ", sh_order)
        print("smooth: ", smooth)
        model = CsaOdfModel(gtab=gtab, sh_order=sh_order, smooth=smooth)
        sh_coeffs = model.fit(data, mask=mask).shm_coeff
    elif model_type == 'SFM':
        print('Fitting SFM')
        print("fa_thr: ", fa_thr)
        response, ratio = auto_response(gtab,
                                        data,
Exemplo n.º 36
0
# load dmri data
print("Loading data and mask.")
data = nib.load(data_path).get_data()
print("Data shape: ", data.shape)

# load mask
mask = nib.load(mask_path).get_data()
print("Mask shape: ", mask.shape)

st = time.time()
radial_border = 4

print(
    "Started fitting SHORE model with radial_border={}".format(radial_border))
asm = ShoreModel(gtab, radial_order=radial_border)
asmfit = asm.fit(data, mask)
shore_coeff = asmfit.shore_coeff
print("SHORE coefficients shape: ", shore_coeff.shape)

# replace nan with 0
print("Replacing with nan with 0. This happens because of inaccurate mask.")
shore_coeff = np.nan_to_num(shore_coeff, 0)

print("Fitting time: {:.5f}".format(time.time() - st))

save_path = join(
    exp_dir, subj_id,
    'shore_features/shore_coefficients_radial_border_{}.npz'.format(
        radial_border))
np.savez(save_path, data=shore_coeff)
Exemplo n.º 37
0
zeta is the scale factor of the SHORE basis.

lambdaN and lambdaL are the radial and angular regularization constants, 
respectively.

For details regarding these four parameters see [Cheng2011]_ and [Merlet2013]_.
"""

radial_order = 6
zeta = 700
lambdaN = 1e-8
lambdaL = 1e-8
asm = ShoreModel(gtab,
                 radial_order=radial_order,
                 zeta=zeta,
                 lambdaN=lambdaN,
                 lambdaL=lambdaL)
"""
Fit the SHORE model to the data
"""

asmfit = asm.fit(data_small)
"""
Load an odf reconstruction sphere
"""

sphere = get_sphere('symmetric724')
"""
Compute the ODFs
"""
                         sphere=sphere,
                         relative_peak_threshold=.5,
                         min_separation_angle=25,
                         mask=mask,
                         return_odf=False,
                         normalize_peaks=True)
 
 GFA = csapeaks.gfa
 GFA_img = nib.Nifti1Image(GFA.astype(np.float32), affine)
 print GFA.shape
 nib.save(GFA_img, os.getcwd()+'/zhibiao/'+f_name+'_GFA.nii.gz')
 print('Saving "GFA.nii.gz" sucessful.')
 
 
 from dipy.reconst.shore import ShoreModel
 asm = ShoreModel(gtab)
 print('Calculating...SHORE msd')
 asmfit = asm.fit(data,mask)
 msd = asmfit.msd()
 msd[np.isnan(msd)] = 0
 
 #print GFA[:,:,slice].T
 print('Saving msd_img.png')
 print msd.shape
 msd_img = nib.Nifti1Image(msd.astype(np.float32), affine)
 nib.save(msd_img, os.getcwd()+'/zhibiao/'+f_name+'_MSD.nii.gz')
 
 """Rtop """
 print('Calculating... rtop_signal')
 rtop_signal = asmfit.rtop_signal()
 rtop_signal[np.isnan(rtop_signal)] = 0
Exemplo n.º 39
0
def main():
    start = time.time()

    with open('config.json') as config_json:
        config = json.load(config_json)

    # Load the data
    dmri_image = nib.load(config['data_file'])
    dmri = dmri_image.get_data()
    affine = dmri_image.affine
    #aparc_im = nib.load(config['freesurfer'])
    aparc_im = nib.load('volume.nii.gz')
    aparc = aparc_im.get_data()
    end = time.time()
    print('Loaded Files: ' + str((end - start)))
    print(dmri.shape)
    print(aparc.shape)

    # Create the white matter and callosal masks
    start = time.time()
    wm_regions = [
        2, 41, 16, 17, 28, 60, 51, 53, 12, 52, 12, 52, 13, 18, 54, 50, 11, 251,
        252, 253, 254, 255, 10, 49, 46, 7
    ]

    wm_mask = np.zeros(aparc.shape)
    for l in wm_regions:
        wm_mask[aparc == l] = 1
    #np.save('wm_mask',wm_mask)
    #p = os.getcwd()+'wm.json'
    #json.dump(wm_mask, codecs.open(p, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4)
    #with open('wm_mask.txt', 'wb') as wm:
    #np.savetxt('wm.txt', wm_mask, fmt='%5s')
    #print(wm_mask)
    # Create the gradient table from the bvals and bvecs

    bvals, bvecs = read_bvals_bvecs(config['data_bval'], config['data_bvec'])

    gtab = gradient_table(bvals, bvecs, b0_threshold=100)
    end = time.time()
    print('Created Gradient Table: ' + str((end - start)))

    ##The probabilistic model##
    """
    # Use the Constant Solid Angle (CSA) to find the Orientation Dist. Function
    # Helps orient the wm tracts
    start = time.time()
    csa_model = CsaOdfModel(gtab, sh_order=6)
    csa_peaks = peaks_from_model(csa_model, dmri, default_sphere,
                                 relative_peak_threshold=.8,
                                 min_separation_angle=45,
                                 mask=wm_mask)
    print('Creating CSA Model: ' + str(time.time() - start))
    """
    # Use the SHORE model to find Orientation Dist. Function
    start = time.time()
    shore_model = ShoreModel(gtab)
    shore_peaks = peaks_from_model(shore_model,
                                   dmri,
                                   default_sphere,
                                   relative_peak_threshold=.8,
                                   min_separation_angle=45,
                                   mask=wm_mask)
    print('Creating Shore Model: ' + str(time.time() - start))

    # Begins the seed in the wm tracts
    seeds = utils.seeds_from_mask(wm_mask, density=[1, 1, 1], affine=affine)
    print('Created White Matter seeds: ' + str(time.time() - start))

    # Create a CSD model to measure Fiber Orientation Dist
    print('Begin the probabilistic model')

    response, ratio = auto_response(gtab, dmri, roi_radius=10, fa_thr=0.7)
    csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
    csd_fit = csd_model.fit(data=dmri, mask=wm_mask)
    print('Created the CSD model: ' + str(time.time() - start))

    # Set the Direction Getter to randomly choose directions

    prob_dg = ProbabilisticDirectionGetter.from_shcoeff(csd_fit.shm_coeff,
                                                        max_angle=30.,
                                                        sphere=default_sphere)
    print('Created the Direction Getter: ' + str(time.time() - start))

    # Restrict the white matter tracking
    classifier = ThresholdTissueClassifier(shore_peaks.gfa, .25)

    print('Created the Tissue Classifier: ' + str(time.time() - start))

    # Create the probabilistic model
    streamlines = LocalTracking(prob_dg,
                                tissue_classifier=classifier,
                                seeds=seeds,
                                step_size=.5,
                                max_cross=1,
                                affine=affine)
    print('Created the probabilistic model: ' + str(time.time() - start))

    # Compute streamlines and store as a list.
    streamlines = list(streamlines)
    print('Computed streamlines: ' + str(time.time() - start))

    #from dipy.tracking.streamline import transform_streamlines
    #streamlines = transform_streamlines(streamlines, np.linalg.inv(affine))

    # Create a tractogram from the streamlines and save it
    tractogram = Tractogram(streamlines, affine_to_rasmm=affine)
    save(tractogram, 'track.tck')
    end = time.time()
    print("Created the tck file: " + str((end - start)))
def dodata(f_name,data_path):
    dipy_home = pjoin(os.path.expanduser('~'), 'dipy_data')
    folder = pjoin(dipy_home, data_path)
    fraw = pjoin(folder, f_name+'.nii.gz')
    fbval = pjoin(folder, f_name+'.bval')
    fbvec = pjoin(folder, f_name+'.bvec')
    flabels = pjoin(folder, f_name+'.nii-label.nii.gz')
    
    bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
    gtab = gradient_table(bvals, bvecs)
    
    img = nib.load(fraw)
    data = img.get_data()
    affine = img.get_affine()
    
    label_img = nib.load(flabels)
    labels=label_img.get_data()
    lap=through_label_sl.label_position(labels, labelValue=1)    
    dataslice = data[40:80, 20:80, lap[2][2] / 2]
    #print lap[2][2]/2
    
    #get_csd_gfa(f_name,data,gtab,dataslice)
    
    maskdata, mask = median_otsu(data, 2, 1, False, vol_idx=range(10, 50), dilate=2) #不去背景
    
    """ get fa and tensor evecs and ODF"""
    from dipy.reconst.dti import TensorModel,mean_diffusivity
    tenmodel = TensorModel(gtab)
    tenfit = tenmodel.fit(data, mask)
    
    sphere = get_sphere('symmetric724')
    
    FA = fractional_anisotropy(tenfit.evals)
    FA[np.isnan(FA)] = 0
      
    np.save(os.getcwd()+'\zhibiao'+f_name+'_FA.npy',FA)
    fa_img = nib.Nifti1Image(FA.astype(np.float32), affine)
    nib.save(fa_img,os.getcwd()+'\zhibiao'+f_name+'_FA.nii.gz')
    print('Saving "DTI_tensor_fa.nii.gz" sucessful.')
    evecs_img = nib.Nifti1Image(tenfit.evecs.astype(np.float32), affine)
    nib.save(evecs_img, os.getcwd()+'\zhibiao'+f_name+'_DTI_tensor_evecs.nii.gz')
    print('Saving "DTI_tensor_evecs.nii.gz" sucessful.')
    MD1 = mean_diffusivity(tenfit.evals)
    nib.save(nib.Nifti1Image(MD1.astype(np.float32), img.get_affine()), os.getcwd()+'\zhibiao'+f_name+'_MD.nii.gz')
    
    
    #tensor_odfs = tenmodel.fit(data[20:50, 55:85, 38:39]).odf(sphere)
    #from dipy.reconst.odf import gfa
    #dti_gfa=gfa(tensor_odfs)
    
    wm_mask = (np.logical_or(FA >= 0.4, (np.logical_and(FA >= 0.15, MD >= 0.0011))))

    response = recursive_response(gtab, data, mask=wm_mask, sh_order=8,
                                  peak_thr=0.01, init_fa=0.08,
                                  init_trace=0.0021, iter=8, convergence=0.001,
                                  parallel=False)
    from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
    csd_model = ConstrainedSphericalDeconvModel(gtab, response)
    
    #csd_fit = csd_model.fit(data)

    from dipy.direction import peaks_from_model

    csd_peaks = peaks_from_model(model=csd_model,
                                 data=data,
                                 sphere=sphere,
                                 relative_peak_threshold=.5,
                                 min_separation_angle=25,
                                 parallel=False)
    
    GFA = csd_peaks.gfa
    
    nib.save(GFA, os.getcwd()+'\zhibiao'+f_name+'_MSD.nii.gz')
    print('Saving "GFA.nii.gz" sucessful.')
    
    from dipy.reconst.shore import ShoreModel
    asm = ShoreModel(gtab)
    print('Calculating...SHORE msd')
    asmfit = asm.fit(data,mask)
    msd = asmfit.msd()
    msd[np.isnan(msd)] = 0
    
    #print GFA[:,:,slice].T
    print('Saving msd_img.png')
    nib.save(msd, os.getcwd()+'\zhibiao'+f_name+'_GFA.nii.gz')