Exemplo n.º 1
0
def test_simple_ball_and_stick_optimization():
    stick = cylinder_models.C1Stick()
    ball = gaussian_models.G1Ball()

    ball_and_stick = (modeling_framework.MultiCompartmentModel(
        models=[ball, stick]))
    gt_mu = np.clip(np.random.rand(2), .3, np.inf)
    gt_lambda_par = (np.random.rand() + 1.) * 1e-9
    gt_lambda_iso = gt_lambda_par / 2.
    gt_partial_volume = 0.3

    gt_parameter_vector = ball_and_stick.parameters_to_parameter_vector(
        C1Stick_1_lambda_par=gt_lambda_par,
        G1Ball_1_lambda_iso=gt_lambda_iso,
        C1Stick_1_mu=gt_mu,
        partial_volume_0=gt_partial_volume,
        partial_volume_1=1 - gt_partial_volume)

    E = ball_and_stick.simulate_signal(scheme, gt_parameter_vector)

    vf_rand = np.random.rand()
    ball_and_stick.set_initial_guess_parameter('C1Stick_1_lambda_par',
                                               (np.random.rand() + 1.) * 1e-9)
    ball_and_stick.set_initial_guess_parameter('G1Ball_1_lambda_iso',
                                               gt_lambda_par / 2.)
    ball_and_stick.set_initial_guess_parameter('C1Stick_1_mu',
                                               np.random.rand(2))
    ball_and_stick.set_initial_guess_parameter('partial_volume_0', vf_rand)
    ball_and_stick.set_initial_guess_parameter('partial_volume_1', 1 - vf_rand)

    res = ball_and_stick.fit(scheme, E).fitted_parameters_vector
    assert_array_almost_equal(gt_parameter_vector, res.squeeze(), 2)
Exemplo n.º 2
0
def test_multi_tissue_mc_model():
    scheme = wu_minn_hcp_acquisition_scheme()
    ball = gaussian_models.G1Ball()
    cyl = cylinder_models.C1Stick()
    models = [ball, cyl]
    S0_responses = [1., 2.]
    mt_mc = modeling_framework.MultiCompartmentModel(
        models=models, S0_tissue_responses=S0_responses)

    mt_mc.set_fixed_parameter('C1Stick_1_lambda_par', 1.7e-9)
    mt_mc.set_fixed_parameter('G1Ball_1_lambda_iso', 3e-9)
    mt_mc.set_fixed_parameter('C1Stick_1_mu', [0., 0.])
    param_dict = {'partial_volume_0': .5, 'partial_volume_1': .5}
    E = mt_mc.simulate_signal(scheme, param_dict)

    mt_mc_fit = mt_mc.fit(scheme, E)
    sig_fracts = mt_mc_fit.fitted_parameters
    vol_fracts = mt_mc_fit.fitted_multi_tissue_fractions
    vol_fracts_norm = mt_mc_fit.fitted_multi_tissue_fractions_normalized

    assert_almost_equal(
        sig_fracts['partial_volume_0'], vol_fracts['partial_volume_0'], 2)
    assert_almost_equal(
        sig_fracts['partial_volume_1'], vol_fracts['partial_volume_1'] * 2., 2)
    assert_almost_equal(
        vol_fracts_norm['partial_volume_0'], 2 / 3., 2)
    assert_almost_equal(
        vol_fracts_norm['partial_volume_1'], 1 / 3., 2)
def test_all_fitted_model_properties():
    stick = cylinder_models.C1Stick()
    watsonstick = distribute_models.SD1WatsonDistributed([stick])
    params = {}
    for parameter, card, in watsonstick.parameter_cardinality.items():
        params[parameter] = (np.random.rand(card) *
                             watsonstick.parameter_scales[parameter])
    data = np.atleast_2d(watsonstick(scheme, **params))

    mcmod = modeling_framework.MultiCompartmentModel([watsonstick])
    mcfit = mcmod.fit(scheme, data)

    vertices = np.random.rand(10, 3)
    vertices /= np.linalg.norm(vertices, axis=1)[:, None]

    assert_(isinstance(mcfit.fitted_parameters, dict))
    assert_(isinstance(mcfit.fitted_parameters_vector, np.ndarray))
    assert_(isinstance(mcfit.fod(vertices), np.ndarray))
    assert_(isinstance(mcfit.fod_sh(), np.ndarray))
    assert_(isinstance(mcfit.peaks_spherical(), np.ndarray))
    assert_(isinstance(mcfit.peaks_cartesian(), np.ndarray))
    assert_(isinstance(mcfit.mean_squared_error(data), np.ndarray))
    assert_(isinstance(mcfit.R2_coefficient_of_determination(data),
                       np.ndarray))
    assert_(isinstance(mcfit.predict(), np.ndarray))

    mcmod_sm = modeling_framework.MultiCompartmentSphericalMeanModel([stick])
    mcfit_sm = mcmod_sm.fit(scheme, data)
    assert_(isinstance(mcfit_sm.fitted_parameters, dict))
    assert_(isinstance(mcfit_sm.fitted_parameters_vector, np.ndarray))
    assert_(isinstance(mcfit.mean_squared_error(data), np.ndarray))
    assert_(isinstance(mcfit.R2_coefficient_of_determination(data),
                       np.ndarray))
    assert_(isinstance(mcfit.predict(), np.ndarray))
Exemplo n.º 4
0
def test_stick_tortuous_zeppelin():
    stick = cylinder_models.C1Stick()
    zeppelin = gaussian_models.G2Zeppelin()

    stick_and_zeppelin = (
        modeling_framework.MultiCompartmentModel(
            models=[stick, zeppelin])
    )

    stick_and_zeppelin.set_tortuous_parameter(
        'G2Zeppelin_1_lambda_perp',
        'C1Stick_1_lambda_par',
        'partial_volume_0',
        'partial_volume_1'
    )
    stick_and_zeppelin.set_equal_parameter(
        'C1Stick_1_mu',
        'G2Zeppelin_1_mu'
    )

    stick_and_zeppelin.set_equal_parameter(
        'G2Zeppelin_1_lambda_par',
        'C1Stick_1_lambda_par'
    )

    fitted_params = (stick_and_zeppelin.fit(
        scheme,
        camino_parallel.signal_attenuation[::20],
    ).fitted_parameters)

    mean_abs_error = np.mean(
        abs(fitted_params['partial_volume_0'].squeeze(
        ) - camino_parallel.fractions[::20]))
    assert_equal(mean_abs_error < 0.02, True)
def test_fitting_without_b0_raises():
    bvals = np.atleast_1d(1e9)
    bvecs = np.atleast_2d([1., 0., 0.])
    scheme = acquisition_scheme_from_bvalues(bvals, bvecs)
    mc = modeling_framework.MultiCompartmentModel([gaussian_models.G1Ball()])
    data = np.atleast_1d(1.)
    assert_raises(ValueError, mc.fit, scheme, data)
Exemplo n.º 6
0
def test_multi_compartment_fod_with_parametric_model(
        odi=0.15, mu=[0., 0.], lambda_iso=3e-9, lambda_par=1.7e-9,
        vf_intra=0.7):
    stick = cylinder_models.C1Stick()
    ball = gaussian_models.G1Ball()
    watsonstick = distribute_models.SD1WatsonDistributed(
        [stick])
    mc_mod = modeling_framework.MultiCompartmentModel([watsonstick, ball])

    sh_mod = modeling_framework.MultiCompartmentSphericalHarmonicsModel(
        [stick, ball])
    sh_mod.set_fixed_parameter('G1Ball_1_lambda_iso', lambda_iso)
    sh_mod.set_fixed_parameter('C1Stick_1_lambda_par', lambda_par)

    simulation_parameters = mc_mod.parameters_to_parameter_vector(
        G1Ball_1_lambda_iso=lambda_iso,
        SD1WatsonDistributed_1_SD1Watson_1_mu=mu,
        SD1WatsonDistributed_1_C1Stick_1_lambda_par=lambda_par,
        SD1WatsonDistributed_1_SD1Watson_1_odi=odi,
        partial_volume_0=vf_intra,
        partial_volume_1=1 - vf_intra)
    data = mc_mod.simulate_signal(scheme, simulation_parameters)

    sh_fit = sh_mod.fit(scheme, data)

    vf_intra_estimated = sh_fit.fitted_parameters['partial_volume_0']
    assert_almost_equal(vf_intra, vf_intra_estimated)

    predicted_signal = sh_fit.predict()

    assert_array_almost_equal(data, predicted_signal[0], 4)
Exemplo n.º 7
0
def test_MIX_fitting_singlemodel():
    stick = cylinder_models.C1Stick()
    stick_mod = (modeling_framework.MultiCompartmentModel(models=[stick]))

    parameter_vector = stick_mod.parameters_to_parameter_vector(
        C1Stick_1_mu=(np.pi / 2., np.pi / 2.), C1Stick_1_lambda_par=1.7e-9)

    E = stick_mod.simulate_signal(scheme, parameter_vector)
    fit = stick_mod.fit(scheme, E, solver='mix').fitted_parameters_vector
    assert_array_almost_equal(abs(fit).squeeze(), parameter_vector, 2)
Exemplo n.º 8
0
def test_stick_and_tortuous_zeppelin_to_spherical_mean_fit():
    """ this is a more complex test to see if we can generate 3D data using a
    stick and zeppelin model, where we assume the perpendicular diffusivity is
    linked to the parallel diffusivity and volume fraction using tortuosity. We
    then use the spherical mean models of stick and zeppelin with the same
    tortuosity assumption to fit the 3D data (and estimating the spherical mean
    of each shell). The final check is whether the parallel diffusivity and
    volume fraction between the 3D and spherical mean models correspond."""

    gt_mu = np.clip(np.random.rand(2), .3, np.inf)
    gt_lambda_par = (np.random.rand() + 1.) * 1e-9
    gt_partial_volume = 0.3

    stick = cylinder_models.C1Stick()
    zeppelin = gaussian_models.G2Zeppelin()

    stick_and_zeppelin = (modeling_framework.MultiCompartmentModel(
        models=[stick, zeppelin]))

    stick_and_zeppelin.set_tortuous_parameter('G2Zeppelin_1_lambda_perp',
                                              'C1Stick_1_lambda_par',
                                              'partial_volume_0',
                                              'partial_volume_1')
    stick_and_zeppelin.set_equal_parameter('C1Stick_1_mu', 'G2Zeppelin_1_mu')

    stick_and_zeppelin.set_equal_parameter('C1Stick_1_lambda_par',
                                           'G2Zeppelin_1_lambda_par')

    gt_parameter_vector = (stick_and_zeppelin.parameters_to_parameter_vector(
        C1Stick_1_lambda_par=gt_lambda_par,
        C1Stick_1_mu=gt_mu,
        partial_volume_0=gt_partial_volume,
        partial_volume_1=1 - gt_partial_volume))

    E = stick_and_zeppelin.simulate_signal(scheme, gt_parameter_vector)

    # now we make the stick and zeppelin spherical mean model and check if the
    # same lambda_par and volume fraction result as the 3D generated data.
    stick_and_tortuous_zeppelin_sm = (
        modeling_framework.MultiCompartmentSphericalMeanModel(
            models=[stick, zeppelin]))

    stick_and_tortuous_zeppelin_sm.set_tortuous_parameter(
        'G2Zeppelin_1_lambda_perp', 'C1Stick_1_lambda_par', 'partial_volume_0',
        'partial_volume_1')
    stick_and_tortuous_zeppelin_sm.set_equal_parameter(
        'G2Zeppelin_1_lambda_par', 'C1Stick_1_lambda_par')

    res_sm = stick_and_tortuous_zeppelin_sm.fit(scheme,
                                                E).fitted_parameters_vector

    assert_array_almost_equal(np.r_[gt_lambda_par, gt_partial_volume],
                              res_sm.squeeze()[:-1], 2)
def test_raise_mix_with_tortuosity_in_mcmodel():
    scheme = wu_minn_hcp_acquisition_scheme()
    stick = cylinder_models.C1Stick()
    zeppelin = gaussian_models.G2Zeppelin()
    mc = modeling_framework.MultiCompartmentModel([stick, zeppelin])
    mc.set_tortuous_parameter('G2Zeppelin_1_lambda_perp',
                              'C1Stick_1_lambda_par', 'partial_volume_0',
                              'partial_volume_1')

    data = stick(scheme, lambda_par=1.7e-9, mu=[0., 0.])

    assert_raises(ValueError, mc.fit, scheme, data, solver='mix')
def test_set_parameter_optimization_bounds_raises():
    ball = gaussian_models.G1Ball()
    mc = modeling_framework.MultiCompartmentModel([ball])
    assert_raises(ValueError, mc.set_parameter_optimization_bounds,
                  'not a valid name', [1, 2])
    assert_raises(ValueError, mc.set_parameter_optimization_bounds,
                  'G1Ball_1_lambda_iso', 1)
    assert_raises(ValueError, mc.set_parameter_optimization_bounds,
                  'G1Ball_1_lambda_iso', [[1, 2], [1, 2]])
    assert_raises(ValueError, mc.set_parameter_optimization_bounds,
                  'G1Ball_1_lambda_iso', [1, 2, 3])
    assert_raises(ValueError, mc.set_parameter_optimization_bounds,
                  'G1Ball_1_lambda_iso', [2, 1])
Exemplo n.º 11
0
def test_multi_tissue_tortuosity_no_s0():
    stick = cylinder_models.C1Stick()
    zeppelin = gaussian_models.G2Zeppelin()
    ball = gaussian_models.G1Ball()

    model = modeling_framework.MultiCompartmentModel(
        models=[stick, zeppelin, ball])
    model.set_tortuous_parameter('G2Zeppelin_1_lambda_perp',
                                 'C1Stick_1_lambda_par', 'partial_volume_0',
                                 'partial_volume_1', True)
    tort = model.parameter_links[0][2]
    s0ic, s0ec = tort.S0_intra, tort.S0_extra
    assert_(s0ic == 1 and s0ec == 1)
Exemplo n.º 12
0
def test_multi_dimensional_x0():
    stick = cylinder_models.C1Stick()
    ball = gaussian_models.G1Ball()
    ball_and_stick = (
        modeling_framework.MultiCompartmentModel(
            models=[ball, stick],)
    )
    gt_lambda_par = (np.random.rand() + 1.) * 1e-9
    gt_lambda_iso = gt_lambda_par / 2.
    gt_partial_volume = 0.3
    gt_mu_array = np.empty((10, 10, 2))

    # I'm putting the orientation of the stick all over the sphere.
    for i, mu1 in enumerate(np.linspace(0, np.pi, 10)):
        for j, mu2 in enumerate(np.linspace(-np.pi, np.pi, 10)):
            gt_mu_array[i, j] = np.r_[mu1, mu2]

    gt_parameter_vector = (
        ball_and_stick.parameters_to_parameter_vector(
            C1Stick_1_lambda_par=gt_lambda_par,
            G1Ball_1_lambda_iso=gt_lambda_iso,
            C1Stick_1_mu=gt_mu_array,
            partial_volume_0=gt_partial_volume,
            partial_volume_1=1 - gt_partial_volume)
    )

    E_array = ball_and_stick.simulate_signal(
        scheme, gt_parameter_vector)

    ball_and_stick.set_initial_guess_parameter(
        'C1Stick_1_lambda_par', gt_lambda_par)
    ball_and_stick.set_initial_guess_parameter(
        'G1Ball_1_lambda_iso', gt_lambda_iso)
    ball_and_stick.set_initial_guess_parameter(
        'C1Stick_1_mu', gt_mu_array)
    ball_and_stick.set_initial_guess_parameter(
        'partial_volume_0', gt_partial_volume)
    ball_and_stick.set_initial_guess_parameter(
        'partial_volume_1', 1 - gt_partial_volume)
    # I'm giving a voxel-dependent initial condition with gt_mu_array
    res = ball_and_stick.fit(scheme, E_array).fitted_parameters_vector
    # optimization should stop immediately as I'm giving the ground truth.
    assert_equal(np.all(np.ravel(res - gt_parameter_vector) == 0.), True)
    # and the parameter vector dictionaries of the results and x0 should also
    # be the same.
    res_parameters = ball_and_stick.parameter_vector_to_parameters(res)
    x0_parameters = ball_and_stick.parameter_vector_to_parameters(
        gt_parameter_vector)
    for key in res_parameters.keys():
        assert_array_equal(x0_parameters[key], res_parameters[key])
Exemplo n.º 13
0
def test_equivalence_sh_distributed_mc_with_mcsh():
    """
    We test if we can input a Watson-distributed zeppelin and stick into an
    SD3SphericalHarmonicsDistributedModel in an MC-model, and compare it with
    an MCSH model with the same watson distribution as a kernel.
    """
    stick = cylinder_models.C1Stick()
    zep = gaussian_models.G2Zeppelin()

    mck_dist = distribute_models.SD1WatsonDistributed([stick, zep])
    mck_dist.set_equal_parameter('G2Zeppelin_1_lambda_par',
                                 'C1Stick_1_lambda_par')
    mck_dist.set_tortuous_parameter('G2Zeppelin_1_lambda_perp',
                                    'G2Zeppelin_1_lambda_par',
                                    'partial_volume_0')

    mcsh = modeling_framework.MultiCompartmentSphericalHarmonicsModel(
        models=[mck_dist], sh_order=8)
    mc = modeling_framework.MultiCompartmentModel([
        distribute_models.SD3SphericalHarmonicsDistributed([mck_dist],
                                                           sh_order=8)
    ])

    lambda_par = 0.
    odi = .02
    sh_coeff = np.ones(45)
    sh_coeff[0] = 1 / (2 * np.sqrt(np.pi))
    pv0 = .3

    params_mcsh = {
        'SD1WatsonDistributed_1_partial_volume_0': pv0,
        'SD1WatsonDistributed_1_G2Zeppelin_1_lambda_par': lambda_par,
        'SD1WatsonDistributed_1_SD1Watson_1_odi': odi,
        'sh_coeff': sh_coeff
    }

    basemod = 'SD3SphericalHarmonicsDistributed_1_'
    params_mc = {
        basemod + 'SD1WatsonDistributed_1_partial_volume_0': pv0,
        basemod + 'SD1WatsonDistributed_1_G2Zeppelin_1_lambda_par': lambda_par,
        basemod + 'SD1WatsonDistributed_1_SD1Watson_1_odi': odi,
        basemod + 'SD3SphericalHarmonics_1_sh_coeff': sh_coeff
    }

    E_mcsh = mcsh.simulate_signal(scheme, params_mcsh)
    E_mc = mc.simulate_signal(scheme, params_mc)

    np.testing.assert_array_almost_equal(E_mcsh, E_mc)
Exemplo n.º 14
0
def test_simple_stick_optimization():
    stick = cylinder_models.C1Stick()
    gt_mu = np.random.rand(2)
    gt_lambda_par = (np.random.rand() + 1.) * 1e-9

    stick_model = modeling_framework.MultiCompartmentModel(models=[stick])

    gt_parameter_vector = stick_model.parameters_to_parameter_vector(
        C1Stick_1_lambda_par=gt_lambda_par, C1Stick_1_mu=gt_mu)

    E = stick_model.simulate_signal(scheme, gt_parameter_vector)

    stick_model.set_initial_guess_parameter('C1Stick_1_lambda_par',
                                            (np.random.rand() + 1.) * 1e-9)
    stick_model.set_initial_guess_parameter('C1Stick_1_mu', np.random.rand(2))
    res = stick_model.fit(scheme, E).fitted_parameters_vector
    assert_array_almost_equal(gt_parameter_vector, res.squeeze(), 2)
Exemplo n.º 15
0
def test_fractions_add_up_to_one():
    dot1 = sphere_models.S1Dot()
    dot2 = sphere_models.S1Dot()
    dot3 = sphere_models.S1Dot()
    dot4 = sphere_models.S1Dot()
    dot5 = sphere_models.S1Dot()
    dots = modeling_framework.MultiCompartmentModel(
        models=[dot1, dot2, dot3, dot4, dot5])
    random_fractions = np.random.rand(5)
    random_fractions /= random_fractions.sum()
    parameter_vector = dots.parameters_to_parameter_vector(
        partial_volume_0=random_fractions[0],
        partial_volume_1=random_fractions[1],
        partial_volume_2=random_fractions[2],
        partial_volume_3=random_fractions[3],
        partial_volume_4=random_fractions[4])
    E = dots.simulate_signal(scheme, parameter_vector)
    assert_array_almost_equal(E, np.ones(len(E)))
Exemplo n.º 16
0
def test_MIX_fitting_multimodel():
    ball = gaussian_models.G1Ball()
    zeppelin = gaussian_models.G2Zeppelin()
    ball_and_zeppelin = (modeling_framework.MultiCompartmentModel(
        models=[ball, zeppelin]))

    parameter_vector = ball_and_zeppelin.parameters_to_parameter_vector(
        G1Ball_1_lambda_iso=2.7e-9,
        partial_volume_0=.2,
        partial_volume_1=.8,
        G2Zeppelin_1_lambda_perp=.5e-9,
        G2Zeppelin_1_mu=(np.pi / 2., np.pi / 2.),
        G2Zeppelin_1_lambda_par=1.7e-9)

    E = ball_and_zeppelin.simulate_signal(scheme, parameter_vector)
    fit = ball_and_zeppelin.fit(scheme, E,
                                solver='mix').fitted_parameters_vector
    assert_array_almost_equal(abs(fit).squeeze(), parameter_vector, 2)
Exemplo n.º 17
0
def test_bingham_dispersed_stick_tortuous_zeppelin():
    stick = cylinder_models.C1Stick()
    zeppelin = gaussian_models.G2Zeppelin()

    bingham_bundle = distribute_models.SD2BinghamDistributed(
        models=[stick, zeppelin])

    bingham_bundle.set_tortuous_parameter(
        'G2Zeppelin_1_lambda_perp',
        'G2Zeppelin_1_lambda_par',
        'partial_volume_0'
    )

    bingham_bundle.set_equal_parameter(
        'G2Zeppelin_1_lambda_par',
        'C1Stick_1_lambda_par')

    bingham_bundle.set_fixed_parameter(
        'G2Zeppelin_1_lambda_par', 1.7e-9)

    bingham_bundle.set_fixed_parameter(
        'SD2Bingham_1_mu', [0., 0.])

    mc_bingham = (
        modeling_framework.MultiCompartmentModel(
            models=[bingham_bundle])
    )

    beta0 = camino_dispersed.beta > 0
    diff17 = camino_dispersed.diffusivities == 1.7e-9
    mask = np.all([beta0, diff17], axis=0)
    E_watson = camino_dispersed.signal_attenuation[mask]
    fractions_watson = camino_dispersed.fractions[mask]

    fitted_params = (mc_bingham.fit(scheme,
                                    E_watson[::200]).fitted_parameters
                     )

    mean_abs_error = np.mean(
        abs(fitted_params['SD2BinghamDistributed_1_partial_volume_0'].squeeze(
        ) - fractions_watson[::200]))
    assert_equal(mean_abs_error < 0.035, True)
Exemplo n.º 18
0
def test_simple_ball_and_stick_optimization_vf_fixed():
    stick = cylinder_models.C1Stick()
    ball = gaussian_models.G1Ball()

    ball_and_stick = (
        modeling_framework.MultiCompartmentModel(
            models=[ball, stick])
    )
    gt_mu = np.clip(np.random.rand(2), .3, np.inf)
    gt_lambda_par = (np.random.rand() + 1.) * 1e-9
    gt_lambda_iso = gt_lambda_par / 2.
    gt_partial_volume = 0.3

    gt_parameter_vector = ball_and_stick.parameters_to_parameter_vector(
        C1Stick_1_lambda_par=gt_lambda_par,
        G1Ball_1_lambda_iso=gt_lambda_iso,
        C1Stick_1_mu=gt_mu,
        partial_volume_0=gt_partial_volume,
        partial_volume_1=1 - gt_partial_volume
    )

    E = ball_and_stick.simulate_signal(
        scheme, gt_parameter_vector)

    E2d = np.array([E, E])

    vf_rand = np.random.rand()
    ball_and_stick.set_fixed_parameter(
        'partial_volume_0', np.r_[vf_rand, vf_rand])
    ball_and_stick.set_fixed_parameter(
        'partial_volume_1', np.r_[1 - vf_rand, 1 - vf_rand])
    ball_and_stick.set_initial_guess_parameter(
        'C1Stick_1_lambda_par', (np.random.rand() + 1.) * 1e-9)
    ball_and_stick.set_initial_guess_parameter(
        'G1Ball_1_lambda_iso', gt_lambda_par / 2.)
    ball_and_stick.set_initial_guess_parameter(
        'C1Stick_1_mu', np.random.rand(2))

    vf_fitted = ball_and_stick.fit(
        scheme, E2d).fitted_parameters['partial_volume_0'][0]
    assert_equal(vf_fitted, vf_rand)
def test_set_fixed_parameter_raises():
    cyl = cylinder_models.C1Stick()
    mod = modeling_framework.MultiCompartmentModel([cyl])
    assert_raises(ValueError, mod.set_fixed_parameter, 'C1Stick_1_mu', [1])
    assert_raises(ValueError, mod.set_fixed_parameter, 'blabla', [1])
Exemplo n.º 20
0
def main():
    # Plot Save Path
    base_plot_path = r'/nfs/masi/nathv/py_src_code_2020/dmipy_model_pictures'
    base_plot_path = os.path.normpath(base_plot_path)

    # Method Saving Paths
    base_save_path = r'/nfs/masi/nathv/miccai_2020/micro_methods_hcp_mini'
    base_save_path = os.path.normpath(base_save_path)

    # Create base saving path for Method
    # TODO The Method name can be made an argument later on
    method_name = 'AXCALIBER'

    # Base HCP Data Path
    base_data_path = r'/nfs/HCP/data'
    base_data_path = os.path.normpath(base_data_path)

    # Subject ID's list
    subj_ID_List = ['125525', '118225', '116726', '115825', '115017', '114823']
    # TODO When needed loop here over the ID list
    for subj_ID in subj_ID_List:
        # Subject Save Path
        subj_save_path = os.path.join(base_save_path, subj_ID)
        if os.path.exists(subj_save_path) == False:
            os.mkdir(subj_save_path)

        # TODO For later the subject data, bval and bvec reading part can be put inside a function
        subj_data_path = os.path.join(base_data_path, subj_ID_List[0], 'T1w',
                                      'Diffusion')

        # Read the Nifti file, bvals and bvecs
        subj_bvals = np.loadtxt(os.path.join(subj_data_path, 'bvals'))
        subj_bvecs = np.loadtxt(os.path.join(subj_data_path, 'bvecs'))

        all_bvals = subj_bvals * 1e6
        all_bvecs = np.transpose(subj_bvecs)

        subj_Acq_Scheme = acquisition_scheme_from_bvalues(all_bvals,
                                                          all_bvecs,
                                                          delta=10.6 * 1e-3,
                                                          Delta=43.1 * 1e-3,
                                                          TE=89.5 * 1e-3)
        print(subj_Acq_Scheme.print_acquisition_info)

        print('Loading the Nifti Data ...')
        data_start_time = time.time()

        subj_babel_object = nib.load(
            os.path.join(subj_data_path, 'data.nii.gz'))
        subj_data = subj_babel_object.get_fdata()
        axial_slice_data = subj_data[58:60, 68:70, 60:62, :]

        mask_babel_object = nib.load(
            os.path.join(subj_data_path, 'nodif_brain_mask.nii.gz'))
        mask_data = mask_babel_object.get_fdata()
        axial_mask_slice_data = mask_data[58:60, 68:70, 60:62]

        data_end_time = time.time()
        data_time = np.int(np.round(data_end_time - data_start_time))

        print('Data Loaded ... Time Taken: {}'.format(data_end_time -
                                                      data_start_time))
        print('The Data Dimensions are: {}'.format(subj_data.shape))

        #### AxCaliber Begin ####
        ball = gaussian_models.G1Ball()
        cylinder = cylinder_models.C4CylinderGaussianPhaseApproximation()
        gamma_cylinder = distribute_models.DD1GammaDistributed(
            models=[cylinder])

        axcaliber_gamma = modeling_framework.MultiCompartmentModel(
            models=[ball, gamma_cylinder])

        axcaliber_gamma.set_fixed_parameter(
            'DD1GammaDistributed_1_C4CylinderGaussianPhaseApproximation_1_lambda_par',
            1.7e-9)
        axcaliber_gamma.set_fixed_parameter(
            'DD1GammaDistributed_1_C4CylinderGaussianPhaseApproximation_1_mu',
            [0, 0])

        print('Fitting the AxCaliber Model ...')
        fit_start_time = time.time()
        mcdmi_fit = axcaliber_gamma.fit(subj_Acq_Scheme,
                                        axial_slice_data,
                                        mask=axial_mask_slice_data,
                                        solver='mix',
                                        maxiter=100,
                                        use_parallel_processing=True,
                                        number_of_processors=32)

        fit_end_time = time.time()
        print('Model Fitting Completed ... Time Taken to fit: {}'.format(
            fit_end_time - fit_start_time))
        fit_time = np.int(np.round(fit_end_time - fit_start_time))

        fitted_parameters = mcdmi_fit.fitted_parameters

        # Get List of Estimated Parameter Names
        para_Names_list = []
        for key, value in fitted_parameters.items():
            para_Names_list.append(key)

        ### Nifti Saving Part
        # Create a directory per subject
        subj_method_save_path = os.path.join(subj_save_path, method_name)
        if os.path.exists(subj_method_save_path) == False:
            os.mkdir(subj_method_save_path)

        # Retrieve the affine from already Read Nifti file to form the header
        affine = subj_babel_object.affine

        # Loop over fitted parameters name list
        for each_fitted_parameter in para_Names_list:
            new_img = nib.Nifti1Image(fitted_parameters[each_fitted_parameter],
                                      affine)

            # Form the file path
            f_name = each_fitted_parameter + '.nii.gz'
            param_file_path = os.path.join(subj_method_save_path, f_name)

            nib.save(new_img, param_file_path)

        print('debug here')
    return None
Exemplo n.º 21
0
def test_multi_voxel_parametric_to_sm_to_sh_fod_watson():
    stick = cylinder_models.C1Stick()
    zeppelin = gaussian_models.G2Zeppelin()
    watsonstick = distribute_models.SD1WatsonDistributed([stick, zeppelin])

    watsonstick.set_equal_parameter('G2Zeppelin_1_lambda_par',
                                    'C1Stick_1_lambda_par')
    watsonstick.set_tortuous_parameter('G2Zeppelin_1_lambda_perp',
                                       'G2Zeppelin_1_lambda_par',
                                       'partial_volume_0')
    mc_mod = modeling_framework.MultiCompartmentModel([watsonstick])

    parameter_dict = {
        'SD1WatsonDistributed_1_SD1Watson_1_mu':
        np.random.rand(10, 2),
        'SD1WatsonDistributed_1_partial_volume_0':
        np.linspace(0.1, 0.9, 10),
        'SD1WatsonDistributed_1_G2Zeppelin_1_lambda_par':
        np.linspace(1.5, 2.5, 10) * 1e-9,
        'SD1WatsonDistributed_1_SD1Watson_1_odi':
        np.linspace(0.3, 0.7, 10)
    }

    data = mc_mod.simulate_signal(scheme, parameter_dict)

    sm_mod = modeling_framework.MultiCompartmentSphericalMeanModel(
        [stick, zeppelin])
    sm_mod.set_equal_parameter('G2Zeppelin_1_lambda_par',
                               'C1Stick_1_lambda_par')
    sm_mod.set_tortuous_parameter('G2Zeppelin_1_lambda_perp',
                                  'G2Zeppelin_1_lambda_par',
                                  'partial_volume_0', 'partial_volume_1')

    sf_watson = []
    for mu, odi in zip(
            parameter_dict['SD1WatsonDistributed_1_SD1Watson_1_mu'],
            parameter_dict['SD1WatsonDistributed_1_SD1Watson_1_odi']):
        watson = distributions.SD1Watson(mu=mu, odi=odi)
        sf_watson.append(watson(sphere.vertices))
    sf_watson = np.array(sf_watson)

    sm_fit = sm_mod.fit(scheme, data)
    sh_mod = sm_fit.return_spherical_harmonics_fod_model()

    sh_fit_auto = sh_mod.fit(scheme, data)  # will pick tournier
    fod_tournier = sh_fit_auto.fod(sphere.vertices)
    assert_array_almost_equal(fod_tournier, sf_watson, 1)

    sh_fit_tournier = sh_mod.fit(scheme,
                                 data,
                                 solver='csd_tournier07',
                                 unity_constraint=False)
    fod_tournier = sh_fit_tournier.fod(sphere.vertices)
    assert_array_almost_equal(fod_tournier, sf_watson, 1)

    sh_fit_cvxpy = sh_mod.fit(scheme,
                              data,
                              solver='csd_cvxpy',
                              unity_constraint=True,
                              lambda_lb=0.)
    fod_cvxpy = sh_fit_cvxpy.fod(sphere.vertices)
    assert_array_almost_equal(fod_cvxpy, sf_watson, 2)

    sh_fit_cvxpy = sh_mod.fit(scheme,
                              data,
                              solver='csd_cvxpy',
                              unity_constraint=False,
                              lambda_lb=0.)
    fod_cvxpy = sh_fit_cvxpy.fod(sphere.vertices)
    assert_array_almost_equal(fod_cvxpy, sf_watson, 2)