Пример #1
0
def warp_tracks(input_tracks_filename, input_flirt_fmatrix, input_fa_filename,  output_filename = None, input_ref = '/usr/share/fsl/data/standard/FMRIB58_FA_1mm.nii.gz'):

    print 'Loading fa, flirt matrix ...'    
    img_fa = nib.load(input_fa_filename)            

    flirt_affine= np.loadtxt(input_flirt_fmatrix)    
        
    img_ref =nib.load(input_ref)
    
    #create affine matrix from flirt     
    mat=flirt2aff(flirt_affine,img_fa,img_ref)        

    #read tracks    
    print 'Loading tracks ...'
    tensor_tracks = load_tracks(input_tracks_filename)
        
    #linear tranform for tractography
    tracks_warped_linear = transform_tracks(tensor_tracks,mat)        

    if output_filename == None:
        filename_save = input_tracks_filename.split('.')[0]+'_linear.dpy'
    else:
        filename_save = os.path.abspath(output_filename)
        
    #save tracks_warped_linear    
    print 'Saving warped tracks into :', filename_save
    dpr_linear = Dpy(filename_save, 'w')
    dpr_linear.write_tracks(tracks_warped_linear)
    dpr_linear.close()
    
    return filename_save
def tracking_prob(dir_src, dir_out, verbose=False):

    wm_name = 'wm_mask_' + par_b_tag + '_' + par_dim_tag + '.nii.gz'
    wm_mask, affine = load_nifti(pjoin(dir_src, wm_name), verbose)

    sh_name = 'sh_' + par_b_tag + '_' + par_dim_tag + '.nii.gz'
    sh, _ = load_nifti(pjoin(dir_src, sh_name), verbose)

    sphere = get_sphere('symmetric724') 

    classifier = ThresholdTissueClassifier(wm_mask.astype('f8'), .5)
    classifier = BinaryTissueClassifier(wm_mask)
    max_dg = ProbabilisticDirectionGetter.from_shcoeff(sh, max_angle=par_trk_max_angle, sphere=sphere)
    seeds = utils.seeds_from_mask(wm_mask, density=2, affine=affine)
    streamlines = LocalTracking(max_dg, classifier, seeds, affine, step_size=par_trk_step_size)
    streamlines = list(streamlines)

    trk_name = 'tractogram_' + par_b_tag + '_' + par_dim_tag + '_' + par_trk_prob_tag + '.trk'
    trk_out = os.path.join(dir_out, trk_name)
 
    save_trk(trk_out, streamlines, affine, wm_mask.shape)

    dpy_out = trk_out.replace('.trk', '.dpy')
    dpy = Dpy(dpy_out, 'w')
    dpy.write_tracks(streamlines)
    dpy.close()
Пример #3
0
def warp_tracks_linearly(flirt_filename,fa_filename, tracks_filename,linear_filename):
    import nibabel as nib
    from dipy.external.fsl import flirt2aff
    
    fsl_ref = '/usr/share/fsl/data/standard/FMRIB58_FA_1mm.nii.gz'
    
    img_fa = nib.load(fa_filename)            

    flirt_affine= np.loadtxt(flirt_filename)    
        
    img_ref =nib.load(fsl_ref)
    
    #create affine matrix from flirt     
    mat=flirt2aff(flirt_affine,img_fa,img_ref)        

    #read tracks    
    tensor_tracks = load_whole_tract(tracks_filename)    
        
    #linear tranform for tractography
    tracks_warped_linear = transform_tracks(tensor_tracks,mat)        

    #save tracks_warped_linear    
    dpr_linear = Dpy(linear_filename, 'w')
    dpr_linear.write_tracks(tracks_warped_linear)
    dpr_linear.close()
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()
Пример #5
0
def test_dpy():

    fd,fname = mkstemp()    
    dpw = Dpy(fname,'w')    
    A=np.ones((5,3))
    B=2*A.copy()
    C=3*A.copy()        
    dpw.write_track(A)
    dpw.write_track(B)
    dpw.write_track(C)            
    dpw.write_tracks([C,B,A])    
    dpw.close()    
    dpr = Dpy(fname,'r')    
    assert_equal(dpr.version()=='0.0.1',True)    
    T=dpr.read_tracksi([0,1,2,0,0,2])    
    print(T)    
    T2=dpr.read_tracks()    
    assert_equal(len(T2),6)    
    dpr.close()
    assert_array_equal(A,T[0])
    assert_array_equal(C,T[5])
    os.remove(fname)

    
    
    
Пример #6
0
def save_tractogram(fname,
                    streamlines,
                    affine,
                    vox_size=None,
                    shape=None,
                    header=None,
                    reduce_memory_usage=False,
                    tractogram_file=None):
    """ Saves tractogram files (*.trk or *.tck or *.dpy)

    Parameters
    ----------
    fname : str
        output trk filename
    streamlines : list of 2D arrays, generator or ArraySequence
        Each 2D array represents a sequence of 3D points (points, 3).
    affine : array_like (4, 4)
        The mapping from voxel coordinates to streamline points.
    vox_size : array_like (3,), optional
        The sizes of the voxels in the reference image (default: None)
    shape : array, shape (dim,), optional
        The shape of the reference image (default: None)
    header : dict, optional
        Metadata associated to the tractogram file(*.trk). (default: None)
    reduce_memory_usage : {False, True}, optional
        If True, save streamlines in a lazy manner i.e. they will not be kept
        in memory. Otherwise, keep all streamlines in memory until saving.
    tractogram_file : class TractogramFile, optional
        Define tractogram class type (TrkFile vs TckFile)
        Default is None which means auto detect format
    """
    if 'dpy' in os.path.splitext(fname)[1].lower():
        dpw = Dpy(fname, 'w')
        dpw.write_tracks(Streamlines(streamlines))
        dpw.close()
        return

    tractogram_file = tractogram_file or detect_format(fname)
    if tractogram_file is None:
        raise ValueError("Unknown format for 'fname': {}".format(fname))

    if vox_size is not None and shape is not None:
        if not isinstance(header, dict):
            header = {}
        header[Field.VOXEL_TO_RASMM] = affine.copy()
        header[Field.VOXEL_SIZES] = vox_size
        header[Field.DIMENSIONS] = shape
        header[Field.VOXEL_ORDER] = "".join(aff2axcodes(affine))

    if reduce_memory_usage and not callable(streamlines):
        sg = lambda: (s for s in streamlines)
    else:
        sg = streamlines

    tractogram_loader = LazyTractogram if reduce_memory_usage else Tractogram
    tractogram = tractogram_loader(sg)
    tractogram.affine_to_rasmm = affine
    track_file = tractogram_file(tractogram, header=header)
    nib.streamlines.save(track_file, fname)
def save_dpy(streamlines, filename):
    ''' Save tractography to a .dpy file'''

    print "Save tracks as .dpy"	
    tracks = [track for track in streamlines]
    dpw = Dpy(filename, 'w')
    dpw.write_tracks(tracks)
    dpw.close()
def create_save_tracks(anisotropy,indices, seeds, low_thresh,filename):
    
    euler = EuDX(anisotropy, 
                        ind=indices, 
                        #odf_vertices=get_sphere('symmetric362'),
                        seeds=seeds, a_low=low_thresh)
                        #odf_vertices=get_sphere('symmetric362').vertices, 
    tracks = [track for track in euler]     
    dpw = Dpy(filename, 'w')
    dpw.write_tracks(tracks)
    dpw.close()
def create_save_tracks(anisotropy, indices, seeds, low_thresh, filename):

    euler = EuDX(
        anisotropy, ind=indices, odf_vertices=get_sphere("symmetric362").vertices, seeds=seeds, a_low=low_thresh
    )

    tensor_tracks_old = [track for track in euler]
    tracks = [track for track in tensor_tracks_old if track.shape[0] > 1]
    dpw = Dpy(filename, "w")
    dpw.write_tracks(tracks)
    dpw.close()
Пример #10
0
def save_tractogram(fname, streamlines, affine, vox_size=None, shape=None,
                    header=None, reduce_memory_usage=False,
                    tractogram_file=None):
    """ Saves tractogram files (*.trk or *.tck or *.dpy)

    Parameters
    ----------
    fname : str
        output trk filename
    streamlines : list of 2D arrays, generator or ArraySequence
        Each 2D array represents a sequence of 3D points (points, 3).
    affine : array_like (4, 4)
        The mapping from voxel coordinates to streamline points.
    vox_size : array_like (3,), optional
        The sizes of the voxels in the reference image (default: None)
    shape : array, shape (dim,), optional
        The shape of the reference image (default: None)
    header : dict, optional
        Metadata associated to the tractogram file(*.trk). (default: None)
    reduce_memory_usage : {False, True}, optional
        If True, save streamlines in a lazy manner i.e. they will not be kept
        in memory. Otherwise, keep all streamlines in memory until saving.
    tractogram_file : class TractogramFile, optional
        Define tractogram class type (TrkFile vs TckFile)
        Default is None which means auto detect format
    """
    if 'dpy' in os.path.splitext(fname)[1].lower():
        dpw = Dpy(fname, 'w')
        dpw.write_tracks(Streamlines(streamlines))
        dpw.close()
        return

    tractogram_file = tractogram_file or detect_format(fname)
    if tractogram_file is None:
        raise ValueError("Unknown format for 'fname': {}".format(fname))

    if vox_size is not None and shape is not None:
        if not isinstance(header, dict):
            header = {}
        header[Field.VOXEL_TO_RASMM] = affine.copy()
        header[Field.VOXEL_SIZES] = vox_size
        header[Field.DIMENSIONS] = shape
        header[Field.VOXEL_ORDER] = "".join(aff2axcodes(affine))

    if reduce_memory_usage and not callable(streamlines):
        sg = lambda: (s for s in streamlines)
    else:
        sg = streamlines

    tractogram_loader = LazyTractogram if reduce_memory_usage else Tractogram
    tractogram = tractogram_loader(sg)
    tractogram.affine_to_rasmm = affine
    track_file = tractogram_file(tractogram, header=header)
    nib.streamlines.save(track_file, fname)
Пример #11
0
def create_save_tracks(anisotropy,indices, seeds, low_thresh,filename):
    #this is new features in new dipy -current 121011 0.6.0.dev
    #print "Computing EuDX reconstruction."
    euler = EuDX(anisotropy, 
                        ind=indices, 
                        odf_vertices=get_sphere('symmetric362').vertices, 
                        seeds=seeds, a_low=low_thresh)
  
    
    euler = EuDX(anisotropy, ind=indices, seeds=seeds, a_low=low_thresh)
    tracks = [track for track in euler]     
    dpw = Dpy(filename, 'w')
    dpw.write_tracks(tracks)
    dpw.close()
Пример #12
0
def roi_intersection(fdpy,fatlas,roi_no,froidpy):    
    dpr=Dpy(fdpy,'r')
    T=dpr.read_tracksi(range(10000))    
    dpr.close()    
    Troi=[]
    wI=get_roi(fatlas,roi_no,0)
    for (i,t) in enumerate(T):
        if i%1000==0:
            print i
        if track_roi_intersection_check(t,wI,.5):
            Troi.append(t)
    print(len(Troi))    
    dpw=Dpy(froidpy,'w')
    dpw.write_tracks(Troi)
    dpw.close()
    
    '''
def create_save_tracks(anisotropy, indices, vertices, seeds, low_thresh, filename):

    from dipy.tracking.eudx import EuDX

    eu = EuDX(FA, peak_indices, odf_vertices=vertices, seeds=seeds, a_low=low_thresh)
    tensor_tracks_old = [streamline for streamline in eu]

    # euler = EuDX(anisotropy,
    #                    ind=indices,
    #                    odf_vertices=get_sphere('symmetric362').vertices,
    #                    seeds=seeds, a_low=low_thresh)
    # tensor_tracks_old = [track for track in euler]

    # print len(tensor_tracks_old)
    tracks = [track for track in tensor_tracks_old if track.shape[0] > 1]
    dpw = Dpy(filename, "w")
    dpw.write_tracks(tracks)
    dpw.close()
Пример #14
0
def runStream(csd_peaks, roi_file, roi_label=1, ang_thr=45., a_low=0.2, step_size=0.1, seeds_per_voxel=30, out_name=None):

    img = nib.load(roi_file)
    affine = img.get_affine()
    mask_data = img.get_data()
    p = np.asarray(np.where(mask_data == roi_label))
    p = p.transpose()

    # seed_points = None
    # for i in p:
    #     points = np.random.uniform(size=[seeds_per_voxel,3]) + (i-0.5)
    #     if seed_points is None:
    #         seed_points = points
    #     else:
    #         seed_points = np.concatenate([seed_points, points], axis=0)

    import dipy.tracking.utils as utils
    seeds = utils.seeds_from_mask(mask_data==1, density=seeds_per_voxel)    
    print '# of seeds: ',len(seeds)

    sphere = get_sphere('symmetric724')
    print "seed eudx tractography"
    eu = EuDX(csd_peaks.peak_values,
              csd_peaks.peak_indices,
              odf_vertices=sphere.vertices,
              step_sz=step_size,
              seeds=seeds,
              ang_thr=ang_thr,
              a_low=a_low)

    csa_streamlines_mult_peaks = [streamline for streamline in eu]

    out_file = 'tracts.dipy'
    if out_name:
        out_file = out_name+'_'+out_file

        from dipy.io.trackvis import save_trk
        save_trk(out_file, csa_streamlines_mult_peaks, affine,
                 mask.shape)

        dpw = Dpy(out_file, 'w')
        dpw.write_tracks(csa_streamlines_mult_peaks)
        print 'write tracts to %s' % out_file
    return (csa_streamlines_mult_peaks, out_file)
Пример #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 test_dpy():
    fname = 'test.bin'
    with InTemporaryDirectory():
        dpw = Dpy(fname, 'w')
        A = np.ones((5, 3))
        B = 2 * A.copy()
        C = 3 * A.copy()
        dpw.write_track(A)
        dpw.write_track(B)
        dpw.write_track(C)
        dpw.write_tracks([C, B, A])
        dpw.close()
        dpr = Dpy(fname, 'r')
        assert_equal(dpr.version() == '0.0.1', True)
        T = dpr.read_tracksi([0, 1, 2, 0, 0, 2])
        T2 = dpr.read_tracks()
        assert_equal(len(T2), 6)
        dpr.close()
        assert_array_equal(A, T[0])
        assert_array_equal(C, T[5])
def test_dpy():
    fname = 'test.bin'

    dpw = Dpy(fname, 'w')
    A = np.ones((5, 3))
    B = 2 * A.copy()
    C = 3 * A.copy()
    dpw.write_track(A)
    dpw.write_track(B)
    dpw.write_track(C)
    dpw.write_tracks([C, B, A])
    dpw.close()
    dpr = Dpy(fname, 'r')
    assert_equal(dpr.version() == '0.0.1', True)
    T = dpr.read_tracksi([0, 1, 2, 0, 0, 2])
    T2 = dpr.read_tracks()
    assert_equal(len(T2), 6)
    dpr.close()
    assert_array_equal(A, T[0])
    assert_array_equal(C, T[5])
Пример #19
0
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
Пример #20
0
def warp_tracks_linearly(flirt_filename,fa_filename, tracks_filename,linear_filename):
    fsl_ref = '/usr/share/fsl/data/standard/FMRIB58_FA_1mm.nii.gz'
    
    img_fa = nib.load(fa_filename)            

    flirt_affine= np.loadtxt(flirt_filename)    
        
    img_ref =nib.load(fsl_ref)
    
    #create affine matrix from flirt     
    mat=flirt2aff(flirt_affine,img_fa,img_ref)        

     #read tracks    
    dpr = Dpy(tracks_filename, 'r')
    tensor_tracks = dpr.read_tracks()
    dpr.close()
        
    #linear tranform for tractography
    tracks_warped_linear = transform_tracks(tensor_tracks,mat)        

    #save tracks_warped_linear    
    dpr_linear = Dpy(linear_filename, 'w')
    dpr_linear.write_tracks(tracks_warped_linear)
    dpr_linear.close()         
Пример #21
0
def test_dpy():
    fname = 'test.bin'
    with InTemporaryDirectory():
        dpw = Dpy(fname, 'w')
        A = np.ones((5, 3))
        B = 2 * A.copy()
        C = 3 * A.copy()
        dpw.write_track(A)
        dpw.write_track(B)
        dpw.write_track(C)
        dpw.write_tracks(Streamlines([C, B, A]))

        all_tracks = np.ascontiguousarray(np.vstack([A, B, C, C, B, A]))
        npt.assert_array_equal(all_tracks, dpw.tracks[:])
        dpw.close()

        dpr = Dpy(fname, 'r')
        npt.assert_equal(dpr.version() == u'0.0.1', True)
        T = dpr.read_tracksi([0, 1, 2, 0, 0, 2])
        T2 = dpr.read_tracks()
        npt.assert_equal(len(T2), 6)
        dpr.close()
        npt.assert_array_equal(A, T[0])
        npt.assert_array_equal(C, T[5])
Пример #22
0
def runStream(csd_peaks, roi_file, roi_label=1, output_file="tracts.dpy", ang_thr=45., a_low=0.2, step_size=0.1, seeds_per_voxel=30):

    img = nib.load(roi_file)
    roidata = img.get_data()
    p = np.asarray(np.where(roidata == roi_label))
    p = p.transpose()

    seed_points = None
    for i in p:
        points = np.random.uniform(size=[seeds_per_voxel,3]) + (i-0.5)
        if seed_points is None:
            seed_points = points
        else:
            seed_points = np.concatenate([seed_points, points], axis=0)

    sphere = get_sphere('symmetric724')
    print "seed eudx tractography"
    eu = EuDX(csd_peaks.peak_values,
              csd_peaks.peak_indices,
              odf_vertices=sphere.vertices,
              step_sz=step_size,
              seeds=seed_points,
              ang_thr=ang_thr,
              a_low=a_low)

    csa_streamlines_mult_peaks = [streamline for streamline in eu]

    ren = fvtk.ren()

    fvtk.add(ren, fvtk.line(csa_streamlines_mult_peaks, line_colors(csa_streamlines_mult_peaks)))
    fvtk.show(ren)

    dpw = Dpy(output_file, 'w')
    dpw.write_tracks(csa_streamlines_mult_peaks)

    return csa_streamlines_mult_peaks
Пример #23
0
Файл: fsl.py Проект: MPDean/dipy
def warp_displacements_tracks(fdpy, ffa, fmat, finv, fdis, fdisa, fref, fdpyw):
    """ Warp tracks from native space to the FMRIB58/MNI space

    We use here the fsl displacements. Have a look at create_displacements to
    see an example of how to use these displacements.

    Parameters
    ------------
    fdpy : filename of the .dpy file with the tractography
    ffa : filename of nifti to be warped
    fmat : filename of .mat  (flirt)
    fdis :  filename of displacements (fnirtfileutils)
    fdisa :  filename of displacements (fnirtfileutils + affine)
    finv : filename of invwarp displacements (invwarp)
    fref : filename of reference volume e.g. (FMRIB58_FA_1mm.nii.gz)
    fdpyw : filename of the warped tractography


    See also
    -----------
    dipy.external.fsl.create_displacements

    """

    # read the tracks from the image space
    dpr = Dpy(fdpy, 'r')
    T = dpr.read_tracks()
    dpr.close()

    # copy them in a new file
    dpw = Dpy(fdpyw, 'w', compression=1)
    dpw.write_tracks(T)
    dpw.close()

    # from fa index to ref index
    res = flirt2aff_files(fmat, ffa, fref)

    # load the reference img
    imgref = nib.load(fref)
    refaff = imgref.get_affine()

    # load the invwarp displacements
    imginvw = nib.load(finv)
    invwdata = imginvw.get_data()
    invwaff = imginvw.get_affine()

    # load the forward displacements
    imgdis = nib.load(fdis)
    disdata = imgdis.get_data()

    # load the forward displacements + affine
    imgdis2 = nib.load(fdisa)
    disdata2 = imgdis2.get_data()

    # from their difference create the affine
    disaff = disdata2 - disdata

    del disdata
    del disdata2

    shape = nib.load(ffa).get_data().shape

    # transform the displacements affine back to image space
    disaff0 = affine_transform(disaff[..., 0], res[:3, :3], res[:3, 3], shape,
                               order=1)
    disaff1 = affine_transform(disaff[..., 1], res[:3, :3], res[:3, 3], shape,
                               order=1)
    disaff2 = affine_transform(disaff[..., 2], res[:3, :3], res[:3, 3], shape,
                               order=1)

    # remove the transformed affine from the invwarp displacements
    di = invwdata[:, :, :, 0] + disaff0
    dj = invwdata[:, :, :, 1] + disaff1
    dk = invwdata[:, :, :, 2] + disaff2

    dprw = Dpy(fdpyw, 'r+')
    rows = len(dprw.f.root.streamlines.tracks)
    blocks = np.round(np.linspace(0, rows, 10)).astype(int)  # lets work in
    #                                                                   blocks
    # print rows
    for i in range(len(blocks) - 1):
        # print blocks[i],blocks[i+1]
        # copy a lot of tracks together
        caboodle = dprw.f.root.streamlines.tracks[blocks[i]:blocks[i + 1]]
        mci = mc(di, caboodle.T, order=1)  # interpolations for i displacement
        mcj = mc(dj, caboodle.T, order=1)  # interpolations for j displacement
        mck = mc(dk, caboodle.T, order=1)  # interpolations for k displacement
        D = np.vstack((mci, mcj, mck)).T
        # go back to mni image space
        WI2 = np.dot(caboodle, res[:3, :3].T) + res[:3, 3] + D
        # and then to mni world space
        caboodlew = np.dot(WI2, refaff[:3, :3].T) + refaff[:3, 3]
        # write back
        dprw.f.root.streamlines.tracks[blocks[i]:blocks[i + 1]] = (
            caboodlew.astype('f4'))
    dprw.close()
Пример #24
0
(as big as the size of you free disk space). With `Dpy` we can support

  * direct indexing from the disk
  * memory usage always low
  * extensions to include different arrays in the same file

Here is a simple example.
"""

from dipy.io.dpy import Dpy
dpw = Dpy('fornix.dpy', 'w')
"""
Write many streamlines at once.
"""

dpw.write_tracks(streamlines2)
"""
Write one track
"""

dpw.write_track(streamlines2[0])
"""
or one track each time.
"""

for t in streamlines:
    dpw.write_track(t)

dpw.close()
"""
Read streamlines directly from the disk using their indices
Пример #25
0
  * direct indexing from the disk
  * memory usage always low
  * extensions to include different arrays in the same file

Here is a simple example.
"""

from dipy.io.dpy import Dpy
dpw = Dpy('fornix.dpy', 'w')

"""
Write many streamlines at once.
"""

dpw.write_tracks(streamlines)

"""
Write one track
"""

dpw.write_track(streamlines[0])

"""
or one track each time.
"""

for t in streamlines:
    dpw.write_track(t)

dpw.close()
Пример #26
0
def read_warp_save_tracks(fdpy,ffa,fmat,finv,fdis,fdisa,fref,fdpyw):   
    
    #read the tracks from the image space 
    dpr=Dpy(fdpy,'r')
    T=dpr.read_tracks()
    dpr.close()    
    
    #copy them in a new file
    dpw=Dpy(fdpyw,'w',compression=1)
    dpw.write_tracks(T)
    dpw.close()
    
    #from fa index to ref index
    res=flirt2aff_files(fmat,ffa,fref)
    
    #load the reference img    
    imgref=nib.load(fref)
    refaff=imgref.get_affine()
    
    #load the invwarp displacements
    imginvw=nib.load(finv)
    invwdata=imginvw.get_data()
    invwaff = imginvw.get_affine()
    
    #load the forward displacements
    imgdis=nib.load(fdis)
    disdata=imgdis.get_data()
    
    #load the forward displacements + affine
    imgdis2=nib.load(fdisa)
    disdata2=imgdis2.get_data()
    
    #from their difference create the affine
    disaff=disdata2-disdata
    
    del disdata
    del disdata2
    
    shape=nib.load(ffa).get_data().shape
    
    #transform the displacements affine back to image space
    disaff0=affine_transform(disaff[...,0],res[:3,:3],res[:3,3],shape,order=1)
    disaff1=affine_transform(disaff[...,1],res[:3,:3],res[:3,3],shape,order=1)
    disaff2=affine_transform(disaff[...,2],res[:3,:3],res[:3,3],shape,order=1)
    
    #remove the transformed affine from the invwarp displacements
    di=invwdata[:,:,:,0] + disaff0
    dj=invwdata[:,:,:,1] + disaff1
    dk=invwdata[:,:,:,2] + disaff2    
    
    dprw=Dpy(fdpyw,'r+')
    rows=len(dprw.f.root.streamlines.tracks)   
    blocks=np.round(np.linspace(0,rows,10)).astype(int)#lets work in blocks
    print rows
    for i in range(len(blocks)-1):        
        print blocks[i],blocks[i+1]   
        #copy a lot of tracks together
        caboodle=dprw.f.root.streamlines.tracks[blocks[i]:blocks[i+1]]
        mci=map_coordinates(di,caboodle.T,order=1) #interpolations for i displacement
        mcj=map_coordinates(dj,caboodle.T,order=1) #interpolations for j displacement
        mck=map_coordinates(dk,caboodle.T,order=1) #interpolations for k displacement            
        D=np.vstack((mci,mcj,mck)).T
        #go back to mni image space                        
        WI2=np.dot(caboodle,res[:3,:3].T)+res[:3,3]+D
        #and then to mni world space
        caboodlew=np.dot(WI2,refaff[:3,:3].T)+refaff[:3,3]
        #write back       
        dprw.f.root.streamlines.tracks[blocks[i]:blocks[i+1]]=caboodlew.astype('f4')
    dprw.close()
Пример #27
0
def humans():   

    no_seeds=10**6
    visualize = False
    save_odfs = False
    dirname = "data/"    
    for root, dirs, files in os.walk(dirname):
        if root.endswith('101_32'):
            
            base_dir = root+'/'
            filename = 'raw'
            base_filename = base_dir + filename
            nii_filename = base_filename + 'bet.nii.gz'
            bvec_filename = base_filename + '.bvec'
            bval_filename = base_filename + '.bval'
            flirt_mat = base_dir + 'DTI/flirt.mat'    
            fa_filename = base_dir + 'DTI/fa.nii.gz'
            fsl_ref = '/usr/share/fsl/data/standard/FMRIB58_FA_1mm.nii.gz'
            dpy_filename = base_dir + 'DTI/res_tracks_dti.dpy'
    
            print bvec_filename
            
            img = nib.load(nii_filename)
            data = img.get_data()

            affine = img.get_affine()
            bvals = np.loadtxt(bval_filename)
            gradients = np.loadtxt(bvec_filename).T # this is the unitary direction of the gradient
            
            tensors = Tensor(data, bvals, gradients, thresh=50)
            FA = tensors.fa()                       
            FA = tensors.fa()
            famask=FA>=.2
            
            ds=DiffusionSpectrum(data,bvals,gradients,odf_sphere='symmetric642',mask=famask,half_sphere_grads=True,auto=True,save_odfs=save_odfs)
            gq=GeneralizedQSampling(data,bvals,gradients,1.2,odf_sphere='symmetric642',mask=famask,squared=False,save_odfs=save_odfs)
            ei=EquatorialInversion(data,bvals,gradients,odf_sphere='symmetric642',mask=famask,half_sphere_grads=True,auto=False,save_odfs=save_odfs,fast=True)
            ei.radius=np.arange(0,5,0.4)
            ei.gaussian_weight=0.05
            ei.set_operator('laplacian')
            ei.update()
            ei.fit()    
            
            ds.PK[FA<.2]=np.zeros(5) 
            ei.PK[FA<.2]=np.zeros(5)
            gq.PK[FA<.2]=np.zeros(5)                   
                        
            print 'create seeds'
            x,y,z,g=ei.PK.shape
            seeds=np.zeros((no_seeds,3))
            sid=0
            while sid<no_seeds:
                rx=(x-1)*np.random.rand()
                ry=(y-1)*np.random.rand()
                rz=(z-1)*np.random.rand()
                seed=np.ascontiguousarray(np.array([rx,ry,rz]),dtype=np.float64)        
                seeds[sid]=seed
                sid+=1
            
            euler = EuDX(a=FA, ind=tensors.ind(), seeds=seeds, a_low=.2)
            dt_tracks = [track for track in euler]                                    
            euler2 = EuDX(a=ds.PK, ind=ds.IN, seeds=seeds, odf_vertices=ds.odf_vertices, a_low=.2)
            ds_tracks = [track for track in euler2]    
            euler3 = EuDX(a=gq.PK, ind=gq.IN, seeds=seeds, odf_vertices=gq.odf_vertices, a_low=.2)
            gq_tracks = [track for track in euler3]
            euler4 = EuDX(a=ei.PK, ind=ei.IN, seeds=seeds, odf_vertices=ei.odf_vertices, a_low=.2)
            ei_tracks = [track for track in euler4]
            
            if visualize:
                renderer = fvtk.ren()
                fvtk.add(renderer, fvtk.line(tensor_tracks, fvtk.red, opacity=1.0))
                fvtk.show(renderer)
            
            print 'Load images to be used for registration'
            img_fa =nib.load(fa_filename)
            img_ref =nib.load(fsl_ref)
            mat=flirt2aff(np.loadtxt(flirt_mat),img_fa,img_ref)
            del img_fa
            del img_ref
            
            print 'transform the tracks'
            dt_linear = transform_tracks(dt_tracks,mat)
            ds_linear = transform_tracks(ds_tracks,mat)
            gq_linear = transform_tracks(gq_tracks,mat)
            ei_linear = transform_tracks(ei_tracks,mat)
                        
            print 'save tensor tracks'
            dpy_filename = base_dir + 'DTI/dt_linear.dpy'
            print dpy_filename
            dpr_linear = Dpy(dpy_filename, 'w')
            dpr_linear.write_tracks(dt_linear)
            dpr_linear.close()
            
            print 'save ei tracks'
            dpy_filename = base_dir + 'DTI/ei_linear.dpy'
            print dpy_filename
            dpr_linear = Dpy(dpy_filename, 'w')
            dpr_linear.write_tracks(ei_linear)
            dpr_linear.close()
            
            print 'save ds tracks'
            dpy_filename = base_dir + 'DTI/ds_linear.dpy'
            print dpy_filename
            dpr_linear = Dpy(dpy_filename, 'w')
            dpr_linear.write_tracks(ds_linear)
            dpr_linear.close()
            
            print 'save gq tracks'
            dpy_filename = base_dir + 'DTI/gq_linear.dpy'
            print dpy_filename
            dpr_linear = Dpy(dpy_filename, 'w')
            dpr_linear.write_tracks(gq_linear)
            dpr_linear.close()
            
            print 'save lengths'
            pkl_filename = base_dir + 'DTI/dt_lengths.pkl'
            save_pickle(pkl_filename,lengths(dt_linear))            
            pkl_filename = base_dir + 'DTI/ei_lengths.pkl'
            save_pickle(pkl_filename,lengths(ei_linear))
            pkl_filename = base_dir + 'DTI/gq_lengths.pkl'
            save_pickle(pkl_filename,lengths(gq_linear))
            pkl_filename = base_dir + 'DTI/ds_lengths.pkl'
            save_pickle(pkl_filename,lengths(ds_linear))
Пример #28
0
def tracking_eudx4csd(dir_src, dir_out, verbose=False,gwmi_seeds=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)


    if gwmi_seeds:
      gwmi_mask_file  = dir_src + '/wm_mask_b1k_2mm_add_gwmi.nii.gz' # dir_src + '/gwmi_' + par_dim_tag + '.nii.gz'
      gwmi_mask_img = nib.load(gwmi_mask_file)
      gwmi_mask_aff = gwmi_mask_img.get_affine()
      gwmi_mask_dat = gwmi_mask_img.get_data()
      seeds = seeds_from_mask(gwmi_mask_dat>0,density=30,affine=gwmi_mask_aff)
      gwmi_tag = '_gwmi_seeds_den30'
    else:
      seeds = par_eudx_seeds 
      gwmi_tag = ''


    # 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=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 + gwmi_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()
Пример #29
0
huge datasets use dipy.io.dpy

* direct indexing from the disk
* memory usage always low
* extendable

"""

from dipy.io.dpy import Dpy
dpw=Dpy('fornix.dpy','w')

"""
write many tracks at once
"""

dpw.write_tracks(tracks2)

"""
write one track
"""

dpw.write_track(tracks2[0]*6)

"""
or one track each time
"""

for t in tracks:
    dpw.write_track(t*3)

dpw.close()
Пример #30
0
def save_tracks_dpy(tracks,filename):
    from dipy.io.dpy import Dpy
    dpw = Dpy(filename, 'w')
    dpw.write_tracks(tracks)
    dpw.close() 
Пример #31
0
    ds=DiffusionSpectrum(data,bvals,gradients,\
                odf_sphere='symmetric642',\
                mask=famask,\
                half_sphere_grads=True,\
                auto=True,\
                save_odfs=False)
    print 'DSI', time()-t
    #ds.PK[FA<.2]=np.zeros(5)
    
    t=time()
    euler=EuDX(a=FA,ind=tensors.ind(),seeds=seeds,a_low=.2)
    T=[track for track in euler] 
    print 'Eudx ten',time()-t,len(T)

    dpr_linear = Dpy(ftracks[0], 'w')
    dpr_linear.write_tracks(T)
    dpr_linear.close()
    del T


    for i,qgrid in enumerate([ds,gqs,ei]):
        t=time()
        euler=EuDX(a=qgrid.PK,ind=qgrid.IN,seeds=seeds,odf_vertices=qgrid.odf_vertices,a_low=.2)
        T=[track for track in euler]     
        print 'Eudx ',time()-t, len(T)
        dpr_linear = Dpy(ftracks[i+1], 'w')
        dpr_linear.write_tracks(T)
        dpr_linear.close()
        del T

Пример #32
0
"""
huge datasets use dipy.io.dpy

* direct indexing from the disk
* memory usage always low
* extendable

"""

from dipy.io.dpy import Dpy
dpw = Dpy('fornix.dpy', 'w')
"""
write many tracks at once
"""

dpw.write_tracks(tracks2)
"""
write one track
"""

dpw.write_track(tracks2[0] * 6)
"""
or one track each time
"""

for t in tracks:
    dpw.write_track(t * 3)

dpw.close()
"""
read tracks directly from the disk using their indices
Пример #33
0
def save_tractogram(sft, filename, bbox_valid_check=True):
    """ Save the stateful tractogram in any format (trk, tck, vtk, fib, dpy)

    Parameters
    ----------
    sft : StatefulTractogram
        The stateful tractogram to save
    filename : string
        Filename with valid extension

    Returns
    -------
    output : bool
        Did the saving work properly
    """

    _, extension = os.path.splitext(filename)
    if extension not in ['.trk', '.tck', '.vtk', '.fib', '.dpy']:
        TypeError('Output filename is not one of the supported format')

    if bbox_valid_check and not sft.is_bbox_in_vox_valid():
        raise ValueError('Bounding box is not valid in voxel space, cannot ' +
                         'save a valid file if some coordinates are invalid')

    old_space = deepcopy(sft.space)
    old_shift = deepcopy(sft.shifted_origin)

    sft.to_rasmm()
    sft.to_center()

    timer = time.time()
    if extension in ['.trk', '.tck']:
        tractogram_type = detect_format(filename)
        header = create_tractogram_header(tractogram_type,
                                          *sft.space_attribute)
        new_tractogram = Tractogram(sft.streamlines,
                                    affine_to_rasmm=np.eye(4))

        if extension == '.trk':
            new_tractogram.data_per_point = sft.data_per_point
            new_tractogram.data_per_streamline = sft.data_per_streamline

        fileobj = tractogram_type(new_tractogram, header=header)
        nib.streamlines.save(fileobj, filename)

    elif extension in ['.vtk', '.fib']:
        save_vtk_streamlines(sft.streamlines, filename, binary=True)
    elif extension in ['.dpy']:
        dpy_obj = Dpy(filename, mode='w')
        dpy_obj.write_tracks(sft.streamlines)
        dpy_obj.close()

    logging.debug('Save %s with %s streamlines in %s seconds',
                  filename, len(sft), round(time.time() - timer, 3))

    if old_space == Space.VOX:
        sft.to_vox()
    elif old_space == Space.VOXMM:
        sft.to_voxmm()

    if old_shift:
        sft.to_corner()

    return True
Пример #34
0
def warp_displacements_tracks(fdpy, ffa, fmat, finv, fdis, fdisa, fref, fdpyw):
    """ Warp tracks from native space to the FMRIB58/MNI space

    We use here the fsl displacements. Have a look at create_displacements to
    see an example of how to use these displacements.

    Parameters
    ------------
    fdpy : filename of the .dpy file with the tractography
    ffa : filename of nifti to be warped
    fmat : filename of .mat  (flirt)
    fdis :  filename of displacements (fnirtfileutils)
    fdisa :  filename of displacements (fnirtfileutils + affine)
    finv : filename of invwarp displacements (invwarp)
    fref : filename of reference volume e.g. (FMRIB58_FA_1mm.nii.gz)
    fdpyw : filename of the warped tractography


    See also
    -----------
    dipy.external.fsl.create_displacements

    """

    # read the tracks from the image space
    dpr = Dpy(fdpy, 'r')
    T = dpr.read_tracks()
    dpr.close()

    # copy them in a new file
    dpw = Dpy(fdpyw, 'w', compression=1)
    dpw.write_tracks(T)
    dpw.close()

    # from fa index to ref index
    res = flirt2aff_files(fmat, ffa, fref)

    # load the reference img
    imgref = nib.load(fref)
    refaff = imgref.affine

    # load the invwarp displacements
    imginvw = nib.load(finv)
    invwdata = imginvw.get_data()

    # load the forward displacements
    imgdis = nib.load(fdis)
    disdata = imgdis.get_data()

    # load the forward displacements + affine
    imgdis2 = nib.load(fdisa)
    disdata2 = imgdis2.get_data()

    # from their difference create the affine
    disaff = disdata2 - disdata

    del disdata
    del disdata2

    shape = nib.load(ffa).get_data().shape

    # transform the displacements affine back to image space
    disaff0 = affine_transform(disaff[..., 0], res[:3, :3], res[:3, 3], shape,
                               order=1)
    disaff1 = affine_transform(disaff[..., 1], res[:3, :3], res[:3, 3], shape,
                               order=1)
    disaff2 = affine_transform(disaff[..., 2], res[:3, :3], res[:3, 3], shape,
                               order=1)

    # remove the transformed affine from the invwarp displacements
    di = invwdata[:, :, :, 0] + disaff0
    dj = invwdata[:, :, :, 1] + disaff1
    dk = invwdata[:, :, :, 2] + disaff2

    dprw = Dpy(fdpyw, 'r+')
    rows = len(dprw.f.root.streamlines.tracks)
    blocks = np.round(np.linspace(0, rows, 10)).astype(int)  # lets work in
    #                                                                   blocks
    # print rows
    for i in range(len(blocks) - 1):
        # print blocks[i],blocks[i+1]
        # copy a lot of tracks together
        caboodle = dprw.f.root.streamlines.tracks[blocks[i]:blocks[i + 1]]
        mci = mc(di, caboodle.T, order=1)  # interpolations for i displacement
        mcj = mc(dj, caboodle.T, order=1)  # interpolations for j displacement
        mck = mc(dk, caboodle.T, order=1)  # interpolations for k displacement
        D = np.vstack((mci, mcj, mck)).T
        # go back to mni image space
        WI2 = np.dot(caboodle, res[:3, :3].T) + res[:3, 3] + D
        # and then to mni world space
        caboodlew = np.dot(WI2, refaff[:3, :3].T) + refaff[:3, 3]
        # write back
        dprw.f.root.streamlines.tracks[blocks[i]:blocks[i + 1]] = (
            caboodlew.astype('f4'))
    dprw.close()
Пример #35
0
def save_tractogram(sft, filename, bbox_valid_check=True):
    """ Save the stateful tractogram in any format (trk, tck, vtk, fib, dpy)

    Parameters
    ----------
    sft : StatefulTractogram
        The stateful tractogram to save
    filename : string
        Filename with valid extension
    bbox_valid_check : bool
        Verification for negative voxel coordinates or values above the
        volume dimensions. Default is True, to enforce valid file.

    Returns
    -------
    output : bool
        True if the saving operation was successful
    """

    _, extension = os.path.splitext(filename)
    if extension not in ['.trk', '.tck', '.vtk', '.fib', '.dpy']:
        raise TypeError('Output filename is not one of the supported format')

    if bbox_valid_check and not sft.is_bbox_in_vox_valid():
        raise ValueError('Bounding box is not valid in voxel space, cannot ' +
                         'load a valid file if some coordinates are ' +
                         'invalid. Please use the function ' +
                         'remove_invalid_streamlines to discard invalid ' +
                         'streamlines or set bbox_valid_check to False')

    old_space = deepcopy(sft.space)
    old_shift = deepcopy(sft.shifted_origin)

    sft.to_rasmm()
    sft.to_center()

    timer = time.time()
    if extension in ['.trk', '.tck']:
        tractogram_type = detect_format(filename)
        header = create_tractogram_header(tractogram_type,
                                          *sft.space_attributes)
        new_tractogram = Tractogram(sft.streamlines, affine_to_rasmm=np.eye(4))

        if extension == '.trk':
            new_tractogram.data_per_point = sft.data_per_point
            new_tractogram.data_per_streamline = sft.data_per_streamline

        fileobj = tractogram_type(new_tractogram, header=header)
        nib.streamlines.save(fileobj, filename)

    elif extension in ['.vtk', '.fib']:
        save_vtk_streamlines(sft.streamlines, filename, binary=True)
    elif extension in ['.dpy']:
        dpy_obj = Dpy(filename, mode='w')
        dpy_obj.write_tracks(sft.streamlines)
        dpy_obj.close()

    logging.debug('Save %s with %s streamlines in %s seconds', filename,
                  len(sft), round(time.time() - timer, 3))

    if old_space == Space.VOX:
        sft.to_vox()
    elif old_space == Space.VOXMM:
        sft.to_voxmm()

    if old_shift:
        sft.to_corner()

    return True
Пример #36
0
	tracks_id_left = load_pickle( cstidx_path + str(sub[id_file])+'_corticospinal_L_3M.pkl')
	tracks_id_right = load_pickle(cstidx_path + str(sub[id_file])+'_corticospinal_R_3M.pkl')
	
	cst_left = [tensor_all_tracks[i] for i  in tracks_id_left]
	cst_right = [tensor_all_tracks[i] for i  in tracks_id_right]

	cst_left_fname = output_path + str(mapping[sub[id_file]])+'_corticospinal_L_3M_registered.dpy'

	cst_right_fname = output_path + str(mapping[sub[id_file]])+'_corticospinal_R_3M_registered.dpy'

	"""
	Save the streamlines.
	"""

	dpw = Dpy(cst_left_fname, 'w')
	dpw.write_tracks(cst_left)    
	dpw.close()
      print len(cst_left)
	print '>>>> Done ', cst_left_fname

	dpw = Dpy(cst_right_fname, 'w')
	dpw.write_tracks(cst_right)    
	dpw.close()
      print len(sct_right)
	print '>>>> Done ', cst_right_fname