예제 #1
0
def test_eudx_bad_seed():
    """Test passing a bad seed to eudx"""
    fimg, fbvals, fbvecs = get_data('small_101D')

    img = ni.load(fimg)
    affine = img.get_affine()
    data = img.get_data()
    gtab = gradient_table(fbvals, fbvecs)
    tensor_model = TensorModel(gtab)
    ten = tensor_model.fit(data)
    ind = quantize_evecs(ten.evecs)

    sphere = get_sphere('symmetric724')
    seed = [1000000., 1000000., 1000000.]
    eu = EuDX(a=ten.fa, ind=ind, seeds=[seed],
              odf_vertices=sphere.vertices, a_low=.2)
    assert_raises(ValueError, list, eu)

    print(data.shape)
    seed = [1., 5., 8.]
    eu = EuDX(a=ten.fa, ind=ind, seeds=[seed],
              odf_vertices=sphere.vertices, a_low=.2)
    track = list(eu)

    seed = [-1., 1000000., 1000000.]
    eu = EuDX(a=ten.fa, ind=ind, seeds=[seed],
              odf_vertices=sphere.vertices, a_low=.2)
    assert_raises(ValueError, list, eu)
예제 #2
0
def test_eudx_further():
    """ Cause we love testin.. ;-)
    """

    fimg,fbvals,fbvecs=get_data('small_101D')

    img=ni.load(fimg)
    affine=img.get_affine()
    data=img.get_data()
    gtab = gradient_table(fbvals, fbvecs)
    tensor_model = TensorModel(gtab)
    ten = tensor_model.fit(data)
    x,y,z=data.shape[:3]
    seeds=np.zeros((10**4,3))
    for i in range(10**4):
        rx=(x-1)*np.random.rand()
        ry=(y-1)*np.random.rand()
        rz=(z-1)*np.random.rand()
        seeds[i]=np.ascontiguousarray(np.array([rx,ry,rz]),dtype=np.float64)

    sphere = get_sphere('symmetric724')

    ind = quantize_evecs(ten.evecs)
    eu=EuDX(a=ten.fa, ind=ind, seeds=seeds,
            odf_vertices=sphere.vertices, a_low=.2)
    T=[e for e in eu]

    #check that there are no negative elements
    for t in T:
        assert_equal(np.sum(t.ravel()<0),0)

    # Test eudx with affine
    def random_affine(seeds):
        affine = np.eye(4)
        affine[:3, :] = np.random.random((3, 4))
        seeds = np.dot(seeds, affine[:3, :3].T)
        seeds += affine[:3, 3]
        return affine, seeds

    # Make two random affines and move seeds
    affine1, seeds1 = random_affine(seeds)
    affine2, seeds2 = random_affine(seeds)

    # Make tracks using different affines
    eu1 = EuDX(a=ten.fa, ind=ind, odf_vertices=sphere.vertices,
               seeds=seeds1, a_low=.2, affine=affine1)
    eu2 = EuDX(a=ten.fa, ind=ind, odf_vertices=sphere.vertices,
               seeds=seeds2, a_low=.2, affine=affine2)

    # Move from eu2 affine2 to affine1
    eu2_to_eu1 = utils.move_streamlines(eu2, output_space=affine1,
                                        input_space=affine2)
    # Check that the tracks are the same
    for sl1, sl2 in zip(eu1, eu2_to_eu1):
        assert_array_almost_equal(sl1, sl2)
예제 #3
0
def test_eudx_further():
    """ Cause we love testin.. ;-)
    """

    fimg,fbvals,fbvecs=get_data('small_101D')

    img=ni.load(fimg)
    affine=img.get_affine()
    data=img.get_data()
    gtab = gradient_table(fbvals, fbvecs)
    tensor_model = TensorModel(gtab)
    ten = tensor_model.fit(data)
    x,y,z=data.shape[:3]
    seeds=np.zeros((10**4,3))
    for i in range(10**4):
        rx=(x-1)*np.random.rand()
        ry=(y-1)*np.random.rand()
        rz=(z-1)*np.random.rand()            
        seeds[i]=np.ascontiguousarray(np.array([rx,ry,rz]),dtype=np.float64)
    
    #print seeds
    #"""
    ind = quantize_evecs(ten.evecs)
    eu=EuDX(a=ten.fa, ind=ind, seeds=seeds, a_low=.2)
    T=[e for e in eu]
    
    #check that there are no negative elements
    for t in T:
        assert_equal(np.sum(t.ravel()<0),0)
예제 #4
0
파일: track.py 프로젝트: wrgr/ndmg
    def fibers_eudx(self, stopping_values, peak_indices, seeds, odf_vertices,
                    cutoff):
        # WGR:TODO figure out how to organize tensor options and formats
        # WGR:TODO figure out how to deal with files on disk vs. in workspace
        """
        Tensors are used to construct fibers

        **Positional Arguments:**

                dti_vol:
                    - Registered DTI volume, from workspace.
                atlas_file:
                    - File containing an atlas (or brain mask).
                gtab:
                    - Structure containing dipy formatted bval/bvec information
        """

        streamline_generator = EuDX(stopping_values,
                                    csd_peaks.peak_indices,
                                    seeds=10**6,
                                    odf_vertices=sphere.vertices,
                                    a_low=0.1)

        streamlines = [streamline for streamline in streamline_generator]

        return streamlines
예제 #5
0
def tensorTractography(tenfit, img, falow=0.3):
    fa = tenfit.fa
    fa[np.isnan(fa)] = 0
    evecs = tenfit.evecs
    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = img.get_header().get_zooms()[:3]
    hdr['voxel_order'] = 'LAS'
    hdr['dim'] = fa.shape

    from dipy.data import get_sphere  #EuDX needs to map voxel dirs on a sphere
    sphere = get_sphere('symmetric724')
    from dipy.reconst.dti import quantize_evecs
    peak_indices = quantize_evecs(evecs, sphere.vertices)

    from dipy.tracking.eudx import EuDX
    eu = EuDX(fa,
              peak_indices,
              odf_vertices=sphere.vertices,
              a_low=falow,
              ang_thr=30.0)
    tensor_streamlines = [streamline for streamline in eu]

    tensor_streamlines_trk = ((sl, None, None) for sl in tensor_streamlines)
    ten_sl_fname = 'tensor_streamlines_tests.trk'
    nib.trackvis.write(ten_sl_fname,
                       tensor_streamlines_trk,
                       hdr,
                       points_space='voxel')
예제 #6
0
def test_eudx_boundaries():
    """
    This test checks that the tracking will exclude seeds in both directions.
    Here we create a volume of shape (50, 60, 40) and we will add 2 seeds
    exactly at the volume's boundaries (49, 0, 0) and (0, 0, 0). Those should
    not generate any streamlines as EuDX does not interpolate on the boundary
    voxels. We also add 3 seeds not in the boundaries which should generate
    streamlines without a problem.
    """

    fa = np.ones((50, 60, 40))
    ind = np.zeros(fa.shape)
    sphere = get_sphere('repulsion724')

    seed = [49., 0, 0]
    seed2 = [0., 0, 0]
    seed3 = [48., 0, 0]
    seed4 = [1., 0, 0]
    seed5 = [5., 5, 5]

    eu = EuDX(a=fa,
              ind=ind,
              seeds=[seed, seed2, seed3, seed4, seed5],
              odf_vertices=sphere.vertices,
              a_low=.2,
              total_weight=0.)
    track = list(eu)

    assert_equal(len(track), 3)
예제 #7
0
def tracking_eudx(dir_src, dir_out, verbose=False):

    # Loading FA and evecs data
    fa_name = 'data_' + par_b_tag + '_' + par_dim_tag + '_FA.nii.gz'
    FA, affine = load_nifti(pjoin(dir_src, fa_name), verbose)

    evecs_name = 'data_' + par_b_tag + '_' + par_dim_tag + '_EV.nii.gz'
    evecs, _ = load_nifti(pjoin(dir_src, evecs_name), verbose)

    # Computation of streamlines
    sphere = get_sphere('symmetric724')
    peak_indices = quantize_evecs(evecs, sphere.vertices)
    streamlines = EuDX(FA.astype('f8'),
                       ind=peak_indices,
                       seeds=par_eudx_seeds,
                       odf_vertices=sphere.vertices,
                       a_low=par_eudx_threshold)

    # Saving tractography
    voxel_size = (par_dim_vox, ) * 3
    dims = FA.shape[:3]
    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = voxel_size
    hdr['voxel_order'] = 'LAS'
    hdr['dim'] = dims
    hdr['vox_to_ras'] = affine
    strm = ((sl, None, None) for sl in streamlines)
    trk_name = 'tractogram_' + par_b_tag + '_' + par_dim_tag + '_' + par_rec_tag + '_' + par_eudx_tag + '.trk'
    trk_out = os.path.join(dir_out, trk_name)
    nib.trackvis.write(trk_out, strm, hdr, points_space='voxel')
예제 #8
0
def uniform_seed_grid():

    #read bvals,gradients and data   
    fimg,fbvals, fbvecs = get_data('small_64D')    
    bvals=np.load(fbvals)
    gradients=np.load(fbvecs)
    img =ni.load(fimg)    
    data=img.get_data()
    
    x,y,z,g=data.shape   

    M=np.mgrid[.5:x-.5:np.complex(0,x),.5:y-.5:np.complex(0,y),.5:z-.5:np.complex(0,z)]
    M=M.reshape(3,x*y*z).T

    print(M.shape)
    print(M.dtype)

    for m in M: 
        print(m)
    gqs = GeneralizedQSampling(data,bvals,gradients)
    iT=iter(EuDX(gqs.QA,gqs.IN,seeds=M))    
    T=[]
    for t in iT:
        T.append(i)
    
    print('lenT',len(T))
    assert_equal(len(T), 1221)
예제 #9
0
def track_eudx_work(trackmodel):
    ten = trackmodel.ten
    ind = trackmodel.ind
    sphere = trackmodel.sphere
    eu = EuDX(a=ten.fa,
              ind=ind,
              seeds=10**5 * 5,
              odf_vertices=sphere.vertices,
              a_low=0.2)
    tracks = [e for e in eu]
    return tracks
예제 #10
0
def fiber_tracking(peaks, mask):
    print "Start Fibertracking"
    seeds = utils.seeds_from_mask(mask, density=[2, 2, 2])
    streamline_generator = EuDX(peaks.peak_values,
                                peaks.peak_indices,
                                odf_vertices=peaks.sphere.vertices,
                                a_low=.05,
                                step_sz=.5,
                                seeds=seeds)
    streamlines = list(streamline_generator)
    return streamlines
def tractography(img, gtab, mask, dwi_dir, do_viz=True):
    data = img.get_data()
    # dirty imputation
    data[np.isnan(data)] = 0
    # Diffusion model
    csd_model = ConstrainedSphericalDeconvModel(gtab, response=None)

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

    # FA values to stop the tractography
    tensor_model = TensorModel(gtab, fit_method='WLS')
    tensor_fit = tensor_model.fit(data, mask)
    fa = fractional_anisotropy(tensor_fit.evals)
    stopping_values = np.zeros(csd_peaks.peak_values.shape)
    stopping_values[:] = fa[..., None]

    # tractography
    streamline_generator = EuDX(stopping_values,
                                csd_peaks.peak_indices,
                                seeds=10**6,
                                odf_vertices=sphere.vertices,
                                a_low=0.1)

    streamlines = [streamline for streamline in streamline_generator]
    streamlines = filter_according_to_length(streamlines)
    np.savez(os.path.join(dwi_dir, 'streamlines.npz'), streamlines)

    #  write the result as images
    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = img.header.get_zooms()[:3]
    hdr['voxel_order'] = 'LAS'
    hdr['dim'] = fa.shape[:3]

    csd_streamlines_trk = ((sl, None, None) for sl in streamlines)
    csd_sl_fname = os.path.join(dwi_dir, 'csd_streamline.trk')
    nib.trackvis.write(csd_sl_fname,
                       csd_streamlines_trk,
                       hdr,
                       points_space='voxel')
    fa_image = os.path.join(dwi_dir, 'fa_map.nii.gz')
    nib.save(nib.Nifti1Image(fa, img.affine), fa_image)
    if 1:
        visualization(os.path.join(dwi_dir, 'streamlines.npz'))

    return streamlines
예제 #12
0
def tracking_eudx4csd(dir_src, dir_out, verbose=False):

    # Load data
    fbval = pjoin(dir_src, 'bvals_' + par_b_tag)
    fbvec = pjoin(dir_src, 'bvecs_' + par_b_tag)
    fdwi = pjoin(dir_src, 'data_' + par_b_tag + '_' + par_dim_tag + '.nii.gz')
    #fmask = pjoin(dir_src, 'nodif_brain_mask_' + par_dim_tag + '.nii.gz')
    fmask = pjoin(dir_src,
                  'wm_mask_' + par_b_tag + '_' + par_dim_tag + '.nii.gz')

    bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
    gtab = gradient_table(bvals, bvecs, b0_threshold=par_b0_threshold)
    data, affine = load_nifti(fdwi, verbose)
    mask, _ = load_nifti(fmask, verbose)

    sphere = get_sphere('symmetric724')

    response, ratio = auto_response(gtab,
                                    data,
                                    roi_radius=par_ar_radius,
                                    fa_thr=par_ar_fa_th)
    # print('Response function', response)

    # Model fitting
    csd_model = ConstrainedSphericalDeconvModel(gtab, response)
    csd_peaks = peaks_from_model(csd_model,
                                 data,
                                 sphere,
                                 relative_peak_threshold=.5,
                                 min_separation_angle=25,
                                 parallel=False)

    # Computation of streamlines
    streamlines = EuDX(csd_peaks.peak_values,
                       csd_peaks.peak_indices,
                       seeds=par_eudx_seeds,
                       odf_vertices=sphere.vertices,
                       a_low=par_eudx_threshold)

    # Saving tractography
    voxel_size = (par_dim_vox, ) * 3
    dims = mask.shape[:3]
    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = voxel_size
    hdr['voxel_order'] = 'LAS'
    hdr['dim'] = dims
    hdr['vox_to_ras'] = affine
    strm = ((sl, None, None) for sl in streamlines)
    trk_name = 'tractogram_' + par_b_tag + '_' + par_dim_tag + '_' + par_csd_tag + '_' + par_eudx_tag + '.trk'
    trk_out = os.path.join(dir_out, trk_name)
    nib.trackvis.write(trk_out, strm, hdr, points_space='voxel')
예제 #13
0
def DTImaps(ImgPath, Bvalpath, Bvecpath, tracto=True):
    data, affine = resli(ImgPath)
    data = Nonlocal(data, affine)
    b0_mask, mask = otsu(data, affine)  #maask binary
    evals, evecs = DTImodel(b0_mask, affine, mask, gtab(Bvalpath, Bvecpath))
    print('--> Calculando el mapa de anisotropia fraccional')
    FA = fractional_anisotropy(evals)
    FA[np.isnan(FA)] = 0
    nib.save(nib.Nifti1Image(FA.astype(np.float32), affine),
             "Mapa_anisotropia_fraccional")
    print('--> Calculando el mapa de anisotropia fraccional RGB')
    FA2 = np.clip(FA, 0, 1)
    RGB = color_fa(FA2, evecs)
    nib.save(nib.Nifti1Image(np.array(255 * RGB, 'uint8'), affine),
             "Mapa_anisotropia_fraccional RGB")
    print('--> Calculando el mapa de difusividad media')
    MD1 = dti.mean_diffusivity(evals)
    nib.save(nib.Nifti1Image(MD1.astype(np.float32), affine),
             "Mapa_difusividad_media")
    if tracto:
        sphere = get_sphere('symmetric724')
        peak_indices = quantize_evecs(evecs, sphere.vertices)

        eu = EuDX(FA.astype('f8'),
                  peak_indices,
                  seeds=500000,
                  odf_vertices=sphere.vertices,
                  a_low=0.15)
        tensor_streamlines = [streamline for streamline in eu]
        new_vox_sz = (2., 2., 2.)
        hdr = nib.trackvis.empty_header()
        hdr['voxel_size'] = new_vox_sz
        hdr['voxel_order'] = 'LAS'
        hdr['dim'] = FA.shape

        tensor_streamlines_trk = ((sl, None, None)
                                  for sl in tensor_streamlines)
        ten_sl_fname = "Tracto.trk"
        nib.trackvis.write(ten_sl_fname,
                           tensor_streamlines_trk,
                           hdr,
                           points_space='voxel')
    return FA
예제 #14
0
def compute_tracking(src_dti_dir, out_trk_dir, subj_name):

    # Loading FA and evecs data
    src_fa_file = os.path.join(src_dti_dir, subj_name + par_fa_suffix)
    fa_img = nib.load(src_fa_file)
    FA = fa_img.get_data()

    src_evecs_file = os.path.join(src_dti_dir, subj_name + par_evecs_suffix)
    evecs_img = nib.load(src_evecs_file)
    evecs = evecs_img.get_data()

    # Computation of streamlines
    sphere = get_sphere('symmetric724')
    peak_indices = dti.quantize_evecs(evecs, sphere.vertices)
    streamlines = EuDX(FA.astype('f8'),
                       ind=peak_indices,
                       seeds=par_eudx_seeds,
                       odf_vertices=sphere.vertices,
                       a_low=par_eudx_threshold)

    # Saving tractography
    voxel_size = fa_img.get_header().get_zooms()[:3]
    dims = FA.shape[:3]
    seed = par_eudx_seeds
    seed = "_%d%s" % (seed / 10**6 if seed > 10**5 else seed / 10**3,
                      'K' if seed < 1000000 else 'M')

    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = voxel_size
    hdr['voxel_order'] = 'LAS'
    hdr['dim'] = dims
    strm = ((sl, None, None) for sl in streamlines
            if length(sl) > par_trk_min and length(sl) < par_trk_max)
    out_trk_file = os.path.join(out_trk_dir, subj_name + seed + par_trk_suffix)
    nib.trackvis.write(out_trk_file, strm, hdr, points_space='voxel')

    tracks = [track for track in streamlines]
    out_dipy_file = os.path.join(out_trk_dir,
                                 subj_name + seed + par_dipy_suffix)
    dpw = Dpy(out_dipy_file, 'w')
    dpw.write_tracks(tracks)
    dpw.close()
예제 #15
0
    def eudx_basic(self, dti_file, mask_file, gtab, stop_val=0.1):
        """
        Tracking with basic tensors and basic eudx - experimental
        We now force seeding at every voxel in the provided mask for
        simplicity.  Future functionality will extend these options.
        **Positional Arguments:**

                dti_file:
                    - File (registered) to use for tensor/fiber tracking
                mask_file:
                    - Brain mask to keep tensors inside the brain
                gtab:
                    - dipy formatted bval/bvec Structure

        **Optional Arguments:**
                stop_val:
                    - Value to cutoff fiber track
        """

        img = nb.load(dti_file)
        data = img.get_data()

        img = nb.load(mask_file)

        mask = img.get_data()

        # use all points in mask
        seedIdx = np.where(mask > 0)  # seed everywhere not equal to zero
        seedIdx = np.transpose(seedIdx)

        model = TensorModel(gtab)
        ten = model.fit(data, mask)
        sphere = get_sphere('symmetric724')
        ind = quantize_evecs(ten.evecs, sphere.vertices)
        eu = EuDX(a=ten.fa,
                  ind=ind,
                  seeds=seedIdx,
                  odf_vertices=sphere.vertices,
                  a_low=stop_val)
        tracks = [e for e in eu]
        return (ten, tracks)
예제 #16
0
model that is a child of OdfModel.

"""

from reconst_csa import csapeaks, sphere
"""
This time we will not use FA as input to EuDX but we will use GFA (generalized FA),
which is more suited for ODF functions. Tracking will stop when GFA is less
than 0.2.
"""

from dipy.tracking.eudx import EuDX

eu = EuDX(csapeaks.gfa,
          csapeaks.peak_indices[..., 0],
          seeds=10000,
          odf_vertices=sphere.vertices,
          a_low=0.2)

csa_streamlines = [streamline for streamline in eu]
"""
Now that we have our streamlines in memory we can save the results on the disk.
For this purpose we can use the TrackVis format (``*.trk``). First, we need to
create a header.
"""

import nibabel as nib

hdr = nib.trackvis.empty_header()
hdr['voxel_size'] = (2., 2., 2.)
hdr['voxel_order'] = 'LAS'
예제 #17
0
def run_to_estimate_dti_maps(path_input,
                             path_output,
                             file_tensor_fitevals="",
                             file_tensor_fitevecs="",
                             fbval="",
                             fbvec=""):
    folder = os.path.dirname(path_input)
    if fbval == "" or fbvec == "":
        folder_sujeto = path_output
        for l in os.listdir(folder_sujeto):
            if "TENSOR" in l and "bval" in l:
                fbval = os.path.join(folder_sujeto, l)
            if "TENSOR" in l and "bvec" in l:
                fbvec = os.path.join(folder_sujeto, l)

    if file_tensor_fitevals == "" or file_tensor_fitevecs == "":

        for i in os.listdir(folder):
            if "DTIEvals" in i:
                file_tensor_fitevals = os.path.join(folder, i)

        for i in os.listdir(folder):
            if "DTIEvecs" in i:
                file_tensor_fitevecs = os.path.join(folder, i)

    if not os.path.exists(os.path.join(folder, "list_maps.txt")):

        # def to_estimate_dti_maps(path_dwi_input, path_output, file_tensor_fitevecs, file_tensor_fitevals):
        ref_name_only = utils.to_extract_filename(file_tensor_fitevecs)
        ref_name_only = ref_name_only[:-9]

        list_maps = []

        img_tensorFitevecs = nib.load(file_tensor_fitevecs)
        img_tensorFitevals = nib.load(file_tensor_fitevals)

        evecs = img_tensorFitevecs.get_data()
        evals = img_tensorFitevals.get_data()

        affine = img_tensorFitevecs.affine

        print(d.separador + d.separador + 'computing of FA map')
        FA = fractional_anisotropy(evals)
        FA[np.isnan(FA)] = 0
        nib.save(
            nib.Nifti1Image(FA.astype(np.float32), affine),
            os.path.join(path_output, ref_name_only + '_FA' + d.extension))

        list_maps.append(
            os.path.join(path_output, ref_name_only + '_FA' + d.extension))

        print(d.separador + d.separador + 'computing of Color FA map')
        FA2 = np.clip(FA, 0, 1)
        RGB = color_fa(FA2, evecs)
        nib.save(
            nib.Nifti1Image(np.array(255 * RGB, 'uint8'), affine),
            os.path.join(path_output, ref_name_only + '_FA_RGB' + d.extension))

        print(d.separador + d.separador + 'computing of MD map')
        MD = dti.mean_diffusivity(evals)
        nib.save(
            nib.Nifti1Image(MD.astype(np.float32), affine),
            os.path.join(path_output, ref_name_only + '_MD' + d.extension))

        list_maps.append(
            os.path.join(path_output, ref_name_only + '_MD' + d.extension))

        print(d.separador + d.separador + 'computing of AD map')
        AD = dti.axial_diffusivity(evals)
        nib.save(
            nib.Nifti1Image(AD.astype(np.float32), affine),
            os.path.join(path_output, ref_name_only + '_AD' + d.extension))

        list_maps.append(
            os.path.join(path_output, ref_name_only + '_AD' + d.extension))

        print(d.separador + d.separador + 'computing of RD map')
        RD = dti.radial_diffusivity(evals)
        nib.save(
            nib.Nifti1Image(RD.astype(np.float32), affine),
            os.path.join(path_output, ref_name_only + '_RD' + d.extension))

        list_maps.append(
            os.path.join(path_output, ref_name_only + '_RD' + d.extension))

        sphere = get_sphere('symmetric724')
        peak_indices = quantize_evecs(evecs, sphere.vertices)

        eu = EuDX(FA.astype('f8'),
                  peak_indices,
                  seeds=300000,
                  odf_vertices=sphere.vertices,
                  a_low=0.15)
        tensor_streamlines = [streamline for streamline in eu]

        hdr = nib.trackvis.empty_header()
        hdr['voxel_size'] = nib.load(path_input).header.get_zooms()[:3]
        hdr['voxel_order'] = 'LAS'
        hdr['dim'] = FA.shape

        tensor_streamlines_trk = ((sl, None, None)
                                  for sl in tensor_streamlines)

        nib.trackvis.write(os.path.join(
            path_output, ref_name_only + '_tractography_EuDx.trk'),
                           tensor_streamlines_trk,
                           hdr,
                           points_space='voxel')

        print(list_maps)
        with open(os.path.join(path_output, "list_maps.txt"), "w") as f:
            for s in list_maps:
                f.write(str(s) + "\n")

    return path_input
예제 #18
0
def experiment1(f_name, data_path):
    "OUTPUT"
    f = open(f_name + '_out.txt', 'w')
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""
    """Read Data"""
    dipy_home = pjoin(os.path.expanduser('~'), '.dipy')

    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()
    print('data.shape (%d, %d, %d, %d)' % data.shape)
    print('Building DTI Model Data......')
    """Load label"""
    label_img = nib.load(flabels)
    labels = label_img.get_data()

    labelpo1 = label_position(labels, 1)
    print labelpo1
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""
    maskdata, mask = median_otsu(data,
                                 3,
                                 1,
                                 False,
                                 vol_idx=range(10, 50),
                                 dilate=2)

    from dipy.reconst.dti import TensorModel
    tenmodel = TensorModel(gtab)
    tenfit = tenmodel.fit(data, mask)

    FA = fractional_anisotropy(tenfit.evals)
    FA[np.isnan(FA)] = 0
    np.save(f_name + '_FA', FA)
    fa_img = nib.Nifti1Image(FA.astype(np.float32), img.get_affine())
    #nib.save(fa_img,f_name+'_DTI_tensor_fa.nii.gz')
    #print('Saving "DTI_tensor_fa.nii.gz" sucessful.')
    evecs_img = nib.Nifti1Image(tenfit.evecs.astype(np.float32),
                                img.get_affine())
    #nib.save(evecs_img, f_name+'_DTI_tensor_evecs.nii.gz')
    #print('Saving "DTI_tensor_evecs.nii.gz" sucessful.')
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""
    ""Fiber Tracking"""
    print('Fiber Tracking......')
    from dipy.tracking.eudx import EuDX
    from dipy.data import get_sphere

    from dipy.tracking import utils
    seeds = utils.seeds_from_mask(labels, density=3)
    print('The number of seeds is %d.' % len(seeds))

    print >> f, ('The number of seeds is %d.' % len(seeds))

    sphere = get_sphere('symmetric724')
    from dipy.reconst.dti import quantize_evecs
    evecs = evecs_img.get_data()
    peak_indices = quantize_evecs(evecs, sphere.vertices)
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""
    streamline_generator = EuDX(FA.astype('f8'),
                                peak_indices,
                                seeds=10**5,
                                odf_vertices=sphere.vertices,
                                a_low=0.2,
                                step_sz=0.5,
                                ang_thr=60.0,
                                total_weight=.5,
                                max_points=10**5)
    streamlines_all = [
        streamlines_all for streamlines_all in streamline_generator
    ]
    """""" """""" """""" """""" """"""
    """Select length bigger than 10"""
    from dipy.tracking.utils import length
    lengths = list(length(streamlines_all))
    select_length = 0
    length = len(streamlines_all)
    j = 0
    for i in range(length):
        if ((lengths[i]) > select_length):
            streamlines_all[j] = streamlines_all[i]
            j = j + 1
    j = j - 1
    streamlines = streamlines_all[0:j]

    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = img.get_header().get_zooms()[:3]
    hdr['voxel_order'] = 'LAS'
    hdr['dim'] = FA.shape[:3]
    """划出roi streamlines"""
    affine = streamline_generator.affine
    cc_streamlines = label_streamlines(streamlines, labels, 1, affine, hdr,
                                       f_name, data_path)
    #M,grouping = connective_label(cc_streamlines, labels, affine, hdr, f_name, data_path)
    label_streamlines_density(cc_streamlines, labels, affine, f_name, img,
                              label_img)
    """两个label的问题"""
    flabels2 = pjoin(folder, f_name + '22.nii-label.nii.gz')
    label_img2 = nib.load(flabels2)
    labels2 = label_img2.get_data()

    cc22_streamlines = label_streamlines(streamlines, labels2, 3, affine, hdr,
                                         f_name, data_path)
    labels3 = labels[:]
    for i in range(len(labels)):
        for j in range(len(labels[i])):
            for k in range(len(labels[i][j])):
                if (labels[i][j][k] == 0 and labels2[i][j][k] != 0):
                    labels3[i][j][k] = labels2[i][j][k]

    M, grouping = connective_label(streamlines, labels3, affine, hdr, f_name,
                                   data_path)
    print M
    print grouping[0, 3]


#experiment1('zhu long ping','patient_data')
예제 #19
0
csa_peaks = peaks_from_model(model=csa_model,
                             data=data,
                             sphere=default_sphere,
                             relative_peak_threshold=relative_peak_threshold,
                             min_separation_angle=min_separation_angle,
                             mask=mask)

#csd_peaks = peaks_from_model(model=csd_model,
#                             data=data,
#                             sphere=default_sphere,
#                             relative_peak_threshold=relative_peak_threshold,
#                             min_separation_angle=min_separation_angle,
#                             mask=mask)

streamline_eudx = EuDX(csa_peaks.peak_values, csa_peaks.peak_indices,
                            odf_vertices=default_sphere.vertices,
                            a_low=threshold_tissue_classifier, step_sz=step_size, seeds=seeds)

save(streamline_eudx, streamline_eudx.affine, mask.shape, '1.trk', lenght_threshold)

detmax_dg = DeterministicMaximumDirectionGetter.from_shcoeff(csa_peaks.shm_coeff, max_angle=max_angle, sphere=default_sphere)
tensor_model = dti.TensorModel(gtab)
dti_fit = tensor_model.fit(data, mask=mask)
FA = fractional_anisotropy(dti_fit.evals)
classifier = ThresholdTissueClassifier(FA, threshold_tissue_classifier)
streamlines_dmdg = LocalTracking(detmax_dg, classifier, seeds, affine, step_size=step_size)

save(streamlines_dmdg, streamline_eudx.affine, mask.shape, '1.trk', lenght_threshold)

classifier = ThresholdTissueClassifier(csa_peaks.gfa, threshold_tissue_classifier)
prob_dg = ProbabilisticDirectionGetter.from_shcoeff(csa_peaks.shm_coeff, max_angle=max_angle, sphere=default_sphere)
# Fit the data using created tensor model
tenfit = tenmodel.fit(data)

# Compute FA
fa = fractional_anisotropy(tenfit.evals)

# Compute spherical coordinates
sphere = get_sphere('symmetric724')  # Symmetric Sphere with 724 vertices

# Get quantize vectors
ind = quantize_evecs(tenfit.evecs, sphere.vertices)
print('ind.shape (%d, %d, %d)' % ind.shape)

# Compute Eular Delta Crossing with FA
eu = EuDX(a=fa, ind=ind, seeds=100000, odf_vertices=sphere.vertices,
          a_low=0.2)  # FA uses a_low = 0.2
streamlines = [line for line in eu]
print('Number of streamlines %i' % len(streamlines))
'''
for line in streamlines:
  print(line.shape)
'''
# Do steamline clustering using QuickBundles (QB) using Eular's Method
# dist_thr (distance threshold) which affects number of clusters and their size
# pts (number of points in each streamline) which will be used for downsampling before clustering
# Default values : dist_thr = 4 & pts = 12
qb = QuickBundles(streamlines, dist_thr=20, pts=20)
clusters = qb.clusters()
print('Number of clusters %i' % qb.total_clusters)
print('Cluster size', qb.clusters_sizes())
예제 #21
0
 **Direction Field (peaks)**

``EuDX`` [Garyfallidis12]_ is a fast algorithm that we use here to generate
streamlines. If the parameter ``seeds`` is a positive integer it will generate
that number of randomly placed seeds everywhere in the volume. Alternatively,
you can specify the exact seed points using an array (N, 3) where N is the
number of seed points. For simplicity, here we will use the first option
(random seeds). ``a_low`` is the threshold of the fist parameter
(``stopping_values``) which means that there will that tracking will stop in
regions with FA < 0.1.
"""

streamline_generator = EuDX(stopping_values,
                            csd_peaks.peak_indices,
                            seeds=10**4,
                            odf_vertices=sphere.vertices,
                            a_low=0.1)

streamlines = [streamline for streamline in streamline_generator]

"""
We can visualize the streamlines using ``fvtk.line`` or ``fvtk.streamtube``.
"""

fvtk.clear(ren)

fvtk.add(ren, fvtk.line(streamlines, line_colors(streamlines)))

print('Saving illustration as csd_streamlines_eudx.png')
fvtk.record(ren, out_path='csd_streamlines_eudx.png', size=(900, 900))
예제 #22
0
파일: track.py 프로젝트: wrgr/ndmg
    def eudx_advanced(self,
                      dti_file,
                      mask_file,
                      gtab,
                      seed_num=100000,
                      stop_val=0.1):
        """
        Tracking with more complex tensors - experimental

        Initializes the graph with nodes corresponding to the number of ROIs

        **Positional Arguments:**

                dti_file:
                    - File (registered) to use for tensor/fiber tracking
                mask_file:
                    - Brain mask to keep tensors inside the brain
                gtab:
                    - dipy formatted bval/bvec Structure

        **Optional Arguments:**
                seed_num:
                    - Number of seeds to use for fiber tracking
                stop_val:
                    - Value to cutoff fiber track
        """

        img = nb.load(dti_file)
        data = img.get_data()

        img = nb.load(mask_file)

        mask = img.get_data()
        mask = mask > 0  # to ensure binary mask
        """
        For the constrained spherical deconvolution we need to estimate the
        response function (see :ref:`example_reconst_csd`) and create a model.
        """

        response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)

        csd_model = ConstrainedSphericalDeconvModel(gtab, response)
        """
        Next, we use ``peaks_from_model`` to fit the data and calculated
        the fiber directions in all voxels.
        """

        sphere = get_sphere('symmetric724')

        csd_peaks = peaks_from_model(model=csd_model,
                                     data=data,
                                     sphere=sphere,
                                     mask=mask,
                                     relative_peak_threshold=.5,
                                     min_separation_angle=25,
                                     parallel=True)
        """
        For the tracking part, we will use ``csd_model`` fiber directions
        but stop tracking where fractional anisotropy (FA) is low (< 0.1).
        To derive the FA, used as a stopping criterion, we need to fit a
        tensor model first. Here, we use weighted least squares (WLS).
        """
        print 'tensors...'

        tensor_model = TensorModel(gtab, fit_method='WLS')
        tensor_fit = tensor_model.fit(data, mask)

        FA = fractional_anisotropy(tensor_fit.evals)
        """
        In order for the stopping values to be used with our tracking
        algorithm we need to have the same dimensions as the
        ``csd_peaks.peak_values``. For this reason, we can assign the
        same FA value to every peak direction in the same voxel in
        the following way.
        """

        stopping_values = np.zeros(csd_peaks.peak_values.shape)
        stopping_values[:] = FA[..., None]

        streamline_generator = EuDX(stopping_values,
                                    csd_peaks.peak_indices,
                                    seeds=seed_num,
                                    odf_vertices=sphere.vertices,
                                    a_low=stop_val)

        streamlines = [streamline for streamline in streamline_generator]

        return streamlines
예제 #23
0
def deterministic(diffusion_file,
                  bvecs_file,
                  bvals_file,
                  trackfile,
                  mask_file=None,
                  order=4,
                  nb_seeds_per_voxel=1,
                  step=0.5):
    """ Compute a deterministic tractography using an ODF model.

    Parameters
    ----------
    diffusion_file: str (mandatory)
        a file containing the preprocessed diffusion data.
    bvecs_file: str (mandatory)
        a file containing the diffusion gradient directions.
    bvals_file: str (mandatory)
        a file containing the diffusion b-values.
    trackfile: str (mandatory)
        a file path where the fibers will be saved in trackvis format.
    mask_file: str (optional, default None)
        an image used to mask the diffusion data during the tractography. If
        not set, all the image voxels are considered.
    order: int (optional, default 4)
        the order of the ODF model.
    nb_seeds_per_voxel: int (optional, default 1)
        the number of seeds per voxel used during the propagation.
    step: float (optional, default 0.5)
        the integration step in voxel fraction used during the propagation.

    Returns
    -------
    streamlines: tuple of 3-uplet
        the computed fiber tracks in trackvis format (points: ndarray shape
        (N,3) where N is the number of points, scalars: None or ndarray shape
        (N, M) where M is the number of scalars per point, properties: None or
        ndarray shape (P,) where P is the number of properties).
    hdr: structured array
        structured array with trackvis header fields (voxel size, voxel order,
        dim).
    """
    # Read diffusion sequence
    bvals, bvecs = read_bvals_bvecs(bvals_file, bvecs_file)
    gtab = gradient_table(bvals, bvecs)
    diffusion_image = nibabel.load(diffusion_file)
    diffusion_array = diffusion_image.get_data()
    if mask_file is not None:
        mask_array = nibabel.load(mask_file).get_data()
    else:
        mask_array = numpy.ones(diffusion_array.shape[:3], dtype=numpy.uint8)

    # Estimate ODF model
    csamodel = shm.CsaOdfModel(gtab, order)
    csapeaks = peaks.peaks_from_model(model=csamodel,
                                      data=diffusion_array,
                                      sphere=peaks.default_sphere,
                                      relative_peak_threshold=.8,
                                      min_separation_angle=45,
                                      mask=mask_array)

    # Compute deterministic tractography in voxel space so affine is equal
    # to identity
    seeds = utils.seeds_from_mask(mask_array, density=nb_seeds_per_voxel)
    streamline_generator = EuDX(csapeaks.peak_values,
                                csapeaks.peak_indices,
                                odf_vertices=peaks.default_sphere.vertices,
                                a_low=.05,
                                step_sz=step,
                                seeds=seeds)
    #  affine = streamline_generator.affine

    # Save the tracks in trackvis format
    hdr = nibabel.trackvis.empty_header()
    hdr["voxel_size"] = diffusion_image.get_header().get_zooms()[:3]
    hdr["voxel_order"] = "LAS"
    hdr["dim"] = diffusion_array.shape[:3]
    streamlines = [track for track in streamline_generator]
    random.shuffle(streamlines)
    streamlines = ((track, None, None) for track in streamlines)
    nibabel.trackvis.write(trackfile, streamlines, hdr, points_space="voxel")

    return streamlines, hdr
예제 #24
0
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)
예제 #25
0
                                  sphere=peaks.default_sphere,
                                  relative_peak_threshold=.8,
                                  min_separation_angle=45,
                                  mask=white_matter)
"""
Now we can use EuDX to track all of the white matter. To keep things reasonably
fast we use ``density=2`` which will result in 8 seeds per voxel. We'll set
``a_low`` (the parameter which determines the threshold of FA/QA under which
tracking stops) to be very low because we've already applied a white matter
mask.
"""

seeds = utils.seeds_from_mask(white_matter, density=2)
streamline_generator = EuDX(csapeaks.peak_values,
                            csapeaks.peak_indices,
                            odf_vertices=peaks.default_sphere.vertices,
                            a_low=.05,
                            step_sz=.5,
                            seeds=seeds)
affine = streamline_generator.affine
streamlines = list(streamline_generator)
"""
The first of the tracking utilities we'll cover here is ``target``. This
function takes a set of streamlines and a region of interest (ROI) and returns
only those streamlines that pass though the ROI. The ROI should be an array
such that the voxels that belong to the ROI are ``True`` and all other voxels
are ``False`` (this type of binary array is sometimes called a mask). This
function can also exclude all the streamlines that pass though an ROI by
setting the ``include`` flag to ``False``. In this example we'll target the
streamlines of the corpus callosum. Our ``labels`` array has a sagittal slice
of the corpus callosum identified by the label value 2. We'll create an ROI
mask from that label and create two sets of streamlines, those that intersect
예제 #26
0
def deterministic(diffusion_file,
                  bvecs_file,
                  bvals_file,
                  outdir,
                  mask_file=None,
                  order=4,
                  nb_seeds_per_voxel=1,
                  step=0.5,
                  fmt="%.4f"):
    """ Compute a deterministic tractography using an ODF model.

    Parameters
    ----------
    diffusion_file: str (mandatory)
        a file containing the preprocessed diffusion data.
    bvecs_file: str (mandatory)
        a file containing the diffusion gradient directions.
    bvals_file: str (mandatory)
        a file containing the diffusion b-values.
    outdir: str (mandatory)
        the output directory.
    mask_file: str (optional, default None)
        an image used to mask the diffusion data during the tractography. If
        not set, all the image voxels are considered.
    order: int (optional, default 4)
        the order of the ODF model.
    nb_seeds_per_voxel: int (optional, default 1)
        the number of seeds per voxel used during the propagation.
    step: float (optional, default 0.5)
        the integration step in voxel fraction used during the propagation.
    fmt: str (optional, default '%.4f')
        the saved track elements format.

    Returns
    -------
    track_file: str
        a determinist model of the white matter organization.
    """
    # Read diffusion sequence
    bvals, bvecs = read_bvals_bvecs(bvals_file, bvecs_file)
    gtab = gradient_table(bvals, bvecs)
    diffusion_array = nibabel.load(diffusion_file).get_data()
    if mask_file is not None:
        mask_array = nibabel.load(mask_file).get_data()
    else:
        mask_array = numpy.ones(diffusion_array.shape[:3], dtype=numpy.uint8)

    # Estimate ODF model
    csamodel = shm.CsaOdfModel(gtab, order)
    csapeaks = peaks.peaks_from_model(model=csamodel,
                                      data=diffusion_array,
                                      sphere=peaks.default_sphere,
                                      relative_peak_threshold=.8,
                                      min_separation_angle=45,
                                      mask=mask_array)

    # Compute deterministic tractography in voxel space so affine is equal
    # to identity
    seeds = utils.seeds_from_mask(mask_array, density=nb_seeds_per_voxel)
    streamline_generator = EuDX(csapeaks.peak_values,
                                csapeaks.peak_indices,
                                odf_vertices=peaks.default_sphere.vertices,
                                a_low=.05,
                                step_sz=step,
                                seeds=seeds)
    affine = streamline_generator.affine
    streamlines = list(streamline_generator)

    # Save the tracks
    track_file = os.path.join(outdir, "fibers.txt")
    savetxt(track_file, streamlines, fmt=fmt)

    return track_file
예제 #27
0
    def _run_interface(self, runtime):
        from dipy.reconst.peaks import peaks_from_model
        from dipy.tracking.eudx import EuDX
        from dipy.data import get_sphere
        # import marshal as pickle
        import pickle as pickle
        import gzip

        if (not (isdefined(self.inputs.in_model)
                 or isdefined(self.inputs.in_peaks))):
            raise RuntimeError(('At least one of in_model or in_peaks should '
                                'be supplied'))

        img = nb.load(self.inputs.in_file)
        imref = nb.four_to_three(img)[0]
        affine = img.affine

        data = img.get_data().astype(np.float32)
        hdr = imref.header.copy()
        hdr.set_data_dtype(np.float32)
        hdr['data_type'] = 16

        sphere = get_sphere('symmetric724')

        self._save_peaks = False
        if isdefined(self.inputs.in_peaks):
            IFLOGGER.info('Peaks file found, skipping ODF peaks search...')
            f = gzip.open(self.inputs.in_peaks, 'rb')
            peaks = pickle.load(f)
            f.close()
        else:
            self._save_peaks = True
            IFLOGGER.info('Loading model and computing ODF peaks')
            f = gzip.open(self.inputs.in_model, 'rb')
            odf_model = pickle.load(f)
            f.close()

            peaks = peaks_from_model(
                model=odf_model,
                data=data,
                sphere=sphere,
                relative_peak_threshold=self.inputs.peak_threshold,
                min_separation_angle=self.inputs.min_angle,
                parallel=self.inputs.multiprocess)

            f = gzip.open(self._gen_filename('peaks', ext='.pklz'), 'wb')
            pickle.dump(peaks, f, -1)
            f.close()

        hdr.set_data_shape(peaks.gfa.shape)
        nb.Nifti1Image(peaks.gfa.astype(np.float32), affine,
                       hdr).to_filename(self._gen_filename('gfa'))

        IFLOGGER.info('Performing tractography')

        if isdefined(self.inputs.tracking_mask):
            msk = nb.load(self.inputs.tracking_mask).get_data()
            msk[msk > 0] = 1
            msk[msk < 0] = 0
        else:
            msk = np.ones(imref.shape)

        gfa = peaks.gfa * msk
        seeds = self.inputs.num_seeds

        if isdefined(self.inputs.seed_coord):
            seeds = np.loadtxt(self.inputs.seed_coord)

        elif isdefined(self.inputs.seed_mask):
            seedmsk = nb.load(self.inputs.seed_mask).get_data()
            assert (seedmsk.shape == data.shape[:3])
            seedmsk[seedmsk > 0] = 1
            seedmsk[seedmsk < 1] = 0
            seedps = np.array(np.where(seedmsk == 1), dtype=np.float32).T
            vseeds = seedps.shape[0]
            nsperv = (seeds // vseeds) + 1
            IFLOGGER.info(
                'Seed mask is provided (%d voxels inside '
                'mask), computing seeds (%d seeds/voxel).', vseeds, nsperv)
            if nsperv > 1:
                IFLOGGER.info('Needed %d seeds per selected voxel (total %d).',
                              nsperv, vseeds)
                seedps = np.vstack(np.array([seedps] * nsperv))
                voxcoord = seedps + np.random.uniform(-1, 1, size=seedps.shape)
                nseeds = voxcoord.shape[0]
                seeds = affine.dot(
                    np.vstack((voxcoord.T, np.ones((1, nseeds)))))[:3, :].T

                if self.inputs.save_seeds:
                    np.savetxt(self._gen_filename('seeds', ext='.txt'), seeds)

        if isdefined(self.inputs.tracking_mask):
            tmask = msk
            a_low = 0.1
        else:
            tmask = gfa
            a_low = self.inputs.gfa_thresh

        eu = EuDX(tmask,
                  peaks.peak_indices[..., 0],
                  seeds=seeds,
                  affine=affine,
                  odf_vertices=sphere.vertices,
                  a_low=a_low)

        ss_mm = [np.array(s) for s in eu]

        trkfilev = nb.trackvis.TrackvisFile([(s, None, None) for s in ss_mm],
                                            points_space='rasmm',
                                            affine=np.eye(4))
        trkfilev.to_file(self._gen_filename('tracked', ext='.trk'))
        return runtime
예제 #28
0
fa = fractional_anisotropy(ten_fit.evals)
cfa = color_fa(fa, ten_fit.evecs)
csamodel = CsaOdfModel(gtab, 6)
sphere = get_sphere('symmetric724')

pmd = peaks_from_model(model=csamodel,
                       data=data,
                       sphere=sphere,
                       relative_peak_threshold=.5,
                       min_separation_angle=25,
                       mask=mask,
                       return_odf=False)
#Deterministic tractography
eu = EuDX(a=fa,
          ind=pmd.peak_indices[..., 0],
          seeds=2000000,
          odf_vertices=sphere.vertices,
          a_low=0.2)
affine = eu.affine
csd_streamlines = list(eu)

#Remove tracts shorter than 30mm
#print np.shape(csd_streamlines)
from dipy.tracking.utils import length
csd_streamlines = [t for t in csd_streamlines if length(t) > 30]

#Trackvis
hdr = nib.trackvis.empty_header()
hdr['voxel_size'] = img.get_header().get_zooms()[:3]
hdr['voxel_order'] = 'LAS'
hdr['dim'] = fa.shape
예제 #29
0
from dipy.reconst.dti import quantize_evecs

peak_indices = quantize_evecs(evecs, sphere.vertices)
"""
EuDX is the fiber tracking algorithm that we use in this example.
The most important parameters are the first one which represents the
magnitude of the peak of a scalar anisotropic function, the
second which represents the indices of the discretized directions of
the peaks and odf_vertices are the vertices of the input sphere.
"""

from dipy.tracking.eudx import EuDX

eu = EuDX(FA.astype('f8'),
          peak_indices,
          seeds=50000,
          odf_vertices=sphere.vertices,
          a_low=0.2)

tensor_streamlines = [streamline for streamline in eu]
"""
We can now save the results in the disk. For this purpose we can use the
TrackVis format (``*.trk``). First, we need to create a header.
"""

hdr = nib.trackvis.empty_header()
hdr['voxel_size'] = fa_img.header.get_zooms()[:3]
hdr['voxel_order'] = 'LAS'
hdr['dim'] = FA.shape
"""
Then we need to input the streamlines in the way that Trackvis format expects them.
예제 #30
0
    et3 = time.time() - st3
    print 'seeding transformation finished, the total seeds are {}, running time is {}'.format(
        seeds.shape[0], et3)

    print 'generating streamlines begins'
    st4 = time.time()
    del data, img, labels, labels_img
    gc.collect()
    print 'data, img, labels, labels_img elete to save memory'

    streamline_generator = EuDX(csapeaks1.peak_values,
                                csapeaks1.peak_indices,
                                odf_vertices=peaks.default_sphere.vertices,
                                a_low=.05,
                                step_sz=.5,
                                seeds=seeds,
                                ang_thr=70.0,
                                length_thr=0.0,
                                total_weight=0.5,
                                max_points=1000,
                                affine=None)
    affine = streamline_generator.affine

    streamlines = Streamlines(streamline_generator)
    et4 = time.time() - st4
    lengths = [length(sl).astype(np.int) for sl in streamlines]
    print 'generating streamlines finished, the length is {}~{}, running time is {}'.format(
        np.min(lengths), np.max(lengths), et4)

    del bm, mask, lengths
    gc.collect()