def test_write(): streams = [] out_f = StringIO() tv.write(out_f, [], {}) yield assert_equal, out_f.getvalue(), tv.empty_header().tostring() out_f.truncate(0) # Write something not-default tv.write(out_f, [], {'id_string':'TRACKb'}) # read it back out_f.seek(0) streams, hdr = tv.read(out_f) yield assert_equal, hdr['id_string'], 'TRACKb' # check that we can pass none for the header out_f.truncate(0) tv.write(out_f, []) out_f.truncate(0) tv.write(out_f, [], None) # check that we check input values out_f.truncate(0) yield (assert_raises, tv.HeaderError, tv.write, out_f, [],{'id_string':'not OK'}) yield (assert_raises, tv.HeaderError, tv.write, out_f, [],{'version':2}) yield (assert_raises, tv.HeaderError, tv.write, out_f, [],{'hdr_size':0})
def test_round_trip(): out_f = StringIO() xyz0 = np.tile(np.arange(5).reshape(5, 1), (1, 3)) xyz1 = np.tile(np.arange(5).reshape(5, 1) + 10, (1, 3)) streams = [(xyz0, None, None), (xyz1, None, None)] tv.write(out_f, streams, {}) out_f.seek(0) streams2, hdr = tv.read(out_f) yield assert_true, streamlist_equal(streams, streams2)
def test_round_trip(): out_f = StringIO() xyz0 = np.tile(np.arange(5).reshape(5,1), (1, 3)) xyz1 = np.tile(np.arange(5).reshape(5,1) + 10, (1, 3)) streams = [(xyz0, None, None), (xyz1, None, None)] tv.write(out_f, streams, {}) out_f.seek(0) streams2, hdr = tv.read(out_f) yield assert_true, streamlist_equal(streams, streams2)
def streams(self): if 'streams' in self._cache: return self._cache['streams'] trk_fname = get_onefile(self._glob_prefix + 'fiber_track_mni.trk') if trk_fname is None: return None streams, hdr = tv.read(trk_fname) self._cache['hdr'] = hdr self._cache['streams'] = streams return streams
def load_reduce_translate(fname, reduction=1): """ Loads a trackvis file using DIPY io, only keeping a ratio of 1/reduction tracks. Performs trajectory approximation to reduce the track lengths. Parameter --------- fname : str The Trackvis file reduction : int, optional The reduction factor (keep only 1 line per set of reduction lines) Returns ------- tracks : list A list of tracks """ lines, hdr = tv.read(fname) print 'loaded,', sys.stdout.flush() #ras = tv.get_affine(hdr) ras = tv.aff_from_hdr(hdr) if not ras[:3,-1].any(): # dot(ras[:3,:3],md_vox) + t = (0,0,0) --> t = -dot(ras[:3,:3],md_vox) md_vox = hdr['dim']/2 t = -np.dot(ras[:3,:3], md_vox) ras[:3,-1] = t tracks = [l[0] for l in lines[::reduction]] del lines ras_cmap = ni_api.AffineTransform.from_params('ijk', 'xyz', ras) flat_tracks, breaks = flatten_tracks(tracks) del tracks flat_tracks_xyz = ras_cmap(flat_tracks) tracks = recombine_flattened_tracks(flat_tracks_xyz, breaks) print 'translated,', sys.stdout.flush() tracks_reduced = [tp.approximate_ei_trajectory(line, alpha=np.pi/4) for line in tracks ] print 'reduced,' sys.stdout.flush() return tracks_reduced
def init(self): import dipy.io.trackvis as tv lines,hdr = tv.read(self.fname) ras = tv.aff_from_hdr(hdr) self.affine=ras tracks = [l[0] for l in lines] if self.yellow_indices != None : tracks = [t for t in tracks if tm.length(t) > 20] print 'tracks loaded' #self.data = [100*np.array([[0,0,0],[1,0,0],[2,0,0]]).astype(np.float32) ,100*np.array([[0,1,0],[0,2,0],[0,3,0]]).astype(np.float32)]#tracks[:20000] if self.dummy_data: self.data = [100*np.array([[0,0,0],[1,0,0],[2,0,0]]).astype(np.float32) ,100*np.array([[0,1,0],[0,2,0],[0,3,0]]).astype(np.float32)] if self.data_subset!=None: self.data = tracks[self.data_subset[0]:self.data_subset[1]] else: self.data = tracks data_stats = np.concatenate(tracks) self.min=np.min(data_stats,axis=0) self.max=np.max(data_stats,axis=0) self.mean=np.mean(data_stats,axis=0) del data_stats del lines self.multiple_colors()
def test_write(): streams = [] out_f = StringIO() tv.write(out_f, [], {}) yield assert_equal(out_f.getvalue(), tv.empty_header().tostring()) out_f.truncate(0) # Write something not-default tv.write(out_f, [], {'id_string': 'TRACKb'}) # read it back out_f.seek(0) streams, hdr = tv.read(out_f) yield assert_equal(hdr['id_string'], 'TRACKb') # check that we can pass none for the header out_f.truncate(0) tv.write(out_f, []) out_f.truncate(0) tv.write(out_f, [], None) # check that we check input values out_f.truncate(0) yield assert_raises(tv.HeaderError, tv.write, out_f, [], {'id_string': 'not OK'}) yield assert_raises(tv.HeaderError, tv.write, out_f, [], {'version': 3}) yield assert_raises(tv.HeaderError, tv.write, out_f, [], {'hdr_size': 0})
from dipy.io import trackvis as tv from dipy.io import pickles as pkl from dipy.core import track_learning as tl from dipy.core import track_performance as pf from dipy.core import track_metrics as tm import time import numpy as np import os fname = '/home/eg01/Data/PBC/pbc2009icdm/brain1/brain1_scan1_fiber_track_mni.trk' C_fname = '/tmp/larch_tree.pkl' appr_fname = '/tmp/larch_tracks.trk' print 'Loading trackvis file...' streams, hdr = tv.read(fname) print 'Copying tracks...' tracks = [i[0] for i in streams] #tracks=tracks[:1000] #print 'Deleting unnecessary data...' del streams #,hdr if not os.path.isfile(C_fname): print 'Starting LARCH ...' tim = time.clock() C, atracks = tl.larch(tracks, [50.**2, 20.**2, 5.**2], True, True) #tracks=[tm.downsample(t,3) for t in tracks]
from dipy.core import track_metrics as tm from dipy.viz import fos from dipy.io import trackvis as tv from dipy.io import pickles as pkl from dipy.core import track_performance as pf import time import numpy as np #fname='/home/eg01/Data/PBC/pbc2009icdm/brain1/brain1_scan1_fiber_track_mni.trk' fname='/home/eg309/Data/PBC/pbc2009icdm/brain1/brain1_scan1_fiber_track_mni.trk' print 'Loading file...' streams,hdr=tv.read(fname) print 'Copying tracks...' T=[i[0] for i in streams] print 'Representing tracks using only 3 pts...' tracks=[tm.downsample(t,3) for t in T] print 'Deleting unnecessary data...' del streams,hdr print 'Hidden Structure Clustering...' now=time.clock() C=pf.local_skeleton_clustering(tracks,d_thr=20) print 'Done in', time.clock()-now,'s.' print 'Reducing the number of points...' T=[pf.approximate_ei_trajectory(t) for t in T]
[8, 10853, 15572], [ 9, 13280, 8461], [ 0, 11275, 9224]]) ''' corr_mat_demo=np.array([[ 1, 10560, 3609],[ 2, 17872, 15377],[ 3, 6447, 3897], [4, 18854, 6409], [ 5, 14416, 4515], [ 7, 9956, 13913], [8, 10853, 15572], [ 9, 13280, 8461], [ 0, 11275, 9224]]) print 'Minimum track length', min_len, 'mm' print 'Number of segments for downsampling',down print 'Number of tracks for detection',rand_tracks print 'Minimum searched track length', min_search_len, 'mm' print 'Maximum searched track length', max_search_len, 'mm' tracks1,hdr1=tv.read(br1path) tracks2,hdr2=tv.read(br2path) tracks3,hdr3=tv.read(br3path) #Load only track points, no scalars or parameters. tracks1=[t[0] for t in tracks1] tracks2=[t[0] for t in tracks2] tracks3=[t[0] for t in tracks3] print 'Before thresholding' print len(tracks1) print len(tracks2) print len(tracks3)
''' Benchmarks for Zhang metrics ''' import os from os.path import join as pjoin import numpy as np import dipy.io.trackvis as tv import dipy.core.track_performance as pf import dipy.core.track_metrics as tm from numpy.testing import measure _data_path = pjoin(os.path.dirname(__file__), 'data') _track_tuples, _ = tv.read(pjoin(_data_path, 'tracks300.trk.gz')) tracks300 = [_t[0] for _t in _track_tuples] def bench_zhang(): print 'Zhang min' print '=' * 10 #ref_time = measure('tm.most_similar_track_zhang(tracks300)') #print 'reference time: %f' % ref_time opt_time = measure('pf.most_similar_track_zhang(tracks300)') print 'optimized time: %f' % opt_time print def bench_cut_plane(): print 'Cut plane' print '=' * 10 opt_time = measure('pf.cut_plane(tracks300, tracks300[0])') print 'optimized time: %f' % opt_time print
''' Benchmarks for Zhang metrics ''' import os from os.path import join as pjoin import numpy as np import dipy.io.trackvis as tv import dipy.core.track_performance as pf import dipy.core.track_metrics as tm from numpy.testing import measure _data_path = pjoin(os.path.dirname(__file__), 'data') _track_tuples, _ = tv.read(pjoin(_data_path, 'tracks300.trk.gz')) tracks300 = [_t[0] for _t in _track_tuples] def bench_zhang(): print 'Zhang min' print '=' * 10 #ref_time = measure('tm.most_similar_track_zhang(tracks300)') #print 'reference time: %f' % ref_time opt_time = measure('pf.most_similar_track_zhang(tracks300)') print 'optimized time: %f' % opt_time print def bench_cut_plane(): print 'Cut plane' print '=' * 10 opt_time = measure('pf.cut_plane(tracks300, tracks300[0])') print 'optimized time: %f' % opt_time
frame = make_window_maker(trajs, colors)() app.MainLoop() del frame del app if __name__ == "__main__": #trajs=[100*np.random.rand(10,3),100*np.random.rand(20,3)] #colors=[np.random.rand(3,),np.random.rand(3,)] from dipy.io import trackvis as tv from dipy.core import track_performance #from enthought.mayavi import mlab #from enthought.tvtk.api import tvtk import numpy as np fname='/home/eg309/Data/PBC/pbc2009icdm/brain1/brain1_scan1_fiber_track_mni.trk' lines, hdr = tv.read(fname) pts = [p[0] for p in lines] pts_reduced = [track_performance.approx_polygon_track(p) for p in pts] red = np.array([1,0,0]) trajs=pts_reduced colors=[np.array([1.,0,0]) for i in range(len(trajs))] show(trajs)
def init(self): br1path='/home/eg01/Data_Backup/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000/dtk_dti_out/dti_FACT.trk' br2path='/home/eg01/Data_Backup/Data/Eleftherios/CBU090134_METHODS/20090227_154122/Series_003_CBU_DTI_64D_iso_1000/dtk_dti_out/dti_FACT.trk' br3path='/home/eg01/Data_Backup/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000/dtk_dti_out/dti_RK2.trk' min_len=20 down=20 rand_tracks=-1 #default 10 min_search_len=70 min_search_len=70 max_search_len=140 corr_mat_demo=np.array([[ 1, 10560, 3609],[ 2, 17872, 15377],[ 3, 6447, 3897], [4, 18854, 6409], [ 5, 14416, 4515], [ 7, 9956, 13913], [8, 10853, 15572], [ 9, 13280, 8461], [ 0, 11275, 9224]]) print 'Minimum track length', min_len, 'mm' print 'Number of segments for downsampling',down print 'Number of tracks for detection',rand_tracks print 'Minimum searched track length', min_search_len, 'mm' print 'Maximum searched track length', max_search_len, 'mm' tracks1,hdr1=tv.read(br1path) tracks2,hdr2=tv.read(br2path) tracks3,hdr3=tv.read(br3path) #Load only track points, no scalars or parameters. tracks1=[t[0] for t in tracks1] tracks2=[t[0] for t in tracks2] tracks3=[t[0] for t in tracks3] print 'Before thresholding' print len(tracks1) print len(tracks2) print len(tracks3) print hdr1['dim'] print hdr2['dim'] print hdr3['dim'] #Apply thresholds tracks1=[t for t in tracks1 if tm.length(t) > min_len] tracks2=[t for t in tracks2 if tm.length(t) > min_len] tracks3=[t for t in tracks3 if tm.length(t) > min_len] print 'After thresholding' print len(tracks1) print len(tracks2) print len(tracks3) print 'Downsampling' tracks1z=[tm.downsample(t,down) for t in tracks1] tracks2z=[tm.downsample(t,down) for t in tracks2] tracks3z=[tm.downsample(t,down) for t in tracks3] print 'Detecting random tracks' lt1=len(tracks1) lt2=len(tracks2) lt3=len(tracks3) if rand_tracks==-1: #use already stored indices t_ind=corr_mat_demo[:,1] t_ind=np.array(t_ind) print 'Indices of tracks for detection', t_ind print 'Finding corresponding tracks' global track2track track2track= self.corresponding_tracks(t_ind,tracks1z,tracks2z) global track2track2 track2track2=self.corresponding_tracks(t_ind,tracks1z,tracks3z) print 'First Correspondance Matrix' print track2track print 'Second Correspondance Matrix' print track2track2 print 'first brain' print track2track[:,1].T print 'second brain' print track2track[:,2].T print 'third brain' print track2track2[:,2].T #fos.add(r,fos.line(tracks1,fos.red,opacity=0.01)) #fos.add(r,fos.line(tracks2,fos.cyan,opacity=0.01)) tracks1zshift = tracks1z tracks2zshift = tracks2z tracks3zshift = tracks3z m1z=np.concatenate(tracks1zshift).mean(axis=0) m2z=np.concatenate(tracks2zshift).mean(axis=0) m3z=np.concatenate(tracks3zshift).mean(axis=0) #tracks1zshift=[t+np.array([-70,0,0]) for t in tracks1z] #tracks2zshift=[t+np.array([70,0,0]) for t in tracks2z] tracks1zshift=[t-m1z for t in tracks1z] tracks2zshift=[t-m2z for t in tracks2z] tracks3zshift=[t-m3z for t in tracks3z] global t1 #devel07 t1=tracks.Tracks(None,data_ext=tracks1zshift) t1.angular_speed = 0.1 t1.brain_color=[1,0,0] t1.manycolors=False t1.opacity = 0.01 t1.orbit_demo=True t1.orbit_anglez_rate = 0. t1.orbit_anglex_rate = 0. t1.orbit_angley_rate = .2 t1.init() t1.position = np.array([-120,0,-30]) print 't1p',t1.position global t2 #devel07 t2=tracks.Tracks(None,data_ext=tracks2zshift) t2.angular_speed = 0.1 t2.brain_color=[0,1,1] t2.manycolors=False t2.opacity = 0.01 t2.orbit_demo=True t2.orbit_anglez_rate = 0. t2.orbit_anglex_rate = 0. t2.orbit_angley_rate = .2 t2.init() t2.position = np.array([0,0,-30]) print 't2p', t2.position global t3 #devel07 t3=tracks.Tracks(None,data_ext=tracks3zshift) t3.angular_speed = 0.1 t3.manycolors=False t3.brain_color=[0,0,1] t3.opacity = 0.01 t3.orbit_demo=True t3.orbit_anglez_rate = 0. t3.orbit_anglex_rate = 0. t3.orbit_angley_rate = .2 t3.init() #t3.position = - #np.concatenate(tracks3zshift).mean(axis=0)+np.array([70,0,0]) t3.position = np.array([120,0,-30]) print 't3p', t3.position self.slots={0:{'actor':t1,'slot':( 0, 800*MS ) }, 1:{'actor':t2,'slot':( 0, 800*MS ) }, 2:{'actor':t3,'slot':( 0, 800*MS ) }}
def __init__(self,fname,colormap=None, line_width=1., shrink=None, thinning = 0, angle_table = None, manycolors = False, brain_color=[1,1,1]): self.position = (0,0,0) self.fname = fname self.manycolors = manycolors #self.color = monocolor self.bbox = None self.list_index = None self.affine = None self.data = None self.list_index = None self.rot_angle = 0 self.colormap = None self.min = None self.max = None self.mean = None self.material_color = False self.fadeout = False self.fadein = False self.fadeout_speed = 0. self.fadein_speed = 0. self.min_length = 20. self.angle = 0. self.angular_speed = .5 self.line_width = line_width self.opacity = 1. self.opacity_rate = 0. self.near_pick = None self.far_pick = None self.near_pick_prev = None self.far_pick_prev = None self.picked_track = None self.pick_color = [1,1,0] #self.brain_color = [1,1,1] # white #self.brain_color = [.941,.862,.510] # buff self.brain_color = brain_color self.yellow_indices = None self.dummy_data = False self.data_subset = [0,20000]#None self.orbit_demo = False self.orbit_anglez =0. self.orbit_anglez_rate = 10. self.orbit_anglex = 0. self.orbit_anglex_rate = 2. self.angle_table = angle_table if angle_table != None: print 'Tracks angle_table shape %s' % str(self.angle_table.shape) self.angle_table_index = 0 #print 'angle_table_index %d' % self.angle_table_index self.shrink = shrink self.picking_example = False import dipy.io.trackvis as tv lines,hdr = tv.read(self.fname) ras = tv.aff_from_hdr(hdr ) self.affine=ras tracks = [l[0] for l in lines] print 'tracks %d loaded' % len(tracks) self.thinning = thinning if self.yellow_indices != None : tracks = [t for t in tracks if tm.length(t) > 20] if self.thinning != 0: tracks = [tracks[k] for k in range(0,len(tracks),self.thinning)] print '%d tracks active' % len(tracks) #self.data = [100*np.array([[0,0,0],[1,0,0],[2,0,0]]).astype(np.float32) ,100*np.array([[0,1,0],[0,2,0],[0,3,0]]).astype(np.float32)]#tracks[:20000] if self.dummy_data: self.data = [100*np.array([[0,0,0],[1,0,0],[2,0,0]]).astype(np.float32) ,100*np.array([[0,1,0],[0,2,0],[0,3,0]]).astype(np.float32)] if self.data_subset!=None: self.data = tracks[self.data_subset[0]:self.data_subset[1]] else: self.data = tracks if self.shrink != None: self.data = [ self.shrink*t for t in self.data] data_stats = np.concatenate(tracks) self.min=np.min(data_stats,axis=0) self.max=np.max(data_stats,axis=0) self.mean=np.mean(data_stats,axis=0) del data_stats del lines
def __init__(self,fname,ang_table=None,colormap=None, line_width=3., shrink=None,subset=None,tracks=None,text=None,text_color=np.array([1,0,0])): self.position = (0,0,0) self.fname = fname self.manycolors = True self.bbox = None self.list_index = None self.affine = None self.data = None self.list_index = None self.rot_angle = 0 self.colormap = None self.text = text self.min = None self.max = None self.mean = None self.material_color = False self.fadeout = False self.fadein = False self.fadeout_speed = 0. self.fadein_speed = 0. self.min_length = 20. self.angle = 0. self.angular_speed = .5 self.line_width = line_width self.opacity = 1. self.near_pick = None self.far_pick = None self.near_pick_prev = None self.far_pick_prev = None self.picked_track = None self.pick_color = [1,1,0] self.brain_color = [1,1,1] self.yellow_indices = None self.dummy_data = False self.tracks = tracks if subset != None: self.data_subset = subset #[0,20000]#None else: self.data_subset = None self.orbit_demo = False self.orbit_anglez = 0. self.orbit_anglez_rate = 10. self.orbit_anglex = 0. self.orbit_anglex_rate = 2. self.angle_table = ang_table self.angle_table_index = 0 self.shrink = shrink self.picking_example = False self.partial_colors = False import dipy.io.trackvis as tv if self.tracks == None: lines,hdr = tv.read(self.fname) ras = tv.aff_from_hdr(hdr) self.affine=ras tracks = [l[0] for l in lines] del lines else: tracks = self.tracks if self.yellow_indices != None : tracks = [t for t in tracks if tm.length(t) > 20] print '%d tracks loaded' % len(tracks) #self.data = [100*np.array([[0,0,0],[1,0,0],[2,0,0]]).astype(np.float32) ,100*np.array([[0,1,0],[0,2,0],[0,3,0]]).astype(np.float32)]#tracks[:20000] if self.dummy_data: self.data = [100*np.array([[0,0,0],[1,0,0],[2,0,0]]).astype(np.float32) ,100*np.array([[0,1,0],[0,2,0],[0,3,0]]).astype(np.float32)] if self.data_subset!=None: self.data = tracks[self.data_subset[0]:self.data_subset[1]] else: self.data = tracks if self.shrink != None: self.data = [ self.shrink*t for t in self.data] data_stats = np.concatenate(tracks) self.min=np.min(data_stats,axis=0) self.max=np.max(data_stats,axis=0) self.mean=np.mean(data_stats,axis=0) del data_stats
app = wx.PySimpleApp() frame = make_window_maker(trajs, colors)() app.MainLoop() del frame del app if __name__ == "__main__": #trajs=[100*np.random.rand(10,3),100*np.random.rand(20,3)] #colors=[np.random.rand(3,),np.random.rand(3,)] from dipy.io import trackvis as tv from dipy.core import track_performance #from enthought.mayavi import mlab #from enthought.tvtk.api import tvtk import numpy as np fname = '/home/eg309/Data/PBC/pbc2009icdm/brain1/brain1_scan1_fiber_track_mni.trk' lines, hdr = tv.read(fname) pts = [p[0] for p in lines] pts_reduced = [track_performance.approx_polygon_track(p) for p in pts] red = np.array([1, 0, 0]) trajs = pts_reduced colors = [np.array([1., 0, 0]) for i in range(len(trajs))] show(trajs)