-
Notifications
You must be signed in to change notification settings - Fork 0
/
lofidi.py
2249 lines (1508 loc) · 63 KB
/
lofidi.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 -*-
'''
Author: Eleftherios Garyfallidis
Description: Local Fiber Direction Construction
'''
import form
import lights
import general
import scipy as sp
import external
import time
from scipy import linalg as la
import os
import Pycluster as pcl
#from enthought.mayavi.mlab import *
def primarydirections(voxsz,normalize=True):
X=voxsz[0]
Xmin=-X/2.0
Xmax=X/2.0
Y=voxsz[1]
Ymin=-Y/2.0
Ymax=Y/2.0
Z=voxsz[2]
Zmin=-Z/2.0
Zmax=Z/2.0
D=sp.array([[0,Ymin,Zmax],
[Xmax,Ymin,Zmax],
[Xmax,Ymin,0],
[Xmax,Ymin,Zmin],
[Xmax,0,Zmax],
[Xmax,0,0],
[Xmax,0,Zmin],
[0,Ymax,Zmax],
[Xmax,Ymax,Zmax],
[Xmax,Ymax,0],
[Xmax,Ymax,Zmin],
[0,0,Zmax],
[0,Ymax,0]])
#print 'D',D
if normalize:
D1=sp.sqrt(D[:,0]**2+D[:,1]**2+D[:,2]**2)
D=D.transpose()/D1
D=D.transpose()
#D2=sp.sqrt(D[:,0]**2+D[:,1]**2+D[:,2]**2)
return D
def normalizeln(x,xp=sp.array([0,255]),fp=sp.array([0,1]),option='minmax'):
#sp.interp(0,sp.array([0,255]),sp.array([-1,1]),left=-2,right=2)
try:
sh=x.shape
x=sp.interp(x.flatten(),xp,fp)
x=x.reshape(sh)
except:
x=sp.interp(x,xp,fp)
return x
def histeq(im,nbr_bins=256):
'''
Histogram Equalization
Code and Information from
http://jesolem.blogspot.com/search/label/histogram
'''
#get image histogram
imhist,bins = sp.histogram(im.flatten(),nbr_bins,normed=True,new=True)
cdf = imhist.cumsum() #cumulative distribution function
#cdf = 255 * cdf / cdf[-1] #normalize
cdf=(nbr_bins-1)*cdf/cdf[-1]
#use linear interpolation of cdf to find new pixel values
#im2 = sp.interp(im.flatten(),bins[50:-1],cdf[50:])
im2 = sp.interp(im.flatten(),bins[:-1],cdf[:])
return im2.reshape(im.shape), cdf
def axialfilter(arr,no):
sz=arr.shape
ker=sp.zeros(sz)
msk=sp.ones((sz[1],sz[2]))
ker[no]=msk
arr=arr*ker
return arr,ker
def coronalfilter(arr,no):
sz=arr.shape
ker=sp.zeros(sz)
msk=sp.ones((sz[0],sz[2]))
ker[:,no]=msk
arr=arr*ker
return arr,ker
def saggitalfilter(arr,no):
sz=arr.shape
ker=sp.zeros(sz)
msk=sp.ones((sz[0],sz[1]))
ker[:,:,no]=msk
arr=arr*ker
return arr,ker
def slicerfilter(arr,point=(0,0,0)):
if arr.ndim != 3:
print('arr needs to be 3d')
arr1,ker1=axialfilter(arr,point[0])
arr2,ker2=coronalfilter(arr,point[1])
arr3,ker3=saggitalfilter(arr,point[2])
ker12=sp.logical_or(ker1,ker2)
ker=sp.logical_or(ker12,ker3)
arr=arr*ker
return arr
def loadeleftheriosdata(fname_dwi_all,dicom_dir):
arr,voxsz,affine = form.loadvol(fname_dwi_all)
print 'Array shape:',arr.shape
binfo=sp.array(form.loadbinfodir(dicom_dir))
bvecs=binfo[:,1:4]
bvals=binfo[:,7]
print 'Binfo shape:',binfo.shape
print 'Bvecs shape:',bvecs.shape
print 'Bvals shape:',bvals.shape
print 'Bvals:',bvals
return arr,voxsz,affine,bvecs,bvals
def loadfibrecupdata(filename,directionsfname,bval):
arr,voxsz,affine = form.loadvol(filename)
print 'Array shape:',arr.shape
bvecs=form.loadbvecs(directionsfname)
bvals=sp.ones(bvecs.shape[0])*bval
print 'Bvecs shape:',bvecs.shape
print 'Bvals shape:',bvals.shape
return arr,voxsz,affine,bvecs,bvals
def morph_mask(vol):
pass
def mask(vol,thr=0):
mask=vol.copy()
mask[vol<=thr]=0
mask[vol>thr]=1
mask=mask.astype('bool')
return mask
def voxeldiffusivity(arr,voxx,voxy,voxz,bvals):
S=arr[voxx,voxy,voxz,:]
S0=S[0]
S1=S[1:]
S0=S0.astype(sp.float64)
S1=S1.astype(sp.float64)
bval=bvals[1:]
bval=bval.astype(sp.float64)
D=-(1/bval)*sp.log(S1/S0)
return D
def subsample(arr,option='default'):
pass
def medianfilter():
pass
def volumediffusivity(arr,bvals,S0ind=0,Sind=sp.arange(1,65),S0thr=100,remnans=1,reminfs=1,remnegs=1):
'''
Calculates the diffusivity for every gradient direction of every voxel in a volume.
'''
if arr.ndim!=4:
print('Incorrect number of dimensions for arr - it has to be 4d')
return
nvoxs=arr.shape[0]*arr.shape[1]*arr.shape[2]
S0=arr[:,:,:,S0ind]
if S0thr:
S0[S0<S0thr]=0
S0=S0.astype(sp.float64)
S1=arr[:,:,:,Sind]
lS=len(Sind)
S0=S0.reshape(nvoxs)
S1=S1.reshape(nvoxs,lS).transpose()
B=bvals[Sind].astype(sp.float64)
D=-1/B*sp.log(S1/S0).transpose()
if remnans:
D[sp.isnan(D)]=0.0
if reminfs:
D[sp.isinf(D)]=0.0
if remnegs:
D[D<0]=0.0
D=D.reshape(arr.shape[0],arr.shape[1],arr.shape[2],lS)
return D
def volumediffusivityprojected(D,voxsz,bvecs,option='square'):
'''
Projects all the bvecs on the pvecs and then multiplies the square of the result
with the relative diffusivity and adds them up for every pvec.
i.e. sum(d(dot(b,p)^2) for every p where b=b-vec, p=p-vec, d = diffusivity
This algorithm returns a 4D array pD and pvecs.
'''
#Get primary directions
pvecs=primarydirections(voxsz,normalize=True)
print 'No of primary vectors', pvecs.shape[0]
print 'bvecs.shape',bvecs.shape
print 'pvecs',pvecs
print 'pvecs.shape',pvecs.shape
#Multiply primary directions with bvecs
#projvecs=sp.dot(bvecs[Sind],pvecs.T)
projvecs=sp.dot(bvecs,pvecs.T)
if option=='square':
projvecs=projvecs**2
elif option=='fourth':
projvecs=projvecs**4
#print 'projvecs',projvecs
print 'projvecs.shape',projvecs.shape
print 'Dshape',D.shape
#Multiply diffusivities with projected vectors
Dsh=D.shape
D=D.reshape(Dsh[0]*Dsh[1]*Dsh[2],Dsh[3])
itrD=iter(D)
pD=sp.zeros((Dsh[0],Dsh[1],Dsh[2],pvecs.shape[0]))
ndi=sp.ndindex(Dsh[0],Dsh[1],Dsh[2])
if option=='square' or option=='fourth':
while True:
try:
d=itrD.next()
#print 'd.shape',d.shape
pD[ndi.next()]=sp.sum(sp.dot(sp.diag(d),projvecs),axis=0)
#pD[ndi.next()]=sp.sum(sp.absolute(sp.dot(sp.diag(d),projvecs))**2,axis=0)
except:
print general.exceptinfo()
#print('Done')
break
else:
while True:
try:
d=itrD.next()
#print 'd.shape',d.shape
pD[ndi.next()]=sp.sum(sp.absolute(sp.dot(sp.diag(d),projvecs)),axis=0)
#pD[ndi.next()]=sp.sum(sp.absolute(sp.dot(sp.diag(d),projvecs))**2,axis=0)
except:
print general.exceptinfo()
#print('Done')
break
print 'pD.shape',pD.shape
print 'pD.min',pD.min()
print 'pD.max',pD.max()
#print 'Normalize pD'
return pD,pvecs
def volumediffusivitystats(D):
print 'Dshape',D.shape
indn=sp.where(D<0.0)
print 'indn',indn
print 'len indn', len(indn)
print 'D[indn]',D[indn]
print 'len D[indn]',len(D[indn]),len(D[indn])/float(D.size)*100,'%'
del indn
indnan=sp.where(sp.isnan(D))
print 'indnan',indnan
print 'len indnan', len(indnan)
print 'D[indnan]',D[indnan]
print 'len D[indnan]',len(D[indnan]),len(D[indnan])/float(D.size)*100,'%'
del indnan
indinf=sp.where(sp.isinf(D))
print 'indinf',indinf
print 'len indinf', len(indinf)
print 'D[indinf]',D[indinf]
print 'len D[indinf]',len(D[indinf]),len(D[indinf])/float(D.size)*100,'%'
del indinf
indneginf=sp.where(sp.isneginf(D))
print 'indneginf',indneginf
print 'len indneginf', len(indneginf)
print 'D[indneginf]',D[indneginf]
print 'len D[indneginf]',len(D[indneginf]),len(D[indneginf])/float(D.size)*100,'%'
del indneginf
indposinf=sp.where(sp.isposinf(D))
print 'indposinf',indposinf
print 'len indposinf', len(indposinf)
print 'D[indposinf]',D[indposinf]
print 'len D[indposinf]',len(D[indposinf]),len(D[indposinf])/float(D.size)*100,'%'
del indposinf
def voxelsignal(arr,voxx,voxy,voxz):
S=arr[voxx,voxy,voxz,:]
return S
def voxelneighb3x3x3(arr,centx,centy,centz,gap=4,shift=sp.array([0,0,0])):
'''
Inputs are a 3d numpy array and voxel coordinates centx,centy,centz
Returns the voxel indices of the 3x3x3 neighborhood and the position of the centers of the neighb. voxels
in space after mult. with gap and adding shift
'''
trans=sp.array([[0,0,0],[1,0,0],[1,-1,0],[0,-1,0],[-1,-1,0],[-1,0,0],[-1,1,0],[0,1,0],[1,1,0],
[0,0,1],[1,0,1],[1,-1,1],[0,-1,1],[-1,-1,1],[-1,0,1],[-1,1,1],[0,1,1],[1,1,1],
[0,0,-1],[1,0,-1],[1,-1,-1],[0,-1,-1],[-1,-1,-1],[-1,0,-1],[-1,1,-1],[0,1,-1],[1,1,-1]])
center=sp.array([centx,centy,centz])
return trans+center,gap*trans+shift
def showvoxelneighb3x3x3(ren,voxinds,centers,R,IND,x,y,z,u,v,w,colr,colg,colb,opacity,texton=1):
itrv=iter(voxinds)
itrc=iter(centers)
itrR=iter(R)
itrin=iter(IND)
#print voxinds.shape
#print centers.shape
#print R.shape
while True:
try:
voxi=itrv.next()
centi=itrc.next()
r=itrR.next()
ind=itrin.next()
xn,yn,zn,un,vn,wn,rn=x[ind],y[ind],z[ind],u[ind],v[ind],w[ind],r[ind]
colrn,colgn,colbn,opacityn= colr[ind],colg[ind],colb[ind],opacity[ind]
#lights.pipeplot(ren,x+centi[0],y+centi[1],z+centi[2],u+centi[0],v+centi[1],w+centi[2],r,colr,colg,colb,opacity,texton)
lights.pipeplot(ren,xn+centi[0],yn+centi[1],zn+centi[2],un+centi[0],vn+centi[1],wn+centi[2],rn,colrn,colgn,colbn,opacityn,texton)
except StopIteration:
#print general.exceptinfo()
break
return
def showvoxelneighb3x3x3urchine(ren,voxinds,centers,R,IND,x,y,z,u,v,w,colr,colg,colb,opacity,texton=1):
itrv=iter(voxinds)
itrc=iter(centers)
itrR=iter(R)
itrin=iter(IND)
print voxinds.shape
print centers.shape
print R.shape
while True:
try:
voxi=itrv.next()
centi=itrc.next()
r=itrR.next()
ind=itrin.next()
xn,yn,zn,un,vn,wn,rn=x[ind],y[ind],z[ind],u[ind],v[ind],w[ind],r[ind]
colrn,colgn,colbn,opacityn= colr[ind],colg[ind],colb[ind],opacity[ind]
#lights.pipeplot(ren,x+centi[0],y+centi[1],z+centi[2],u+centi[0],v+centi[1],w+centi[2],r,colr,colg,colb,opacity,texton)
lights.pipeplot(ren,xn+centi[0],yn+centi[1],zn+centi[2],un+centi[0],vn+centi[1],wn+centi[2],rn,colrn,colgn,colbn,opacityn,texton)
except StopIteration:
#print general.exceptinfo()
break
return
def indvoxelneighb(arr,voxinds,operation='default',option='default',bvals=None):
R=[]
itrv=iter(voxinds)
IND=[]
while True:
try:
voxi=itrv.next()
r=arr[voxi[0],voxi[1],voxi[2]]
if operation=='default':
r=r*1.0
r=1/r
else:
pass
if option=='default':
try:
lr=len(r)
IND.append(sp.arange(lr))
except:
print('general',general.exceptinfo())
elif option=='min':
IND.append(vectormanip(r,option='min'))
elif option=='max':
IND.append(vectormanip(r,option='max'))
elif option=='sort':
IND.append(vectormanip(r,option='max'))
else:
print('I do not know what to do')
IND.append(sp.NaN)
R.append(r)
except StopIteration:
#print general.exceptinfo()
R=sp.array(R)
IND=sp.array(IND)
break
return R,IND
def vectormanip(v,option='max',mask=None,avgs=1):
'''
Manipulate a scipy one-dimensional array v and output its indices
Example:
v=sp.array([5, 4, 3, 2])
ind=lofidi.vectormanip(v,option='boolean',mask=sp.array([1,0,0,1]))
v[ind]=sp.array([5, 2])
'''
if option=='max':
try:
ind=v.argmax()
except:
ind = 0
elif option=='min':
try:
ind=v.argmax()
except:
ind = 0
elif option=='sort':
try:
ind=v.argsort()
except:
ind = 0
elif option=='boolean':
if mask!=None:
try:
ind = sp.where(mask>0)
except:
ind = sp.arange(1)
elif option=='avgs':
if avgs>1:
list_ind=[]
for i in xrange(avgs):
ind=sp.where(mask==i)
list_ind.append(ind)
return list_ind
else:
ind=0
else:
try:
lv=len(v)
except:
lv=1
ind = sp.arange(lv)
return ind
def simpletensor(arr,bvals,bvecs,S0ind,Sind,thr=50.0):
'''
Calculate tensors from a 4d numpy array and return an FA image and much more.
bvals and bvecs must be provided as well.
FA calculated from Mori et.al, Neuron 2006
See also David Tuch PhD thesis p. 64 and Mahnaz Maddah thesis p. 44 for the tensor derivation.
What this algorithm does? Solves a system of equations for every voxel j
g0^2*d00 + g1^2*d11+g2^2*d22+ 2*g1*g0*d01+ 2*g0*g2*d02+2*g1*g2*d12 = - ln(S_ij/S0_j)/b_i
where b_i the current b-value and g_i=[g0,g1,g2] the current gradient direction. dxx are the values of
the symmetric matrix D. dxx are also the unknown variables.
D= [[d00 ,d01,d02],
[d01,d11,d12],
[d02,d12,d22]]
Output:
'''
if arr.ndim!=4:
print('Please provide a 4d numpy array as arr here')
return
B=bvals[Sind].astype('float32')
G=bvecs[Sind].astype('float32')
print 'B.shape',B.shape
print 'G.shape',G.shape
arsh=arr.shape
volshape=(arsh[0],arsh[1],arsh[2])
voxno=arsh[0]*arsh[1]*arsh[2]
directionsno=len(Sind)
arr=arr.astype('float32')
#A=sp.zeros((directionsno,6))
#FA=sp.zeros(volshape,dtype='float32')
#msk=sp.zeros(volshape,dtype='float32')
S=arr[:,:,:,Sind]
S0=arr[:,:,:,S0ind]
S0[S0<thr]=0.0
print 'S.shape',S.shape
print 'S0.shape',S0.shape
S=S.reshape(voxno,directionsno)
S0=S0.reshape(voxno)
S=S.transpose()
#S[S<1.0]=1.0
#S0[S0<1.0]=1.0
print '#voxno',voxno
print '#directionsno',directionsno
print '#S.shape',S.shape
print '#S0.shape',S0.shape
#S[S<thr]=0
S=sp.log(S/S0)
print 'S.shape',S.shape
print 'S0.shape',S0.shape
S=S.transpose()
print 'S.shape',S.shape
print 'S0.shape',S0.shape
#Remove NaNs (0/0) and Inf (very small numbers in log)
S[sp.isnan(S)]=0
S[sp.isinf(S)]=0
S=-S/B
itrG=iter(G)
#itrA=iter(A)
A=[] # this variable will hold the matrix of the Ax=S system which we will solve for every voxel
while True:
try:
g=itrG.next()
#g1,g2,g3=g[0],g[1],g[2]
#A.append(sp.array([g1*g1,g2*g2,g3*g3,2*g1*g2,2*g1*g3,2*g2*g3]))
A.append(sp.array([g[0]*g[0],g[1]*g[1],g[2]*g[2],2*g[0]*g[1],2*g[0]*g[2],2*g[1]*g[2]]))
except StopIteration:
A=sp.array(A)
break
print 'A.shape',A.shape
print 'S.shape',S.shape
print 'S0.shape',S0.shape
S=S.transpose()
#Remove NaNs (0/0) and Inf (very small numbers in log)
#S[sp.isnan(S)]=1
#S[sp.isinf(S)]=1
d,resids,rank,sing=la.lstsq(A,S)
print 'd.shape',d.shape
d=d.transpose()
print 'd.shape',d.shape
itrd=iter(d)
tensors=[]
while True:
try:
d00,d11,d22,d01,d02,d12=itrd.next()
#print x0,x1,x2,x3,x4,x5
D=sp.array([[d00, d01, d02],[d01,d11,d12],[d02,d12,d22]])
evals,evecs=la.eigh(D)
l1=evals[0]; l2=evals[1]; l3=evals[2]
FA=sp.sqrt( ( (l1-l2)**2 + (l2-l3)**2 + (l3-l1)**2 )/( 2*(l1**2+l2**2+l3**2) ) )
#tensors.append(sp.array([l1,l2,l3,evecs[0,0],evecs[1,0],evecs[2,0],evecs[0,1],evecs[1,1],evecs[2,1],evecs[0,2],evecs[1,2],evecs[2,2],FA]))
tensors.append([l1,l2,l3,evecs[0,0],evecs[1,0],evecs[2,0],evecs[0,1],evecs[1,1],evecs[2,1],evecs[0,2],evecs[1,2],evecs[2,2],FA])
except StopIteration:
tensors=sp.array(tensors)
break
tensors[sp.isnan(tensors)]=0
tensors[sp.isinf(tensors)]=0
tensors=tensors.reshape((arsh[0],arsh[1],arsh[2],13))
print 'tensors.shape:', tensors.shape
return tensors
def testshowsignalfibrecup():
'''
See also showdiffusivityfibrecup
When option='min' in indvoxelneighb look the changes in shape
Array shape: (64, 64, 3, 130)
Bvecs shape: (130, 3)
Bvals shape: (130,)
IND [ 21 120 52 58 102 116 28 80 86 56 14 103 87 6 120 85 63 107
58 68 106 96 102 56 60 38 46]
voxinds.shape (27, 3)
centers.shape (27, 3)
R.shape (27, 130)
IND.shape (27,)
x.shape (130,)
Showvoxelneighb here will visualize the min 1/S where S is the signal for every voxel
When option='default' in indvoxelneighb i.e. all the signal is visualized therefore if len(S)=130 then
every ind of IND will have 130 elements.
Array shape: (64, 64, 3, 130)
Bvecs shape: (130, 3)
Bvals shape: (130,)
IND [[ 0 1 2 ..., 127 128 129]
[ 0 1 2 ..., 127 128 129]
[ 0 1 2 ..., 127 128 129]
...,
[ 0 1 2 ..., 127 128 129]
[ 0 1 2 ..., 127 128 129]
[ 0 1 2 ..., 127 128 129]]
voxinds.shape (27, 3)
centers.shape (27, 3)
R.shape (27, 130)
IND.shape (27, 130)
x.shape (130,)
'''
#fname='/home/eg01/Data/Fibre_Cup/3x3x3/dwi-b0650.nii'
#directions='/home/eg01/Data/Fibre_Cup/3x3x3/diffusion_directions.txt'
fname='/home/eg309/Data/Fibre_Cup/3x3x3/dwi-b0650.nii'
directions='/home/eg309/Data/Fibre_Cup/3x3x3/diffusion_directions.txt'
seeds3x3x3mm=sp.array([[51,23,1],[46,21,1],[51,34,1],[47, 32, 1],[41, 33, 1], [46, 38, 1], [44, 46, 1], [38, 48, 1], [31, 39, 1] , [21, 48, 1] , [17, 45, 1], [12, 40, 1], [11, 25, 1] , [12, 17, 1], [24, 24, 1], [36, 9, 1] ])
seeds6x6x6mm=sp.array([[40,26,0],[38,25,0],[40,31,0],[38, 30, 0],[36, 32, 0], [38, 34, 0], [37, 37, 0], [34, 39, 0], [30, 34, 0] , [26, 39, 0] , [24, 37, 0], [21, 35, 0], [20, 27, 0] , [22, 23, 0], [28, 26, 0], [33, 20, 0] ])
arr,voxsz,affine,bvecs,bvals=loadfibrecupdata(fname,directions,bval=650)
centx=arr.shape[0]/2
centy=arr.shape[1]/2
centz=arr.shape[2]/2
indS1=sp.arange(1,65)
u,v,w=bvecs[:,0],bvecs[:,1],bvecs[:,2]
#u,v,w=bvecs[indS1,0],bvecs[indS1,1],bvecs[indS1,2]
x,y,z=-u,-v,-w
lu=len(u)
colr,colg,colb,opacity=sp.ones(lu),sp.zeros(lu),sp.zeros(lu),sp.ones(lu)
curx,cury,curz=centx,centy,centz
#curx,cury,curz=45,31,1
#curx,cury,curz=38,48,1
voxinds,centers=voxelneighb3x3x3(arr,centx=curx,centy=cury,centz=curz,gap=4,shift=sp.array([0,0,0]))
R,IND=indvoxelneighb(arr,voxinds,option='default')
print 'IND',IND
print 'voxinds.shape',voxinds.shape
print 'centers.shape',centers.shape
print 'R.shape',R.shape
print 'IND.shape',IND.shape
print 'x.shape',x.shape
ren=lights.renderer()
showvoxelneighb3x3x3(ren,voxinds,centers,R,IND,x,y,z,u,v,w,colr,colg,colb,opacity,texton=0)
ax=lights.axes(scale=(6,6,6),opacity=0.5)
ren.AddActor(ax)
ren.ResetCamera()
ap=lights.AppThread(frame_type=0,ren=ren,width=1024,height=800)
def testdiffusivityprojection():
'''
fname='/home/eg01/Data/Fibre_Cup/3x3x3/dwi-b0650.nii'
directions='/home/eg01/Data/Fibre_Cup/3x3x3/diffusion_directions.txt'
#fname='/home/eg309/Data/Fibre_Cup/3x3x3/dwi-b0650.nii'
#directions='/home/eg309/Data/Fibre_Cup/3x3x3/diffusion_directions.txt'
seeds3x3x3mm=sp.array([[51,23,1],[46,21,1],[51,34,1],[47, 32, 1],[41, 33, 1], [46, 38, 1], [44, 46, 1], [38, 48, 1], [31, 39, 1] , [21, 48, 1] , [17, 45, 1], [12, 40, 1], [11, 25, 1] , [12, 17, 1], [24, 24, 1], [36, 9, 1] ])
seeds6x6x6mm=sp.array([[40,26,0],[38,25,0],[40,31,0],[38, 30, 0],[36, 32, 0], [38, 34, 0], [37, 37, 0], [34, 39, 0], [30, 34, 0] , [26, 39, 0] , [24, 37, 0], [21, 35, 0], [20, 27, 0] , [22, 23, 0], [28, 26, 0], [33, 20, 0] ])
arr,voxsz,affine,bvecs,bvals=loadfibrecupdata(fname,directions,bval=650)
'''
#'''
#fname_dwi_all='/backup/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000/dtk_dti_out/dwi_all.nii'
#fname_dwi_all='/home/eg309/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000/dtk_dti_out/dwi_all.nii'
dicom_dir='/backup/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000'
#dicom_dir='/home/eg309/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000'
fname_dwi_all=dicom_dir+'/dtk_dti_out/dwi_all.nii'
arr,voxsz,affine,bvecs,bvals=loadeleftheriosdata(fname_dwi_all,dicom_dir)
#'''
#Demo dataset
#arr=sp.array([[[0,100,100,0],[100,100,100,100],[0,100,100,0]],[[0,100,100,0],[100,100,100,100],[0,100,100,0]],[[0,100,100,0],[100,100,100,100],[0,100,100,0]]])
print 'Arr.shape',arr.shape
centx=arr.shape[0]/2
centy=arr.shape[1]/2
centz=arr.shape[2]/2
Sind=sp.arange(1,65)
print 'Arr.min', arr.min()
print 'Arr.max', arr.max()
now=time.clock()
D=volumediffusivity(arr,bvals,S0ind=0,Sind=Sind,S0thr=0)
print 'Time:',time.clock()-now
print 'Dmin',D.min()
print 'Dmax',D.max()
import draw
draw.pyplot.figure(1)
draw.pyplot.hist(D,100)
draw.pyplot.show()
form.savevol(os.path.dirname(fname_dwi_all)+'/D.nii',D,affine)
#return
#D=normalizeln(D,xp=sp.array([D.min(),D.max()]),yp=sp.array([0,255]))
#print 'After normalization',D.min(), D.max()
now=time.clock()
pD,pvecs=volumediffusivityprojected(D,voxsz,bvecs[Sind])
print 'Time:',time.clock()-now
print('pD.MaX',pD.max())
'''
#form.savevol('Dvol.nii',D,affine)
#Dhist,bins=sp.histogram(pD,20,new=True)
import draw
draw.pyplot.figure(1)
draw.pyplot.hist(pD,20)
draw.pyplot.show()
'''
#pD=normalizeln(pD,xp=sp.array([pD.min(),pD.max()]),fp=sp.array([0,1]))
pD=normalizeln(pD,xp=(pD.min(),pD.max()),fp=sp.array([0.0,1.0]))
print 'pD.shape',pD.shape
print 'pD.min',pD.min()
print 'pD.max',pD.max()
'''
D,cdf=histeq(D)
draw.pyplot.figure(2)
draw.pyplot.hist(D,20)
draw.pyplot.show()
print 'After hist. equalization', D.min(),D.max()
form.savevol('Dvoleq.nii',D,affine)
'''
ren=lights.renderer()
form.savevol(os.path.dirname(fname_dwi_all)+'/pD2.nii',pD,affine)
#form.savevol('/home/eg309/Data/Test/pD.nii',pD,affine)
pvecs.tofile(os.path.dirname(fname_dwi_all)+'/pvecs')
#pvecs.tofile('/home/eg309/Data/Test/pvecs')
#'''
pd=pD[centx,centy,centz]
print 'pd',pd
print 'pvecs.shape',pvecs.shape
i=0
for vec in pvecs:
print 'vec',vec
if pd[i]>0:
ren.AddActor(lights.tube(point1=(0,0,0),point2=pd[i]*vec,color=(1,0,0.7),opacity=1,radius=0.05,capson=1))
#lights.label(ren,text=str(sp.around(vec,decimals=2)),pos=vec,scale=(0.05,0.05,0.05),color=(1,1,1))
lights.label(ren,text=str(sp.around(pd[i],decimals=2)),pos=vec,scale=(0.05,0.05,0.05),color=(1,1,1))
i=i+1
#ren.AddActor(lights.cube())
ren.AddActor(lights.axes(scale=(2,2,2),opacity=0.3))
ren.ResetCamera()
ap=lights.AppThread(frame_type=0,ren=ren,width=1024,height=800)
#'''
def testgeneratelabels():
dname='/backup/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000/dtk_dti_out'
fname=dname+'/pD.nii'
#fname='/home/eg01/Data/Test/pD.nii'
arr,voxsz,affine=form.loadvol(fname)
pvecs=sp.fromfile(dname+'/pvecs')
print 'pvecs.shape',pvecs.shape
pvecs=pvecs.reshape(13,3)
fname_spm_segment=dname+'/c3dti_b0.nii'
mask_spm,voxsz2,affine2=form.loadvol(fname_spm_segment)