Exemple #1
0
def reconst_gqi_fodf_return_sh_coeffs(bval_path,bvec_path,data_path,data_var):

    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]

    gqmodel = GeneralizedQSamplingModel(gtab, sampling_length=1.2)

    #gqfit = gqmodel.fit(dataslice, mask=mask)
    sphere = get_sphere('symmetric724')
    #ODF = gqfit.odf(sphere)
    #odf = gqmodel.fit(data).odf(sphere)

    gqpeaks = peaks_from_model(model=gqmodel,
                               data=data,
                               sphere=sphere,
                               relative_peak_threshold=.5,
                               min_separation_angle=25,
                               return_odf=True,
                               normalize_peaks=True)

    print('Debug here')
    fodfs_shm = gqpeaks.shm_coeff
    return fodfs_shm
def dipy_gt():
    print("Loading slice...")
    sample_slice, qvecs, gtab = load_slice('./test_data/david_data', '3112_BL_data_subject_space.nii.gz', gtab=True)
    mapmodel = GeneralizedQSamplingModel(gtab)
    mapfit = mapmodel.fit(sample_slice)
    sphere = get_sphere('repulsion724')
    odfs = mapfit.odf(sphere)
    vis_2d_field(odfs, sphere)
Exemple #3
0
def test_mvoxel_gqi():
    data, gtab = dsi_voxels()
    sphere = get_sphere('symmetric724')

    gq = GeneralizedQSamplingModel(gtab, 'standard')
    gqfit = gq.fit(data)
    all_odfs = gqfit.odf(sphere)

    # Check that the first and last voxels each have 2 peaks
    odf = all_odfs[0, 0, 0]
    directions, values, indices = peak_directions(odf, sphere, .35, 25)
    assert_equal(directions.shape[0], 2)
    odf = all_odfs[-1, -1, -1]
    directions, values, indices = peak_directions(odf, sphere, .35, 25)
    assert_equal(directions.shape[0], 2)
Exemple #4
0
def test_gqi():
    #load symmetric 724 sphere
    sphere = get_sphere('symmetric724')
    #load icosahedron sphere
    sphere2 = create_unit_sphere(5)
    btable = np.loadtxt(get_data('dsi515btable'))
    bvals = btable[:, 0]
    bvecs = btable[:, 1:]
    gtab = gradient_table(bvals, bvecs)
    data, golden_directions = SticksAndBall(gtab,
                                            d=0.0015,
                                            S0=100,
                                            angles=[(0, 0), (90, 0)],
                                            fractions=[50, 50],
                                            snr=None)
    gq = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=1.4)

    #symmetric724
    gqfit = gq.fit(data)
    odf = gqfit.odf(sphere)
    directions, values, indices = peak_directions(odf, sphere, .35, 25)
    assert_equal(len(directions), 2)
    assert_almost_equal(angular_similarity(directions, golden_directions), 2,
                        1)

    #5 subdivisions
    gqfit = gq.fit(data)
    odf2 = gqfit.odf(sphere2)
    directions, values, indices = peak_directions(odf2, 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]
        odf = gq.fit(data).odf(sphere2)
        directions, values, indices = 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)
Exemple #5
0
data.shape ``(96, 96, 60, 203)``

This dataset has anisotropic voxel sizes, therefore reslicing is necessary.
"""

affine = img.affine
"""
Read the voxel size from the image header.
"""

voxel_size = img.header.get_zooms()[:3]
"""
Instantiate the model and apply it to the data.
"""

gqmodel = GeneralizedQSamplingModel(gtab, sampling_length=3)
"""
The parameter ``sampling_length`` is used here to

Lets just use one slice only from the data.
"""

dataslice = data[:, :, data.shape[2] // 2]

mask = dataslice[..., 0] > 50

gqfit = gqmodel.fit(dataslice, mask=mask)
"""
Load an ODF reconstruction sphere
"""
def dmri_recon(sid,
               data_dir,
               out_dir,
               resolution,
               recon='csd',
               dirs='',
               num_threads=2):
    import tempfile
    #tempfile.tempdir = '/om/scratch/Fri/ksitek/'

    import os
    oldval = None
    if 'MKL_NUM_THREADS' in os.environ:
        oldval = os.environ['MKL_NUM_THREADS']
    os.environ['MKL_NUM_THREADS'] = '%d' % num_threads
    ompoldval = None
    if 'OMP_NUM_THREADS' in os.environ:
        ompoldval = os.environ['OMP_NUM_THREADS']
    os.environ['OMP_NUM_THREADS'] = '%d' % num_threads
    import nibabel as nib
    import numpy as np
    from glob import glob

    if resolution == '0.2mm':
        filename = 'Reg_S64550_nii4d.nii'
        #filename = 'angular_resample/dwi_%s.nii.gz'%dirs
        fimg = os.path.abspath(glob(os.path.join(data_dir, filename))[0])
    else:
        filename = 'Reg_S64550_nii4d_resamp-%s.nii.gz' % (resolution)
        fimg = os.path.abspath(
            glob(os.path.join(data_dir, 'resample', filename))[0])
    print("dwi file = %s" % fimg)
    fbval = os.path.abspath(
        glob(os.path.join(data_dir, 'bvecs', 'camino_120_RAS.bvals'))[0])
    print("bval file = %s" % fbval)
    fbvec = os.path.abspath(
        glob(os.path.join(data_dir, 'bvecs',
                          'camino_120_RAS_flipped-xy.bvecs'))[0])
    #                                          'angular_resample',
    #                                          'dwi_%s.bvecs'%dirs))[0])
    print("bvec file = %s" % fbvec)
    img = nib.load(fimg)
    data = img.get_fdata()

    affine = img.get_affine()

    prefix = sid

    from dipy.io import read_bvals_bvecs
    bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
    '''
    from dipy.core.gradients import vector_norm
    b0idx = []
    for idx, val in enumerate(bvals):
        if val < 1:
            pass
            #bvecs[idx] = [1, 0, 0]
        else:
            b0idx.append(idx)
            #print "b0idx=%d"%idx
    #print "input bvecs:"
    #print bvecs
    bvecs[b0idx, :] = bvecs[b0idx, :]/vector_norm(bvecs[b0idx])[:, None]
    #print "bvecs after normalization:"
    #print bvecs
    '''

    from dipy.core.gradients import gradient_table
    gtab = gradient_table(bvals, bvecs)
    gtab.bvecs.shape == bvecs.shape
    gtab.bvecs
    gtab.bvals.shape == bvals.shape
    gtab.bvals

    #from dipy.segment.mask import median_otsu
    #b0_mask, mask = median_otsu(data[:, :, :, b0idx].mean(axis=3).squeeze(), 4, 4)

    if resolution == '0.2mm':
        mask_name = 'Reg_S64550_nii_b0-slice_mask.nii.gz'
        fmask1 = os.path.join(data_dir, mask_name)
    else:
        mask_name = 'Reg_S64550_nii_b0-slice_mask_resamp-%s.nii.gz' % (
            resolution)
        fmask1 = os.path.join(data_dir, 'resample', mask_name)
    print("fmask file = %s" % fmask1)
    mask = nib.load(fmask1).get_fdata()
    ''' DTI model & save metrics '''
    from dipy.reconst.dti import TensorModel
    print("running tensor model")
    tenmodel = TensorModel(gtab)
    tenfit = tenmodel.fit(data, mask)

    from dipy.reconst.dti import fractional_anisotropy
    print("running FA")
    FA = fractional_anisotropy(tenfit.evals)
    FA[np.isnan(FA)] = 0
    fa_img = nib.Nifti1Image(FA, img.get_affine())
    tensor_fa_file = os.path.abspath('%s_tensor_fa.nii.gz' % (prefix))
    nib.save(fa_img, tensor_fa_file)

    from dipy.reconst.dti import axial_diffusivity
    print("running AD")
    AD = axial_diffusivity(tenfit.evals)
    AD[np.isnan(AD)] = 0
    ad_img = nib.Nifti1Image(AD, img.get_affine())
    tensor_ad_file = os.path.abspath('%s_tensor_ad.nii.gz' % (prefix))
    nib.save(ad_img, tensor_ad_file)

    from dipy.reconst.dti import radial_diffusivity
    print("running RD")
    RD = radial_diffusivity(tenfit.evals)
    RD[np.isnan(RD)] = 0
    rd_img = nib.Nifti1Image(RD, img.get_affine())
    tensor_rd_file = os.path.abspath('%s_tensor_rd.nii.gz' % (prefix))
    nib.save(rd_img, tensor_rd_file)

    from dipy.reconst.dti import mean_diffusivity
    print("running MD")
    MD = mean_diffusivity(tenfit.evals)
    MD[np.isnan(MD)] = 0
    md_img = nib.Nifti1Image(MD, img.get_affine())
    tensor_md_file = os.path.abspath('%s_tensor_md.nii.gz' % (prefix))
    nib.save(md_img, tensor_md_file)

    evecs = tenfit.evecs
    evec_img = nib.Nifti1Image(evecs, img.get_affine())
    tensor_evec_file = os.path.abspath('%s_tensor_evec.nii.gz' % (prefix))
    nib.save(evec_img, tensor_evec_file)
    ''' ODF model '''
    useFA = True
    print("creating %s model" % recon)
    if recon == 'csd':
        from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
        from dipy.reconst.csdeconv import auto_response
        response, ratio = auto_response(gtab, data, roi_radius=10,
                                        fa_thr=0.5)  # 0.7

        model = ConstrainedSphericalDeconvModel(gtab, response)
        useFA = True
        return_sh = True
    elif recon == 'csa':
        from dipy.reconst.shm import CsaOdfModel, normalize_data
        model = CsaOdfModel(gtab, sh_order=8)
        useFA = True
        return_sh = True
    elif recon == 'gqi':
        from dipy.reconst.gqi import GeneralizedQSamplingModel
        model = GeneralizedQSamplingModel(gtab)
        return_sh = False
    else:
        raise ValueError('only csd, csa supported currently')
        from dipy.reconst.dsi import (DiffusionSpectrumDeconvModel,
                                      DiffusionSpectrumModel)
        model = DiffusionSpectrumDeconvModel(gtab)
    '''reconstruct ODFs'''
    from dipy.data import get_sphere
    sphere = get_sphere('symmetric724')
    #odfs = fit.odf(sphere)

    # with CSD/GQI, uses > 50GB per core; don't get greedy with cores!
    from dipy.reconst.peaks import peaks_from_model
    print("running peaks_from_model")
    peaks = peaks_from_model(
        model=model,
        data=data,
        sphere=sphere,
        mask=mask,
        return_sh=return_sh,
        return_odf=False,
        normalize_peaks=True,
        npeaks=5,
        relative_peak_threshold=.5,
        min_separation_angle=10,  #25,
        parallel=num_threads > 1,
        nbr_processes=num_threads)

    # save the peaks
    from dipy.io.peaks import save_peaks
    peaks_file = os.path.abspath('%s_peaks.pam5' % (prefix))
    save_peaks(peaks_file, peaks)

    # save the spherical harmonics
    shm_coeff_file = os.path.abspath('%s_shm_coeff.nii.gz' % (prefix))
    if return_sh:
        shm_coeff = peaks.shm_coeff
        nib.save(nib.Nifti1Image(shm_coeff, img.get_affine()), shm_coeff_file)
    else:
        # if it's not a spherical model, output it as an essentially null file
        np.savetxt(shm_coeff_file, [0])

    # save the generalized fractional anisotropy image
    gfa_img = nib.Nifti1Image(peaks.gfa, img.get_affine())
    model_gfa_file = os.path.abspath('%s_%s_gfa.nii.gz' % (prefix, recon))
    nib.save(gfa_img, model_gfa_file)

    #from dipy.reconst.dti import quantize_evecs
    #peak_indices = quantize_evecs(tenfit.evecs, sphere.vertices)
    #eu = EuDX(FA, peak_indices, odf_vertices = sphere.vertices,
    #a_low=0.2, seeds=10**6, ang_thr=35)
    ''' probabilistic tracking '''
    '''
    from dipy.direction import ProbabilisticDirectionGetter
    from dipy.tracking.local import LocalTracking
    from dipy.tracking.streamline import Streamlines
    from dipy.io.streamline import save_trk

    prob_dg = ProbabilisticDirectionGetter.from_shcoeff(shm_coeff,
                                                        max_angle=45.,
                                                        sphere=sphere)
    streamlines_generator = LocalTracking(prob_dg,
                                          affine,
                                          step_size=.5,
                                          max_cross=1)

    # Generate streamlines object
    streamlines = Streamlines(streamlines_generator)

    affine = img.get_affine()
    vox_size=fa_img.get_header().get_zooms()[:3]

    fname = os.path.abspath('%s_%s_prob_streamline.trk' % (prefix, recon))
    save_trk(fname, streamlines, affine, vox_size=vox_size)
    '''
    ''' deterministic tracking with EuDX method'''
    from dipy.tracking.eudx import EuDX
    print("reconstructing with EuDX")
    if useFA:
        eu = EuDX(
            FA,
            peaks.peak_indices[..., 0],
            odf_vertices=sphere.vertices,
            a_low=0.001,  # default is 0.0239
            seeds=10**6,
            ang_thr=75)
    else:
        eu = EuDX(
            peaks.gfa,
            peaks.peak_indices[..., 0],
            odf_vertices=sphere.vertices,
            #a_low=0.1,
            seeds=10**6,
            ang_thr=45)

    sl_fname = os.path.abspath('%s_%s_det_streamline.trk' % (prefix, recon))

    # trying new dipy.io.streamline module, per email to neuroimaging list
    # 2018.04.05
    from nibabel.streamlines import Field
    from nibabel.orientations import aff2axcodes
    affine = img.get_affine()
    vox_size = fa_img.get_header().get_zooms()[:3]
    fov_shape = FA.shape[:3]

    if vox_size is not None and fov_shape is not None:
        hdr = {}
        hdr[Field.VOXEL_TO_RASMM] = affine.copy()
        hdr[Field.VOXEL_SIZES] = vox_size
        hdr[Field.DIMENSIONS] = fov_shape
        hdr[Field.VOXEL_ORDER] = "".join(aff2axcodes(affine))

    tractogram = nib.streamlines.Tractogram(eu)
    tractogram.affine_to_rasmm = affine
    trk_file = nib.streamlines.TrkFile(tractogram, header=hdr)
    nib.streamlines.save(trk_file, sl_fname)

    if oldval:
        os.environ['MKL_NUM_THREADS'] = oldval
    else:
        del os.environ['MKL_NUM_THREADS']
    if ompoldval:
        os.environ['OMP_NUM_THREADS'] = ompoldval
    else:
        del os.environ['OMP_NUM_THREADS']

    print('all output files created')

    return (tensor_fa_file, tensor_evec_file, model_gfa_file, sl_fname, affine,
            tensor_ad_file, tensor_rd_file, tensor_md_file, shm_coeff_file,
            peaks_file)
Exemple #7
0
def test_gqi():

    #load odf sphere
    vertices, faces = sphere_vf_from('symmetric724')
    edges = unique_edges(faces)
    half_vertices, half_edges, half_faces = reduce_antipodal(vertices, faces)

    #load bvals and gradients
    btable = np.loadtxt(get_data('dsi515btable'))
    bvals = btable[:, 0]
    bvecs = btable[:, 1:]
    S, stics = SticksAndBall(bvals,
                             bvecs,
                             d=0.0015,
                             S0=100,
                             angles=[(0, 0), (90, 0), (90, 90)],
                             fractions=[50, 50, 0],
                             snr=None)
    #pdf0,odf0,peaks0=standard_dsi_algorithm(S,bvals,bvecs)
    S2 = S.copy()
    S2 = S2.reshape(1, len(S))

    odf_sphere = (vertices, faces)
    ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere)
    dsfit = ds.fit(S)
    assert_equal((dsfit.peak_values > 0).sum(), 3)

    #change thresholds
    ds.relative_peak_threshold = 0.5
    ds.angular_distance_threshold = 30
    dsfit = ds.fit(S)
    assert_equal((dsfit.peak_values > 0).sum(), 2)

    #1 fiber
    S, stics = SticksAndBall(bvals,
                             bvecs,
                             d=0.0015,
                             S0=100,
                             angles=[(0, 0), (90, 0), (90, 90)],
                             fractions=[100, 0, 0],
                             snr=None)
    ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere)
    ds.relative_peak_threshold = 0.5
    ds.angular_distance_threshold = 20
    dsfit = ds.fit(S)
    QA = dsfit.qa
    #1/0
    assert_equal(np.sum(QA > 0), 1)

    #2 fibers
    S, stics = SticksAndBall(bvals,
                             bvecs,
                             d=0.0015,
                             S0=100,
                             angles=[(0, 0), (90, 0), (90, 90)],
                             fractions=[50, 50, 0],
                             snr=None)
    ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere)
    ds.relative_peak_threshold = 0.5
    ds.angular_distance_threshold = 20
    dsfit = ds.fit(S)
    QA = dsfit.qa
    assert_equal(np.sum(QA > 0), 2)

    #3 fibers
    S, stics = SticksAndBall(bvals,
                             bvecs,
                             d=0.0015,
                             S0=100,
                             angles=[(0, 0), (90, 0), (90, 90)],
                             fractions=[33, 33, 33],
                             snr=None)
    ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere)
    ds.relative_peak_threshold = 0.5
    dsfit = ds.fit(S)
    QA = dsfit.qa
    assert_equal(np.sum(QA > 0), 3)

    #isotropic
    S, stics = SticksAndBall(bvals,
                             bvecs,
                             d=0.0015,
                             S0=100,
                             angles=[(0, 0), (90, 0), (90, 90)],
                             fractions=[0, 0, 0],
                             snr=None)
    ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere)
    dsfit = ds.fit(S)
    QA = dsfit.qa
    assert_equal(np.sum(QA > 0), 0)

    #3 fibers DSI2
    S, stics = SticksAndBall(bvals,
                             bvecs,
                             d=0.0015,
                             S0=100,
                             angles=[(0, 0), (90, 0), (90, 90)],
                             fractions=[33, 33, 33],
                             snr=None)
    ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere, squared=True)
    ds.relative_peak_threshold = 0.5
    dsfit = ds.fit(S, gfa_thr=0.05)
    QA = dsfit.qa

    #3 fibers DSI2 with a 3D volume
    data = np.zeros((3, 3, 3, len(S)))
    data[..., :] = S.copy()
    dsfit = ds.fit(data, gfa_thr=0.05)
    #1/0
    assert_array_almost_equal(np.sum(dsfit.peak_values > 0, axis=-1),
                              3 * np.ones((3, 3, 3)))