Example #1
0
def test_positivity_constraint(radial_order=6):
    gtab = get_gtab_taiwan_dsi()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S, _ = generate_signal_crossing(gtab, l1, l2, l3, angle2=60)
    S_noise = add_noise(S, snr=20, S0=100.)

    gridsize = 20
    max_radius = 15e-3  # 20 microns maximum radius
    r_grad = mapmri.create_rspace(gridsize, max_radius)

    # The positivity constraint does not make the pdf completely positive
    # but greatly decreases the amount of negativity in the constrained points.
    # We test if the amount of negative pdf has decreased more than 90%

    mapmod_no_constraint = MapmriModel(gtab,
                                       radial_order=radial_order,
                                       laplacian_regularization=False,
                                       positivity_constraint=False)
    mapfit_no_constraint = mapmod_no_constraint.fit(S_noise)
    pdf = mapfit_no_constraint.pdf(r_grad)
    pdf_negative_no_constraint = pdf[pdf < 0].sum()

    mapmod_constraint = MapmriModel(gtab,
                                    radial_order=radial_order,
                                    laplacian_regularization=False,
                                    positivity_constraint=True,
                                    pos_grid=gridsize,
                                    pos_radius='adaptive')
    mapfit_constraint = mapmod_constraint.fit(S_noise)
    pdf = mapfit_constraint.pdf(r_grad)
    pdf_negative_constraint = pdf[pdf < 0].sum()

    assert_equal((pdf_negative_constraint / pdf_negative_no_constraint) < 0.1,
                 True)

    # the same for isotropic scaling
    mapmod_no_constraint = MapmriModel(gtab,
                                       radial_order=radial_order,
                                       laplacian_regularization=False,
                                       positivity_constraint=False,
                                       anisotropic_scaling=False)
    mapfit_no_constraint = mapmod_no_constraint.fit(S_noise)
    pdf = mapfit_no_constraint.pdf(r_grad)
    pdf_negative_no_constraint = pdf[pdf < 0].sum()

    mapmod_constraint = MapmriModel(gtab,
                                    radial_order=radial_order,
                                    laplacian_regularization=False,
                                    positivity_constraint=True,
                                    anisotropic_scaling=False,
                                    pos_grid=gridsize,
                                    pos_radius='adaptive')
    mapfit_constraint = mapmod_constraint.fit(S_noise)
    pdf = mapfit_constraint.pdf(r_grad)
    pdf_negative_constraint = pdf[pdf < 0].sum()

    assert_equal((pdf_negative_constraint / pdf_negative_no_constraint) < 0.1,
                 True)
Example #2
0
def test_positivity_constraint(radial_order=6):
    gtab = get_gtab_taiwan_dsi()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S, _ = generate_signal_crossing(gtab, l1, l2, l3, angle2=60)
    S_noise = add_noise(S, snr=20, S0=100.)

    gridsize = 20
    max_radius = 15e-3  # 20 microns maximum radius
    r_grad = mapmri.create_rspace(gridsize, max_radius)

    # the posivitivity constraint does not make the pdf completely positive
    # but greatly decreases the amount of negativity in the constrained points.
    # we test if the amount of negative pdf has decreased more than 90%

    mapmod_no_constraint = MapmriModel(gtab, radial_order=radial_order,
                                       laplacian_regularization=False,
                                       positivity_constraint=False)
    mapfit_no_constraint = mapmod_no_constraint.fit(S_noise)
    pdf = mapfit_no_constraint.pdf(r_grad)
    pdf_negative_no_constraint = pdf[pdf < 0].sum()

    mapmod_constraint = MapmriModel(gtab, radial_order=radial_order,
                                    laplacian_regularization=False,
                                    positivity_constraint=True,
                                    pos_grid=gridsize,
                                    pos_radius='adaptive')
    mapfit_constraint = mapmod_constraint.fit(S_noise)
    pdf = mapfit_constraint.pdf(r_grad)
    pdf_negative_constraint = pdf[pdf < 0].sum()

    assert_equal((pdf_negative_constraint / pdf_negative_no_constraint) < 0.1,
                 True)

    # the same for isotropic scaling
    mapmod_no_constraint = MapmriModel(gtab, radial_order=radial_order,
                                       laplacian_regularization=False,
                                       positivity_constraint=False,
                                       anisotropic_scaling=False)
    mapfit_no_constraint = mapmod_no_constraint.fit(S_noise)
    pdf = mapfit_no_constraint.pdf(r_grad)
    pdf_negative_no_constraint = pdf[pdf < 0].sum()

    mapmod_constraint = MapmriModel(gtab, radial_order=radial_order,
                                    laplacian_regularization=False,
                                    positivity_constraint=True,
                                    anisotropic_scaling=False,
                                    pos_grid=gridsize,
                                    pos_radius='adaptive')
    mapfit_constraint = mapmod_constraint.fit(S_noise)
    pdf = mapfit_constraint.pdf(r_grad)
    pdf_negative_constraint = pdf[pdf < 0].sum()

    assert_equal((pdf_negative_constraint / pdf_negative_no_constraint) < 0.1,
                 True)
Example #3
0
def add_noise(vol, snr=1.0, S0=None, noise_type='rician'):
    """ Add noise of specified distribution to a 4D array.

    Parameters
    -----------
    vol : array, shape (X,Y,Z,W)
        Diffusion measurements in `W` directions at each ``(X, Y, Z)`` voxel
        position.
    snr : float, optional
        The desired signal-to-noise ratio.  (See notes below.)
    S0 : float, optional
        Reference signal for specifying `snr` (defaults to 1).
    noise_type : string, optional
        The distribution of noise added. Can be either 'gaussian' for Gaussian
        distributed noise, 'rician' for Rice-distributed noise (default) or
        'rayleigh' for a Rayleigh distribution.

    Returns
    --------
    vol : array, same shape as vol
        Volume with added noise.

    Notes
    -----
    SNR is defined here, following [1]_, as ``S0 / sigma``, where ``sigma`` is
    the standard deviation of the two Gaussian distributions forming the real
    and imaginary components of the Rician noise distribution (see [2]_).

    References
    ----------
    .. [1] Descoteaux, Angelino, Fitzgibbons and Deriche (2007) Regularized,
           fast and robust q-ball imaging. MRM, 58: 497-510
    .. [2] Gudbjartson and Patz (2008). The Rician distribution of noisy MRI
           data. MRM 34: 910-914.

    Examples
    --------
    >>> signal = np.arange(800).reshape(2, 2, 2, 100)
    >>> signal_w_noise = add_noise(signal, snr=10, noise_type='rician')

    """
    orig_shape = vol.shape
    vol_flat = np.reshape(vol.copy(), (-1, vol.shape[-1]))

    if S0 is None:
        S0 = np.max(vol)

    for vox_idx, signal in enumerate(vol_flat):
        vol_flat[vox_idx] = vox.add_noise(signal,
                                          snr=snr,
                                          S0=S0,
                                          noise_type=noise_type)

    return np.reshape(vol_flat, orig_shape)
Example #4
0
def test_l1_CV(radial_order=4, time_order=2):
    gtab_4d = generate_gtab4D()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S = generate_signal_crossing(gtab_4d, l1, l2, l3)
    S_noise = add_noise(S, S0=1., snr=10)
    qtdmri_mod_l1_cv = qtdmri.QtdmriModel(
        gtab_4d, radial_order=radial_order, time_order=time_order,
        l1_regularization=True, l1_weighting="CV"
    )
    qtdmri_fit_noise = qtdmri_mod_l1_cv.fit(S_noise)
    assert_(qtdmri_fit_noise.alpha >= 0)
Example #5
0
def test_l1_CV(radial_order=4, time_order=2):
    gtab_4d = generate_gtab4D()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S = generate_signal_crossing(gtab_4d, l1, l2, l3)
    S_noise = add_noise(S, S0=1., snr=10)
    qtdmri_mod_l1_cv = qtdmri.QtdmriModel(
        gtab_4d, radial_order=radial_order, time_order=time_order,
        l1_regularization=True, l1_weighting="CV"
    )
    qtdmri_fit_noise = qtdmri_mod_l1_cv.fit(S_noise)
    assert_(qtdmri_fit_noise.alpha >= 0)
Example #6
0
def test_snr():
    np.random.seed(1978)

    s = single_tensor(gtab)

    # For reasonably large SNR, var(signal) ~= sigma**2, where sigma = 1/SNR
    for snr in [5, 10, 20]:
        sigma = 1.0 / snr
        for j in range(1000):
            s_noise = add_noise(s, snr, 1, noise_type='rician')

        assert_array_almost_equal(np.var(s_noise - s), sigma**2, decimal=2)
Example #7
0
def test_snr():
    np.random.seed(1978)

    s = single_tensor(gtab)

    # For reasonably large SNR, var(signal) ~= sigma**2, where sigma = 1/SNR
    for snr in [5, 10, 20]:
        sigma = 1.0 / snr
        for j in range(1000):
            s_noise = add_noise(s, snr, 1, noise_type='rician')

        assert_array_almost_equal(np.var(s_noise - s), sigma**2, decimal=2)
Example #8
0
def add_noise(vol, snr=1.0, S0=None, noise_type='rician'):
    """ Add noise of specified distribution to a 4D array.

    Parameters
    -----------
    vol : array, shape (X,Y,Z,W)
        Diffusion measurements in `W` directions at each ``(X, Y, Z)`` voxel
        position.
    snr : float, optional
        The desired signal-to-noise ratio.  (See notes below.)
    S0 : float, optional
        Reference signal for specifying `snr` (defaults to 1).
    noise_type : string, optional
        The distribution of noise added. Can be either 'gaussian' for Gaussian
        distributed noise, 'rician' for Rice-distributed noise (default) or
        'rayleigh' for a Rayleigh distribution.

    Returns
    --------
    vol : array, same shape as vol
        Volume with added noise.

    Notes
    -----
    SNR is defined here, following [1]_, as ``S0 / sigma``, where ``sigma`` is
    the standard deviation of the two Gaussian distributions forming the real
    and imaginary components of the Rician noise distribution (see [2]_).

    References
    ----------
    .. [1] Descoteaux, Angelino, Fitzgibbons and Deriche (2007) Regularized,
           fast and robust q-ball imaging. MRM, 58: 497-510
    .. [2] Gudbjartson and Patz (2008). The Rician distribution of noisy MRI
           data. MRM 34: 910-914.

    Examples
    --------
    >>> signal = np.arange(800).reshape(2, 2, 2, 100)
    >>> signal_w_noise = add_noise(signal, snr=10, noise_type='rician')

    """
    orig_shape = vol.shape
    vol_flat = np.reshape(vol.copy(), (-1, vol.shape[-1]))

    if S0 is None:
        S0 = np.max(vol)

    for vox_idx, signal in enumerate(vol_flat):
        vol_flat[vox_idx] = vox.add_noise(signal, snr=snr, S0=S0,
                                          noise_type=noise_type)

    return np.reshape(vol_flat, orig_shape)
Example #9
0
def get_test_data():
    gtab = get_3shell_gtab()
    evals_list = [np.array([1.7E-3, 0.4E-3, 0.4E-3]),
                  np.array([6.0E-4, 4.0E-4, 4.0E-4]),
                  np.array([3.0E-3, 3.0E-3, 3.0E-3])]
    s0 = [0.8, 1, 4]
    signals = [single_tensor(gtab, x[0], x[1]) for x in zip(s0, evals_list)]
    tissues = [0, 0, 2, 0, 1, 0, 0, 1, 2]  # wm=0, gm=1, csf=2
    data = [add_noise(signals[tissue], 80, s0[0]) for tissue in tissues]
    data = np.asarray(data).reshape((3, 3, 1, len(signals[0])))
    tissues = np.asarray(tissues).reshape((3, 3, 1))
    masks = [np.where(tissues == x, 1, 0) for x in range(3)]
    responses = [np.concatenate((x[0], [x[1]])) for x in zip(evals_list, s0)]
    return gtab, data, masks, responses
Example #10
0
def test_laplacian_GCV_higher_weight_with_noise(radial_order=4, time_order=2):
    gtab_4d = generate_gtab4D()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S = generate_signal_crossing(gtab_4d, l1, l2, l3)
    S_noise = add_noise(S, S0=1., snr=10)

    qtdmri_mod_laplacian_GCV = qtdmri.QtdmriModel(
        gtab_4d, radial_order=radial_order, time_order=time_order,
        laplacian_regularization=True, laplacian_weighting="GCV"
    )

    qtdmri_fit_no_noise = qtdmri_mod_laplacian_GCV.fit(S)
    qtdmri_fit_noise = qtdmri_mod_laplacian_GCV.fit(S_noise)

    assert_(qtdmri_fit_noise.lopt > qtdmri_fit_no_noise.lopt)
Example #11
0
def test_laplacian_GCV_higher_weight_with_noise(radial_order=4, time_order=2):
    gtab_4d = generate_gtab4D()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S = generate_signal_crossing(gtab_4d, l1, l2, l3)
    S_noise = add_noise(S, S0=1., snr=10)

    qtdmri_mod_laplacian_GCV = qtdmri.QtdmriModel(
        gtab_4d, radial_order=radial_order, time_order=time_order,
        laplacian_regularization=True, laplacian_weighting="GCV"
    )

    qtdmri_fit_no_noise = qtdmri_mod_laplacian_GCV.fit(S)
    qtdmri_fit_noise = qtdmri_mod_laplacian_GCV.fit(S_noise)

    assert_(qtdmri_fit_noise.lopt > qtdmri_fit_no_noise.lopt)
Example #12
0
import numpy as np
from dipy.data import fetch_stanford_hardi, read_stanford_hardi
from dipy.sims.voxel import add_noise

# Read data
fetch_stanford_hardi()
img, gtab = read_stanford_hardi()
data = img.get_data()

# Add Rician noise
from dipy.segment.mask import median_otsu
b0_slice = data[:, :, :, 1]
b0_mask, mask = median_otsu(b0_slice)
np.random.seed(1)
data_noisy = add_noise(data, 10.0, np.mean(b0_slice[mask]), noise_type='rician')

# Select a small part of it.
padding = 3  # Include a larger region to avoid boundary effects
data_small = data[25-padding:40+padding, 65-padding:80+padding, 35:42]
data_noisy_small = data_noisy[25-padding:40+padding, 65-padding:80+padding, 35:42]

"""
Enables/disables interactive visualization
"""

interactive = False

"""
Fit an initial model to the data, in this case Constrained Spherical
Deconvolution is used.
Example #13
0
def test_laplacian_regularization(radial_order=6):
    gtab = get_gtab_taiwan_dsi()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S, _ = generate_signal_crossing(gtab, l1, l2, l3, angle2=60)
    S_noise = add_noise(S, snr=20, S0=100.)

    weight_array = np.linspace(0, .3, 301)
    mapmod_unreg = MapmriModel(gtab,
                               radial_order=radial_order,
                               laplacian_regularization=False,
                               laplacian_weighting=weight_array)
    mapmod_laplacian_array = MapmriModel(gtab,
                                         radial_order=radial_order,
                                         laplacian_regularization=True,
                                         laplacian_weighting=weight_array)
    mapmod_laplacian_gcv = MapmriModel(gtab,
                                       radial_order=radial_order,
                                       laplacian_regularization=True,
                                       laplacian_weighting="GCV")

    # test the Generalized Cross Validation
    # test if GCV gives very low if there is no noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S)
    assert_equal(mapfit_laplacian_array.lopt < 0.01, True)

    # test if GCV gives higher values if there is noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S_noise)
    lopt_array = mapfit_laplacian_array.lopt
    assert_equal(lopt_array > 0.01, True)

    # test if continuous GCV gives the same the one based on an array
    mapfit_laplacian_gcv = mapmod_laplacian_gcv.fit(S_noise)
    lopt_gcv = mapfit_laplacian_gcv.lopt
    assert_almost_equal(lopt_array, lopt_gcv, 2)

    # test if laplacian reduced the norm of the laplacian in the reconstruction
    mu = mapfit_laplacian_gcv.mu
    laplacian_matrix = mapmri.mapmri_laplacian_reg_matrix(
        mapmod_laplacian_gcv.ind_mat, mu, mapmod_laplacian_gcv.S_mat,
        mapmod_laplacian_gcv.T_mat, mapmod_laplacian_gcv.U_mat)

    coef_unreg = mapmod_unreg.fit(S_noise)._mapmri_coef
    coef_laplacian = mapfit_laplacian_gcv._mapmri_coef

    laplacian_norm_unreg = np.dot(coef_unreg,
                                  np.dot(coef_unreg, laplacian_matrix))
    laplacian_norm_laplacian = np.dot(coef_laplacian,
                                      np.dot(coef_laplacian, laplacian_matrix))

    assert_equal(laplacian_norm_laplacian < laplacian_norm_unreg, True)

    # the same for isotropic scaling
    mapmod_unreg = MapmriModel(gtab,
                               radial_order=radial_order,
                               laplacian_regularization=False,
                               laplacian_weighting=weight_array,
                               anisotropic_scaling=False)
    mapmod_laplacian_array = MapmriModel(gtab,
                                         radial_order=radial_order,
                                         laplacian_regularization=True,
                                         laplacian_weighting=weight_array,
                                         anisotropic_scaling=False)
    mapmod_laplacian_gcv = MapmriModel(gtab,
                                       radial_order=radial_order,
                                       laplacian_regularization=True,
                                       laplacian_weighting="GCV",
                                       anisotropic_scaling=False)

    # test the Generalized Cross Validation
    # test if GCV gives zero if there is no noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S)
    assert_equal(mapfit_laplacian_array.lopt < 0.01, True)

    # test if GCV gives higher values if there is noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S_noise)
    lopt_array = mapfit_laplacian_array.lopt
    assert_equal(lopt_array > 0.01, True)

    # test if continuous GCV gives the same the one based on an array
    mapfit_laplacian_gcv = mapmod_laplacian_gcv.fit(S_noise)
    lopt_gcv = mapfit_laplacian_gcv.lopt
    assert_almost_equal(lopt_array, lopt_gcv, 2)

    # test if laplacian reduced the norm of the laplacian in the reconstruction
    mu = mapfit_laplacian_gcv.mu
    laplacian_matrix = mapmri.mapmri_isotropic_laplacian_reg_matrix(
        radial_order, mu[0])

    coef_unreg = mapmod_unreg.fit(S_noise)._mapmri_coef
    coef_laplacian = mapfit_laplacian_gcv._mapmri_coef

    laplacian_norm_unreg = np.dot(coef_unreg,
                                  np.dot(coef_unreg, laplacian_matrix))
    laplacian_norm_laplacian = np.dot(coef_laplacian,
                                      np.dot(coef_laplacian, laplacian_matrix))

    assert_equal(laplacian_norm_laplacian < laplacian_norm_unreg, True)
Example #14
0
    def classify(self, image, nclasses, beta, tolerance=None, max_iter=None):
        r"""
        This method uses the Maximum a posteriori - Markov Random Field
        approach for segmentation by using the Iterative Conditional Modes and
        Expectation Maximization to estimate the parameters.

        Parameters
        ----------
        image : ndarray,
                3D structural image.
        nclasses : int,
                number of desired classes.
        beta : float,
                smoothing parameter, the higher this number the smoother the
                output will be.
        tolerance: float,
                value that defines the percentage of change tolerated to
                prevent the ICM loop to stop. Default is 1e-05.
        max_iter : float,
                fixed number of desired iterations. Default is 100.
                If the user only specifies this parameter, the tolerance
                value will not be considered. If none of these two
                parameters

        Returns
        -------
        initial_segmentation : ndarray,
                3D segmented image with all tissue types
                specified in nclasses.
        final_segmentation : ndarray,
                3D final refined segmentation containing all
                tissue types.
        PVE : ndarray,
                3D probability map of each tissue type.
        """

        nclasses = nclasses + 1  # One extra class for the background
        energy_sum = [1e-05]

        com = ConstantObservationModel()
        icm = IteratedConditionalModes()

        if image.max() > 1:
            image = np.interp(image, [0, image.max()], [0.0, 1.0])

        mu, sigma = com.initialize_param_uniform(image, nclasses)
        p = np.argsort(mu)
        mu = mu[p]
        sigma = sigma[p]
        sigmasq = sigma**2

        neglogl = com.negloglikelihood(image, mu, sigmasq, nclasses)
        seg_init = icm.initialize_maximum_likelihood(neglogl)

        mu, sigma = com.seg_stats(image, seg_init, nclasses)
        sigmasq = sigma**2

        zero = np.zeros_like(image) + 0.001
        zero_noise = add_noise(zero, 10000, 1, noise_type='gaussian')
        image_gauss = np.where(image == 0, zero_noise, image)

        final_segmentation = np.empty_like(image)
        initial_segmentation = seg_init.copy()

        if max_iter is not None and tolerance is None:

            for i in range(max_iter):

                if self.verbose:
                    print('>> Iteration: ' + str(i))

                PLN = icm.prob_neighborhood(seg_init, beta, nclasses)
                PVE = com.prob_image(image_gauss, nclasses, mu, sigmasq, PLN)

                mu_upd, sigmasq_upd = com.update_param(image_gauss, PVE, mu,
                                                       nclasses)
                ind = np.argsort(mu_upd)
                mu_upd = mu_upd[ind]
                sigmasq_upd = sigmasq_upd[ind]

                negll = com.negloglikelihood(image_gauss, mu_upd, sigmasq_upd,
                                             nclasses)
                final_segmentation, energy = icm.icm_ising(
                    negll, beta, seg_init)

                if self.save_history:
                    self.segmentations.append(final_segmentation)
                    self.pves.append(PVE)
                    self.energies.append(energy)
                    self.energies_sum.append(energy[energy > -np.inf].sum())

                seg_init = final_segmentation.copy()
                mu = mu_upd.copy()
                sigmasq = sigmasq_upd.copy()

        else:
            max_iter = 100

            if tolerance is None:
                tolerance = 1e-05
            for i in range(max_iter):

                if self.verbose:
                    print('>> Iteration: ' + str(i))

                PLN = icm.prob_neighborhood(seg_init, beta, nclasses)
                PVE = com.prob_image(image_gauss, nclasses, mu, sigmasq, PLN)

                mu_upd, sigmasq_upd = com.update_param(image_gauss, PVE, mu,
                                                       nclasses)
                ind = np.argsort(mu_upd)
                mu_upd = mu_upd[ind]
                sigmasq_upd = sigmasq_upd[ind]

                negll = com.negloglikelihood(image_gauss, mu_upd, sigmasq_upd,
                                             nclasses)
                final_segmentation, energy = icm.icm_ising(
                    negll, beta, seg_init)
                energy_sum.append(energy[energy > -np.inf].sum())

                if self.save_history:
                    self.segmentations.append(final_segmentation)
                    self.pves.append(PVE)
                    self.energies.append(energy)
                    self.energies_sum.append(energy[energy > -np.inf].sum())

                if i % 10 == 0 and i != 0:

                    tol = tolerance * (np.amax(energy_sum) -
                                       np.amin(energy_sum))

                    test_dist = np.absolute(
                        np.amax(energy_sum[np.size(energy_sum) - 5:i]) -
                        np.amin(energy_sum[np.size(energy_sum) - 5:i]))

                    if test_dist < tol:

                        break

                seg_init = final_segmentation.copy()
                mu = mu_upd.copy()
                sigmasq = sigmasq_upd.copy()

        PVE = PVE[..., 1:]

        return initial_segmentation, final_segmentation, PVE
import numpy as np
from dipy.data import fetch_stanford_hardi, read_stanford_hardi
from dipy.sims.voxel import add_noise
from dipy.core.gradients import gradient_table

# Read data
fetch_stanford_hardi()
img, gtab = read_stanford_hardi()
data = img.get_data()

# Add Rician noise
from dipy.segment.mask import median_otsu
b0_mask, mask = median_otsu(data)
np.random.seed(1)
data_noisy = add_noise(data, 1, np.mean(data[mask]), noise_type='rician')

# Select a small part of it
data_small = data[25:40, 65:80, 35:42]
data_noisy_small = data_noisy[25:40, 65:80, 35:42]

"""
Fit an initial model to the data, in this case Constrained Spherical
Deconvolution is used.
"""

# Perform CSD on the original data
from dipy.reconst.csdeconv import auto_response
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
csd_model_orig = ConstrainedSphericalDeconvModel(gtab, response)
Example #16
0
def test_laplacian_regularization(radial_order=6):
    gtab = get_gtab_taiwan_dsi()
    l1, l2, l3 = [0.0015, 0.0003, 0.0003]
    S, _ = generate_signal_crossing(gtab, l1, l2, l3, angle2=60)
    S_noise = add_noise(S, snr=20, S0=100.)

    weight_array = np.linspace(0, .3, 301)
    mapmod_unreg = MapmriModel(gtab, radial_order=radial_order,
                               laplacian_regularization=False,
                               laplacian_weighting=weight_array)
    mapmod_laplacian_array = MapmriModel(gtab, radial_order=radial_order,
                                         laplacian_regularization=True,
                                         laplacian_weighting=weight_array)
    mapmod_laplacian_gcv = MapmriModel(gtab, radial_order=radial_order,
                                       laplacian_regularization=True,
                                       laplacian_weighting="GCV")

    # test the Generalized Cross Validation
    # test if GCV gives very low if there is no noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S)
    assert_equal(mapfit_laplacian_array.lopt < 0.01, True)

    # test if GCV gives higher values if there is noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S_noise)
    lopt_array = mapfit_laplacian_array.lopt
    assert_equal(lopt_array > 0.01, True)

    # test if continuous GCV gives the same the one based on an array
    mapfit_laplacian_gcv = mapmod_laplacian_gcv.fit(S_noise)
    lopt_gcv = mapfit_laplacian_gcv.lopt
    assert_almost_equal(lopt_array, lopt_gcv, 2)

    # test if laplacian reduced the norm of the laplacian in the reconstruction
    mu = mapfit_laplacian_gcv.mu
    laplacian_matrix = mapmri.mapmri_laplacian_reg_matrix(
        mapmod_laplacian_gcv.ind_mat, mu, mapmod_laplacian_gcv.S_mat,
        mapmod_laplacian_gcv.T_mat, mapmod_laplacian_gcv.U_mat)

    coef_unreg = mapmod_unreg.fit(S_noise)._mapmri_coef
    coef_laplacian = mapfit_laplacian_gcv._mapmri_coef

    laplacian_norm_unreg = np.dot(
        coef_unreg, np.dot(coef_unreg, laplacian_matrix))
    laplacian_norm_laplacian = np.dot(
        coef_laplacian, np.dot(coef_laplacian, laplacian_matrix))

    assert_equal(laplacian_norm_laplacian < laplacian_norm_unreg, True)

    # the same for isotropic scaling
    mapmod_unreg = MapmriModel(gtab, radial_order=radial_order,
                               laplacian_regularization=False,
                               laplacian_weighting=weight_array,
                               anisotropic_scaling=False)
    mapmod_laplacian_array = MapmriModel(gtab, radial_order=radial_order,
                                         laplacian_regularization=True,
                                         laplacian_weighting=weight_array,
                                         anisotropic_scaling=False)
    mapmod_laplacian_gcv = MapmriModel(gtab, radial_order=radial_order,
                                       laplacian_regularization=True,
                                       laplacian_weighting="GCV",
                                       anisotropic_scaling=False)

    # test the Generalized Cross Validation
    # test if GCV gives zero if there is no noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S)
    assert_equal(mapfit_laplacian_array.lopt < 0.01, True)

    # test if GCV gives higher values if there is noise
    mapfit_laplacian_array = mapmod_laplacian_array.fit(S_noise)
    lopt_array = mapfit_laplacian_array.lopt
    assert_equal(lopt_array > 0.01, True)

    # test if continuous GCV gives the same the one based on an array
    mapfit_laplacian_gcv = mapmod_laplacian_gcv.fit(S_noise)
    lopt_gcv = mapfit_laplacian_gcv.lopt
    assert_almost_equal(lopt_array, lopt_gcv, 2)

    # test if laplacian reduced the norm of the laplacian in the reconstruction
    mu = mapfit_laplacian_gcv.mu
    laplacian_matrix = mapmri.mapmri_isotropic_laplacian_reg_matrix(
        radial_order, mu[0])

    coef_unreg = mapmod_unreg.fit(S_noise)._mapmri_coef
    coef_laplacian = mapfit_laplacian_gcv._mapmri_coef

    laplacian_norm_unreg = np.dot(
        coef_unreg, np.dot(coef_unreg, laplacian_matrix))
    laplacian_norm_laplacian = np.dot(
        coef_laplacian, np.dot(coef_laplacian, laplacian_matrix))

    assert_equal(laplacian_norm_laplacian < laplacian_norm_unreg, True)
Example #17
0
from dipy.io.gradients import read_bvals_bvecs
from dipy.sims.voxel import add_noise

# Read data
hardi_fname, hardi_bval_fname, hardi_bvec_fname = get_fnames('stanford_hardi')
data = load_nifti_data(hardi_fname)
bvals, bvecs = read_bvals_bvecs(hardi_bval_fname, hardi_bvec_fname)
gtab = gradient_table(bvals, bvecs)

# Add Rician noise
from dipy.segment.mask import median_otsu
b0_slice = data[:, :, :, 1]
b0_mask, mask = median_otsu(b0_slice)
np.random.seed(1)
data_noisy = add_noise(data,
                       10.0,
                       np.mean(b0_slice[mask]),
                       noise_type='rician')

# Select a small part of it.
padding = 3  # Include a larger region to avoid boundary effects
data_small = data[25 - padding:40 + padding, 65 - padding:80 + padding, 35:42]
data_noisy_small = data_noisy[25 - padding:40 + padding,
                              65 - padding:80 + padding, 35:42]
"""
Enables/disables interactive visualization
"""

interactive = False
"""
Fit an initial model to the data, in this case Constrained Spherical
Deconvolution is used.
Example #18
0
image[..., :nslices] = single_slice[..., None]

# Set up parameters
nclasses = 4
beta = np.float64(0.0)
max_iter = 10
background_noise = True

# Making squares
square = np.zeros((256, 256, 3), dtype=np.int16)
square[42:213, 42:213, :] = 1
square[71:185, 71:185, :] = 2
square[99:157, 99:157, :] = 3

square_gauss = np.zeros((256, 256, 3)) + 0.001
square_gauss = add_noise(square_gauss, 10000, 1, noise_type='gaussian')
square_gauss[42:213, 42:213, :] = 1
noise_1 = np.random.normal(1.001, 0.0001,
                           size=square_gauss[42:213, 42:213, :].shape)
square_gauss[42:213, 42:213, :] = square_gauss[42:213, 42:213, :] + noise_1
square_gauss[71:185, 71:185, :] = 2
noise_2 = np.random.normal(2.001, 0.0001,
                           size=square_gauss[71:185, 71:185, :].shape)
square_gauss[71:185, 71:185, :] = square_gauss[71:185, 71:185, :] + noise_2
square_gauss[99:157, 99:157, :] = 3
noise_3 = np.random.normal(3.001, 0.0001,
                           size=square_gauss[99:157, 99:157, :].shape)
square_gauss[99:157, 99:157, :] = square_gauss[99:157, 99:157, :] + noise_3

square_1 = np.zeros((256, 256, 3)) + 0.001
square_1 = add_noise(square_1, 10000, 1, noise_type='gaussian')
Example #19
0
def test_greyscale_iter():

    max_iter = 15
    beta = np.float64(0.1)

    com = ConstantObservationModel()
    icm = IteratedConditionalModes()

    mu, sigma = com.initialize_param_uniform(image, nclasses)
    sigmasq = sigma ** 2
    neglogl = com.negloglikelihood(image, mu, sigmasq, nclasses)
    initial_segmentation = icm.initialize_maximum_likelihood(neglogl)
    npt.assert_(initial_segmentation.max() == nclasses - 1)
    npt.assert_(initial_segmentation.min() == 0)

    mu, sigma = com.seg_stats(image, initial_segmentation, nclasses)
    sigmasq = sigma ** 2
    npt.assert_(mu[0] >= 0.0)
    npt.assert_(mu[1] >= 0.0)
    npt.assert_(mu[2] >= 0.0)
    npt.assert_(mu[3] >= 0.0)
    npt.assert_(sigmasq[0] >= 0.0)
    npt.assert_(sigmasq[1] >= 0.0)
    npt.assert_(sigmasq[2] >= 0.0)
    npt.assert_(sigmasq[3] >= 0.0)

    if background_noise:
        zero = np.zeros_like(image) + 0.001
        zero_noise = add_noise(zero, 10000, 1, noise_type='gaussian')
        image_gauss = np.where(image == 0, zero_noise, image)
    else:
        image_gauss = image

    final_segmentation = np.empty_like(image)
    seg_init = initial_segmentation.copy()
    energies = []

    for i in range(max_iter):

        PLN = icm.prob_neighborhood(initial_segmentation, beta,
                                    nclasses)
        npt.assert_(np.all((PLN >= 0) & (PLN <= 1.0)))

        if beta == 0.0:

            npt.assert_almost_equal(PLN[50, 50, 1, 0], 0.25, True)
            npt.assert_almost_equal(PLN[50, 50, 1, 1], 0.25, True)
            npt.assert_almost_equal(PLN[50, 50, 1, 2], 0.25, True)
            npt.assert_almost_equal(PLN[50, 50, 1, 3], 0.25, True)
            npt.assert_almost_equal(PLN[147, 129, 1, 0], 0.25, True)
            npt.assert_almost_equal(PLN[147, 129, 1, 1], 0.25, True)
            npt.assert_almost_equal(PLN[147, 129, 1, 2], 0.25, True)
            npt.assert_almost_equal(PLN[147, 129, 1, 3], 0.25, True)
            npt.assert_almost_equal(PLN[61, 152, 1, 0], 0.25, True)
            npt.assert_almost_equal(PLN[61, 152, 1, 1], 0.25, True)
            npt.assert_almost_equal(PLN[61, 152, 1, 2], 0.25, True)
            npt.assert_almost_equal(PLN[61, 152, 1, 3], 0.25, True)
            npt.assert_almost_equal(PLN[100, 100, 1, 0], 0.25, True)
            npt.assert_almost_equal(PLN[100, 100, 1, 1], 0.25, True)
            npt.assert_almost_equal(PLN[100, 100, 1, 2], 0.25, True)
            npt.assert_almost_equal(PLN[100, 100, 1, 3], 0.25, True)

        PLY = com.prob_image(image_gauss, nclasses, mu, sigmasq, PLN)
        npt.assert_(np.all((PLY >= 0) & (PLY <= 1.0)))
        npt.assert_(PLY[50, 50, 1, 0] > PLY[50, 50, 1, 1])
        npt.assert_(PLY[50, 50, 1, 0] > PLY[50, 50, 1, 2])
        npt.assert_(PLY[50, 50, 1, 0] > PLY[50, 50, 1, 3])
        npt.assert_(PLY[100, 100, 1, 3] > PLY[100, 100, 1, 0])
        npt.assert_(PLY[100, 100, 1, 3] > PLY[100, 100, 1, 1])
        npt.assert_(PLY[100, 100, 1, 3] > PLY[100, 100, 1, 2])

        mu_upd, sigmasq_upd = com.update_param(image_gauss, PLY, mu, nclasses)        
        npt.assert_(mu_upd[0] >= 0.0)
        npt.assert_(mu_upd[1] >= 0.0)
        npt.assert_(mu_upd[2] >= 0.0)
        npt.assert_(mu_upd[3] >= 0.0)    
        npt.assert_(sigmasq_upd[0] >= 0.0)
        npt.assert_(sigmasq_upd[1] >= 0.0)
        npt.assert_(sigmasq_upd[2] >= 0.0)
        npt.assert_(sigmasq_upd[3] >= 0.0)

        negll = com.negloglikelihood(image_gauss,
                                     mu_upd, sigmasq_upd, nclasses)
        npt.assert_(negll[50, 50, 1, 0] < negll[50, 50, 1, 1])
        npt.assert_(negll[50, 50, 1, 0] < negll[50, 50, 1, 2])
        npt.assert_(negll[50, 50, 1, 0] < negll[50, 50, 1, 3])
        npt.assert_(negll[100, 100, 1, 3] < negll[100, 100, 1, 0])
        npt.assert_(negll[100, 100, 1, 3] < negll[100, 100, 1, 1])
        npt.assert_(negll[100, 100, 1, 3] < negll[100, 100, 1, 2])

        final_segmentation, energy = icm.icm_ising(negll, beta,
                                                   initial_segmentation)
        print(energy[energy > -np.inf].sum())
        energies.append(energy[energy > -np.inf].sum())

        initial_segmentation = final_segmentation.copy()
        mu = mu_upd.copy()
        sigmasq = sigmasq_upd.copy()

    npt.assert_(energies[-1] < energies[0])

    difference_map = np.abs(seg_init - final_segmentation)
    npt.assert_(np.abs(np.sum(difference_map)) != 0)