-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfreesurfer_summary.py
executable file
·1507 lines (1268 loc) · 59.5 KB
/
freesurfer_summary.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
from __future__ import division
import os
import re
import seaborn as sns
from os.path import join, basename, dirname, isfile
import sys
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.pyplot import cm
import argparse
import itertools
import textwrap
from progressbar import ProgressBar
import time
from sklearn.cluster import KMeans
import warnings
warnings.filterwarnings("ignore", 'This pattern has match groups')
#import tksurferCapture
pd.options.mode.chained_assignment = None # default='warn'
__author__ = 'kcho'
plt.style.use('ggplot')
class FreesurferDirectories(object):
"""Freesurfer directories class"""
def __init__(self, fs_directories:list):
self.cortex_df = pd.DataFrame()
self.subcortex_df = pd.DataFrame()
for fs_directory in fs_directories:
f = Freesurfer(fs_directory)
cortical_df_tmp = f.cortical_df
cortical_df_tmp['subject'] = f.subject
cortical_df_tmp['group'] = f.group
self.cortex_df = pd.concat([self.cortex_df, cortical_df_tmp])
subcortical_df_tmp = f.subcortical_df
subcortical_df_tmp['subject'] = f.subject
subcortical_df_tmp['group'] = f.group
self.subcortex_df = pd.concat([self.subcortex_df, subcortical_df_tmp])
# self.cortex_df_subj_row = pd.pivot_table(self.cortex_df,
# values=['thickness', 'volume'],
# index=['subject', 'group'],
# columns=['roi', 'side'])
# self.subcortex_df_subj_row = pd.pivot_table(self.subcortex_df,
# values=['volume'],
# index=['subject', 'group'],
# columns=['roi'])
# self.final_df = pd.merge(self.cortex_df_subj_row,
# self.subcortex_df_subj_row, on=['subject', 'group'], how='inner')
class Freesurfer(object):
def __init__(self, freesurfer_dir):
self.freesurfer_dir = freesurfer_dir
os.environ["FREESURFER_HOME"] = '/usr/local/freesurfer'
os.environ["SUBJECTS_DIR"] = dirname(self.freesurfer_dir)
self.cortical_df = aparcstats2table(self.freesurfer_dir, 'aparc')
self.subcortical_df = asegstats2table(self.freesurfer_dir)
# Grep subject naming from the directory
bcs_naming_regrex = '\w{3}_BCS\d{3}_\w{2,4}'
kjs_naming_regrex = '\w{3}\d{2}_\w{2,4}'
try:
self.subject = re.search('{bcs}|{kjs}'.format(bcs=bcs_naming_regrex,
kjs=kjs_naming_regrex),
freesurfer_dir).group(0)
self.group = self.subject[:3]
except:
self.subject = basename(freesurfer_dir)
self.group = self.subject[:3]
# Add group and subject information to the table
for df_tmp in self.cortical_df, self.subcortical_df:
df_tmp['group'] = self.group
df_tmp['subject'] = self.subject
class fs_eight_cortex:
def __init__(self):
ofc = ['parsorbitalis', 'medialorbitofrontal',
'lateralorbitofrontal']
mpfc = ['caudalanteriorcingulate',
'rostralanteriorcingulate', 'superiorfrontal']
lpfc = [ 'parstriangularis', 'rostralmiddlefrontal',
'frontalpole', 'parsopercularis']
smc = [ 'precentral', 'caudalmiddlefrontal',
'postcentral', 'paracentral']
pc = ['inferiorparietal', 'supramarginal',
'precuneus', 'posteriorcingulate',
'isthmuscingulate', 'superiorparietal']
mtc = ['entorhinal', 'parahippocampal', 'fusiform']
ltc = ['transversetemporal', 'superiortemporal',
'bankssts', 'inferiortemporal',
'middletemporal', 'temporalpole']
occ = ['pericalcarine', 'lingual',
'lateraloccipital', 'cuneus']
tmp_dict = {'OFC' : ofc, 'MPFC' : mpfc,
'LPFC' : lpfc, 'SMC' : smc,
'MTC' : mtc, 'LTC' : ltc,
'PC' : pc, 'OCC' : occ}
self.eight_cortex_dict = tmp_dict
def demo_match(age, age_range, sex, all_data_Loc):
'''
by yb
'''
matching = pd.read_csv(all_data_Loc)
upper = int(age) + age_range
lower = int(age) - age_range
matching_age = matching[(matching['age'] >= lower) & (matching['age'] <= upper)]
matching_sex = matching_age[matching_age['sex'] == sex]
# see column names
if 'thickness' in matching.columns:
matched = matching_sex[['side', 'roi', 'region', 'thickness','thicknessstd', 'volume', 'subject']]
matched_mean = matched.groupby(['roi','side','region']).mean().reset_index()
matched_std = matched.groupby(['roi','side','region']).std().reset_index()
matched_std = matched_std.rename(columns={'thickness': 'thickstd',
'thicknessstd': 'per_region_std',
'volume': 'volumestd'})
matched_mean_std = pd.merge(matched_mean, matched_std, how='inner')
elif 'thickness' not in matching.columns:
matched = matching_sex[['roi', 'volume', 'region', 'subject']]
matched_mean = matched.groupby(['roi', 'region']).mean().reset_index()
matched_std = matched.groupby(['roi','region']).std().reset_index()
matched_std = matched_std.rename(columns={'volume': 'volumestd'})
matched_mean_std = pd.merge(matched_mean, matched_std, how='inner')
return matched_mean_std
def getGroupMeanInfo(meanDfLoc):
'''
Read cortical thickness of all control subjects
'''
df = pd.read_csv(meanDfLoc, index_col=0)
if 'roi' not in df.columns or 'region' not in df.columns:
df['roi'] = df.subroi.str[3:]
df['region'] = df.roi.apply(getRegion)
df.to_csv(meanDfLoc)
# meanDf to have averaged values for all groups
meanDf = df.groupby(['roi','side','region']).mean().reset_index()
meanDf.columns = ['roi','side','region', 'thickavg','thickstd']
df_name = 'CCNC_mean'
return meanDf, df_name
def makeMean(inputDirs):
'''
inputDirs is the freesurfer directories to be merged into
background information
'''
cortical_dfs = pd.DataFrame()
subcortical_dfs = pd.DataFrame()
pbar = ProgressBar().start()
# mri spreadsheet
mri_excel_loc = '/home/kangik/Dropbox/MRI/MRI.xls'
mri_excel = pd.ExcelFile(mri_excel_loc)
nor_df = mri_excel.parse('NOR')
nor_df = nor_df[(nor_df.timeline=='baseline')][['folderName','age','sex']]
for fsDirNum, fsDir in enumerate(inputDirs):
pbar.update((fsDirNum/len(inputDirs)) * 100)
# aparcstats2table
cortical_df = aparcstats2table(os.path.abspath(fsDir), 'aparc')
cortical_df['subject'] = basename(fsDir)
cortical_dfs = pd.concat([cortical_dfs, cortical_df])
# asegstats2table
# df.columns = ['roi', 'volume', 'region']
# regions are subocortex
subcortical_df = asegstats2table(os.path.abspath(fsDir))
subcortical_df['subject'] = basename(fsDir)
subcortical_dfs = pd.concat([subcortical_dfs, subcortical_df])
pbar.finish()
cortical_dfs = pd.merge(cortical_dfs, nor_df,
left_on='subject',
right_on='folderName',
how='left')
subcortical_dfs = pd.merge(subcortical_dfs, nor_df,
left_on='subject',
right_on='folderName',
how='left')
cortical_dfs.to_csv('all_cortical_dfs_{date}.csv'.format(
date = time.strftime("%Y_%m_%d")))
subcortical_dfs.to_csv('all_subcortical_dfs_{date}.csv'.format(
date = time.strftime("%Y_%m_%d")))
mean_cortical_dfs = cortical_dfs.groupby(['side', 'roi', 'region']).mean()
mean_subcortical_dfs = subcortical_dfs.groupby(['roi', 'region']).mean()
# thickstd : standard deviation of thickness across subjects
# thicknessstd : mean of standard deviations of thicknness in each regions
mean_cortical_dfs['volumestd'] = cortical_dfs.groupby(['side', 'roi', 'region']).std()['volume']
mean_cortical_dfs['thickstd'] = cortical_dfs.groupby(['side', 'roi', 'region']).std()['thickness']
mean_subcortical_dfs['volumestd'] = subcortical_dfs.groupby(['roi', 'region']).std()['volume']
mean_cortical_dfs.to_csv('mean_cortical_dfs_{date}.csv'.format(
date = time.strftime("%Y_%m_%d")))
mean_subcortical_dfs.to_csv('mean_subcortical_dfs_{date}.csv'.format(
date = time.strftime("%Y_%m_%d")))
#print mean_subcortical_dfs
def freesurferSummary(inputDirs,
nameList=False,
ageList=False, genderList=False,
colorList=False,
ageRange=3, nobackground=False):
'''
Summarizes freesurfer outputs using matplotlib
- Cortical thickness and volume
- Subcortical volumes & ICV
'''
# Collect infoDfs and names
cortical_dfs = []
subcortical_dfs = []
fsNames = []
# Loop through every fs directories
if not ageList:
to_iter = enumerate(zip(inputDirs, ['']*len(inputDirs), ['']*len(inputDirs)))
else:
to_iter = enumerate(zip(inputDirs, ageList, genderList))
for fsDirNum, (fsDir, age, gender) in to_iter:
if nameList:
subjNames = '{name} {gender} {age}'.format(
name = nameList[fsDirNum],
gender = gender,
age = age)
else:
subjNames = input('{0} Subject initial :'.format(fsDir))
fsNames.append(subjNames)
# Label approach
# fsInfoDf.append(collectStats(os.path.abspath(fsDir)))
# aparcstats2table
cortical_df = aparcstats2table(os.path.abspath(fsDir), 'aparc')
cortical_df['subject'] = subjNames
cortical_dfs.append(cortical_df)
# asegstats2table
# df.columns = ['roi', 'volume', 'region']
# regions are subocortex
subcortical_df = asegstats2table(os.path.abspath(fsDir))
subcortical_df['subject'] = subjNames
subcortical_dfs.append(subcortical_df)
if nobackground==False: # Mean graph option turned on
# Read CCNC healthy control information
for age, gender in zip(ageList, genderList):
# csv with all subjects' data
mean_cortical_df_loc = '/Volume/CCNC_BI_3T/freesurfer/NOR/all_cortical_dfs_2017_07_04.csv'
mean_subcortical_df_loc = '/Volume/CCNC_BI_3T/freesurfer/NOR/all_subcortical_dfs_2017_07_04.csv'
# Yoobin function added here
mean_cortical_df = demo_match(age, ageRange, gender,
mean_cortical_df_loc)
mean_subcortical_df = demo_match(age, ageRange, gender,
mean_subcortical_df_loc)
# Add CCNC HCs informat
cortical_dfs.append(mean_cortical_df)
subcortical_dfs.append(mean_subcortical_df)
# Mean graph name with age and gender information
mgName = 'CCNC_mean {age} age range: {ageRange} {gender}'.format(age=age,
ageRange=ageRange,
gender=gender)
fsNames.append(mgName)
# Make line plots of cortical thickness for each hemisphere
# draw_thickness_list(cortical_dfs, fsNames, colorList, nobackground)
# draw_volume_list(cortical_dfs, fsNames, colorList, nobackground)
# draw_subcortical_volume_list(subcortical_dfs, fsNames, colorList, nobackground)
# tksurferCapture.main(fsDir, join(fsDir,
# 'tmp',
# 'thick_kev_detailed_new.csv'))
def getRegion(roi):
'''
find region of the detailed freesurfer label
eg) regions : 'LPFC', 'OFC', 'MPFC', 'LTC', 'MTC', 'SMC', 'PC' or 'OCC'
'''
roiDict = get_cortical_rois()
for region, roiList in roiDict.items():
if roi in roiList:
return region
def reorder_df(df, colName, orderList):
gb = df.groupby(colName)
newDf = pd.concat([gb.get_group(x) for x in orderList])
newDf = newDf.reset_index()
return newDf
def draw_subcortical_volume_list(infoDfList, nameList, colorList, nobackground):
'''
Draw graph that summarizes subcortical volumes from
freesurfer outputs.
The last items in the given input lists are that of meandf.
1. Separate out data that has side information.
2. Divide the rest of volumes in
to four graphs according to the volumes
'''
number_of_graphs = 4
# mean infoDf
meanDf = infoDfList[-1]
# remove regions
regions_to_remove = ['BrainSegVol', 'BrainSegVolNotVent',
'BrainSegVolNotVentSurf', 'MaskVol',
'SupraTentorialVol', 'SupraTentorialVolNotVent',
'SupraTentorialVolNotVentVox',
'SubCortGrayVol', 'Brain-Stem',
'Left-Cerebellum-Cortex',
'Right-Cerebellum-Cortex',
'Left-Cerebellum-White-Matter',
'Right-Cerebellum-White-Matter',
'BrainSegVol-to-eTIV',
'MaskVol-to-eTIV',
'5th-Ventricle',
'Optic-Chiasm',
'SurfaceHoles',
'lhSurfaceHoles', 'rhSurfaceHoles',
'WM-hypointensities',
'non-WM-hypointensities',
'Right-non-WM-hypointensities',
'Left-non-WM-hypointensities',
'Right-WM-hypointensities',
'Left-WM-hypointensities',
'Right-vessel', 'Left-vessel']
meanDf = meanDf[(~meanDf.roi.isin(regions_to_remove))]
rois_with_side = meanDf.roi[meanDf.roi.str.contains('(Left|Right)')]
meanDf_withside = meanDf[meanDf.roi.isin(rois_with_side)]
meanDf_withoutside = meanDf[~meanDf.roi.isin(rois_with_side)]
# kmeans
# volume range divisions
graphNum = 4
# data to divide
subcortical_volumes_mean = np.array(meanDf_withoutside.volume).reshape(-1,1)
# settin up and training the kmeans model
kmeans = KMeans(n_clusters=graphNum,
random_state=0).fit(subcortical_volumes_mean)
# chage here later
# gives error without
# pd.options.mode.chained_assignment = None # default='warn'
meanDf_withoutside['gtype'] = kmeans.labels_
# Graphs
fig = plt.figure(figsize=(22,12), facecolor='white')
fig.suptitle("Sub-cortical Volume Summary", fontsize=20)
# axes
# Upper axes : Data with side information
gs = gridspec.GridSpec(3,4)
left_ax = plt.subplot(gs[0,:])
right_ax = plt.subplot(gs[1,:])
axes_side = [left_ax, right_ax]
# Lower axes : Data without side information
# K-means clustered
ax1 = plt.subplot(gs[2,0])
ax2 = plt.subplot(gs[2,1])
ax3 = plt.subplot(gs[2,2])
ax4 = plt.subplot(gs[2,3])
axes = [ax1, ax2, ax3, ax4]
# color definition
color=iter(cm.rainbow(np.linspace(0,1,len(infoDfList))))
sig_diff_region = []
# For every subject information dataframes
for infoDfNum, (infoDf, subjName) in enumerate(zip(infoDfList, nameList)):
# Setting graph colours
if colorList:
# if meanDf is on, colorList is one shorter.
try:
c = colorList[infoDfNum]
except:
c = 'b'
else:
c = next(color)
# For subcortical main structures,
# divided left and right
df = infoDf[(~infoDf.roi.isin(regions_to_remove))]
df_side = df[(df.roi.isin(rois_with_side))]
df_side.loc[:, 'side'] = df_side.roi.str.extract('(Left|Right)', expand=False)
df_side.loc[:, 'merged_roi'] = df.roi.str.extract('\w{4,5}-(\S*)', expand=False)
df_without_side = df[~(df.roi.isin(rois_with_side))]
for sideNum, side in enumerate(['Left', 'Right']):
side_df = df_side.groupby('side').get_group(side)
side_df = side_df.sort_values('merged_roi')
ax = axes_side[sideNum]
if 'CCNC_mean' in subjName:
#ax.plot(infodf.thickavg, '--', c=c, label=subjName)
eb = ax.errorbar(range(len(side_df.merged_roi.unique())),
side_df.volume,
side_df.volumestd*2,
marker='^',
label=subjName,
color='b',
ecolor='b',
alpha=0.7)
plotline, caplines, barlinecols = eb
barlinecols[0].set_linestyle('--')
plotline.set_linestyle('--')
else:
ax.plot(range(len(side_df.merged_roi)),
side_df.volume,
c=c,
marker='o',
label=subjName)
if nobackground==False:
### annotation
mergedDf = pd.merge(meanDf_withside,
side_df,
on='roi',
how='right')
mergedDf['mean_sub_indv'] = mergedDf.volume_x - mergedDf.volume_y
# Reorder Dfs
mergedDf = mergedDf.sort_values('roi')
#mergedDf = reorder_df(mergedDf, 'region', roiOrder)
#for sigNum, row in enumerate(mergedDf[abs(mergedDf['mean_sub_indv']) > 0.5].iterrows()):
# greater than two standard deviation
arrowSize = np.mean(side_df.volume.std())
for sigNum, row in enumerate(mergedDf[abs(mergedDf['mean_sub_indv']) > mergedDf['volumestd']*2].iterrows()):
if (sigNum+1) % 2 == 0:
sign = 1
diff = arrowSize/2
else:
sign = -1
diff = 0
if row[1].mean_sub_indv < 0:
col = 'green'
sign = 1
else:
col = 'red'
textLoc_y = row[1].volume_y + (sign * arrowSize) + diff
if row[1].roi not in sig_diff_region:
ax.annotate(row[1].roi,
xy = (row[0], row[1].volume_y),
xycoords='data',
xytext = (row[0], textLoc_y),
textcoords='data',
arrowprops = dict(facecolor=col,
shrinkB=5,
alpha=0.5),
horizontalalignment='center',
fontsize=15)
sig_diff_region.append(row[1].roi)
ax.grid(False)
ax.set_xlim(-.5, len(side_df.merged_roi)+0.5)
ax.set_xticks(range(len(side_df.merged_roi)))
ax.set_xticklabels(side_df.merged_roi)
ax.patch.set_facecolor('white')
ax.autoscale(enable=True, axis='x')
# Bottom three graphs
for axNum, ax in enumerate(axes):
# List of rois in subgroups
roi_order = meanDf_withoutside[(meanDf_withoutside.gtype==axNum)].roi
# Subgroup roi df
df = infoDf[(infoDf.roi.isin(roi_order))]
df = df.sort_values('roi')
#df = df.set_index('roi').reindex(roi_order).reset_index() # sort
#df['gtype'] = axNum
if 'CCNC_mean' in subjName:
eb = ax.errorbar(range(len(df.roi.unique())),
df.volume,
df.volumestd*2,
marker='^',
label=subjName,
color='b',
ecolor='b',
alpha=0.7)
plotline, caplines, barlinecols = eb
barlinecols[0].set_linestyle('--')
plotline.set_linestyle('--')
else:
ax.plot(range(len(roi_order)),
df.volume,
c=c,
marker='o',
label=subjName)
if nobackground==False:
### annotation
meanDf_set = meanDf.loc[(meanDf.roi.isin(roi_order))]
mergedDf = pd.merge(meanDf_set,
df,
on=['roi','region'],
how='inner')
mergedDf['mean_sub_indv'] = mergedDf.volume_x - mergedDf.volume_y
# Reorder Dfs
mergedDf = mergedDf.sort_values('roi')
#mergedDf = reorder_df(mergedDf, 'region', roiOrder)
#for sigNum, row in enumerate(mergedDf[abs(mergedDf['mean_sub_indv']) > 0.5].iterrows()):
# greater than two standard deviation
arrowSize = np.mean(df.volume.std())
for sigNum, row in enumerate(mergedDf[abs(mergedDf['mean_sub_indv']) > mergedDf['volumestd']*2].iterrows()):
if (sigNum+1) % 2 == 0:
sign = 1
diff = arrowSize/2
else:
sign = -1
diff = 0
if row[1].mean_sub_indv < 0:
col = 'green'
sign = 1
else:
col = 'red'
textLoc_y = row[1].volume_y + (sign * arrowSize) + diff
if row[1].roi not in sig_diff_region:
ax.annotate(row[1].roi,
xy = (row[0], row[1].volume_y),
xycoords='data',
xytext = (row[0], textLoc_y),
textcoords='data',
arrowprops = dict(facecolor=col,
shrinkB=5,
alpha=0.5),
horizontalalignment='center',
fontsize=15)
sig_diff_region.append(row[1].roi)
# axis settings
#ax = axes[snum]
ax.patch.set_facecolor('white')
# Graph settings
#ax.set_ylim(-5000, 35000)
#ax.set_xlabel('Subcortical ROI', fontsize=16)
ax.set_xticks(range(len(roi_order)))
#ax.set_xticklabels(['' for x in roiList])
ax.set_xlim(-.5, len(df.roi)+0.5)
ax.grid(False)
ax.autoscale(enable=True, axis='x')
ax.set_xticklabels(df.roi)
labels = ax.get_xticklabels()
if len(roi_order) > 3:
plt.setp(labels, rotation=30)
plt.tight_layout(pad=7, w_pad=3, h_pad=0.2)
ax2.set_xticklabels(['Total Intra-cranial Volume'], rotation=0)
ax2.set_ylim(1000000, 2200000)
left_ax.legend()
legend = left_ax.legend(frameon = 1)
frame = legend.get_frame()
frame.set_facecolor('white')
#fig.show()
fname = 'subcortical_volume_summary.png'
fig.savefig(fname)
print('feh %s' %join(os.getcwd(), fname))
def draw_volume_list(infoDfList, nameList, colorList, nobackground):
# graph order from left
roiOrder = ['LPFC', 'OFC', 'MPFC', 'LTC', 'MTC', 'SMC', 'PC', 'OCC']
fig, axes = plt.subplots(nrows=2, figsize=(22,12), facecolor='white')
fig.suptitle("Cortical Volume Summary", fontsize=20)
# color definition
color=iter(cm.rainbow(np.linspace(0,1,len(infoDfList))))
# mean infoDf
meanDf = infoDfList[-1]
roiList = meanDf.roi.unique()
sig_diff_region = []
for infoDfNum, (infoDf, subjName) in enumerate(zip(infoDfList, nameList)):
infoDf_gb = infoDf.groupby('side')
if colorList:
# if meanDf is on, colorList is one shorter.
try:
c = colorList[infoDfNum]
except:
c = 'b'
else:
c = next(color)
for snum, side in enumerate(['lh', 'rh']):
infodf = infoDf_gb.get_group(side)
# Reorder Dfs
infodf = infodf.sort_values(['roi','side'])
infodf = reorder_df(infodf, 'region', roiOrder)
ax = axes[snum]
if 'CCNC_mean' in subjName:
#ax.plot(infodf.thickavg, '--', c=c, label=subjName)
eb = ax.errorbar(range(len(roiList)),
infodf.volume,
infodf.volumestd*2,
marker='^',
label=subjName,
color='b',
ecolor='b',
alpha=0.7)
plotline, caplines, barlinecols = eb
barlinecols[0].set_linestyle('--')
plotline.set_linestyle('--')
else:
ax.plot(infodf.volume, c=c, marker='o', label=subjName)
if nobackground==False:
### annotation
mergedDf = pd.merge(meanDf,
infodf,
on=['roi','side','region'],
how='inner')
mergedDf['mean_sub_indv'] = mergedDf.volume_x - mergedDf.volume_y
# Reorder Dfs
mergedDf = mergedDf.sort_values(['roi','side'])
mergedDf = reorder_df(mergedDf, 'region', roiOrder)
#for sigNum, row in enumerate(mergedDf[abs(mergedDf['mean_sub_indv']) > 0.5].iterrows()):
# greater than two standard deviation
for sigNum, row in enumerate(mergedDf[abs(mergedDf['mean_sub_indv']) > mergedDf['volumestd']*2].iterrows()):
if (sigNum+1) % 2 == 0:
sign = 1
diff = 2500
else:
sign = -1
diff = 0
if row[1].mean_sub_indv < 0:
col = 'green'
sign = 1
else:
col = 'red'
textLoc_y = row[1].volume_y + (sign * 5000) + diff
if row[1].roi not in sig_diff_region:
ax.annotate(row[1].roi,
xy = (row[0], row[1].volume_y),
xycoords='data',
xytext = (row[0], textLoc_y),
textcoords='data',
arrowprops = dict(facecolor=col,
shrinkB=5,
alpha=0.5),
horizontalalignment='center',
fontsize=15)
sig_diff_region.append(row[1].roi)
# axis settings
for snum, side in enumerate(['lh', 'rh']):
ax = axes[snum]
ax.patch.set_facecolor('white')
# Graph settings
ax.set_ylim(-5000, 35000)
ax.set_xlabel(side, fontsize=16)
ax.set_xticks(range(len(roiList)))
ax.set_xticklabels(['' for x in roiList])
ax.set_xlim(-.5, 32.5)
ax.grid(False)
ax.legend()
legend = ax.legend(frameon = 1)
frame = legend.get_frame()
frame.set_facecolor('white')
# Background fill (group discrimination)
roiDict = get_cortical_rois()
roiOrder_full = [[x]*len(roiDict[x]) for x in roiOrder]
roiOrder_one_list = list(itertools.chain.from_iterable(roiOrder_full))
roiOrder_array = np.array(roiOrder_one_list)
regionToHighlight = roiOrder[1::2]
xCoords = [np.where(roiOrder_array==x)[0] for x in regionToHighlight]
for x in xCoords:
ax.axvspan(x[0], x[-1], alpha=0.5)
startNum = 0
for region in roiOrder:
x_starting_point = startNum
startNum = startNum + len(roiDict[region])
ax.text((x_starting_point-.5 + startNum-.5)/2, 1.2,
region,
horizontalalignment='center',
alpha=.4,
fontsize=15)
ax.set_xticklabels(infodf.roi)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=30)
plt.tight_layout(pad=7, w_pad=3, h_pad=0.2)
#fig.show()
fname = 'volume_summary.png'
fig.savefig(fname)
print('feh %s' %join(os.getcwd(), fname))
def draw_thickness_list(infoDfList, nameList, colorList, nobackground):
# graph order from left
roiOrder = ['LPFC', 'OFC', 'MPFC', 'LTC', 'MTC', 'SMC', 'PC', 'OCC']
fig, axes = plt.subplots(nrows=2, figsize=(22,12), facecolor='white')
fig.suptitle("Cortical thickness in all regions", fontsize=20)
# color definition
color=iter(cm.rainbow(np.linspace(0,1,len(infoDfList))))
# mean infoDf
meanDf = infoDfList[-1]
roiList = meanDf.roi.unique()
sig_diff_region = []
for infoDfNum, (infoDf, subjName) in enumerate(zip(infoDfList, nameList)):
infoDf_gb = infoDf.groupby('side')
if colorList:
# if meanDf is on, colorList is one shorter.
try:
c = colorList[infoDfNum]
except:
c = 'b'
else:
c = next(color)
for snum, side in enumerate(['lh', 'rh']):
infodf = infoDf_gb.get_group(side)
# Reorder Dfs
infodf = infodf.sort_values(['roi','side'])
infodf = reorder_df(infodf, 'region', roiOrder)
ax = axes[snum]
if 'CCNC_mean' in subjName:
#ax.plot(infodf.thickavg, '--', c=c, label=subjName)
eb = ax.errorbar(range(len(roiList)),
infodf.thickness,
infodf.thickstd*2,
marker='^',
label=subjName,
color='b',
ecolor='b',
alpha=0.7)
plotline, caplines, barlinecols = eb
barlinecols[0].set_linestyle('--')
plotline.set_linestyle('--')
else:
ax.plot(infodf.thickness, c=c, marker='o', label=subjName)
### annotation
if nobackground==False:
mergedDf = pd.merge(meanDf,
infodf,
on=['roi','side','region'],
how='inner')
mergedDf['mean_sub_indv'] = mergedDf.thickness_x - mergedDf.thickness_y
# Reorder Dfs
mergedDf = mergedDf.sort_values(['roi','side'])
mergedDf = reorder_df(mergedDf, 'region', roiOrder)
# Greater than two standard deviation
for sigNum, row in enumerate(mergedDf[abs(mergedDf['mean_sub_indv']) > mergedDf['thickstd'] *2].iterrows()):
if (sigNum+1) % 2 == 0:
sign = 1
diff = 0.5
else:
sign = -1
diff = 0
if row[1].mean_sub_indv < 0:
col = 'green'
sign = 1
else:
col = 'red'
textLoc_y = row[1].thickness_y + (sign*1) + diff
if row[1].roi not in sig_diff_region:
ax.annotate(row[1].roi,
xy = (row[0], row[1].thickness_y),
xycoords='data',
xytext = (row[0], textLoc_y),
textcoords='data',
arrowprops = dict(facecolor=col,
shrinkB=5,
alpha=0.5),
horizontalalignment='center',
fontsize=15)
sig_diff_region.append(row[1].roi)
# axis settings
for snum, side in enumerate(['lh', 'rh']):
ax = axes[snum]
ax.patch.set_facecolor('white')
# Graph settings
ax.set_ylim(1, 4)
ax.set_xlabel(side, fontsize=16)
ax.set_xticks(range(len(roiList)))
ax.set_xticklabels(['' for x in roiList])
ax.set_xlim(-.5, 32.5)
ax.grid(False)
ax.legend()
legend = ax.legend(frameon = 1)
frame = legend.get_frame()
frame.set_facecolor('white')
# Background fill (group discrimination)
roiDict = get_cortical_rois()
roiOrder_full = [[x]*len(roiDict[x]) for x in roiOrder]
roiOrder_one_list = list(itertools.chain.from_iterable(roiOrder_full))
roiOrder_array = np.array(roiOrder_one_list)
regionToHighlight = roiOrder[1::2]
xCoords = [np.where(roiOrder_array==x)[0] for x in regionToHighlight]
for x in xCoords:
ax.axvspan(x[0], x[-1], alpha=0.5)
startNum = 0
for region in roiOrder:
x_starting_point = startNum
startNum = startNum + len(roiDict[region])
ax.text((x_starting_point-.5 + startNum-.5)/2, 1.2,
region,
horizontalalignment='center',
alpha=.4,
fontsize=15)
ax.set_xticklabels(infodf.roi)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=30)
plt.tight_layout(pad=7, w_pad=3, h_pad=0.2)
#fig.show()
fname = 'thickness_summary.png'
fig.savefig(fname)
print('feh %s' %join(os.getcwd(), fname))
def dictWithTuple2df(infoDict):
df = pd.DataFrame.from_dict(infoDict)
df = df.T.reset_index()
df.columns = ['subroi', 'numvert', 'surfarea', 'grayvol',
'thickavg', 'thickstd',
'meancurv', 'gauscurv', 'foldind', 'curvind']
df['side'] = df['subroi'].str[:2]
df['roi'] = df.subroi.str[3:]
df['region'] = df.roi.apply(getRegion)
return df
def getInfoFromLabel(fsDir,roiDict):
'''
Change this function to use pandas and numpy
'''
infoDict={}
pbar = ProgressBar().start()
totalNum = 2 * len(roiDict.keys())
num = 1
for side in ['lh','rh']:
for cortex, rois in roiDict.items():
if len(rois) > 1:
command = 'mris_anatomical_stats \
-l {loc}/{side}_{cortex} {name} {side} 2>/dev/null'.format(
loc=join(fsDir,'tmp'),
side=side,
cortex=cortex,
name=basename(fsDir)
)
else:
command = 'mris_anatomical_stats \
-l {loc}/{side}.{cortex}.label {name} {side} 2>/dev/null'.format(
loc=join(fsDir,'tmp'),
side=side,
cortex=cortex,
name=basename(fsDir)
)
output=os.popen(re.sub('\s+',' ',command)).read()
pbar.update((num/totalNum) * 100)
num+=1
#print output
try:
thickness = re.search('thickness\s+=\s+(\S+)\s+mm\s+\S+\s+(\S+)', output).group(1,2)
numvert = re.search('number of vertices\s+=\s+(\S+)', output).group(1)
surfarea = re.search('total surface area\s+=\s+(\S+)', output).group(1)
grayvol = re.search('total gray matter volume\s+=\s+(\S+)', output).group(1)
meancurv = re.search('average integrated rectified mean curvature\s+=\s+(\S+)', output).group(1)
gauscurv = re.search('average integrated rectified Gaussian curvature\s+=\s+(\S+)', output).group(1)
foldind = re.search('folding index\s+=\s+(\S+)', output).group(1)
curvind = re.search('intrinsic curvature index\s+=\s+(\S+)', output).group(1)
except:
sys.exit('{0} : re.search with mris_antomical_stats not working. Check row data or FS environment'.format(fsDir))
thickness = tuple([float(x) for x in thickness])
infoDict[side+'_'+cortex] = [float(x) for x in [numvert, surfarea, grayvol,
thickness[0], thickness[1],
meancurv, gauscurv, foldind, curvind]]
pbar.finish()
return infoDict
def mergeLabel(fsDir, roiDict):
'''
Merge labels into one label
merge the labels in the roiDict.values --> label roiDict.keys
'''
for side in ['lh','rh']:
for cortex, rois in roiDict.items():
inLabelLocs = [join(fsDir,'tmp',side+'.'+x+'.label') for x in rois]
inLabelForms = ' '.join(['-i '+x for x in inLabelLocs])
outLabel = join(fsDir,'tmp',side+'_'+cortex)
command = 'mri_mergelabels \
{inLabel} \
-o {outLabel} \
2>/dev/null'.format(inLabel = inLabelForms,
outLabel = outLabel)
os.popen(command).read()
def makeLabel(fsDir):
'''
Run mri_annotation2label for lh and rh hemisphere.
Creates labels in $fsDir/tmp
'''
fsDirName = basename(fsDir)
labelOutDir = join(fsDir, 'tmp')
# below must be defined here, in order for the FS to run
os.environ["FREESURFER_HOME"] = '/usr/local/freesurfer'
os.environ["SUBJECTS_DIR"] = dirname(fsDir)
for side in ['lh','rh']:
command = 'mri_annotation2label \
--subject {basename} \
--hemi {side} \
--outdir {outDir} \
--ctab {outDir}/{side}_ctab.txt \
2>/dev/null'.format(basename=fsDirName,
side=side,
outDir=labelOutDir)
#print re.sub('\s+',' ',command)
os.popen(re.sub('\s+',' ',command)).read()
def asegstats2table(fsDir):
os.environ["FREESURFER_HOME"] = '/usr/local/freesurfer'
os.environ["SUBJECTS_DIR"] = dirname(fsDir)
output_text = join(fsDir, 'tmp', 'subcortex_table.txt')
command = 'python2 /data/pnl/soft/pnlpipe3/freesurfer/bin/asegstats2table \
--subjects {dirName} \
-t {output_text}'.format(fsbin=join(os.environ['FREESURFER_HOME'], 'bin'),
dirName = basename(fsDir),