コード例 #1
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)
コード例 #2
0
ファイル: test_propagation.py プロジェクト: szho42/dipy
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)
    
    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)
コード例 #3
0
ファイル: test_propagation.py プロジェクト: szho42/dipy
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)

    seed = [1000000., 1000000., 1000000.]
    eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], a_low=.2)
    try:
        track = list(eu)
    except ValueError as ve:        
        if ve.args[0] == 'Seed outside boundaries':
            print(ve)
   
    print(data.shape)
    seed = [1., 5., 8.]
    eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], a_low=.2)    
    track = list(eu)
    
    seed = [-1., 1000000., 1000000.]
    eu = EuDX(a=ten.fa, ind=ind, seeds=[seed], a_low=.2)
    try:
        track = list(eu)
    except ValueError as ve:
        if ve.args[0] == 'Seed outside boundaries':
            print(ve)
コード例 #4
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')
コード例 #5
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)
コード例 #6
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')
コード例 #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')    

    dpy_out = trk_out.replace('.trk', '.dpy')
    dpy = Dpy(dpy_out, 'w')
    dpy.write_tracks(streamlines)
    dpy.close()
コード例 #8
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.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)
コード例 #9
0
def DIPY_nii2streamlines(imgfile, maskfile, bvals, bvecs, output_prefix):
    import numpy as np
    import nibabel as nib
    import os

    from dipy.reconst.dti import TensorModel

    print "nii2streamlines"

    img = nib.load(imgfile)
    bvals = np.genfromtxt(bvals)
    bvecs = np.genfromtxt(bvecs)
    if bvecs.shape[1] != 3:
        bvecs = bvecs.T
    print bvecs.shape

    from nipype.utils.filemanip import split_filename
    _, prefix, _  = split_filename(imgfile)
    from dipy.data import gradient_table
    gtab = gradient_table(bvals, bvecs)
    data = img.get_data()
    affine = img.get_affine()
    zooms = img.get_header().get_zooms()[:3]
    new_zooms = (2., 2., 2.)
    data2, affine2 = data, affine
    mask = nib.load(maskfile).get_data().astype(np.bool)
    tenmodel = TensorModel(gtab)
    tenfit = tenmodel.fit(data2, mask)

    from dipy.reconst.dti import fractional_anisotropy
    FA = fractional_anisotropy(tenfit.evals)
    FA[np.isnan(FA)] = 0
    fa_img = nib.Nifti1Image(FA, img.get_affine())
    nib.save(fa_img, experiment_dir + '/' + ('%s_tensor_fa.nii.gz' % prefix))
    evecs = tenfit.evecs
    evec_img = nib.Nifti1Image(evecs, img.get_affine())
    nib.save(evec_img, experiment_dir + '/' + ('%s_tensor_evec.nii.gz' % prefix))

    from dipy.data import get_sphere
    sphere = get_sphere('symmetric724')
    from dipy.reconst.dti import quantize_evecs

    peak_indices = quantize_evecs(tenfit.evecs, sphere.vertices)

    from dipy.tracking.eudx import EuDX
    eu = EuDX(FA, peak_indices, odf_vertices = sphere.vertices, a_low=0.2, seeds=10**6, ang_thr=35)
    tensor_streamlines = [streamline for streamline in eu]
    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = new_zooms
    hdr['voxel_order'] = 'LPS'
    hdr['dim'] = data2.shape[:3]

    import dipy.tracking.metrics as dmetrics
    tensor_streamlines = ((sl, None, None) for sl in tensor_streamlines if dmetrics.length(sl) > 15)
    ten_sl_fname = experiment_dir + '/' + ('%s_streamline.trk' % prefix)
    nib.trackvis.write(ten_sl_fname, tensor_streamlines, hdr, points_space='voxel')
    return ten_sl_fname
コード例 #10
0
def test_eudx_further():
    """ Cause we love testin.. ;-)
    """

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

    img = ni.load(fimg)
    affine = img.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)
コード例 #11
0
ファイル: track.py プロジェクト: CaseyWeiner/m2g
    def tens_mod_est(self):

        print("Fitting tensor model...")
        self.model = TensorModel(self.gtab)
        self.ten = self.model.fit(self.data, self.wm_in_dwi_data)
        self.fa = self.ten.fa
        self.fa[np.isnan(self.fa)] = 0
        self.sphere = get_sphere("repulsion724")
        self.ind = quantize_evecs(self.ten.evecs, self.sphere.vertices)
        return self.ten
コード例 #12
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)
コード例 #13
0
ファイル: reconstruction.py プロジェクト: FNNDSC/F3000
  def streamlines( fa_file, evecs_file, fibers_file ):
    '''
    Generate streamlines from FA and EVECS maps and store a TrackVis file.
    
    fa_file
      the fa map file path
    evecs_file
      the evecs map file path
    fibers_file
      the TrackVis output file path
    '''

    # load the inputs
    fa_image = nibabel.load( fa_file )
    evecs_image = nibabel.load( evecs_file )

    fa_map = fa_image.get_data()
    evecs_map = evecs_image.get_data()

    # clean-up FA map
    fa_map[numpy.isnan( fa_map )] = 0

    # load evenly distributed sphere of 724 points
    sphere = dipy.data.get_sphere( 'symmetric724' )

    # apply the sphere for discretization
    peak_indices = reconstructer.quantize_evecs( evecs_map, sphere.vertices )

    # perform tracking
    print 'start tracking'
    tracking_results = tracker.EuDX( fa_map, peak_indices, seeds=1000000, odf_vertices=sphere.vertices, a_low=0.2 )
    streamlines = [streamline for streamline in tracking_results]
    print 'end tracking'

    # save as .TRK file
    trk_header = nibabel.trackvis.empty_header()
    # trk_header['voxel_size'] = fa_image.get_header().get_zooms()[:3]
    # trk_header['voxel_order'] = 'LPS'
    trk_header['dim'] = fa_map.shape
    trk_header['n_count'] = len(streamlines)

    # adjust trackvis header according to affine from FA
    nibabel.trackvis.aff_to_hdr( fa_image.get_affine(), trk_header, True, True )

    trk_tracks = ( ( sl, None, None ) for sl in streamlines )

    nibabel.trackvis.write( fibers_file, trk_tracks, trk_header, points_space='voxel' )
コード例 #14
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
コード例 #15
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()
    affine = fa_img.get_affine()

    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
    hdr['vox_to_ras'] = affine
    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()
コード例 #16
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()
コード例 #17
0
def track_gen_model(brain_mask_file, dwi_data_file, dwi_bval_file,
                    dwi_bvec_file):
    img_mask = nib.load(brain_mask_file)
    img, gtab = dwi.get_dwi_img_gtab(dwi_data_file, dwi_bval_file,
                                     dwi_bvec_file)
    data_mask = img_mask.get_data()
    affine = img.get_affine()
    data = img.get_data()

    model = TensorModel(gtab)
    ten = model.fit(data, mask=data_mask)
    sphere = get_sphere('symmetric724')
    ind = quantize_evecs(ten.evecs, sphere.vertices)

    p = Struct()
    p.affine = affine
    p.sphere = sphere
    p.ten = ten
    p.ind = ind
    return p
コード例 #18
0
def tractography_rec(imag, bvals, bvecs, seed, threshold):
    ''' Script to generate tractography. Uses the EuDX function from dipy. Returns tractography and FA.
    
    Parameters
    ----------
    imag: NiftiImage object 
    bvals: bvals array
    bvecs: bvecs array
    seed: int or ndarray (Parameter for the EuDX function)
    threshold : float (Parameter for the EuDX function)
    '''

    print "Retrieving data and affine"
    data = img.get_data()
    affine = img.get_affine()

    #new version of dipy
    print "Computing tensor model"
    gradients = gradient_table(bvals,bvecs)
    tensor_model = dti.TensorModel(gradients)
    tensors = tensor_model.fit(data)

    print "Computing FA"
    FA = dti.fractional_anisotropy(tensors.evals)
    FA[np.isnan(FA)] = 0

    print "Computing evecs"
    evecs_img = nib.Nifti1Image(tensors.evecs.astype(np.float32), affine)
    evecs = evecs_img.get_data()

    sphere = get_sphere('symmetric724')
    peak_indices = dti.quantize_evecs(evecs, sphere.vertices)
    
    print "Computing EuDX reconstruction."
    streamlines = EuDX(FA.astype('f8'),
                        ind=peak_indices,
			seeds=seed,
                        odf_vertices= sphere.vertices,
                        a_low=threshold)

    return streamlines, FA
コード例 #19
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)
コード例 #20
0
ファイル: test_life.py プロジェクト: gauvinalexandre/dipy
def test_fit_data():
    fdata, fbval, fbvec = dpd.get_data('small_25')
    gtab = grad.gradient_table(fbval, fbvec)
    ni_data = nib.load(fdata)
    data = ni_data.get_data()
    dtmodel = dti.TensorModel(gtab)
    dtfit = dtmodel.fit(data)
    sphere = dpd.get_sphere()
    peak_idx = dti.quantize_evecs(dtfit.evecs, sphere.vertices)
    eu = edx.EuDX(dtfit.fa.astype('f8'), peak_idx,
                  seeds=list(nd.ndindex(data.shape[:-1])),
                  odf_vertices=sphere.vertices, a_low=0)
    tensor_streamlines = [streamline for streamline in eu]
    life_model = life.FiberModel(gtab)
    life_fit = life_model.fit(data, tensor_streamlines)
    model_error = life_fit.predict() - life_fit.data
    model_rmse = np.sqrt(np.mean(model_error ** 2, -1))
    matlab_rmse, matlab_weights = dpd.matlab_life_results()
    # Lower error than the matlab implementation for these data:
    npt.assert_(np.median(model_rmse) < np.median(matlab_rmse))
    # And a moderate correlation with the Matlab implementation weights:
    npt.assert_(np.corrcoef(matlab_weights, life_fit.beta)[0, 1] > 0.6)
コード例 #21
0
ファイル: track.py プロジェクト: htygithub/ndmg
    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)
コード例 #22
0
ファイル: test_life.py プロジェクト: oesteban/dipy
def test_fit_data():
    fdata, fbval, fbvec = dpd.get_data('small_25')
    gtab = grad.gradient_table(fbval, fbvec)
    ni_data = nib.load(fdata)
    data = ni_data.get_data()
    dtmodel = dti.TensorModel(gtab)
    dtfit = dtmodel.fit(data)
    sphere = dpd.get_sphere()
    peak_idx = dti.quantize_evecs(dtfit.evecs, sphere.vertices)
    eu = edx.EuDX(dtfit.fa.astype('f8'),
                  peak_idx,
                  seeds=list(nd.ndindex(data.shape[:-1])),
                  odf_vertices=sphere.vertices,
                  a_low=0)
    tensor_streamlines = [streamline for streamline in eu]
    life_model = life.FiberModel(gtab)
    life_fit = life_model.fit(data, tensor_streamlines)
    model_error = life_fit.predict() - life_fit.data
    model_rmse = np.sqrt(np.mean(model_error**2, -1))
    matlab_rmse, matlab_weights = dpd.matlab_life_results()
    # Lower error than the matlab implementation for these data:
    npt.assert_(np.median(model_rmse) < np.median(matlab_rmse))
    # And a moderate correlation with the Matlab implementation weights:
    npt.assert_(np.corrcoef(matlab_weights, life_fit.beta)[0, 1] > 0.68)
コード例 #23
0
ファイル: tracking.py プロジェクト: baothien/tiensy
def tracking(input_filename_fa, input_filename_evecs, num_seeds=10000, low_thresh=0.2, output_filename=None):

    # print 'Tracking ...'

    # print 'Loading data ...'

    fa_img = nib.load(input_filename_fa)
    FA = fa_img.get_data()

    evecs_img = nib.load(input_filename_evecs)
    evecs = evecs_img.get_data()

    FA[np.isnan(FA)] = 0

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

    eu = EuDX(FA, peak_indices, seeds=num_seeds, odf_vertices=sphere.vertices, a_low=low_thresh)

    tensor_tracks_old = [streamline for streamline in eu]

    # remove one point tracks
    tracks = [track for track in tensor_tracks_old if track.shape[0] > 1]
    # tracks =  create_tracks(FA, peak_indices,sphere.vertices, num_seeds, low_thresh)

    if output_filename == None:
        filename_save = "tracks_dti.dpy"
    else:
        filename_save = os.path.abspath(output_filename)

    # print 'Saving tracks to:', filename_save
    dpw = Dpy(filename_save, "w")
    dpw.write_tracks(tracks)
    dpw.close()

    return filename_save
コード例 #24
0
gtab = gradient_table(bvals, bvecs)

# Create tensor model
tenmodel = TensorModel(gtab)

# 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
コード例 #25
0
ファイル: nii_2_tracks.py プロジェクト: JDWarner/dipy
For the discretization procedure we use an evenly distributed sphere of 724
points which we can access using the get_sphere function.
"""

from dipy.data import get_sphere

sphere = get_sphere('symmetric724')

"""
We use quantize_evecs (evecs here stands for eigen vectors) to apply the
discretization.
"""

from dipy.reconst.dti import quantize_evecs

peak_indices = quantize_evecs(tenfit.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, peak_indices, odf_vertices = sphere.vertices, a_low=0.2)

tensor_streamlines = [streamline for streamline in eu]
コード例 #26
0
def dwi_dipy_run(dwi_dir,
                 node_size,
                 dir_path,
                 conn_model,
                 parc,
                 atlas_select,
                 network,
                 wm_mask=None):
    import os
    import glob
    import re
    import nipype.interfaces.fsl as fsl
    from dipy.reconst.dti import TensorModel, quantize_evecs
    from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, recursive_response
    from dipy.tracking.local import LocalTracking, ThresholdTissueClassifier
    from dipy.tracking import utils
    from dipy.direction import peaks_from_model
    from dipy.tracking.eudx import EuDX
    from dipy.data import get_sphere
    from dipy.core.gradients import gradient_table
    from dipy.io import read_bvals_bvecs

    def atoi(text):
        return int(text) if text.isdigit() else text

    def natural_keys(text):
        return [atoi(c) for c in re.split('(\d+)', text)]

    dwi_img = "%s%s" % (dwi_dir, '/dwi.nii.gz')
    nodif_brain_mask_path = "%s%s" % (dwi_dir, '/nodif_brain_mask.nii.gz')
    bvals = "%s%s" % (dwi_dir, '/bval')
    bvecs = "%s%s" % (dwi_dir, '/bvec')

    img = nib.load(dwi_img)
    data = img.get_data()

    # Loads mask and ensures it's a true binary mask
    img = nib.load(nodif_brain_mask_path)
    mask = img.get_data()
    mask = mask > 0

    [bvals, bvecs] = read_bvals_bvecs(bvals, bvecs)
    gtab = gradient_table(bvals, bvecs)

    # Estimates some tensors
    model = TensorModel(gtab)
    ten = model.fit(data, mask)
    sphere = get_sphere('symmetric724')
    ind = quantize_evecs(ten.evecs, sphere.vertices)

    # Tractography
    if conn_model == 'csd':
        trac_mod = 'csd'
    else:
        conn_model = 'tensor'
        trac_mod = ten.fa

    affine = img.affine
    print('Tracking with tensor model...')
    if wm_mask is None:
        mask = nib.load(mask).get_data()
        mask[0, :, :] = False
        mask[:, 0, :] = False
        mask[:, :, 0] = False
        seeds = utils.seeds_from_mask(mask, density=2)
    else:
        wm_mask_data = nib.load(wm_mask).get_data()
        wm_mask_data[0, :, :] = False
        wm_mask_data[:, 0, :] = False
        wm_mask_data[:, :, 0] = False
        seeds = utils.seeds_from_mask(wm_mask_data, density=2)
    #seeds = random_seeds_from_mask(ten.fa > 0.3, seeds_count=num_total_samples)

    if conn_model == 'tensor':
        eu = EuDX(a=trac_mod,
                  ind=ind,
                  seeds=seeds,
                  odf_vertices=sphere.vertices,
                  a_low=0.05,
                  step_sz=.5)
        tracks = [e for e in eu]
    elif conn_model == 'csd':
        print('Tracking with CSD model...')
        if wm_mask is None:
            response = recursive_response(gtab,
                                          data,
                                          mask=mask.astype('bool'),
                                          sh_order=8,
                                          peak_thr=0.01,
                                          init_fa=0.08,
                                          init_trace=0.0021,
                                          iter=8,
                                          convergence=0.001,
                                          parallel=True)
        else:
            response = recursive_response(gtab,
                                          data,
                                          mask=wm_mask_data.astype('bool'),
                                          sh_order=8,
                                          peak_thr=0.01,
                                          init_fa=0.08,
                                          init_trace=0.0021,
                                          iter=8,
                                          convergence=0.001,
                                          parallel=True)
        csd_model = ConstrainedSphericalDeconvModel(gtab, response)
        csd_peaks = peaks_from_model(model=csd_model,
                                     data=data,
                                     sphere=sphere,
                                     relative_peak_threshold=.5,
                                     min_separation_angle=25,
                                     parallel=True)
        tissue_classifier = ThresholdTissueClassifier(ten.fa, 0.1)
        streamline_generator = LocalTracking(csd_peaks,
                                             tissue_classifier,
                                             seeds,
                                             affine=affine,
                                             step_size=0.5)
        tracks = [e for e in streamline_generator]

    if parc is True:
        node_size = 'parc'

    if network:
        seeds_dir = "%s%s%s%s%s%s%s" % (dir_path, '/seeds_', network, '_',
                                        atlas_select, '_', str(node_size))
    else:
        seeds_dir = "%s%s%s%s%s" % (dir_path, '/seeds_', atlas_select, '_',
                                    str(node_size))

    seed_files = glob.glob("%s%s" % (seeds_dir, '/*diff.nii.gz'))

    seed_files.sort(key=natural_keys)

    # Binarize ROIs
    print('\nBinarizing seed masks...')
    j = 1
    for i in seed_files:
        args = ' -bin '
        out_file = "%s%s" % (i.split('.nii.gz')[0], '_bin.nii.gz')
        maths = fsl.ImageMaths(in_file=i, op_string=args, out_file=out_file)
        os.system(maths.cmdline)
        args = ' -mul ' + str(j)
        maths = fsl.ImageMaths(in_file=out_file,
                               op_string=args,
                               out_file=out_file)
        os.system(maths.cmdline)
        j = j + 1

    # Create atlas from ROIs
    seed_files = glob.glob("%s%s" % (seeds_dir, '/*diff_bin.nii.gz'))

    seed_files.sort(key=natural_keys)

    print('\nMerging seed masks into single labels image...')
    label_sum = "%s%s" % (seeds_dir, '/all_rois.nii.gz')
    args = ' -add ' + i
    maths = fsl.ImageMaths(in_file=seed_files[0],
                           op_string=args,
                           out_file=label_sum)
    os.system(maths.cmdline)

    for i in seed_files:
        args = ' -add ' + i
        maths = fsl.ImageMaths(in_file=label_sum,
                               op_string=args,
                               out_file=label_sum)
        os.system(maths.cmdline)

    labels_im = nib.load(label_sum)
    labels_data = labels_im.get_data().astype('int')
    conn_matrix, grouping = utils.connectivity_matrix(
        tracks,
        labels_data,
        affine=affine,
        return_mapping=True,
        mapping_as_streamlines=True)
    conn_matrix[:3, :] = 0
    conn_matrix[:, :3] = 0

    return conn_matrix
コード例 #27
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
コード例 #28
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')
コード例 #29
0
def nii2streamlines(imgfile, maskfile, bvals, bvecs):
    import numpy as np
    import nibabel as nib
    import os

    from dipy.reconst.dti import TensorModel

    img = nib.load(imgfile)
    bvals = np.genfromtxt(bvals)
    bvecs = np.genfromtxt(bvecs)
    if bvecs.shape[1] != 3:
        bvecs = bvecs.T

    from nipype.utils.filemanip import split_filename
    _, prefix, _ = split_filename(imgfile)

    from dipy.data import gradient_table

    gtab = gradient_table(bvals, bvecs)
    data = img.get_data()
    affine = img.get_affine()
    zooms = img.get_header().get_zooms()[:3]
    new_zooms = (2., 2., 2.)
    data2, affine2 = data, affine
    mask = nib.load(maskfile).get_data().astype(np.bool)
    tenmodel = TensorModel(gtab)
    tenfit = tenmodel.fit(data2, mask)

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

    evecs = tenfit.evecs

    evec_img = nib.Nifti1Image(evecs, img.get_affine())
    nib.save(evec_img, '%s_tensor_evec.nii.gz' % prefix)

    from dipy.data import get_sphere
    sphere = get_sphere('symmetric724')
    from dipy.reconst.dti import quantize_evecs

    peak_indices = quantize_evecs(tenfit.evecs, sphere.vertices)

    from dipy.tracking.eudx import EuDX

    eu = EuDX(FA,
              peak_indices,
              odf_vertices=sphere.vertices,
              a_low=0.2,
              seeds=10**6,
              ang_thr=35)
    tensor_streamlines = [streamline for streamline in eu]

    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = new_zooms
    hdr['voxel_order'] = 'LPS'
    hdr['dim'] = data2.shape[:3]

    import dipy.tracking.metrics as dmetrics
    tensor_streamlines = ((sl, None, None) for sl in tensor_streamlines
                          if dmetrics.length(sl) > 15)

    ten_sl_fname = '%s_streamline.trk' % prefix

    nib.trackvis.write(ten_sl_fname,
                       tensor_streamlines,
                       hdr,
                       points_space='voxel')
    return ten_sl_fname
コード例 #30
0
def dwi_dipy_run(dwi_dir,
                 node_size,
                 dir_path,
                 conn_model,
                 parc,
                 atlas_select,
                 network,
                 wm_mask=None):
    from dipy.reconst.dti import TensorModel, quantize_evecs
    from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, recursive_response
    from dipy.tracking.local import LocalTracking, ActTissueClassifier
    from dipy.tracking import utils
    from dipy.direction import peaks_from_model
    from dipy.tracking.eudx import EuDX
    from dipy.data import get_sphere, default_sphere
    from dipy.core.gradients import gradient_table
    from dipy.io import read_bvals_bvecs
    from dipy.tracking.streamline import Streamlines
    from dipy.direction import ProbabilisticDirectionGetter, ClosestPeakDirectionGetter, BootDirectionGetter
    from nibabel.streamlines import save as save_trk
    from nibabel.streamlines import Tractogram

    ##
    dwi_dir = '/Users/PSYC-dap3463/Downloads/bedpostx_s002'
    img_pve_csf = nib.load(
        '/Users/PSYC-dap3463/Downloads/002_all/tmp/reg_a/t1w_vent_csf_diff_dwi.nii.gz'
    )
    img_pve_wm = nib.load(
        '/Users/PSYC-dap3463/Downloads/002_all/tmp/reg_a/t1w_wm_in_dwi_bin.nii.gz'
    )
    img_pve_gm = nib.load(
        '/Users/PSYC-dap3463/Downloads/002_all/tmp/reg_a/t1w_gm_mask_dwi.nii.gz'
    )
    labels_img = nib.load(
        '/Users/PSYC-dap3463/Downloads/002_all/tmp/reg_a/dwi_aligned_atlas.nii.gz'
    )
    num_total_samples = 10000
    tracking_method = 'boot'  # Options are 'boot', 'prob', 'peaks', 'closest'
    procmem = [2, 4]
    ##

    if parc is True:
        node_size = 'parc'

    dwi_img = "%s%s" % (dwi_dir, '/dwi.nii.gz')
    nodif_brain_mask_path = "%s%s" % (dwi_dir, '/nodif_brain_mask.nii.gz')
    bvals = "%s%s" % (dwi_dir, '/bval')
    bvecs = "%s%s" % (dwi_dir, '/bvec')

    dwi_img = nib.load(dwi_img)
    data = dwi_img.get_data()
    [bvals, bvecs] = read_bvals_bvecs(bvals, bvecs)
    gtab = gradient_table(bvals, bvecs)
    gtab.b0_threshold = min(bvals)
    sphere = get_sphere('symmetric724')

    # Loads mask and ensures it's a true binary mask
    mask_img = nib.load(nodif_brain_mask_path)
    mask = mask_img.get_data()
    mask = mask > 0

    # Fit a basic tensor model first
    model = TensorModel(gtab)
    ten = model.fit(data, mask)
    fa = ten.fa

    # Tractography
    if conn_model == 'csd':
        print('Tracking with csd model...')
    elif conn_model == 'tensor':
        print('Tracking with tensor model...')
    else:
        raise RuntimeError("%s%s" % (conn_model, ' is not a valid model.'))

    # Combine seed counts from voxel with seed counts total
    wm_mask_data = img_pve_wm.get_data()
    wm_mask_data[0, :, :] = False
    wm_mask_data[:, 0, :] = False
    wm_mask_data[:, :, 0] = False
    seeds = utils.seeds_from_mask(wm_mask_data,
                                  density=1,
                                  affine=dwi_img.get_affine())
    seeds_rnd = utils.random_seeds_from_mask(ten.fa > 0.02,
                                             seeds_count=num_total_samples,
                                             seed_count_per_voxel=True)
    seeds_all = np.vstack([seeds, seeds_rnd])

    # Load tissue maps and prepare tissue classifier (Anatomically-Constrained Tractography (ACT))
    background = np.ones(img_pve_gm.shape)
    background[(img_pve_gm.get_data() + img_pve_wm.get_data() +
                img_pve_csf.get_data()) > 0] = 0
    include_map = img_pve_gm.get_data()
    include_map[background > 0] = 1
    exclude_map = img_pve_csf.get_data()
    act_classifier = ActTissueClassifier(include_map, exclude_map)

    if conn_model == 'tensor':
        ind = quantize_evecs(ten.evecs, sphere.vertices)
        streamline_generator = EuDX(a=fa,
                                    ind=ind,
                                    seeds=seeds_all,
                                    odf_vertices=sphere.vertices,
                                    a_low=0.05,
                                    step_sz=.5)
    elif conn_model == 'csd':
        print('Tracking with CSD model...')
        response = recursive_response(
            gtab,
            data,
            mask=img_pve_wm.get_data().astype('bool'),
            sh_order=8,
            peak_thr=0.01,
            init_fa=0.05,
            init_trace=0.0021,
            iter=8,
            convergence=0.001,
            parallel=True)
        csd_model = ConstrainedSphericalDeconvModel(gtab, response)
        if tracking_method == 'boot':
            dg = BootDirectionGetter.from_data(data,
                                               csd_model,
                                               max_angle=30.,
                                               sphere=default_sphere)
        elif tracking_method == 'prob':
            try:
                print(
                    'First attempting to build the direction getter directly from the spherical harmonic representation of the FOD...'
                )
                csd_fit = csd_model.fit(
                    data, mask=img_pve_wm.get_data().astype('bool'))
                dg = ProbabilisticDirectionGetter.from_shcoeff(
                    csd_fit.shm_coeff, max_angle=30., sphere=default_sphere)
            except:
                print(
                    'Sphereical harmonic not available for this model. Using peaks_from_model to represent the ODF of the model on a spherical harmonic basis instead...'
                )
                peaks = peaks_from_model(
                    csd_model,
                    data,
                    default_sphere,
                    .5,
                    25,
                    mask=img_pve_wm.get_data().astype('bool'),
                    return_sh=True,
                    parallel=True,
                    nbr_processes=procmem[0])
                dg = ProbabilisticDirectionGetter.from_shcoeff(
                    peaks.shm_coeff, max_angle=30., sphere=default_sphere)
        elif tracking_method == 'peaks':
            dg = peaks_from_model(model=csd_model,
                                  data=data,
                                  sphere=default_sphere,
                                  relative_peak_threshold=.5,
                                  min_separation_angle=25,
                                  mask=img_pve_wm.get_data().astype('bool'),
                                  parallel=True,
                                  nbr_processes=procmem[0])
        elif tracking_method == 'closest':
            csd_fit = csd_model.fit(data,
                                    mask=img_pve_wm.get_data().astype('bool'))
            pmf = csd_fit.odf(default_sphere).clip(min=0)
            dg = ClosestPeakDirectionGetter.from_pmf(pmf,
                                                     max_angle=30.,
                                                     sphere=default_sphere)
        streamline_generator = LocalTracking(dg,
                                             act_classifier,
                                             seeds_all,
                                             affine=dwi_img.affine,
                                             step_size=0.5)
        del dg
        try:
            del csd_fit
        except:
            pass
        try:
            del response
        except:
            pass
        try:
            del csd_model
        except:
            pass
        streamlines = Streamlines(streamline_generator, buffer_size=512)

    save_trk(Tractogram(streamlines, affine_to_rasmm=dwi_img.affine),
             'prob_streamlines.trk')
    tracks = [sl for sl in streamlines if len(sl) > 1]
    labels_data = labels_img.get_data().astype('int')
    labels_affine = labels_img.affine
    conn_matrix, grouping = utils.connectivity_matrix(
        tracks,
        labels_data,
        affine=labels_affine,
        return_mapping=True,
        mapping_as_streamlines=True,
        symmetric=True)
    conn_matrix[:3, :] = 0
    conn_matrix[:, :3] = 0

    return conn_matrix
コード例 #31
0
ファイル: core.py プロジェクト: jrudascas/ConnectivityTrack
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),
             path_output + ref_name_only + '_FA' + d.extension)

    list_maps.append(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),
             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),
             path_output + ref_name_only + '_MD' + d.extension)

    list_maps.append(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),
             path_output + ref_name_only + '_AD' + d.extension)

    list_maps.append(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),
             path_output + ref_name_only + '_RD' + d.extension)

    list_maps.append(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_dwi_input).get_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(path_output + ref_name_only + '_tractography_EuDx.trk',
                       tensor_streamlines_trk,
                       hdr,
                       points_space='voxel')

    return list_maps
コード例 #32
0
ファイル: tracking_eudx_tensor.py プロジェクト: MarcCote/dipy
For the discretization procedure we use an evenly distributed sphere of 724
points which we can access using the get_sphere function.
"""

from dipy.data import get_sphere

sphere = get_sphere('symmetric724')

"""
We use quantize_evecs (evecs here stands for eigen vectors) to apply the
discretization.
"""

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
from dipy.tracking.streamline import Streamlines

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

tensor_streamlines = Streamlines(eu)
コード例 #33
0
For the discretization procedure we use an evenly distributed sphere of 724
points which we can access using the get_sphere function.
"""

from dipy.data import get_sphere

sphere = get_sphere('symmetric724')
"""
We use quantize_evecs (evecs here stands for eigen vectors) to apply the
discretization.
"""

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)
コード例 #34
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')