-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchimera_parcellation.py
2144 lines (1697 loc) · 99.8 KB
/
chimera_parcellation.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 -*-
import os
import sys
import numpy as np
import pandas as pd
import tqdm
from pathlib import Path
import bids
from bids import BIDSLayout
import nibabel as nib
from glob import glob
from operator import itemgetter
from datetime import datetime
import argparse
import csv
import json
import subprocess
import scipy.ndimage as sc
import concurrent.futures
import time
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
class MyBIDs:
def __init__(self, bids_dir: str):
fold_list = os.listdir(bids_dir)
subjids = []
for it in fold_list:
if 'sub-' in it:
subjids.append(it)
subjids.sort()
bidsdict = {}
for subjid in subjids:
subjdir = os.path.join(bids_dir, subjid)
sesids = []
if os.path.isdir(subjdir):
fold_list = os.listdir(subjdir)
for it in fold_list:
if 'ses-' in it:
sesids.append(it)
sesids.sort()
bidsdict.__setitem__(subjid, sesids)
self.value = bidsdict
def add(self, key, value):
print(key)
print(value)
self[key] = value
def get_subjids(self, bids_dir: str):
fold_list = os.listdir(bids_dir)
subjids = []
for it in fold_list:
if 'sub-' in it:
subjids.append(it)
subjids.sort()
self.subjids = subjids
return subjids
def get_sesids(self, bids_dir: str, subjid):
sesids = []
subjdir = os.path.join(bids_dir, subjid)
if os.path.isdir(subjdir):
fold_list = os.listdir(subjdir)
for it in fold_list:
if 'ses-' in it:
sesids.append(it)
sesids.sort()
self.sesids = sesids
return sesids
# Print iterations progress
def _printprogressbar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printend="\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printend - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledlength = int(length * iteration // total)
bar = fill * filledlength + '-' * (length - filledlength)
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=printend)
# Print New Line on Complete
if iteration == total:
print()
# Loading the JSON file containing the available parcellations
def _load_parctype_json():
cwd = os.getcwd()
serJSON = os.path.join(cwd, 'parcTypes.json')
with open(serJSON) as f:
data = json.load(f)
return data
def _build_args_parser():
formatter = lambda prog: argparse.HelpFormatter(prog, max_help_position=52)
from argparse import ArgumentParser
p = argparse.ArgumentParser(formatter_class=SmartFormatter, description='\n Help \n')
requiredNamed = p.add_argument_group('Required arguments')
requiredNamed.add_argument('--regions', '-r', action='store_true', required=False,
help="R| List of available parcellations for each supra-region. \n"
"\n")
requiredNamed.add_argument('--bidsdir', '-b', action='store', required=False, metavar='BIDSDIR', type=str, nargs=1,
help="R| BIDs dataset folder. \n"
"\n")
requiredNamed.add_argument('--derivdir', '-d', action='store', required=False, metavar='DERIVDIR', type=str, nargs=1,
help="R| BIDs derivative folder containing the derivatives folder. \n"
"\n",
default='None')
requiredNamed.add_argument('--parcodes', '-p', action='store', required=False,
metavar='CODE', type=str, nargs=1,
help="R| Sequence of nine one-character identifiers (one per each supra-region).\n"
" The defined supra-regions are: 1) Cortex, 2) Basal ganglia, 3) Thalamus, \n"
" 4) Amygdala, 5) Hippocampus, 6) Hypothalamus, 7) Cerebellum, 8) Brainstem. \n"
"\n"
"Example: \n"
"Parcellation code: HFMIIIFIF.\n"
" 1. Cortical parcellation (H): HCP-MMP1 cortical parcellation (Glasser et al, 2016).\n"
" 2. Basal ganglia parcellation (F): FreeSurfer subcortical parcellation (Fischl et al, 2002).\n"
" 3. Thalamic parcellation (M): Atlas-based thalamic parcellation (Najdenovska et al, 2018).\n"
" 4. Amygdala parcellation (I): Amygdala nuclei parcellation (Saygin et al, 2017).\n"
" 5. Hippocampus parcellation (I): Hippocampus subfield parcellation (Iglesias et al, 2015).\n"
" 6. Hypothalamus parcellation (I): Hypothalamus parcellation (Billot et al, 2020).\n"
" 7. Cerebellum parcellation (F): Default FreeSurfer cerebellum segmentation.\n"
" 8. Brainstem parcellation (I): Brainstem parcellation (Iglesias et al, 2015).\n"
" 9. Gyral White Matter parcellation (F): WM parcellation according to the selected cortical parcellation.\n"
"\n"
"Use the --regions or -r options to show all the available parcellations for eact supra-region.\n"
"\n")
requiredNamed.add_argument('--nthreads', '-n', action='store', required=False, metavar='NTHREADS', type=str, nargs=1,
help="R| Number of processes to run in parallel. \n", default=['1'])
requiredNamed.add_argument('--growwm', '-g', action='store', required=False, metavar='GROWWM', type=str, nargs=1,
help="R| Grow of GM labels inside the white matter in mm. \n", default=['2'])
requiredNamed.add_argument('--t1s', '-t', action='store', required=False, metavar='T1FILE', type=str, nargs=1,
help="R| File containing the basename of the NIFTI images that will be ran. \n"
" This file is useful to tun Chimera, only, on certain T1s in case of multiple T1s \n"
" for the same session.\n"
" Example of this file: \n"
" sub-00001_ses-0001_run-2 \n"
" sub-00001_ses-0003_run-1\n"
" sub-00001_ses-post_acq-mprage\n"
" \n", default='None')
requiredNamed.add_argument('--force', '-f', action='store_true', required=False,
help="R| Overwrite the results. \n"
"\n")
p.add_argument('--verbose', '-v', action='store', required=False,
type=int, nargs=1,
help='verbosity level: 1=low; 2=debug')
args = p.parse_args()
if args.derivdir is None or args.bidsdir is None or args.parcodes is None :
print('--bidsdir, --derivdir and --parcodes are REQUIRED arguments')
sys.exit()
bids_dir = args.bidsdir[0]
deriv_dir = args.derivdir[0]
if args.regions is True:
print('Available parcellations for each supra-region:')
_print_availab_parcels()
sys.exit()
if not os.path.isdir(deriv_dir):
print("\n")
print("Please, supply a valid BIDs derivative directory.")
p.print_help()
sys.exit()
if not os.path.isdir(bids_dir):
print("\n")
print("Please, supply a valid BIDs directory.")
p.print_help()
sys.exit()
return p
def _print_availab_parcels(reg_name=None):
data = _load_parctype_json()
if reg_name is None:
supra_keys = data.keys()
parc_help = ''
for sup in supra_keys:
parc_opts = data[sup]
parc_help = '{} "{}:\n"'.format(parc_help, sup)
print(sup + ':')
for opts in parc_opts:
desc = data[sup][opts]["Atlas"]
cita = data[sup][opts]["Citation"]
parc_help = '{} "{}: {} {}\n"'.format(parc_help, opts, desc, cita)
print(' {}: {} {}'.format(opts, desc, cita))
print('')
else:
parc_opts = data[reg_name]
print(reg_name + ':')
for opts in parc_opts:
desc = data[reg_name][opts]["Atlas"]
cita = data[reg_name][opts]["Citation"]
print(' {}: {} {}'.format(opts, desc, cita))
print('')
def _get_region_features(im_parc, st_codes, st_names, st_red, st_green, st_blue):
# Extract the code, name and RGB triplet from colorLUT file for the structures appearing in the image im_parc
temp = np.unique(im_parc)
ind_non = np.nonzero(temp)
temp = temp[ind_non[0]]
temp = temp.astype(int)
pos = search(st_codes, temp)
reg_codes = list(itemgetter(*pos)(st_codes))
reg_names = list(itemgetter(*pos)(st_names))
reg_red = list(itemgetter(*pos)(st_red))
reg_green = list(itemgetter(*pos)(st_green))
reg_blue = list(itemgetter(*pos)(st_blue))
return reg_codes, reg_names, reg_red, reg_green, reg_blue
def _my_ismember(a, b):
values, indices = np.unique(a, return_inverse=True)
is_in_list = np.isin(a, b)
idx = indices[is_in_list].astype(int)
return values, idx
def _parc_tsv_table(codes, names, colors, tsv_filename):
# Table for parcellation
# 1. Converting colors to hexidecimal string
seg_hexcol = []
nrows, ncols = colors.shape
for i in np.arange(0, nrows):
seg_hexcol.append(rgb2hex(colors[i, 0], colors[i, 1], colors[i, 2]))
bids_df = pd.DataFrame(
{
'index': np.asarray(codes),
'name': names,
'color': seg_hexcol
}
)
# print(bids_df)
# Save the tsv table
with open(tsv_filename, 'w+') as tsv_file:
tsv_file.write(bids_df.to_csv(sep='\t', index=False))
# Find Structures
def _search_in_atlas(in_atlas, st_tolook, out_atlas, labmax):
for i, v in enumerate(st_tolook):
result = np.where(in_atlas == v)
out_atlas[result[0], result[1], result[2]] = i + labmax + 1
# print('%u === %u', v, i + labmax + 1)
labmax = labmax + len(st_tolook)
return out_atlas, labmax
# Search the value inside a vector
def search(values, st_tolook):
ret = []
for v in st_tolook:
index = values.index(v)
ret.append(index)
return ret
def rgb2hex(r, g, b):
return "#{:02x}{:02x}{:02x}".format(r, g, b)
def hex2rgb(hexcode):
return tuple(map(ord, hexcode[1:].decode('hex')))
def _find_images_in_path(new_path, str_ext):
# This function finds images in a folder that contain certain string in its file name
temp_var = glob(new_path + os.path.sep + str_ext)
return temp_var
def _subfields2hbt(temp_ip, hipp_codes):
# This function groups hippocampus subfields in head, body and tail
hbtimage = np.zeros(np.shape(temp_ip), dtype='int16')
# Creating Head
bool_ind = np.in1d(temp_ip, hipp_codes[0:8])
bool_ind = np.reshape(bool_ind, np.shape(temp_ip))
result = np.where(bool_ind == True)
hbtimage[result[0], result[1], result[2]] = 1
# Creating Body
bool_ind = np.in1d(temp_ip, hipp_codes[9:16])
bool_ind = np.reshape(bool_ind, np.shape(temp_ip))
result = np.where(bool_ind == True)
hbtimage[result[0], result[1], result[2]] = 2
# Creating Tail
bool_ind = np.in1d(temp_ip, hipp_codes[17])
bool_ind = np.reshape(bool_ind, np.shape(temp_ip))
result = np.where(bool_ind == True)
hbtimage[result[0], result[1], result[2]] = 3
# Creating Fissure
bool_ind = np.in1d(temp_ip, hipp_codes[18])
bool_ind = np.reshape(bool_ind, np.shape(temp_ip))
result = np.where(bool_ind == True)
hbtimage[result[0], result[1], result[2]] = 4
return hbtimage
def _select_t1s(t1s, t1file):
with open(t1file) as file:
t1s2run = [line.rstrip() for line in file]
out_t1s = [s for s in t1s if any(xs in s for xs in t1s2run)]
return out_t1s
def tissue_seg_table(tsv_filename):
# Table for tissue segmentation
# 1. Default values for tissues segmentation table
seg_rgbcol = np.array([[172, 0, 0], [0, 153, 76], [0, 102, 204]])
seg_codes = np.array([1, 2, 3])
seg_names = ['cerebro_spinal_fluid', 'gray_matter', 'white_matter']
seg_acron = ['CSF', 'GM', 'WM']
# 2. Converting colors to hexidecimal string
seg_hexcol = []
nrows, ncols = seg_rgbcol.shape
for i in np.arange(0, nrows):
seg_hexcol.append(rgb2hex(seg_rgbcol[i, 0], seg_rgbcol[i, 1], seg_rgbcol[i, 2]))
bids_df = pd.DataFrame(
{
'index': seg_codes,
'name': seg_names,
'abbreviation': seg_acron,
'color': seg_hexcol
}
)
# Save the tsv table
with open(tsv_filename, 'w+') as tsv_file:
tsv_file.write(bids_df.to_csv(sep='\t', index=False))
def read_fscolorlut(lutFile):
# Readind a color LUT file
fid = open(lutFile)
LUT = fid.readlines()
fid.close()
# Make dictionary of labels
LUT = [row.split() for row in LUT]
st_names = []
st_codes = []
cont = 0
for row in LUT:
if len(row) > 1 and row[0][0] != '#' and row[0][0] != '\\\\': # Get rid of the comments
st_codes.append(int(row[0]))
st_names.append(row[1])
if cont == 0:
st_colors = np.array([[int(row[2]), int(row[3]), int(row[4])]])
else:
ctemp = np.array([[int(row[2]), int(row[3]), int(row[4])]])
st_colors = np.append(st_colors, ctemp, axis=0)
cont = cont + 1
return st_codes, st_names, st_colors
def _launch_annot2ind(fs_annot, ind_annot, hemi, out_dir, fullid, atlas):
# Creating the hemisphere id
if hemi == 'lh':
hemicad = 'L'
elif hemi == 'rh':
hemicad = 'R'
# Moving the Annot to individual space
subprocess.run(['mri_surf2surf', '--srcsubject', 'fsaverage', '--trgsubject', fullid,
'--hemi', hemi, '--sval-annot', fs_annot,
'--tval', ind_annot],
stdout=subprocess.PIPE, universal_newlines=True)
# Copying the resulting annot to the output folder
out_annot = os.path.join(out_dir, fullid + '_hemi-' + hemicad + '_space-orig_' + atlas + '_dparc.annot')
subprocess.run(['cp', ind_annot, out_annot], stdout=subprocess.PIPE, universal_newlines=True)
return out_annot
def _launch_gcs2ind(fssubj_dir, fs_gcs, ind_annot, hemi, out_dir, fullid, atlas):
# Creating the hemisphere id
if hemi == 'lh':
hemicad = 'L'
elif hemi == 'rh':
hemicad = 'R'
# Moving the GCS to individual space
cort_file = os.path.join(fssubj_dir, fullid, 'label', hemi + '.cortex.label')
sph_file = os.path.join(fssubj_dir, fullid, 'surf', hemi + '.sphere.reg')
subprocess.run(['mris_ca_label', '-l', cort_file, fullid, hemi, sph_file,
fs_gcs, ind_annot], stdout=subprocess.PIPE, universal_newlines=True)
# Copying the resulting annot to the output folder
out_annot = os.path.join(out_dir, fullid + '_hemi-' + hemicad + '_space-orig_' + atlas + '_dparc.annot')
subprocess.run(['cp', ind_annot, out_annot],
stdout=subprocess.PIPE, universal_newlines=True)
return out_annot
def _launch_freesurfer(t1file:str, fssubj_dir:str, fullid:str):
os.environ["SUBJECTS_DIR"] = fssubj_dir
# Computing FreeSurfer
subprocess.run(['recon-all', '-subjid', '-i', t1file, fullid, '-all'],
stdout=subprocess.PIPE, universal_newlines=True)
return
def _launch_surf2vol(fssubj_dir, out_dir, fullid, atlas, gm_grow):
if 'desc' not in atlas:
atlas_str = atlas + '_desc-'
else:
atlas_str = atlas
if atlas == "aparc":
atlas_str = "atlas-desikan_desc-aparc"
elif atlas == "aparc.a2009s":
atlas_str = "atlas-destrieux_desc-a2009s"
out_parc = []
for g in gm_grow:
out_vol = os.path.join(out_dir, fullid + '_space-orig_' + atlas_str + 'grow' + g + 'mm_dseg.nii.gz')
if g == '0':
# Creating the volumetric parcellation using the annot files
subprocess.run(['mri_aparc2aseg', '--s', fullid, '--annot', atlas,
'--hypo-as-wm', '--new-ribbon', '--o', out_vol],
stdout=subprocess.PIPE, universal_newlines=True)
else:
# Creating the volumetric parcellation using the annot files
subprocess.run(['mri_aparc2aseg', '--s', fullid, '--annot', atlas, '--wmparc-dmax', g, '--labelwm',
'--hypo-as-wm', '--new-ribbon', '--o', out_vol],
stdout=subprocess.PIPE, universal_newlines=True)
# Moving the resulting parcellation from conform space to native
raw_vol = os.path.join(fssubj_dir, fullid, 'mri', 'rawavg.mgz')
subprocess.run(['mri_vol2vol', '--mov', out_vol, '--targ', raw_vol,
'--regheader', '--o', out_vol, '--no-save-reg', '--interp', 'nearest'],
stdout=subprocess.PIPE, universal_newlines=True)
out_parc.append(out_vol)
return out_parc
def _parc_conform2native(cform_mgz, nat_nii, fssubj_dir, fullid):
# Moving the resulting parcellation from conform space to native
raw_vol = os.path.join(fssubj_dir, fullid, 'mri', 'rawavg.mgz')
subprocess.run(['mri_vol2vol', '--mov', cform_mgz, '--targ', raw_vol,
'--regheader', '--o', nat_nii, '--no-save-reg', '--interp', 'nearest'],
stdout=subprocess.PIPE, universal_newlines=True)
def _compute_abased_thal_parc(t1, vol_tparc, deriv_dir, pathcad, fullid, aseg_nii, out_str):
cwd = os.getcwd()
thal_spam = os.path.join(cwd, 'thalamic_nuclei_MIALatlas', 'Thalamus_Nuclei-HCP-4DSPAMs.nii.gz')
t1_temp = os.path.join(cwd, 'mni_icbm152_t1_tal_nlin_asym_09c', 'mni_icbm152_t1_tal_nlin_asym_09c.nii.gz')
# Creating spatial transformation folder
stransf_dir = os.path.join(deriv_dir, 'ants-transf2mni', pathcad, 'anat')
if not os.path.isdir(stransf_dir):
try:
os.makedirs(stransf_dir)
except OSError:
print("Failed to make nested output directory")
defFile = os.path.join(stransf_dir, fullid + '_space-MNI152NLin2009cAsym_')
if not os.path.isfile(defFile + 'desc-t12mni_1InverseWarp.nii.gz'):
# Registration to MNI template
subprocess.run(['antsRegistrationSyN.sh', '-d', '3', '-f', t1_temp, '-m', t1, '-t', 's',
'-o', defFile + 'desc-t12mni_'],
stdout=subprocess.PIPE, universal_newlines=True)
mial_dir = os.path.dirname(vol_tparc)
# Creating ouput directory
if not os.path.isdir(mial_dir):
try:
os.makedirs(mial_dir)
except OSError:
print("Failed to make nested output directory")
mial_thalparc = os.path.join(mial_dir, fullid + '_space-orig_desc-' + out_str +'_dseg.nii.gz')
mial_thalspam = os.path.join(mial_dir, fullid + '_space-orig_desc-' + out_str +'_probseg.nii.gz')
# Applying spatial transform
subprocess.run(['antsApplyTransforms', '-d', '3', '-e', '3', '-i', thal_spam,
'-o', mial_thalspam, '-r', t1, '-t', defFile + 'desc-t12mni_1InverseWarp.nii.gz',
'-t','[' + defFile + 'desc-t12mni_0GenericAffine.mat,1]', '-n', 'Linear'],
stdout=subprocess.PIPE, universal_newlines=True)
# Creating MaxProb
_spams2maxprob(mial_thalspam, 0.05, mial_thalparc, aseg_nii, 10, 49)
mial_thalparc = [mial_thalparc]
return mial_thalparc
def _fs_addon_parcellations(vol_tparc, fullid, fssubj_dir, parcid, out_str):
volatlas_dir = os.path.dirname(vol_tparc)
# Creating ouput directory
if not os.path.isdir(volatlas_dir):
try:
os.makedirs(volatlas_dir)
except OSError:
print("Failed to make nested output directory")
if parcid == 'thalamus':
# Running Thalamic parcellation
process = subprocess.run(
['segmentThalamicNuclei.sh', fullid, fssubj_dir],
stdout=subprocess.PIPE, universal_newlines=True)
thal_mgz = os.path.join(fssubj_dir, fullid, 'mri', 'ThalamicNuclei.v12.T1.mgz')
# Moving Thalamic parcellation to native space
_parc_conform2native(thal_mgz, vol_tparc, fssubj_dir, fullid)
out_parc = [vol_tparc]
elif parcid == 'amygdala' or parcid == 'hippocampus':
# Running Hippocampal and Amygdala parcellation
process = subprocess.run(
['segmentHA_T1.sh', fullid, fssubj_dir],
stdout=subprocess.PIPE, universal_newlines=True)
# Moving Hippocampal and amygdala parcellation to native space
lh_mgz = os.path.join(fssubj_dir, fullid, 'mri', 'lh.hippoAmygLabels-T1.v21.mgz')
lh_gz = os.path.join(volatlas_dir, fullid + '_space-orig_hemi-L_desc-' + out_str + '_dseg.nii.gz')
_parc_conform2native(lh_mgz, lh_gz, fssubj_dir, fullid)
rh_mgz = os.path.join(fssubj_dir, fullid, 'mri', 'rh.hippoAmygLabels-T1.v21.mgz')
rh_gz = os.path.join(volatlas_dir, fullid + '_space-orig_hemi-R_desc-' + out_str + '_dseg.nii.gz')
_parc_conform2native(rh_mgz, rh_gz, fssubj_dir, fullid)
out_parc = [lh_gz, rh_gz]
elif parcid == 'hypothalamus':
# Running Hypothalamus parcellation
os.system("WRITE_POSTERIORS=1")
process = subprocess.run(
['mri_segment_hypothalamic_subunits', '--s', fullid, '--sd', fssubj_dir, '--write_posteriors'],
stdout=subprocess.PIPE, universal_newlines=True)
# Moving Hypothalamus to native space
hypo_mgz = os.path.join(fssubj_dir, fullid, 'mri', 'hypothalamic_subunits_seg.v1.mgz')
hypo_gz = os.path.join(volatlas_dir, fullid + '_space-orig_desc-' + out_str + '_dseg.nii.gz')
_parc_conform2native(hypo_mgz, hypo_gz, fssubj_dir, fullid)
out_parc = [hypo_gz]
elif parcid == 'brainstem':
# Running Brainstem parcellation
# os.environ["WRITE_POSTERIORS"] = 1
os.system("WRITE_POSTERIORS=1")
process = subprocess.run(
['segmentBS.sh', fullid, fssubj_dir],
stdout=subprocess.PIPE, universal_newlines=True)
# Moving Hypothalamus to native space
bs_mgz = os.path.join(fssubj_dir, fullid, 'mri', 'brainstemSsLabels.v12.mgz')
bs_gz = os.path.join(volatlas_dir, fullid + '_space-orig_desc-' + out_str + '_dseg.nii.gz')
_parc_conform2native(bs_mgz, bs_gz, fssubj_dir, fullid)
out_parc = [bs_gz]
return out_parc
def _spams2maxprob(spamImage:str, thresh:float=0.05, maxpName:str=None, thalMask:str=None, thl_code:int=10, thr_code:int=49):
# ---------------- Thalamic nuclei (MIAL) ------------ #
thalm_codesl = np.array([1, 2, 3, 4, 5, 6, 7])
thalm_codesr = np.array([8, 9, 10, 11, 12, 13, 14])
thalm_names = ['pulvinar', 'ventral-anterior', 'mediodorsal', 'lateral-posterior-ventral-posterior-group', 'pulvinar-medial-centrolateral-group', 'ventrolateral', 'ventral-posterior-ventrolateral-group']
prefix = "thal-lh-"
thalm_namesl = [prefix + s.lower() for s in thalm_names]
prefix = "thal-rh-"
thalm_namesr = [prefix + s.lower() for s in thalm_names]
thalm_colorsl = np.array([[255, 0, 0], [0, 255, 0], [255, 255, 0], [255, 123, 0], [0, 255, 255], [255, 0, 255], [0, 0, 255]])
thalm_colorsr = thalm_colorsl
# ---------------- Creating output filenames ------------ #
outDir = os.path.dirname(spamImage)
fname = os.path.basename(spamImage)
tempList = fname.split('_')
tempList[-1] = 'dseg.nii.gz'
if not maxpName:
maxpName = os.path.join(outDir, '_'.join(tempList))
tempList[-1] = 'dseg.lut'
lutName = os.path.join(outDir, '_'.join(tempList))
tempList[-1] = 'dseg.tsv'
tsvName = os.path.join(outDir, '_'.join(tempList))
maxlist = maxpName.split(os.path.sep)
tsvlist = tsvName.split(os.path.sep)
lutlist = lutName.split(os.path.sep)
# ---------------- Creating Maximum probability Image ------------- #
# Reading the thalamic parcellation
spam_Ip = nib.load(spamImage)
affine = spam_Ip.affine
spam_Ip = spam_Ip.get_fdata()
spam_Ip[spam_Ip < thresh] = 0
spam_Ip[spam_Ip > 1] = 1
# 1. Left Hemisphere
It = spam_Ip[:, :, :, :7]
ind = np.where(np.sum(It, axis=3) == 0)
maxprob_thl = spam_Ip[:, :, :, :7].argmax(axis=3) + 1
maxprob_thl[ind] = 0
if thalMask:
Itemp = nib.load(thalMask)
Itemp = Itemp.get_fdata()
index = np.where(Itemp != thl_code)
maxprob_thl[index[0], index[1], index[2]] = 0
# 2. Right Hemisphere
It = spam_Ip[:, :, :, 7:]
ind = np.where(np.sum(It, axis=3) == 0)
maxprob_thr = spam_Ip[:, :, :, 7:].argmax(axis=3) + 1
maxprob_thr[ind] = 0
if thalMask:
index = np.where(Itemp != thr_code)
maxprob_thr[index[0], index[1], index[2]] = 0
ind = np.where(maxprob_thr != 0)
maxprob_thr[ind] = maxprob_thr[ind] + 7
# Saving the Nifti file
imgcoll = nib.Nifti1Image(maxprob_thr.astype('int16') + maxprob_thl.astype('int16'), affine)
nib.save(imgcoll, maxpName)
# Creating the corresponding TSV file
_parc_tsv_table(np.concatenate((thalm_codesl, thalm_codesr)),
np.concatenate((thalm_namesl, thalm_namesr)),
np.concatenate((thalm_colorsl, thalm_colorsr)),
tsvName)
# Creating and saving the corresponding colorlut table
now = datetime.now()
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
luttable = ['# $Id: <BIDsDirectory>/derivatives/{} {} \n'.format('/'.join(lutlist[-5:]), date_time),
'# Corresponding parcellation: ',
'# <BIDsDirectory>/derivatives/' + '/'.join(maxlist[-5:]) ,
'# <BIDsDirectory>/derivatives/' + '/'.join(tsvlist[-5:]) + '\n']
luttable.append('{:<4} {:<50} {:>3} {:>3} {:>3} {:>3} \n '.format("#No.", "Label Name:", "R", "G", "B", "A"))
luttable.append("# Left Hemisphere. Thalamic nuclei parcellation (MIAL, Najdenovska and Alemán-Gómez et al, 2018)")
for roi_pos, roi_name in enumerate(thalm_namesl):
luttable.append('{:<4} {:<50} {:>3} {:>3} {:>3} {:>3}'.format(roi_pos + 1, roi_name, thalm_colorsl[roi_pos,0], thalm_colorsl[roi_pos,1], thalm_colorsl[roi_pos,2], 0))
nright = roi_pos +1
luttable.append('\n')
luttable.append("# Right Hemisphere. Thalamic nuclei parcellation")
for roi_pos, roi_name in enumerate(thalm_namesr):
luttable.append('{:<4} {:<50} {:>3} {:>3} {:>3} {:>3}'.format(nright + roi_pos + 1, roi_name, thalm_colorsr[roi_pos,0], thalm_colorsr[roi_pos,1], thalm_colorsr[roi_pos,2], 0))
with open(lutName, 'w') as colorLUT_f:
colorLUT_f.write('\n'.join(luttable))
# def _build_parcellation(layout, bids_dir, deriv_dir, ent_dict, parccode):
def _build_parcellation(t1, bids_dir, deriv_dir, parccode, growwm):
# layout = bids.BIDSLayout(bids_dir, validate=False)
anat_dir = os.path.dirname(t1)
t1_name = os.path.basename(t1)
temp_entities = t1_name.split('_')[:-1]
fullid = "_".join(temp_entities)
if "ses" in fullid:
ses_index = [i for i, s in enumerate(temp_entities) if 'ses' in s]
path_cad = temp_entities[0] + os.path.sep + temp_entities[ses_index[0]]
else:
path_cad = temp_entities[0]
# layout = BIDSLayout(anat_dir, validate=False)
# ent_dict = layout.parse_file_entities(t1)
# ######## ------------- Creating the full ID. It is used for a correct image file naming. ------------ #
# if 'session' in ent_dict.keys():
# pattern_fullid = "sub-{subject}_ses-{session}_run-{run}"
# path_cad = "sub-" + ent_dict["subject"] + os.path.sep + "ses-" + ent_dict["session"]
# else:
# pattern_fullid = "sub-{subject}_run-{run}"
# path_cad = "sub-" + ent_dict["subject"]
# fullid = os.path.basename(layout.build_path(ent_dict, pattern_fullid, validate=False))
######## ------------- Reading the parcellation dictionary ------------ #
parcdict = _load_parctype_json()
######## ------------- Detecting FreeSurfer Subjects Directory ------------ #
fshome_dir = os.getenv('FREESURFER_HOME')
fssubj_dir = os.path.join(deriv_dir, 'freesurfer')
os.environ["SUBJECTS_DIR"] = fssubj_dir
if not os.path.isdir(fssubj_dir):
print("The freesurfer subjects directory is not inside the derivative folder.")
sys.exit()
######## ------------- Reading FreeSurfer color lut table ------------ #
lutFile = os.path.join(fshome_dir, 'FreeSurferColorLUT.txt')
st_codes, st_names, st_colors = read_fscolorlut(lutFile)
######## ------------- Labelling the structures ------------ #
# 1. ---------------- Detecting White matter ------------------------- #
wm_codesl = np.array([2, 5001])
idx = search(st_codes, wm_codesl)
wm_namesl = ['wm-lh-brain-segmented', 'wm-lh-brain-unsegmented']
wm_colorsl = st_colors[idx]
wm_codesr = np.array([41, 5002])
idx = search(st_codes, wm_codesr)
wm_namesr = ['wm-rh-brain-segmented', 'wm-rh-brain-unsegmented']
wm_colorsr = st_colors[idx]
cc_codes = np.array([250, 251, 252, 253, 254, 255])
idx = search(st_codes, cc_codes)
cc_names = np.array(st_names)[idx].tolist()
prefix = 'wm-brain-'
cc_names = [prefix + s.lower() for s in cc_names]
cc_names = [s.replace('_', '-').lower() for s in cc_names]
cc_colors = st_colors[idx]
wm_codes = np.concatenate((wm_codesl.astype(int), wm_codesr.astype(int), cc_codes.astype(int)))
wm_names = ['wm-brain-white_matter']
wm_colors = np.array([[255, 255, 255]])
# 2. ---------------- Detecting Subcortical structures (Freesurfer) ------------------------- #
subc_codesl = np.array([11, 12, 13, 26])
idx = search(st_codes, subc_codesl)
subc_namesl = np.array(st_names)[idx].tolist()
subc_namesl = [s.replace('Left-', 'subc-lh-').lower() for s in subc_namesl]
subc_colorsl = st_colors[idx]
subc_codesr = np.array([50, 51, 52, 58])
idx = search(st_codes, subc_codesr)
subc_namesr = np.array(st_names)[idx].tolist()
subc_namesr = [s.replace('Right-', 'subc-rh-').lower() for s in subc_namesr]
subc_colorsr = st_colors[idx]
# 3. ---------------- Detecting Thalamic structures (Freesurfer) ------------------------- #
thalf_codesl = np.ones((1,), dtype=int) * 10
idx = [st_codes.index(thalf_codesl)]
# idx = search(st_codes, thalf_codesl)
thalf_namesl = np.array(st_names)[idx].tolist()
thalf_namesl = [s.replace('Left-', 'thal-lh-').lower() for s in thalf_namesl]
thalf_colorsl = st_colors[idx]
thalf_codesr = np.ones((1,), dtype=int) * 49
idx = [st_codes.index(thalf_codesr)]
# idx = search(st_codes, thalf_codesr)
thalf_namesr = np.array(st_names)[idx].tolist()
thalf_namesr = [s.replace('Right-', 'thal-rh-').lower() for s in thalf_namesr]
thalf_colorsr = st_colors[idx]
# 3. ---------------- Detection of Thalamic nuclei (Iglesias)------------ #
thali_codesl = np.array(
[8103, 8104, 8105, 8106, 8108, 8109, 8110, 8111, 8112, 8113, 8115, 8116, 8117, 8118, 8119, 8120, 8121, 8122,
8123, 8125, 8126, 8127, 8128, 8129, 8130, 8133, 8134])
thali_codesr = np.array(
[8203, 8204, 8205, 8206, 8208, 8209, 8210, 8211, 8212, 8213, 8215, 8216, 8217, 8218, 8219, 8220, 8221, 8222,
8223, 8225, 8226, 8227, 8228, 8229, 8230, 8233, 8234])
idx = search(st_codes, thali_codesl)
thali_namesl = np.array(st_names)[idx].tolist()
thali_colorsl = st_colors[idx]
thali_namesl = [s.replace('_', '-') for s in thali_namesl]
thali_namesl = [s.replace('Left-', 'thal-lh-').lower() for s in thali_namesl]
idx = search(st_codes, thali_codesr)
thali_namesr = np.array(st_names)[idx].tolist()
thali_colorsr = st_colors[idx]
thali_namesr = [s.replace('_', '-') for s in thali_namesr]
thali_namesr = [s.replace('Right-', 'thal-rh-').lower() for s in thali_namesr]
# 3. ---------------- Detection of Thalamic nuclei (MIAL)------------ #
thalm_codesl = np.array([1, 2, 3, 4, 5, 6, 7])
thalm_codesr = np.array([8, 9, 10, 11, 12, 13, 14])
thalm_names = ['pulvinar', 'ventral-anterior', 'mediodorsal', 'lateral-posterior-ventral-posterior-group',
'pulvinar-medial-centrolateral-group', 'ventrolateral', 'ventral-posterior-ventrolateral-group']
prefix = "thal-lh-"
thalm_namesl = [prefix + s.lower() for s in thalm_names]
prefix = "thal-rh-"
thalm_namesr = [prefix + s.lower() for s in thalm_names]
thalm_colorsl = np.array(
[[255, 0, 0], [0, 255, 0], [255, 255, 0], [255, 123, 0], [0, 255, 255], [255, 0, 255], [0, 0, 255]])
thalm_colorsr = thalm_colorsl
# 4. ---------------- Detecting Amygdala structures (Freesurfer) ------------------------- #
amygf_codesl = np.ones((1,), dtype=int) * 18
idx = [st_codes.index(amygf_codesl)]
# idx = search(st_codes, amygf_codesl)
amygf_namesl = np.array(st_names)[idx].tolist()
amygf_namesl = [s.replace('Left-', 'amygd-lh-').lower() for s in amygf_namesl]
amygf_colorsl = st_colors[idx]
amygf_codesr = np.ones((1,), dtype=int) * 54
idx = [st_codes.index(amygf_codesr)]
# idx = search(st_codes, amygf_codesr)
amygf_namesr = np.array(st_names)[idx].tolist()
amygf_namesr = [s.replace('Right-', 'amygd-rh-').lower() for s in amygf_namesr]
amygf_colorsr = st_colors[idx]
# 4. ---------------- Detecting Amygdala nuclei (Iglesias) ------------------------- #
amygi_codesl = np.array([7001, 7003, 7005, 7006, 7007, 7008, 7009, 7010, 7015])
idx = search(st_codes, amygi_codesl)
amygi_namesl = np.array(st_names)[idx].tolist()
amygi_colorsl = st_colors[idx]
amygi_codesr = amygi_codesl
amygi_namesr = amygi_namesl
amygi_colorsr = amygi_colorsl
prefix = "amygd-lh-"
amygi_namesl = [prefix + s.lower() for s in amygi_namesl]
amygi_namesl = [s.replace('_', '-') for s in amygi_namesl]
prefix = "amygd-rh-"
amygi_namesr = [prefix + s.lower() for s in amygi_namesr]
amygi_namesr = [s.replace('_', '-') for s in amygi_namesr]
# 5. ---------------- Detecting Hippocampus structures (Freesurfer) ------------------------- #
hippf_codesl = np.ones((1,), dtype=int) * 17
idx = [st_codes.index(hippf_codesl)]
# idx = search(st_codes, hippf_codesl)
hippf_namesl = np.array(st_names)[idx].tolist()
hippf_namesl = [s.replace('Left-', 'hipp-lh-').lower() for s in hippf_namesl]
hippf_colorsl = st_colors[idx]
hippf_codesr = np.ones((1,), dtype=int) * 53
idx = [st_codes.index(hippf_codesr)]
# idx = search(st_codes, hippf_codesr)
hippf_namesr = np.array(st_names)[idx].tolist()
hippf_namesr = [s.replace('Right-', 'hipp-rh-').lower() for s in hippf_namesr]
hippf_colorsr = st_colors[idx]
# 5. ---------------- Detecting Hippocampus nuclei (Iglesias) ------------------------- #
hippi_codesl = np.array(
[203, 233, 235, 237, 239, 241, 243, 245, 211, 234, 236, 238, 240, 242, 244, 246, 212, 226, 215])
idx = search(st_codes, hippi_codesl)
hippi_namesl = np.array(st_names)[idx].tolist()
hippi_colorsl = st_colors[idx]
hippi_codesr = hippi_codesl
hippi_namesr = hippi_namesl
hippi_colorsr = hippi_colorsl
prefix = "hipp-lh-"
hippi_namesl = [prefix + s.lower() for s in hippi_namesl]
hippi_namesl = [s.replace('_', '-') for s in hippi_namesl]
prefix = "hipp-rh-"
hippi_namesr = [prefix + s.lower() for s in hippi_namesr]
hippi_namesr = [s.replace('_', '-') for s in hippi_namesr]
# 5. ---------------- Detecting Hippocampus nuclei and grouping in Head, Body and Tail (Iglesias) ------------------------- #
hipph_codesl = np.array([1, 2, 3, 4])
hipph_namesl = ['hipp-lh-hippocampus-head', 'hipp-lh-hippocampus-body', 'hipp-lh-hippocampus-tail',
'hipp-lh-hippocampus-fissure']
hipph_colorsl = np.array([[255, 0, 0], [0, 255, 0], [255, 255, 0], [255, 123, 0]])
hipph_codesr = np.array([1, 2, 3, 4])
hipph_namesr = ['hipp-rh-hippocampus-head', 'hipp-rh-hippocampus-body', 'hipp-rh-hippocampus-tail',
'hipp-rh-hippocampus-fissure']
hipph_colorsr = np.array([[255, 0, 0], [0, 255, 0], [255, 255, 0], [255, 123, 0]])
# 6. ---------------- Segmenting the hypothalamus using the VentralDC (Connectomics Lab) ------------ #
# Ventral DC Left
vdcf_codel = 28
vdcf_namesl = ["vdc-lh-ventraldc"]
vdcf_colorsl = np.array([[165, 42, 42]])
# Ventral DC Right
vdc_coder = 60
vdcf_namesr = ["vdc-rh-ventraldc"]
vdcf_colorsr = np.array([[165, 42, 42]])
# Third Ventricle
vent3_code = 14
# Hypothalamus
hypf_namesl = ["hypo-lh-hypothalamus"]
hypf_colorsl = np.array([[204, 182, 142]])
hypf_namesr = ["hypo-rh-hypothalamus"]
hypf_colorsr = np.array([[204, 182, 142]])
# 6. ---------------- Detection of hypothalamic nuclei (Iglesias) ------------ #
hypi_codesl = np.array([801, 802, 803, 804, 805])
hypi_codesr = np.array([806, 807, 808, 809, 810])
idx = search(st_codes, hypi_codesl)
hypi_namesl = np.array(st_names)[idx].tolist()
hypi_colorsl = st_colors[idx]
hypi_namesl = [s.replace('_', '-') for s in hypi_namesl]
hypi_namesl = [s.replace('L-hypothalamus-', 'hypo-lh-').lower() for s in hypi_namesl]
idx = search(st_codes, hypi_codesr)
hypi_namesr = np.array(st_names)[idx].tolist()
hypi_colorsr = st_colors[idx]
hypi_namesr = [s.replace('_', '-') for s in hypi_namesr]
hypi_namesr = [s.replace('R-hypothalamus-', 'hypo-rh-').lower() for s in hypi_namesr]
# 7. ---------------- Detecting Cerbellum structures (Freesurfer) ------------------------- #
cerebf_codesl = np.ones((1,), dtype=int) * 8
idx = [st_codes.index(cerebf_codesl)]
cerebf_namesl = ['cer-lh-cerebellum']
cerebf_colorsl = st_colors[idx]
cerebf_codesr = np.ones((1,), dtype=int) * 47
idx = [st_codes.index(cerebf_codesr)]
cerebf_namesr = ['cer-rh-cerebellum']
cerebf_colorsr = st_colors[idx]
# 8. ---------------- Detection of Brainstem (FreeSurfer) ------------ #
bstemf_codes = np.ones((1,), dtype=int) * 16
idx = search(st_codes, bstemf_codes)
bstemf_names = ['brain-stem-brainstem']
bstemf_colors = st_colors[idx]
# 8. ---------------- Detection of Brainstem (Iglesias) ------------ #
bstemi_codes = np.array([173, 174, 175, 178])
idx = search(st_codes, bstemi_codes)
bstemi_names = np.array(st_names)[idx].tolist()
bstemi_colors = st_colors[idx]
prefix = "brain-stem-"
bstemi_names = [prefix + s.lower() for s in bstemi_names]
## ================ Creating the new parcellation
lut_lines = ['{:<4} {:<40} {:>3} {:>3} {:>3} {:>3} \n \n'.format("#No.", "Label Name:", "R", "G", "B", "A")]
parc_desc_lines = ["# Parcellation code: " + parccode]
if len(parccode) != 9: # Length of the parcellation string
parccode = parccode.ljust(9, 'N')