Ejemplo n.º 1
0
def test_track_volumes():
    # simplest case
    vol_dims = (1, 2, 3)
    tracks = ([[0, 0, 0], [0, 1, 1]], )
    tracks = [np.array(t) for t in tracks]
    ex_counts, ex_els = tracks_to_expected(tracks, vol_dims)
    tcs, tes = tvo.track_counts(tracks, vol_dims, [1, 1, 1])
    assert_array_equal(tcs, ex_counts)
    assert_array_equal(tes, ex_els)
    # check only counts returned for return_elements=False
    tcs = tvo.track_counts(tracks, vol_dims, [1, 1, 1], False)
    assert_array_equal(tcs, ex_counts)

    # non-unique points, non-integer points, points outside
    vol_dims = (5, 10, 15)
    tracks = ([[-1, 0, 1], [0, 0.1, 0], [1, 1, 1], [1, 1, 1],
               [2, 2, 2]], [[0.7, 0, 0], [1, 1, 1], [1, 2, 2], [1, 11, 0]])
    tracks = [np.array(t) for t in tracks]
    ex_counts, ex_els = tracks_to_expected(tracks, vol_dims)
    tcs, tes = tvo.track_counts(tracks, vol_dims, [1, 1, 1])
    assert_array_equal(tcs, ex_counts)
    assert_array_equal(tes, ex_els)
    # points with non-unit voxel sizes
    vox_sizes = [1.4, 2.1, 3.7]
    float_tracks = []
    for t in tracks:
        float_tracks.append(t * vox_sizes)
    tcs, tes = tvo.track_counts(float_tracks, vol_dims, vox_sizes)
    assert_array_equal(tcs, ex_counts)
    assert_array_equal(tes, ex_els)
Ejemplo n.º 2
0
def volumn_intersec(tract1, tract2, vol_dims, voxel_size, disp=False):
    from dipy.tracking.vox2track import track_counts
    
    #compute the number of fiber crossing every voxel
    tcv1 = track_counts(tract1,vol_dims, voxel_size, return_elements=False)
    tcv2 = track_counts(tract2,vol_dims, voxel_size, return_elements=False)

    count = 0    
    count1 = 0
    count2 = 0
    for x in np.arange(vol_dims[0]):
        for y in np.arange(vol_dims[1]):
            for z in np.arange(vol_dims[2]):
                if tcv1[x,y,z]>0:
                    count1 = count1 + 1
                    #count1 = count1 + tcv1[x,y,z]
                    
                if tcv2[x,y,z]>0:
                    count2 = count2 + 1
                    #count2 = count2 + tcv2[x,y,z]
                
                if tcv1[x,y,z]>0 and tcv2[x,y,z]>0:
                    count = count + 1
                    #count = count +  min(tcv1[x,y,z],tcv2[x,y,z])
                    
    if disp:
        viz_vol1(tcv1,fvtk.colors.red)
        viz_vol1(tcv2,fvtk.colors.blue)
    return count1, count2, count
Ejemplo n.º 3
0
 def maskout_tracks(self):
     """ retrieve ids of virtuals which go through the mask
     """
     mask = self.slicer.mask        
     #tracks = self.tracks_shifted
     tracks = self.virtuals_shifted
     #tcs,self.tes = track_counts(tracks,mask.shape,(1,1,1),True)
     tcs,tes = track_counts(tracks,mask.shape,(1,1,1),True)
     # print 'tcs:',tcs
     # print 'tes:',len(self.tes.keys())
     #find volume indices of mask's voxels
     roiinds=np.where(mask==1)
     #make it a nice 2d numpy array (Nx3)
     roiinds=np.array(roiinds).T
     #get tracks going through the roi
     # print "roiinds:", len(roiinds)
     # mask_tracks,mask_tracks_inds=bring_roi_tracks(tracks,roiinds,self.tes)
     mask_tracks_inds = []
     for voxel in roiinds:
         try:
             #mask_tracks_inds+=self.tes[tuple(voxel)]
             mask_tracks_inds+=tes[tuple(voxel)]
         except KeyError:
             pass
     mask_tracks_inds = list(set(mask_tracks_inds))
     print("Masked tracks %d" % len(mask_tracks_inds))
     print("mask_tracks_inds: %s" % mask_tracks_inds)
     return mask_tracks_inds
Ejemplo n.º 4
0
def connectivity_matrix(streamlines, rois):
    tcs, tes = track_counts(streamlines, rois.shape, return_elements=True)
    srois = {}

    for i in range(1, 41):
        roi_indices = np.array(np.where(rois == i)).T
        for roind in roi_indices:
            try:
                for s in tes[tuple(roind)]:
                    try:
                        srois[s].append(i - 1)
                    except KeyError:
                        srois[s] = [i - 1]
            except KeyError:
                pass

    mat = np.zeros((40, 40))
    for s in srois:
        srois[s] = set(srois[s])
        if len(srois[s]) >= 3:            
            continue
        if len(srois[s]) < 2:            
            continue

        try:
            mat[tuple(srois[s])] += 1
        except IndexError:
            print IndexError
            print srois[s]

    return mat, srois, 100 * mat.sum() / np.float(len(streamlines))
Ejemplo n.º 5
0
 def maskout_tracks(self):
     """ retrieve ids of virtuals which go through the mask
     """
     mask = self.slicer.mask
     #tracks = self.tracks_shifted
     tracks = self.virtuals_shifted
     #tcs,self.tes = track_counts(tracks,mask.shape,(1,1,1),True)
     tcs, tes = track_counts(tracks, mask.shape, (1, 1, 1), True)
     # print 'tcs:',tcs
     # print 'tes:',len(self.tes.keys())
     #find volume indices of mask's voxels
     roiinds = np.where(mask == 1)
     #make it a nice 2d numpy array (Nx3)
     roiinds = np.array(roiinds).T
     #get tracks going through the roi
     # print "roiinds:", len(roiinds)
     # mask_tracks,mask_tracks_inds=bring_roi_tracks(tracks,roiinds,self.tes)
     mask_tracks_inds = []
     for voxel in roiinds:
         try:
             #mask_tracks_inds+=self.tes[tuple(voxel)]
             mask_tracks_inds += tes[tuple(voxel)]
         except KeyError:
             pass
     mask_tracks_inds = list(set(mask_tracks_inds))
     print("Masked tracks %d" % len(mask_tracks_inds))
     print("mask_tracks_inds: %s" % mask_tracks_inds)
     return mask_tracks_inds
Ejemplo n.º 6
0
def roi_track_counts(fdpy,fref,fatlas,roi_no,dist_transf=True,fres=None):
    
    dpr=Dpy(fdpy,'r')
    T=dpr.read_tracks()
    dpr.close()
    
    img=nib.load(fref)
    affine=img.get_affine()
    zooms = img.get_header().get_zooms()
    iaffine=np.linalg.inv(affine)
    T2=[]
    #go back to volume space
    for t in T:
        T2.append(np.dot(t,iaffine[:3,:3].T)+iaffine[:3,3])
    del T
    
    tcs,tes=track_counts(T2,img.get_shape(),zooms,True)
    
    atlas_img=nib.load(fatlas)
    atlas=atlas_img.get_data()
    roi=atlas.copy()
    roi[atlas!=roi_no]=0
    
    if dist_transf:
        roi2=distance_transform_cdt(roi)
        roi[roi2!=roi2.max()]=0
        I=np.array(np.where(roi==roi_no)).T
    else:
        I=np.array(np.where(roi==roi_no)).T    
    
    """    
    if erosion_level>0:
        roi2=binary_erosion(roi,cross,erosion_level)                 
        I=np.array(np.where(roi2==True)).T
    else:        
        roi2=distance_transform_cdt(roi)        
        I=np.array(np.where(roi==roi_no)).T        
    """
    
    #print I.shape    
    #nib.save(nib.Nifti1Image(roi2,affine),'/tmp/test.nii.gz')
    
    Ttes=[]
    for iroi in I:
        try:
            Ttes.append(tes[tuple(iroi)])
        except KeyError:
            pass
    
    Ttes=list(set(list(chain.from_iterable(Ttes))))    
    T2n=np.array(T2,dtype=np.object)
    res=list(T2n[Ttes])
    
    #back to world space
    res2=[]
    for t in res:
        res2.append(np.dot(t,affine[:3,:3].T)+affine[:3,3])
    np.save(fres,np.array(res2,dtype=np.object))
Ejemplo n.º 7
0
def count_tracks_mask(tracks,shape,mask,value):
    tcs,tes=track_counts(tracks,shape,return_elements=True)    
    inds=np.array(np.where(mask==value)).T
    tracks_mask=[]
    for p in inds:
        try:
            tracks_mask+=tes[tuple(p)]
        except KeyError:
            pass
    return list(set(tracks_mask))
Ejemplo n.º 8
0
def test_track_volumes():
    # simplest case
    vol_dims = (1, 2, 3)
    tracks = ([[0, 0, 0],
               [0, 1, 1]],)
    tracks = [np.array(t) for t in tracks]
    ex_counts, ex_els = tracks_to_expected(tracks, vol_dims)
    tcs, tes = tvo.track_counts(tracks, vol_dims, [1,1,1])
    assert_array_equal(tcs, ex_counts)
    assert_array_equal( tes, ex_els)
    # check only counts returned for return_elements=False
    tcs = tvo.track_counts(tracks, vol_dims, [1,1,1], False)
    assert_array_equal(tcs, ex_counts)

    # non-unique points, non-integer points, points outside
    vol_dims = (5, 10, 15)
    tracks = ([[-1, 0, 1],
               [0, 0.1, 0],
               [1, 1, 1],
               [1, 1, 1],
               [2, 2, 2]],
              [[0.7, 0, 0],
               [1, 1, 1],
               [1, 2, 2],
               [1, 11, 0]])
    tracks = [np.array(t) for t in tracks]
    ex_counts, ex_els = tracks_to_expected(tracks, vol_dims)
    tcs, tes = tvo.track_counts(tracks, vol_dims, [1,1,1])
    assert_array_equal( tcs, ex_counts)
    assert_array_equal( tes, ex_els)
    # points with non-unit voxel sizes
    vox_sizes = [1.4, 2.1, 3.7]
    float_tracks = []
    for t in tracks:
        float_tracks.append(t * vox_sizes)
    tcs, tes = tvo.track_counts(float_tracks, vol_dims, vox_sizes)
    assert_array_equal(tcs, ex_counts)
    assert_array_equal(tes, ex_els)
Ejemplo n.º 9
0
def count(tract_filename, roi_anat, roi_idx_range):
    roi_img = nib.load(roi_anat)
    voxel_dim = roi_img.get_header()['pixdim'][1:4]
    anat_dim = roi_img.get_header().get_data_shape()

    # Detect the format of the tracts file.
    # IF TRK, load and shift
    # ELSE, load
    tracts_format = tc.detect_format(tract_filename)
    tracts_file = tracts_format(tract_filename, anatFile=roi_anat)

    if tracts_format is tc.FORMATS["trk"]:
        tracts = np.array([s - voxel_dim / 2. for s in tracts_file.load_all()])
    else:
        tracts = np.array([s for s in tracts_file])

    _, tes = track_counts(tracts, anat_dim, voxel_dim, True)

    # If the data is a 4D volume with only one element in 4th dimension,
    # this will make it 3D, to correctly work with the tes variable.
    roi_data = roi_img.get_data().squeeze()

    if len(roi_data.shape) > 3:
        raise ValueError('Tract counting will fail with an anatomy of ' +
                         'more than 3 dimensions.')

    roi_counts = []

    for roi_idx in roi_idx_range:
        roi_vox_idx = izip(*np.where(roi_data == roi_idx))
        tractIdx_per_voxel = [set(tes.get(idx, [])) for idx in roi_vox_idx]

        if len(tractIdx_per_voxel) > 0:
            unique_streamline_idx = set.union(*tractIdx_per_voxel)
            roi_counts.append((roi_idx, len(unique_streamline_idx)))

    return roi_counts
Ejemplo n.º 10
0
from nibabel.trackvis import write, empty_header

grid = np.mgrid[1.1:1.8:3j, 1.1:1.8:3j, .5:5]
grid = np.rollaxis(grid, 0, 4)

streamlines = []

for ii in grid:
    for jj in ii:
        streamlines.append(jj)

#Treat these streamlines as if they are in trackvis format and generate counts
counts_trackvis = density_map(streamlines, (4, 4, 5), (1, 1, 1))

#Treat these streamlines as if they are in nifti format and generate counts
counts_nifti = track_counts(streamlines, (4, 4, 5), (1, 1, 1),
                            return_elements=False)

print("saving trk files and track_count volumes")
aff = np.eye(4)
aff[0, 0] = -1
img = nib.Nifti1Image(counts_trackvis.astype('int16'), aff)
nib.save(img, 'counts_trackvis.nii.gz')
img = nib.Nifti1Image(counts_nifti.astype('int16'), aff)
nib.save(img, 'counts_nifti.nii.gz')

hdr = empty_header()
hdr['voxel_size'] = (1, 1, 1)
hdr['voxel_order'] = 'las'
hdr['vox_to_ras'] = aff
hdr['dim'] = counts_nifti.shape
Ejemplo n.º 11
0
print 'No reduced tracks ',len(ten_tracks)

raw_input('Press enter...')


#load the rois
imsk1=nib.load(dname+'/'+froi1)
roi1=imsk1.get_data()
imsk2=nib.load(dname+'/'+froi2)
roi2=imsk2.get_data()

print 'roi dimensions', roi1.shape,roi2.shape
print 'roi voxels', np.sum(roi1==255),np.sum(roi2==255)
#tcs track counts volume
#tes dictionary of tracks passing from voxels
tcs,tes=track_counts(ten_tracks,data.shape[:3],(1,1,1),True)

#find volume indices of mask's voxels
roiinds1=np.where(roi1==255)
roiinds2=np.where(roi2==255)

#make it a nice 2d numpy array (Nx3)
roiinds1=np.array(roiinds1).T
roiinds2=np.array(roiinds2).T

def bring_roi_tracks(tracks,roiinds,tes):
    """
    bring the tracks from the roi region and their indices
    """
    cnt=0    
    sinds=[]
Ejemplo n.º 12
0
from nibabel.trackvis import write, empty_header

grid = np.mgrid[1.1:1.8:3j,1.1:1.8:3j,.5:5]
grid = np.rollaxis(grid, 0, 4)

streamlines = []

for ii in grid:
    for jj in ii:
        streamlines.append(jj)

#Treat these streamlines as if they are in trackvis format and generate counts
counts_trackvis = density_map(streamlines, (4,4,5), (1,1,1))

#Treat these streamlines as if they are in nifti format and generate counts
counts_nifti = track_counts(streamlines, (4,4,5), (1,1,1), 
                            return_elements=False)

print("saving trk files and track_count volumes")
aff = np.eye(4)
aff[0, 0] = -1
img = nib.Nifti1Image(counts_trackvis.astype('int16'), aff)
nib.save(img, 'counts_trackvis.nii.gz')
img = nib.Nifti1Image(counts_nifti.astype('int16'), aff)
nib.save(img, 'counts_nifti.nii.gz')

hdr = empty_header()
hdr['voxel_size'] = (1,1,1)
hdr['voxel_order'] = 'las'
hdr['vox_to_ras'] = aff
hdr['dim'] = counts_nifti.shape