-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnmri_processing_functions_mri.py
1762 lines (1417 loc) · 67 KB
/
nmri_processing_functions_mri.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 python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 12:54:37 2020
@author: nfocke
"""
import nibabel as nib
import os, subprocess
import numpy as np
import nmri_functions as nmri
from nipype.interfaces import fsl, freesurfer, ants
#%%
def enableANTs(reqVersion="20200326"):
"""
Function to make sure that ANTs is available for further calls from Python
scripts in system PATH, note, this will usually NOT export to the parent shell
----------
reqVersion : string of version to use, default 20200326
----------
"""
import shutil
# check if we have ANTs, use a marker binary to check
currPath=shutil.which("N4BiasFieldCorrection")
# check if the requested version of ANTs exists at the usual path
toolPath=os.path.join(os.environ["NMRI_TOOLS"],"ANTs",reqVersion,"bin")
if not os.path.exists(toolPath):
raise RuntimeError("The requested version/toolpath does not exist ("+toolPath+") or not readable, fatal")
if currPath is None:
# we do not have our marker in path, so add
print(f'adding ANTs dir = {toolPath} to system path')
os.environ["PATH"] += os.pathsep + toolPath
else:
# we already have a version, check if the right one
currPath=os.path.dirname(currPath)
currVersion=os.path.basename(os.path.dirname(currPath))
if currVersion != reqVersion:
# need to get a different version, remove the old from path
allItems=os.environ["PATH"].split(os.pathsep)
print(f'removing old ANTs dir = {currPath} from system path')
while currPath in allItems:
allItems.remove(currPath)
# add the new
allItems.append(toolPath)
# and save path as environ variable
print(f'adding new ANTs dir = {toolPath} to system path')
os.environ["PATH"]=os.pathsep.join(allItems)
#%%
def enableFreesurfer(reqVersion="6.0.0", subjectsDir=""):
"""
Function to make sure that Freesurfer is available for further calls from Python
scripts in system PATH, note, this will usually NOT export to the parent shell
----------
reqVersion : string of version to use, default 6.0.0
subjectsDir : set up a specific subjects_dir or use the version default
----------
"""
import shutil
import re
# check if we have Freesurfer, use a marker binary to check
currPath=shutil.which("recon-all")
# check if the requested version of Freesurfer exists at the usual path
toolPath=os.path.join(os.environ["NMRI_TOOLS"],"freesurfer",reqVersion)
if not os.path.exists(toolPath):
raise RuntimeError("The requested version/toolpath does not exist ("+toolPath+") or not readable, fatal")
# determine subjects dir
if subjectsDir=="":
# set the default
if os.getenv("NMRI_FREESURFER_SUBJECTS") is not None:
subjectsDir=os.path.join(os.getenv("NMRI_FREESURFER_SUBJECTS"),reqVersion)
else:
subjectsDir=os.path.join("/usr/users/nmri/freesurfer",reqVersion)
if currPath is None:
# we do not have our marker in path, so add
print(f'adding Freesurfer dir = {toolPath} to system path')
os.environ["FREESURFER_HOME"] = toolPath
os.environ["SUBJECTS_DIR"] = subjectsDir
os.environ["FREESURFERVERSION"] = reqVersion
os.environ["PERL5LIB"] = os.path.join(toolPath,"mni","share","perl5")
os.environ["LOCAL_DIR"] = os.path.join(toolPath,"local")
os.environ["FSFAST_HOME"] = os.path.join(toolPath,"fsfast")
os.environ["FMRI_ANALYSIS_DIR"] = os.path.join(toolPath,"fsfast")
os.environ["FUNCTIONALS_DIR"] = os.path.join(toolPath,"sessions")
os.environ["MINC_LIB_DIR"] = os.path.join(toolPath,"mni","lib")
os.environ["MNI_DIR"] = os.path.join(toolPath,"mni")
os.environ["MNI_DATAPATH"] = os.path.join(toolPath,"mni","data")
# note that Python does not take back env variables from external commands, so we need to deal with PATH ourselves
allItems=os.environ["PATH"].split(os.pathsep)
allItems.append(os.path.join(toolPath,"bin"))
allItems.append(os.path.join(toolPath,"fsfast","bin"))
allItems.append(os.path.join(toolPath,"mni","bin"))
allItems.append(os.path.join(toolPath,"tktools"))
os.environ["PATH"]=os.pathsep.join(allItems)
else:
# we already have a version, check if the right one
currPath=os.path.dirname(currPath)
currVersion=os.path.basename(os.path.dirname(currPath))
if currVersion != reqVersion:
# need to get a different version, remove the old from path
allItems=os.environ["PATH"].split(os.pathsep)
r=re.compile(".*/freesurfer/.*")
newItems=[]
for item in allItems:
if r.match(item) is None:
newItems.append(item)
else:
print(f'removing old Freesurfer dir = {item} from system path')
allItems=newItems
print(f'adding Freesurfer dir = {toolPath} to system path')
os.environ["FREESURFER_HOME"] = toolPath
os.environ["SUBJECTS_DIR"] = subjectsDir
os.environ["FREESURFERVERSION"] = reqVersion
os.environ["PERL5LIB"] = os.path.join(toolPath,"mni","share","perl5")
os.environ["LOCAL_DIR"] = os.path.join(toolPath,"local")
os.environ["FSFAST_HOME"] = os.path.join(toolPath,"fsfast")
os.environ["FMRI_ANALYSIS_DIR"] = os.path.join(toolPath,"fsfast")
os.environ["FUNCTIONALS_DIR"] = os.path.join(toolPath,"sessions")
os.environ["MINC_LIB_DIR"] = os.path.join(toolPath,"mni","lib")
os.environ["MNI_DIR"] = os.path.join(toolPath,"mni")
os.environ["MNI_DATAPATH"] = os.path.join(toolPath,"mni","data")
# note that Python does not take back env variables from external commands, so we need to deal with PATH ourselves
allItems.append(os.path.join(toolPath,"bin"))
allItems.append(os.path.join(toolPath,"fsfast","bin"))
allItems.append(os.path.join(toolPath,"mni","bin"))
allItems.append(os.path.join(toolPath,"tktools"))
os.environ["PATH"]=os.pathsep.join(allItems)
else:
# all seems set, just set subjects dir
os.environ["SUBJECTS_DIR"] = subjectsDir
def getFreesurferVersion():
import shutil
# use a marker binary to check
currPath=shutil.which("recon-all")
# we already have a version, check if the right one
if currPath is not None:
currPath=os.path.dirname(currPath)
currVersion=os.path.basename(os.path.dirname(currPath))
else:
print("Freesurfer does not seem to be in path")
currVersion=None
return currVersion
#%% FSL setup
def enableFSL(reqVersion="6.0.4"):
"""
Function to make sure that FSL is available for further calls from Python
scripts in system PATH, note, this will usually NOT export to the parent shell
----------
reqVersion : string of version to use, default 6.0.4
----------
"""
import shutil, re
# check if we have FSL, use a marker binary to check
currPath=shutil.which("fsleyes")
# check if the requested version of FSL exists at the usual path
toolPath=os.path.join(os.environ["NMRI_TOOLS"],"fsl",reqVersion,"bin")
if not os.path.exists(toolPath):
raise RuntimeError("The requested version/toolpath does not exist ("+toolPath+") or not readable, fatal")
if currPath is None:
# we do not have our marker in path, so add
print(f'adding FSL dir = {toolPath} to system path')
os.environ["PATH"] += os.pathsep + toolPath
else:
# we already have a version, check if the right one
currPath=os.path.dirname(currPath)
currVersion=os.path.basename(os.path.dirname(currPath))
if currVersion != reqVersion:
# need to get a different version, remove the old from path
allItems=os.environ["PATH"].split(os.pathsep)
r=re.compile(".*/fsl.*/.*")
newItems=[]
for item in allItems:
if r.match(item) is None:
newItems.append(item)
else:
print(f'removing old FSL dir = {item} from system path')
allItems=newItems
# add the new
allItems.append(toolPath)
# and save path as environ variable
print(f'adding new FSL dir = {toolPath} to system path')
os.environ["PATH"]=os.pathsep.join(allItems)
os.environ["FSLDIR"] = os.path.dirname(toolPath)
os.environ["FSL_DIR"] = os.path.dirname(toolPath)
os.environ["FSLTCLSH"] = os.path.join(toolPath,"bin","fsltclsh")
os.environ["FSLVERSION"] = reqVersion
os.environ["FSLWISH"] = os.path.join(toolPath,"bin","fslwish")
#%%
def enablec3d(reqVersion="c3d-1.1.0-Linux-x86_64"):
"""
Function to make sure that C3D is available for further calls from Python
scripts in system PATH, note, this will usually NOT export to the parent shell
----------
reqVersion : string of version to use, default c3d-1.1.0-Linux-x86_64
----------
"""
import shutil
# check if we have ANTs, use a marker binary to check
currPath=shutil.which("c3d_affine_tool")
# check if the requested version of c3d exists at the usual path
toolPath=os.path.join(os.environ["NMRI_TOOLS"],"c3d",reqVersion,"bin")
if not os.path.exists(toolPath):
raise RuntimeError("The requested version/toolpath does not exist ("+toolPath+") or not readable, fatal")
if currPath is None:
# we do not have our marker in path, so add
print(f'adding c3d dir = {toolPath} to system path')
os.environ["PATH"] += os.pathsep + toolPath
else:
# we already have a version, check if the right one
currPath=os.path.dirname(currPath)
currVersion=os.path.basename(os.path.dirname(currPath))
if currVersion != reqVersion:
# need to get a different version, remove the old from path
allItems=os.environ["PATH"].split(os.pathsep)
print(f'removing old c3d dir = {currPath} from system path')
while currPath in allItems:
allItems.remove(currPath)
# add the new
allItems.append(toolPath)
# and save path as environ variable
print(f'adding new c3d dir = {toolPath} to system path')
os.environ["PATH"]=os.pathsep.join(allItems)
def fsl2itk(fslMat,itkMat,ref,src):
"""
Function to convert a FSL mat / affine 4D text file to an ITK/ANTs transformation
----------
fslMat : is read
itkMat : is written
ref : reference image (the one that is not moved)
src : the image that is moved by the transforms
----------
"""
if not os.path.exists(fslMat):
raise FileNotFoundError(fslMat)
if not os.path.exists(ref):
raise FileNotFoundError(ref)
if not os.path.exists(fslMat):
raise FileNotFoundError(src)
enablec3d()
os.system(f'c3d_affine_tool -ref {ref} -src {src} {fslMat} -fsl2ras -oitk {itkMat}')
if not os.path.exists(itkMat):
raise RuntimeError(f"The expected ITK transformation file {itkMat} was not found. May be a file permission or script error. Check output above.")
#%% MCR / cluster
def determineClusterEngine():
"""
Will determine the cluster enginge and surround.
Currently supported for GWDG/slurm and nmri-srv/SGE
----------
"""
import subprocess, re, shutil
ret=subprocess.run(["hostname","-A"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# extract response
olist=ret.stdout.decode("utf-8").split("\n")
if ret.returncode==0 and len(olist)>1:
if re.search('gwdg.cluster',olist[0]) is not None:
cluster_env='gwdg'
elif re.search('nmri-srv',olist[0]) is not None:
cluster_env='nmri-srv'
elif re.search('hlrn.de',olist[0]) is not None:
cluster_env='hlrn'
else:
cluster_env="unknown"
# check if we have slurm command(s)
gridSched=shutil.which("squeue")
if gridSched is not None:
cluster_eng='slurm'
else:
gridSched=shutil.which("qsub")
if gridSched is not None:
cluster_eng='sge'
else:
cluster_eng='unknown'
return (cluster_env, cluster_eng)
def enableMCR(reqVersion="R2018b"):
"""
Function to make sure that MCR (Matlab Runtime) is available for further calls from Python
scripts in system PATH, note, this will usually NOT export to the parent shell
----------
reqVersion : string of version to use, default R2018b
----------
"""
import shutil
(cluster_env, cluster_eng)=determineClusterEngine()
# determine MCR path (for GWDG and nmri-srv)
mcr_path=""
if cluster_env=="gwdg":
if reqVersion[-5:]=='2018b':
mcr_path='/usr/product/matlab/MCR/v95'; # gwdg
elif reqVersion[-5:]=='2017a':
mcr_path='/usr/product/matlab/MCR/v92';
elif reqVersion[-5:]=='2020b':
mcr_path='/opt/sw/rev/20.12/haswell/gcc-9.3.0/matlab-mcr-R2020b-7ynb4r/v99/';
elif cluster_env=="nmri-srv":
mcr_path='/tools/MCR/R2017a/v92'
if mcr_path=="":
raise ValueError("Could not determine the MCR path for {reqVersion} and cluster_env={cluster_env}")
currPath=shutil.which("matlab_helper")
toolPath=os.path.join(mcr_path,"bin","glnxa64")
# check if the requested version of MCR exists at the usual path
if not os.path.exists(toolPath):
raise RuntimeError("The requested version/toolpath does not exist ("+toolPath+") or not readable, fatal")
if currPath is None:
# we do not have our marker in path, so add to path
os.environ["PATH"] += os.pathsep + os.path.join(mcr_path,"bin","glnxa64") + os.pathsep + os.path.join(mcr_path,"bin")
# and check again
currPath=shutil.which("matlab_helper")
if currPath is None:
raise RuntimeError("Could not find the marker exec even after adding to path, check the MCR path "+mcr_path)
else:
# we already have a version, check if the right one
currPath=os.path.dirname(currPath)
currVersion=os.path.basename(os.path.dirname(os.path.dirname(currPath)))
if currVersion != os.path.basename(mcr_path):
# need to get a different version, remove the old from path
allItems=os.environ["PATH"].split(os.pathsep)
print(f'removing old MCR dir = {currPath} from system path')
while currPath in allItems:
allItems.remove(currPath)
# also remove before dir
currPath=os.path.dirname(currPath)
print(f'removing old MCR dir = {currPath} from system path')
while currPath in allItems:
allItems.remove(currPath)
# add the new
allItems.insert(0,os.path.join(mcr_path,"bin"))
allItems.insert(0,os.path.join(mcr_path,"bin","glnxa64"))
# and save path as environ variable
print(f'adding new MCR dir = {mcr_path} to system path')
os.environ["PATH"]=os.pathsep.join(allItems)
return mcr_path
#%%
def merge_version_images(infiles,strategy="average"):
"""
Perform merging or selection of a version in case of multiple repetitions of images
----------
infiles : list of filenames
strategy : how to select the eventual imnage, defaul average
average : realign_3D and average (including bet option)
first: take the first version only (no average)
last: take the last version only (no average)
----------
"""
import shutil
plains=[]
for infile in infiles:
plain=nmri.remove_version(infile)
if plain not in plains:
plains.append(plain)
if len(plains)!=1:
raise RuntimeError("There is not a single unique image to be extracted from the version images, fatal")
mversions=list()
if len(infiles) > 1 :
# we have version, so deal with the selection
if strategy=="average":
# use normal script to do the works
sep=" "
cmd="realign_3D -bet "+plains[0]+" "+sep.join(infiles)
os.system(cmd)
cmd="fslmaths "+plains[0]+" -Tmean "+plains[0]
os.system(cmd)
for i in range(len(infiles)):
mversions.append(nmri.get_version(infiles[i]))
elif strategy=="first":
infiles.sort()
shutil.copyfile(infiles[0],plains[0])
mversions.append(nmri.get_version(infiles[0]))
elif strategy=="last":
infiles.sort()
shutil.copyfile(infiles[-1],plains[0])
mversions.append(nmri.get_version(infiles[-1]))
else:
raise RuntimeError("Not a valid merge strategy="+strategy)
# deal with the JSON
if os.path.exists(plains[0]):
# seems to have worked, so also generate a JSON with some info based on potentially existing JSON
nmri.add_to_JSON(nmri.remove_ext(infiles[0])+".json",{"merging_strategy":strategy,"merged_versions":mversions},nmri.remove_ext(plains[0])+".json",overwrite=1,merge=0)
for i in range(1,len(infiles)):
nmri.merge_JSON(nmri.remove_ext(plains[0])+".json",nmri.remove_ext(infiles[i])+".json",nmri.remove_ext(plains[0])+".json",merge=1)
print('...version merging done:', plains[0], '\n')
return plains[0]
else:
raise RuntimeError("Version merging/selection failed")
#%% Image Calculations
def makeAverage(infiles,outfile):
# make an average
N=len(infiles)
print("Making average of",N,"images...")
# use 1st image as reference
refimg=nib.load(infiles[0])
avgImg=np.zeros(refimg.shape,dtype=np.float64)
for i in range(N):
img=nib.load(infiles[i])
if img.shape!=refimg.shape:
raise RuntimeError("Mismatch of image dimensions for "+infiles[i])
imgDat=img.get_fdata(dtype=np.float32)
avgImg+=imgDat/N
# and save
new_img=nib.Nifti1Image(avgImg,refimg.affine,header=refimg.header) #img.header takes care of the cast to original type -> float/int etc
nib.save(new_img, outfile)
def makeAverageMode(infiles,outfile):
# make an average of MRIs/volumes using a mode (most frequent observation approach, e.g. for altases)
N=len(infiles)
print("Making mode average of",N,"images...")
# use 1st image as reference
refimg=nib.load(infiles[0])
allImg=np.zeros(refimg.shape+(N,),dtype=np.float32)
for i in range(N):
img=nib.load(infiles[i])
if img.shape!=refimg.shape:
raise RuntimeError("Mismatch of image dimensions for "+infiles[i])
imgDat=img.get_fdata(dtype=np.float32)
allImg[:,:,:,i]=imgDat
# now get the mode
modeImg=np.zeros(refimg.shape,dtype=np.float32)
for x in range(refimg.shape[0]):
print(".",end="")
for y in range(refimg.shape[1]):
for z in range(refimg.shape[2]):
(vals,counts)=np.unique(allImg[x,y,z,:], return_counts=True)
modeImg[x,y,z]=vals[np.argmax(counts)]
# and save
new_img=nib.Nifti1Image(modeImg,refimg.affine,header=refimg.header) #img.header takes care of the cast to original type -> float/int etc
nib.save(new_img, outfile)
def makeAverageSurf(infiles,outfile):
# make an average of surfaces, this will only work if the vertices are comparable, e.g. for SUMA points but not for indiviudal Freesurfer surfaces
N=len(infiles)
print("Making average of",N,"surfaces...")
# use 1st surface as reference
refsurf=nib.load(infiles[0])
refPos=refsurf.agg_data('NIFTI_INTENT_POINTSET')
refTri=refsurf.agg_data('NIFTI_INTENT_TRIANGLE')
avgSurf=np.zeros(refPos.shape,dtype=np.float64)
for i in range(N):
surf=nib.load(infiles[i])
thisPos=surf.agg_data('NIFTI_INTENT_POINTSET')
thisTri=surf.agg_data('NIFTI_INTENT_TRIANGLE')
if thisPos.shape!=refPos.shape:
raise RuntimeError("Mismatch of positions dimensions for "+infiles[i])
if np.logical_not(np.all(thisTri==refTri)):
raise RuntimeError("Mismatch of triangels/faces for "+infiles[i])
avgSurf+=thisPos/N
# and save
outsurf=nib.gifti.GiftiImage()
outsurf.add_gifti_data_array(nib.gifti.gifti.GiftiDataArray(data=avgSurf,intent='NIFTI_INTENT_POINTSET'))
outsurf.add_gifti_data_array(nib.gifti.gifti.GiftiDataArray(data=refTri,intent='NIFTI_INTENT_TRIANGLE'))
nib.save(outsurf, outfile)
#%% Orientation Functions
def setOrientation(infile,orientation="radiological",overwrite=0):
"""
Makes sure that the orientation of the image is radiological / neurological and flips otherwise
----------
infile : string / path with filename
orientation: radiological / neurological
overwrite : overwrite the imgage (1) or (0, default) create a new image with ".reorient" flag
----------
returns : path the the unaltered or orientiented image
"""
import subprocess
# start with checkin options
if not nmri.imtest(infile):
raise RuntimeError(f"Input file {infile} is not an image or not exiting")
overwrite=overwrite==1
if orientation!="radiological" and orientation!="neurological":
raise RuntimeError(f"{orientation} is not a legal choice")
# now determine the current orientation
img=nib.load(infile)
# determine standard ax codes
axCodes=list(nib.aff2axcodes(img.affine))
# find the R/L dim
flip=0
if "R" in axCodes:
latDim=axCodes.index("R")
if orientation=="radiological":
flip=1
elif "L" in axCodes:
latDim=axCodes.index("L")
if orientation=="neurological":
flip=1
else:
raise RuntimeError(f"Could not determine the orientation of file={infile}, likely somethin is correct in the affine hdr")
# now do the flip, in FSL
if flip:
print("Need to flip L/R for",infile)
os.environ["FSLOUTPUTTYPE"]=nmri.get_filetype(infile)
# make a new name, if requested
if overwrite:
outfile=infile
else:
outfile=nmri.remove_ext(infile)+".reorient"+nmri.get_ext(infile)
cmd=["imcp",infile,outfile]
ret=subprocess.run(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if ret.returncode!=0:
print("FSL out:\n",ret.stdout.decode("utf-8"),"FSL err:\n",ret.stderr.decode("utf-8"))
raise RuntimeError("Flip failed, see above for details")
# make sure we use the right FSL filetype
# now flip
cmd=["fslorient","-swaporient",outfile]
ret=subprocess.run(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if ret.returncode==0:
rot=["x","y","z"]
rot[latDim]="-"+rot[latDim]
cmd=["fslswapdim",outfile]
cmd+=rot
cmd.append(outfile)
ret=subprocess.run(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if ret.returncode==0:
print(f"L/R flip succeeded, written to {outfile}")
else:
print("FSL out:\n",ret.stdout.decode("utf-8"),"FSL err:\n",ret.stderr.decode("utf-8"))
raise RuntimeError("Flip failed, see above for details")
else:
print("FSL out:\n",ret.stdout.decode("utf-8"),"FSL err:\n",ret.stderr.decode("utf-8"))
raise RuntimeError("Flip failed, see above for details")
return outfile
else:
return infile
#%% file handeling functions
def unGZIP(infiles):
"""
Will do an in-place de-gzipping (of e.g. .nii.gz)
----------
infiles : list of string / path with filename
----------
returns:
outfiles : list of de-compressed files
----------
"""
import gzip
import shutil
outfiles=[]
for thisFile in infiles:
if os.path.exists(thisFile):
(baseFile, ext)=os.path.splitext(thisFile)
if ext==".gz" or ext==".GZ":
print("Unzipping",thisFile)
with gzip.open(thisFile, 'rb') as f_in:
with open(baseFile, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
if os.path.exists(baseFile):
# remove original is uncompressed exists
os.remove(thisFile)
outfiles.append(baseFile)
else:
# assume already de-compressed
print(thisFile,"seems already unzipped")
outfiles.append(thisFile)
else:
print("ERROR: File not found",thisFile)
return outfiles
#%%
def doBrainExtraction(infile, maskfile="", outfile="", fraction="", robust=1, gen_mask=1): # Doing Brain Extraction
"""
Perform brain extraction with FSL BET
----------
infile : string / path with filename
maskfile: optional, string / path with filename
outfile : optional, string / path with filename
----------
"""
enableFSL()
print('Doing brain extraction for', infile)
inbase=nmri.remove_ext(infile)
extension=nmri.get_ext(infile)
robust=robust==1
gen_mask=gen_mask==1
# if not set, make a conventional name
if outfile=="":
outfile=inbase+".brain"+extension
if maskfile=="":
maskfile=inbase+".brain.mask"+extension
# if not set, determine fraction based on tag group
if fraction=="":
taggrp=nmri.get_tag_group(nmri.get_tag(infile))
if taggrp=="t1":
fraction=0.5
elif taggrp=="t2":
fraction=0.4
elif taggrp=="dti":
fraction=0.2
else:
# no idea, so use defalut
fraction=0.5
btr = fsl.BET()
btr.inputs.in_file = infile
btr.inputs.frac = fraction
btr.inputs.robust = robust
btr.inputs.out_file = outfile
btr.inputs.mask = gen_mask
btr.inputs.output_type = nmri.get_filetype(outfile)
btr.run()
if os.path.exists(outfile):
# seems to have worked, so also generate a JSON with some info based on potentially existing JSON
nmri.add_to_JSON(nmri.remove_ext(infile)+".json",{"brain_masked":"bet", "bet-nipype":nmri.nipype_inputs_to_dict(btr.inputs)},nmri.remove_ext(outfile)+".json")
# deal with mask
if gen_mask:
os.rename(nmri.remove_ext(outfile)+'_mask'+extension, maskfile)
nmri.add_to_JSON(nmri.remove_ext(infile)+".json",{"brain_masked":"bet", "bet-nipype":nmri.nipype_inputs_to_dict(btr.inputs)},nmri.remove_ext(maskfile)+".json")
print('...bet brain masking done:', outfile, '\n')
else:
raise RuntimeError(f"Expected bet image={outfile} not generated, possible permission or script error")
def doRemoveNegativeValues(infile, outfile=""): # Removes negative values e.g. for N4 bias-correction (as the intensities are log transformed)
"""
Function to remove negative values from image
----------
infile : string / path with filename
outfile : optional, string / path with filename
if no outfile given, will overwrite infile
----------
Will only write/overwrite if negative values are present
"""
print('Checking for negative values in: ', infile)
tempImage = nib.load(infile)
tempVol = tempImage.get_fdata()
tempVol_all_positve = tempVol.clip(min = 0.00001) # making any negative values to zero
# check for any differens
if not np.array_equal(tempVol_all_positve,tempVol):
# Nifti1
if tempImage.header['sizeof_hdr'] == 348:
tempImage_all_positive = nib.Nifti1Image(tempVol_all_positve, tempImage.affine, tempImage.header)
# Nifti2
elif tempImage.header['sizeof_hdr'] == 540:
tempImage_all_positive = nib.Nifti2Image(tempVol_all_positve, tempImage.affine, tempImage.header)
else:
raise IOError('input image header problem in saving the file', infile)
if outfile=="":
outfile=infile
nib.save(tempImage_all_positive, outfile)
print('...negative values where found and removed in', outfile, '\n')
def doNBiasFieldCorrection(infile, outfile="", nu="N3"): # Doing N3/N4 Bias-Field Correction
"""
Function to run BIAS correction using N3 or N4 with default settings
----------
infile : string / path with filename
outfile : optional, string / path with filename
if no outfile given, will create a new vile with nu_corr suffix
nu : N3 or N4
----------
"""
inbase=nmri.remove_ext(infile)
extension=nmri.get_ext(infile)
# if not set, make a conventional name
if outfile=="":
outfile=inbase+".nu_corr"+extension
if nu=="N4":
# Doing N4 Bias-Field Correction
enableANTs()
print('Doing bias correction using N4 for', infile)
n = ants.N4BiasFieldCorrection()
n.inputs.dimension = 3
n.inputs.input_image = infile
n.inputs.save_bias = False
n.inputs.output_image = outfile
n.inputs.bspline_fitting_distance = 100
n.inputs.rescale_intensities = True
n.inputs.convergence_threshold = 0
n.inputs.shrink_factor = 2
n.inputs.n_iterations = [50,50,50,50]
n.inputs.histogram_sharpening = (0.14, 0.01, 200)
n.run()
elif nu=="N3":
# Doing N3 Bias-Field Correction
print('Doing bias correction using N3 for', infile)
n = freesurfer.MNIBiasCorrection()
n.inputs.in_file = infile
n.inputs.iterations = 4
n.inputs.distance = 50
n.inputs.out_file = outfile
n.inputs.protocol_iterations = 1000
else:
raise f"NU={nu} not supported"
n.run()
if os.path.exists(outfile):
# seems to have worked, so also generate a JSON with some info based on potentially existing JSON
nmri.add_to_JSON(nmri.remove_ext(infile)+".json",{"NU":nu, "NU-nipype":nmri.nipype_inputs_to_dict(n.inputs)},nmri.remove_ext(outfile)+".json")
print('...bias-corection',nu,'done:', outfile, '\n')
else:
raise RuntimeError(f"Expected NU corrected image={outfile} not generated, possible permission or script error")
#%%
def doFLIRT(infile, reference, outfile="", outmat="", matDir="", dof=6, costfunc="", interpfunc="spline", use_bet=1, generate_outfile=1,nmri_logic=1):
# make logical
use_bet=use_bet==1
generate_outfile=generate_outfile==1
nmri_logic=nmri_logic==1
# deal with a smart selection of references / tags
inputDir,inputFile=os.path.split(infile)
inputBase=nmri.remove_ext(inputFile)
referenceDir,referenceFile=os.path.split(reference)
referenceBase=nmri.remove_ext(referenceFile)
# estimate the working dir (in NMRI standards)
subjectDir=os.path.dirname(inputDir)
if nmri_logic:
# use NMRI storage standards to determine .mat files / classes
if matDir=="" or not os.path.exists(matDir):
matDir=os.path.join(subjectDir,"mat")
if not os.path.exists(matDir):
os.makedirs(matDir,exist_ok=True)
bn=nmri.get_basename(inputFile)
inputTag=nmri.get_tag(inputFile)
if inputTag is None:
raise RuntimeError("Could not determine the sequence/tag group of "+inputFile)
referenceTag=nmri.get_tag(referenceFile)
if referenceTag is None:
raise RuntimeError("Could not determine the sequence/tag group of "+referenceFile)
# get the tag groups
inputTagGrp=nmri.get_tag_group(inputTag)
if inputTagGrp is None:
Warning("TagGroup not defined for: "+inputTag)
inputTagGrp=inputTag
referenceTagGrp=nmri.get_tag_group(referenceTag)
if referenceTagGrp is None:
Warning("TagGroup not defined for: "+referenceTag)
referenceTagGrp=referenceTag
# get the version of the file (if any)
imgver=nmri.get_version(inputFile)
if imgver is None:
imgver=""
refver=nmri.get_version(referenceFile)
if refver is None:
refver=""
# now combine the version and group for .mat file
inputMatGrp=inputTagGrp+imgver
referenceMatGrp=referenceTagGrp+refver
if outmat=="":
outmat=os.path.join(matDir,bn+"."+inputMatGrp+"-"+referenceMatGrp+".mat")
outmat_inv=os.path.join(matDir,bn+"."+referenceMatGrp+"-"+inputMatGrp+".mat")
else:
# use generic defaults
if costfunc=="":
costfunc="normcorr"
if outmat=="":
(fname,ext)=os.path.splitext(infile)
outmat = fname+".reg.mat"
# tags are not relevant
referenceMatGrp=nmri.remove_ext(os.path.basename(reference))
inputMatGrp=nmri.remove_ext(os.path.basename(infile))
# check if we have the needed mats
if not os.path.exists(outmat):
# not present, so estimate transform now
# determine cost function from tags, if not set
if costfunc=="":
if referenceTagGrp==inputTagGrp:
# within modality
costfunc="normcorr"
else:
# seems to be cross-modality, use mutual information
costfunc="normcorr"
# if not set, make a conventional name
extension=nmri.get_ext(inputFile)
if outfile=="":
outfile=os.path.join(inputDir,inputBase+".FLIRT-"+referenceMatGrp+extension)
# check if we want to use a bet-based transform
if use_bet:
# deal with reference first
referenceBet=os.path.join(referenceDir,referenceBase+".brain"+extension)
if not os.path.exists(referenceBet):
# run bet
doBrainExtraction(reference,outfile=referenceBet,gen_mask=0)
# deal with source then
inputBet=os.path.join(inputDir,inputBase+".brain"+extension)
if not os.path.exists(inputBet):
# run bet
doBrainExtraction(infile,outfile=inputBet,gen_mask=0)
# now setup FLIRT
print(f"Running FLIRT of {inputMatGrp} to {referenceMatGrp} (dof={dof}, cost={costfunc})...")
flt = fsl.FLIRT()
if use_bet:
flt.inputs.in_file = inputBet
flt.inputs.reference = referenceBet
flt.inputs.out_file =nmri.remove_ext(inputBet)+".FLIRT-"+referenceMatGrp+extension
else:
flt.inputs.in_file = infile
flt.inputs.reference = reference
flt.inputs.out_file = outfile
flt.inputs.dof = dof
flt.inputs.cost_func = costfunc
flt.inputs.out_matrix_file = outmat
flt.inputs.output_type = nmri.get_filetype(outfile)
flt.inputs.interp = interpfunc
flt.run()
# for some reason Nipype always generates an outfile, even if not requested
if not generate_outfile:
os.remove(flt.inputs.out_file)
if not os.path.exists(outmat):
raise RuntimeError("Could not run the FLIRT of "+flt.inputs.in_file+" to "+flt.inputs.reference+", often a permission problem, or FSL not available")
else:
# seems to have worked
if "outmat_inv" in locals() and not os.path.exists(outmat_inv):
# generate inverted FLIRT mat (its fast and small)
invrt=fsl.ConvertXFM()
invrt.inputs.in_file=outmat
invrt.inputs.invert_xfm=True
invrt.inputs.out_file=outmat_inv
invrt.run()
if "outmat_inv" not in locals():
outmat_inv="" # so make return tuple valid
# so generate an outfile if so requested
if generate_outfile and not os.path.exists(outfile):
# make my own command...some issue with Nipype
cmd=f"flirt -in {infile} -ref {reference} -init {outmat} -out {outfile} -applyxfm -interp {interpfunc}"
os.system(cmd)
# applyxfm = fsl.ApplyXFM()
# applyxfm.inputs.in_file = infile
# applyxfm.inputs.in_matrix_file = outmat
# applyxfm.inputs.out_file = outfile
# applyxfm.inputs.reference = reference
# applyxfm.inputs.apply_xfm = True
# applyxfm.run()
if os.path.exists(outfile):
# also generate a JSON with some info based on potentially existing JSON
nmri.add_to_JSON(nmri.remove_ext(infile)+".json",{"coregistered":"flirt", "flirt-nipype":nmri.nipype_inputs_to_dict(flt.inputs)},nmri.remove_ext(outfile)+".json")
print('...transformation done ', outfile, '\n')
# return the .mat files as tuple
return outmat,outmat_inv
#%%
def doANTs_registration(infile, reference, outfile, warpfile="", inMskfile="",refMskfile="",numThreads=4, synStep=0.1,synUpdateVariancePenalty=3,synTotalVariancePenalty=0,costFunc=["MI","MI","CC"],doRigid=1,doAffine=1,doSyn=1):
import sys
enableANTs()
# ants always likes to write the warp
if warpfile=="":
warpfile=nmri.remove_ext(outfile)+"_warp"
cmd="antsRegistration"
cmd+=" -d 3" #dimensionality
cmd+=f" -o [{warpfile},{outfile}]"
# make mask a list for all stages, if string
if inMskfile=="" and refMskfile=="":
useMasks=False
else:
useMasks=True
# now check the number
doRigid=doRigid==1
doAffine=doAffine==1
doSyn=doSyn==1
steps=doRigid+doAffine+doSyn
if type(inMskfile)==str:
inMskfile=[inMskfile]*steps
if type(refMskfile)==str:
refMskfile=[refMskfile]*steps
if type(costFunc)==str:
costFunc=[costFunc]*steps
if len(refMskfile)!=steps:
raise RuntimeError(f"RefMask list needs to be {steps} element list (one per registration step), or one string")
if len(inMskfile)!=steps:
raise RuntimeError(f"InMask list needs to be {steps} element list (one per registration step), or one string")
if len(costFunc)<steps:
raise RuntimeError(f"costFunc list needs to be at least {steps} element list (one per registration step), or one string")
cmd+=" -a 1" # write out composite transform
cmd+=" -n BSpline" # interpolation