-
Notifications
You must be signed in to change notification settings - Fork 0
/
pbc.py
2093 lines (1410 loc) · 60.1 KB
/
pbc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
The Dipy team for the PBC Competition
Examples
------------
>>> import pbc
>>> path='/home/eg01/Data/PBC/pbc2009icdm'
>>> G,hdr=pbc.load_training_set(path)
>>> pbc.show_training_set(G)
>>> pbc.calculate_properties_training_set(G,hdr)
>>> pbc.print_properties_training_set(G)
Notes
-------
X -> Front to Back
Y -> Left to Right
Z -> Up to Down
'''
import os
import lights
import form
import time
import scipy as sp
import numpy as np
from copy import copy,deepcopy
import numpy.linalg as npla
import volumeimages as vi
from dipy.core import track_performance as pf
from dipy.viz import fos
#from dipy.viz import phos
from dipy.core import track_metrics as tm
from dipy.core import track_learning as tl
from scipy.interpolate import splprep, splev
import scipy.ndimage as nd
import pbc1109
from pbc1109 import track_volumes as tv
import mdp
def training_set_as_dict(T,L):
''' Represent training set a dict whith keys 0 to 8. Where 0 to 8 corresponds to labels
'None','Arcuate','Cingulum','Corticospinal','Forceps Major','Fornix','Inferior Occipitofrontal Fasciculus','Superior Longitudinal Fasciculus','Uncinate'
Input
------
T : list of tracks represented as arrays of shape Mx3
L : array shape N,2 representing the labels where first column is the index of the track and second column is the corresponding label
Returns
---------
G : dict
'''
node={'label_name':'','tracks':[],'indices':[],'centers':sp.array([0,0,0]),'curvatures':[],'lengths':[],'mids2center':[]}
G={ 0:deepcopy(node),1:deepcopy(node), 2:deepcopy(node),3:deepcopy(node),
4:deepcopy(node),5:deepcopy(node), 6:deepcopy(node),7:deepcopy(node),
8:deepcopy(node)}
Labels=['None','Arcuate','Cingulum','Corticospinal','Forceps Major','Fornix','Inferior Occipitofrontal Fasciculus','Superior Longitudinal Fasciculus','Uncinate']
for i in [0,1,2,3,4,5,6,7,8]:
G[i]['label_name']=Labels[i]
L=L.astype(int)
L[:,0]=L[:,0]-1
print 'Indexing tracks to their corresponding label'
for (i,label) in L:
G[label]['tracks'].append(T[i])
G[label]['indices'].append(i)
return G
def load_training_set(path):
''' Load brain1 scan1
'''
ds=pbc1109.PBCData(path)
print 'Loading training set which is brain 1 scan 1'
b11=ds.get_data(1,1)
#copy streamlines
print 'Copying streamlines'
S=b11.streams
#copy hdr
print 'Copying header'
hdr=b11.hdr
#copy track points in tracks
print 'Copying all tracks in a list'
tracks=[s[0] for s in S]
#copy labels
labels=b11.labels
#create a graph representing the training set
print 'Creating a graph representing the training set'
G=training_set_as_dict(tracks,labels)
del ds
del S
R={1: 197816, 2: 15009, 3: 157189,4: 64423,5: 118191,6: 168055,7: 123041,8: 88647}
print 'Printing indices for references '
print R
return G,hdr,R
def load_training_set_plus(path):
''' Load brain1 scan1
plus relative indices and reference fibers
'''
ds=pbc1109.PBCData(path)
print 'Loading training set which is brain 1 scan 1'
b11=ds.get_data(1,1)
#copy streamlines
print 'Copying streamlines'
S=b11.streams
#copy hdr
print 'Copying header'
hdr=b11.hdr
#copy track points in tracks
print 'Copying all tracks in a list'
tracks=[s[0] for s in S]
#copy labels
labels=b11.labels
#create a graph representing the training set
print 'Creating a graph representing the training set'
G=training_set_as_dict(tracks,labels)
del ds
del S
R={1: 197816, 2: 15009, 3: 157189,4: 64423,5: 118191,6: 168055,7: 123041,8: 88647}
relR = {}
ref = {}
for b in [1,2,3,4,5,6,7,8]:
relR[b] = G[b]['indices'].index(R[b])
ref[b] = G[b]['tracks'][relR[b]]
print 'Printing indices for reference fibers'
print R
print 'Printing relative indices for reference fibers'
print relR
return G,hdr,R,relR,ref
def load_approximate_training_set(path):
''' Load brain1 scan1
'''
ds=pbc1109.PBCData(path)
print 'Loading training set which is brain 1 scan 1'
b11=ds.get_data(1,1)
#copy streamlines
print 'Copying streamlines'
S=b11.streams
#copy hdr
print 'Copying header'
hdr=b11.hdr
#copy track points in tracks
print 'Copying all tracks in a list'
#tracks=[s[0] for s in S]
#!!!!!!!!!!!!
tracksa=load_approximate_tracks(path,1,1)
#copy labels
labels=b11.labels
#create a graph representing the training set
print 'Creating a graph representing the training set'
G=training_set_as_dict(tracksa,labels)
del ds
del S
R={1: 79032, 2: 115651, 3: 76983, 4: 17556, 5: 206781, 6: 168055, 7: 59215, 8: 88647}
print 'Printing indices for references '
print R
return G,hdr,R
def show_training_set(G,show=True):
''' Show training_set represented as a dictionary using fos
The plan is to see the labeled bundles with different colors along with their label_names.
In plus the start point of every track is visualized with green and then end point with red.
The label names are hanging from the start points of the tracks.
The blue sphere represents the center of the volume (91,109,91).
'''
r=fos.ren()
#colors_labels=[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]
colors_labels=np.random.rand(9,3)
#colors_labels=
for g in [1,2,3,4,5,6,7,8]:
fos.add(r,fos.line(G[g]['tracks'],colors=colors_labels[g]))
for g in [1,2,3,4,5,6,7,8]:
#for track in G[g]['tracks']:
T=G[g]['tracks']
start=np.array([t[0] for t in T])
end=np.array([t[-1] for t in T])
fos.add(r,fos.dots(start,color=(0,1,0.2)))
fos.add(r,fos.dots(end,color=(1,0,0)))
fos.label(r,text=' '+str(g)+'.'+G[g]['label_name'],pos=start[0],scale=(2,2,2))
#fos.add(r,fos.sphere(position=(91,109,91),radius=5,thetares=8,phires=8,color=(0,0,1),opacity=1,tessel=0))
r.ResetCamera()
if show:
fos.show(r)
def mori_atlas_labels():
labels={
0:'Unclassified',
1:'Middle cerebellar peduncle',
2:'Pontine crossing tract (a part of MCP)',
3:'Genu of corpus callosum',
4:'Body of corpus callosum',
5:'Splenium of corpus callosum',
6:'Fornix (column and body of fornix)',
7:'Corticospinal tract R',
8:'Corticospinal tract L',
9:'Medial lemniscus R',
10:'Medial lemniscus L',
11:'Inferior cerebellar peduncle R',
12:'Inferior cerebellar peduncle L',
13:'Superior cerebellar peduncle R',
14:'Superior cerebellar peduncle L',
15:'Cerebral peduncle R',
16:'Cerebral peduncle L',
17:'Anterior limb of internal capsule R',
18:'Anterior limb of internal capsule L',
19:'Posterior limb of internal capsule R',
20:'Posterior limb of internal capsule L',
21:'Retrolenticular part of internal capsule R',
22:'Retrolenticular part of internal capsule L',
23:'Anterior corona radiata R',
24:'Anterior corona radiata L',
25:'Superior corona radiata R',
26:'Superior corona radiata L',
27:'Posterior corona radiata R',
28:'Posterior corona radiata L',
29:'Posterior thalamic radiation (include optic radiation) R',
30:'Posterior thalamic radiation (include optic radiation) L',
31:'Sagittal stratum (include inferior longitidinal fasciculus and inferior fronto-occipital fasciculus) R',
32:'Sagittal stratum (include inferior longitidinal fasciculus and inferior fronto-occipital fasciculus) L' ,
33:'External capsule R',
34:'External capsule L',
35:'Cingulum (cingulate gyrus) R',
36:'Cingulum (cingulate gyrus) L',
37:'Cingulum (hippocampus) R',
38:'Cingulum (hippocampus) L',
39:'Fornix (cres) / Stria terminalis (can not be resolved with current resolution) R' ,
40:'Fornix (cres) / Stria terminalis (can not be resolved with current resolution) L' ,
41:'Superior longitudinal fasciculus R',
42:'Superior longitudinal fasciculus L',
43:'Superior fronto-occipital fasciculus (could be a part of anterior internal capsule) R',
44:'Superior fronto-occipital fasciculus (could be a part of anterior internal capsule) L' ,
45:'Uncinate fasciculus R',
46:'Uncinate fasciculus L',
47:'Tapetum R',
48:'Tapetum L'}
print('Problem with labels')
return None
#return labels
def load_loni_atlas(path):
#path='/backup/Data/ICBM_Atlas/ICBM_Wmpm'
atlasfn=path+'/ICBM_WMPM.nii'
labelfn=path+'/LabelLookupTable.txt'
if os.path.isfile(atlasfn)==False:
print('File does not exist')
return None,None,None
img = vi.load(atlasfn)
arr = np.array(img.get_data())
voxsz = img.get_metadata().get_zooms()
aff = img.get_affine()
#labels = np.fromfile(labels_fname, dtype=np.uint, sep=' ')
lines = []
with open(labelfn, 'rt') as f:
for line in f:
lines.append([val.strip() for val in line.split('\t') if val.strip()])
lines[-1][2]=lines[-1][2]+' '+lines[-1][3]
lines[-1]=[lines[-1][0],lines[-1][1],lines[-1][2]]
labels=lines
return arr,voxsz,aff,labels
def copy_object(arr,thr):
arr_tmp=np.zeros(arr.shape).astype('uint8')
arr_tmp[np.where(arr==thr)]=1
return arr_tmp
def load_mori_atlas(atlasfn=None):
if atlasfn==None:
atlasfn='/home/eg01/Data/Mori_Template/FSL/JHU-WhiteMatter-labels-1mm.nii'
if os.path.isfile(atlasfn)==False:
print('File does not exist')
return None,None,None
img = vi.load(atlasfn)
arr = np.array(img.get_data())
voxsz = img.get_metadata().get_zooms()
aff = img.get_affine()
labels=mori_atlas_labels()
#return arr,voxsz,aff,labels
print('Problem with the labels do not use this function')
return None
def show_atlas(arr,voxsz,aff,labels,G):
opacitymap=np.vstack((np.arange(1,51),np.linspace(0.02,0.1,50))).T
opacitymap=np.vstack((opacitymap,np.array([0,0])))
opacitymap=np.sort(opacitymap,axis=0)
v=np.linspace(0,1,51)
red=np.interp(v,[0,0.35,0.66,0.89,1],[0,0,1,1,0.5])
green=np.interp(v,[0,0.125,0.375,0.64,0.91,1],[0,0,1,1,0,0])
blue=np.interp(v,[0,0.11,0.34,0.65,1],[0.5,1,1,0,0])
#colormap=np.vstack((np.arange(51),np.linspace(0,1,51),0*np.linspace(0,1,51),1-np.linspace(0,1,51))).T
colormap=np.vstack((np.arange(51),red,green,blue)).T
colormap=colormap.astype('float32')
r=fos.ren()
fos.clear(r)
print 'min',arr.min(), 'max',arr.max()
arr2=np.zeros(arr.shape).astype('uint8')
#47 UNC-R Uncinate fasciculus right
ind=np.where(arr==47)
arr2[ind]=255
#48 UNC-L Uncinate fasciculus left
ind=np.where(arr==48)
arr2[ind]=255
#7 CST-R Corticospinal tract right
ind=np.where(arr==7)
arr2[ind]=255
#8 CST-L Corticospinal tract left
ind=np.where(arr==8)
arr2[ind]=255
v=fos.volume(arr2,voxsz,aff)
#v=fos.volume(arr2,voxsz,aff,info=1,opacitymap=opacitymap,colormap=colormap)
#c=fos.contour(arr,voxsz,levels=np.arange(1,51),colors=np.random.rand(50,3),opacities=np.linspace(0.45,0.5,50))
#c=fos.contour(arr,voxsz,levels=np.arange(1,51),colors=np.random.rand(50,3),opacities=np.ones(50))
#c=fos.contour(arr,voxsz,levels=np.arange(1,3),colors=np.random.rand(2,3),opacities=np.ones(2))
#c=fos.contour(arr,voxsz,levels=np.arange(45,51),colors=np.random.rand(50,3),opacities=np.ones(50))
#c=fos.contour(arr,voxsz,levels=[7,8],colors=np.random.rand(2,3),opacities=np.ones(2))
#colors_labels=np.random.rand(9,3)
#fos.add(r,c)
fos.add(r,v)
'''
for g in [1,2,3,4,5,6,7,8]:
bundle=G[g]['tracks']
#bundle=[t+np.array([-90,-108,-90]) for t in bundle]
fos.add(r,fos.line(bundle,colors=colors_labels[g]))
'''
fos.show(r)
def calculate_properties_training_set(G,hdr):
center=hdr['dim']/2.0
center=pbc1109.vox2mm(center,hdr)
for g in G:
G[g]['curvatures']=[tm.mean_curvature(t) for t in G[g]['tracks'] ]
G[g]['mean_cluster_curvature']=np.mean(np.array(G[g]['curvatures']))
G[g]['lengths']=[tm.length(t) for t in G[g]['tracks'] ]
G[g]['mean_length']=np.mean(np.array(G[g]['lengths']))
G[g]['mids2center']=[tm.midpoint2point(t,center) for t in G[g]['tracks']]
G[g]['mean_mids2center']=np.mean(np.array(G[g]['mids2center']))
def print_properties_training_set(G):
for g in G:
print str(g),'.',G[g]['label_name'],'\n mean_cluster_curvature', round(G[g]['mean_cluster_curvature'],3),'mean_length',round(G[g]['mean_length'],3),'mean_mids2center',round(G[g]['mean_mids2center'],2)
def load_tracks(path,brain,scan):
''' Load tracks from a PBC path
Parameters:
---------------
path : string
brain : int
from 1 to 3
scan : int
from 1 to 2
Returns:
---------
tracks : sequence of arrays
vol_dims : tuple
volume dimensions
'''
ds=pbc1109.PBCData(path)
print 'Loading training set which is brain 1 scan 1'
b11=ds.get_data(brain,scan)
#copy streamlines
print 'Copying streamlines'
S=b11.streams
#copy hdr
print 'Copying header'
hdr=b11.hdr
vol_dims=hdr['dim']
print hdr['dim']
#copy track points in tracks
print 'Copying all tracks in a list'
tracks=[s[0] for s in S]
#print 'Counting ...'
return tracks,vol_dims
def save_pickle(fname,dix):
import cPickle
out=open(fname,'wb')
cPickle.dump(dix,out)
out.close()
def load_pickle(fname):
import cPickle
inp=open(fname,'rb')
dix=cPickle.load(inp)
inp.close()
return dix
def helix(segs=100):
''' Return a helix with some noise please
'''
# make ascending spiral in 3-space
t=np.linspace(0,1.75*2*np.pi,segs)
x = np.sin(t)
y = np.cos(t)
z = t
# add noise
#x+= np.random.normal(scale=0.1, size=x.shape)
#y+= np.random.normal(scale=0.1, size=y.shape)
#z+= np.random.normal(scale=0.1, size=z.shape)
xyz=np.vstack((x,y,z)).T
return xyz
def sine(segs=100):
t=np.linspace(0,1.75*2*np.pi,segs)
x =t
y=5*np.sin(5*t)
z=np.zeros(x.shape)
xyz=np.vstack((x,y,z)).T
return xyz
def show_simultaneously_3_brains(path):
tracks11, vol_dims11=load_tracks(path,1,1)
tracks21, vol_dims21=load_tracks(path,2,1)
tracks31, vol_dims21=load_tracks(path,3,1)
tracks11z=[tm.downsample(t,10) for t in tracks11]
tracks21z=[tm.downsample(t,10) for t in tracks21]
tracks31z=[tm.downsample(t,10) for t in tracks31]
r=fos.ren()
tracks11zshift=[t+np.array([-100,0,0]) for t in tracks11z]
tracks21zshift=[t+np.array([50,0,0]) for t in tracks21z]
tracks31zshift=[t+np.array([200,0,0]) for t in tracks31z]
fos.clear(r)
fos.add(r,fos.line(tracks11zshift,np.array([1,0,0]),opacity=0.01))
fos.add(r,fos.line(tracks21zshift,np.array([0,0,1]),opacity=0.01))
fos.add(r,fos.line(tracks31zshift,np.array([0,1,0]),opacity=0.01))
fos.add(r,fos.axes(scale=(100,100,100)))
r11_21=np.array([[47148, 105906],
[15009, 61271],
[33939, 88274],
[88045, 91305],
[118191, 206474],
[19383, 237434],
[192033, 184828],
[187807, 3638]])
r11_31=np.array([[47148, 147694],
[15009, 55511],
[33939, 179046],
[88045, 114472],
[118191, 58137],
[19383, 202141],
[192033, 212647],
[187807, 12772]])
for ref in r11_21:
fos.add(r,fos.line(tracks11zshift[ref[0]],np.array([1,1,0]),opacity=1))
fos.add(r,fos.line(tracks21zshift[ref[1]],np.array([1,1,0]),opacity=1))
for ref in r11_31:
fos.add(r,fos.line(tracks31zshift[ref[1]],np.array([1,1,0]),opacity=1))
fos.show(r)
def show_similarity_track_bundle(tno,bundle,S):
''' Show similarity of a specific track using a blue (far) red (close) colormap
'''
r=tm.track_bundle_similarity(tno,S)
blue=np.interp(r,[r.min(),r.max()],[0,1])
green=np.zeros(blue.shape)
red=blue[::-1]
colormap=np.vstack((red,green,blue)).T
#colormap=fos.colors(ref,'jet')
r=fos.ren()
fos.add(r,fos.line(bundle,colormap))
fos.add(r,fos.line(bundle[tno],np.array([1,1,0])))
fos.show(r)
def show_similarity_most_similar_track_bundle(bundle,S):
''' Show similarity of the most similar track using a blue (far) red (close) colormap.
'''
tno=tm.most_similar_track(S)
show_similarity_track_bundle(tno,bundle,S)
def show_cut_planes(tracks,ref):
'''
'''
r=fos.ren()
hit,div=pf.cut_plane(tracks,ref)
for p in range(len(hit)):
D=[ np.vstack((hit[p][d], hit[p][d]+div[p][d])) for d in range(len(hit[p])) ]
D2=[ hit[p][d] for d in range(len(hit[p])) ]
fos.add(r,fos.line(D,fos.red))
fos.add(r,fos.dots(np.array(D2),fos.green))
fos.add(r,fos.line(ref,fos.golden))
#uncinate2=[t+np.array([30,0,0]) for t in tracks]
#fos.add(r,fos.line(uncinate2,fos.blue))
fos.show(r)
def show_cut_planes2(hit,div,ref):
'''
'''
r=fos.ren()
#
for p in range(len(hit)):
D=[ np.vstack((hit[p][d], hit[p][d]+div[p][d])) for d in range(len(hit[p])) ]
D2=[ hit[p][d] for d in range(len(hit[p])) ]
fos.add(r,fos.line(D,fos.red))
fos.add(r,fos.dots(np.array(D2),fos.green))
fos.add(r,fos.line(ref,fos.golden))
#uncinate2=[t+np.array([30,0,0]) for t in tracks]
#fos.add(r,fos.line(uncinate2,fos.blue))
fos.show(r)
def show_cut_color(hit,ref,bundle=None):
r=fos.ren()
fos.clear(r)
#C=fos.colors(v,colormap='jet')
cnt=0
for i in range(len(hit)):
#lh=len(hit[i][:,:3])
#print lh#, len(C[i*cnt:i*cnt+lh])
#fos.add(r,fos.point(hit[i][:,:3],C[cnt:cnt+lh] ))
#fos.label(r,str(hit[i][:,3]),hit
'''
for h in hit[i]:
#fos.label(r,str(np.round(100*h[3])),pos=(h[0],h[1],h[2]),scale=(0.05,0.05,0.05),color=(h[3],0,1-h[3]))
fos.add(r,fos.dots(h[:3],color=(h[3],0,1-h[3])))
'''
#red=hit[i][:,3]
#green=np.zeros(red.shape)
#blue=1-red
v=hit[i][:,3]
red=np.interp(v,[0,0.35,0.66,0.89,1],[0,0,1,1,0.5])
green=np.interp(v,[0,0.125,0.375,0.64,0.91,1],[0,0,1,1,0,0])
blue=np.interp(v,[0,0.11,0.34,0.65,1],[0.5,1,1,0,0])
colors=np.vstack((red,green,blue)).T
fos.add(r,fos.point(hit[i][:,:3],colors,point_radius=0.05))
#cnt=cnt+lh
fos.add(r,fos.line(ref,fos.golden))
if bundle!=None:
fos.add(r,fos.line(bundle,fos.green,opacity=0.1))
fos.show(r)
def all_hits_all_references(path):
G,hdr,R=load_training_set(path)
#Ga,hdr,Ra=load_approximate_training_set(path)
tracks,vol_dims=load_tracks(path,1,1)
tracksa=load_approximate_tracks(path,1,1)
hits={}
for g in [1,2,3,4,5,6,7,8]:
print 'Processing ', G[g]['label_name']
ref=tracks[R[g]]
tracksar,indicesr=tl.rm_far_tracks(ref,tracksa,dist=25.)
hits[g]=pf.cut_plane(tracksar,ref)
return hits,R
def all_bundles_references(path):
#G,hdr=load_training_set(path)
G,hdr=load_approximate_training_set(path)
print 'Loading labeled bundles and indices'
'''
1 arcuate 2 cingulum 3 corticospinal 4 forceps_major 5 fornix 6 inferior_occipitofrontal_fasciculus
7 superior_longitudinal_fasciculus 8 uncinate
'''
B={}
Bi={}
for g in [1,2,3,4,5,6,7,8]:
B[g]=G[g]['tracks']
Bi[g]=G[g]['indices']
R={}
print 'Find ref fibers'
for g in [1,2,3,4,5,6,7,8]:
si,s = pf.most_similar_track_mam(B[g])
R[g]=Bi[g][si]
return B,Bi,R
def save_approximate_tracks(path):
''' Save approximate tracks in PBC directory
'''
# B1S1 is already saved
print 'Saving at '+ path+'/B1S2a.pkl'
tracks,vol_dim=load_tracks(path,1,2)
tracksa=[tm.approximate_trajectory_partitioning(t) for t in tracks]
save_pickle(path+'/B1S2a.pkl',tracksa)
print 'Saving at '+ path+'/B2S1a.pkl'
tracks,vol_dim=load_tracks(path,2,1)
tracksa=[tm.approximate_trajectory_partitioning(t) for t in tracks]
save_pickle(path+'/B2S1a.pkl',tracksa)
# B2S2 is not provided yet
print 'Saving at '+ path+'/B3S1a.pkl'
tracks,vol_dim=load_tracks(path,3,1)
tracksa=[tm.approximate_trajectory_partitioning(t) for t in tracks]
save_pickle(path+'/B3S1a.pkl',tracksa)
print 'Saving at '+ path+'/B3S2a.pkl'
tracks,vol_dim=load_tracks(path,3,2)
tracksa=[tm.approximate_trajectory_partitioning(t) for t in tracks]
save_pickle(path+'/B3S2a.pkl',tracksa)
def load_approximate_tracks(path,brain,scan):
''' Load approximate tracks for specific brain and scan
'''
return load_pickle(path+'/B'+str(brain)+'S'+str(scan)+'a.pkl')
def show_similarity_most_similar_track_all_training_set(G,option='avg'):
''' Show similarity between most similar tracks in the bundles of the training set
Yellow tracks are the most similar tracks.
Parameters:
--------------
option : string
'avg' or 'min' or 'max'
'''
t1=time.clock()
r=fos.ren()
for g in [1,2,3,4,5,6,7,8]:
#for g in [8]:
#bundle=[tm.downsample(t,10) for t in G[g]['tracks']]
bundle=G[g]['tracks']
print 'len_bundle',len(bundle)
#tno,s=tm.bundle_similarities_mam_fast(bundle)
tno=G[g]['index_most_similar_avg']
s=G[g]['similarity_avg']
print 'No_tracks',len(bundle)
print s.shape
blue=np.interp(s,[s.min(),s.max()],[0,1])
#blue=np.interp(s,[0,10],[0,1])
green=np.zeros(blue.shape)
red=blue[::-1]
colormap=np.vstack((red,green,blue)).T
fos.add(r,fos.line(bundle,colormap))
fos.add(r,fos.line(bundle[tno],np.array([1,1,0])))
print 'time:',time.clock()-t1
fos.show(r)
def show_longest_tracks_and_bottlenecks_training_set(G):
r=fos.ren()
for g in [1,2,3,4,5,6,7,8]:
print g,G[g]['label_name']
bundle=G[g]['tracks']
colors=np.random.rand(8,3)
l=fos.line(bundle, colors=colors)
fos.add(r,l)
all=[tm.length(t) for t in bundle]
all=np.array(all)
ilongest=all.argmax()
print g,ilongest
l2=fos.line(bundle[ilongest],colors=np.array([1,0,0]))
fos.add(r,l2)
#downsample first
bundlez=[tm.downsample(t,10) for t in bundle]
bc,br=bottleneck(bundlez,0.98)
G[g]['big_ball_center']=bc
G[g]['big_ball_radius']=br
fos.add(r,fos.sphere(position=bc,radius=br,opacity=0.5))
'''
fbc,fbr=bottleneck_fit(bundle,bc,br)
G[g]['ball_center']=fbc
G[g]['ball_radius']=fbr
fos.add(r,fos.sphere(position=fbc,radius=fbr,opacity=0.5))
'''
fos.show(r)
def bottleneck(bundle,ref=None,alpha=1):
''' Find the bottleneck of a bundle of tracks
Notes:
--------
Description of the algorithm
A. Find the bottleneck riding a fiber in the bundle {usually the longest or another fiber}.
1. for each point along longest track in the bundle:
for each radius from the set of radii
for each track in the bundle
calculate the number of intersecting tracks with the sphere
2. Find the spheres which had the most fibers intersecting them.
3. From these spheres return only the one with the smallest radius.
'''
if ref==None:
all=[tm.length(t) for t in bundle]
all=np.array(all)
ilongest=all.argmax()
else:
ilongest=ref
longest=bundle[ilongest]
radii_set=np.linspace(2,20,50)
lc=len(longest)
lr=len(radii_set)
CR=np.zeros((lc,lr))
ic=0
for c in longest:
ir=0
for r in radii_set:
ts=[ tm.inside_sphere(t,c,r) for t in bundle]
CR[ic,ir]=ts.count(True)
ir+=1
ic+=1
iCR=np.where(CR>=alpha*CR.max())
iminr=iCR[1].argmin()
bigsph_center=longest[iCR[0][iminr]]
bigsph_radius=radii_set[iCR[1][iminr]]
return bigsph_center,bigsph_radius
def bottleneck_fit(bundle,bigsph_center=None,bigsph_radius=None):
'''
Notes :
---------
for all points inside big sphere
for all radii
'''
radii_set=np.linspace(2,20,50)
if bigsph_center !=None and bigsph_radius != None:
centers=[ tm.inside_sphere_points(t,bigsph_center,bigsph_radius) for t in bundle]
centers=np.vstack(centers)
else:
centers =np.vstack(bundle)
random_index=np.round(centers.shape[0]*np.random.rand(30)).astype(int)
centers=centers[random_index]
CR=np.zeros((centers.shape[0],len(radii_set)))
for i in range(centers.shape[0]):
for r in radii_set:
ts=[ tm.inside_sphere(t,centers[i],r) for t in bundle]
CR[i,r]=ts.count(True)
iCR=np.where(CR==CR.max())
iminr=iCR[1].argmin()
sph_center=centers[iCR[0][iminr]]
sph_radius=radii_set[iCR[1][iminr]]
return sph_center,sph_radius
def test_mam_performance():
path='/home/eg01/Data/PBC/pbc2009icdm'
G,hdr=load_training_set(path)
for g in [1,2,3,4,5,6,7,8]:
tracks=G[g]['tracks']
#tracks, vol_dims=load_tracks(path,1,1)
#print(pf.zhang(np.random.rand(100)))
#t1=time.clock()
#print(pf.zhang(tracks[0:10]))
#print 'time',time.clock()-t1
#pf.zhang(tracks[0:100])
t1=time.clock()
si,s=pf.most_similar_track_mam(tracks)
print 'time',time.clock()-t1
G[g]['index_most_similar']=si