-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstats.py
141 lines (112 loc) · 5.53 KB
/
stats.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
import nibabel as nb
def group_giftis(fileList,inputCol=[],outColNames=[],\
outFileNames=[],outFileNamePattern='{}.func.gii',\
groupSummary=[],groupStats=True,replaceNaNs=True):
"""
Created on Mon Mar 25 08:36:34 2019
Takes N func.gii files with P columns each (i.e., from each subject)
and creates P group func.gii files, with N columns (i.e., for each condition).
Also saves group summary file (mean across columns), if desired.
INPUTS:
fileList: Text file with full paths to func.gii files
VARARGIN_OPTIONS:
inputCol: Only use the column(s) specified by [colidx] from the input files
DEFAULT: use all columns from input files
outFileNames: Name the outputfiles ['f1','f2']
DEFAULT: use outFileNamePattern to generate them
outColNames: Name the columns in output files
DEFAULT: names of input files
outFileNamePattern: Specify pattern for naming of group files
DEFAULT: '{}.func.gii'
groupSummary: Name of the group summary file
DEFAULT: empty (do not create group summary file)
groupStats: Run group summary file using nanmean
DEFAULT: True (False will use mean)
replaceNaNs: NaNs will be replaced with 0
DEFAULT: True (varagin deprecated)
@author: joern.diedrichsen@googlemail.com (Python conversion: switt)
"""
# replaceNaNs = 0
funcGiftis = list()
numRows = []
numCols = []
with open(fileList, 'r') as f:
giftiFileList = f.read()
giftiFileList = giftiFileList.split()
for i in range(len(giftiFileList)):
fileName = (giftiFileList[i]).strip()
if os.path.isfile(fileName)==False:
print("Warning: File {} does not exist; replacing with NaNs".\
format(fileName))
numCols.append(np.nan)
numRows.array(np.nan)
else:
funcGiftisTemp = nb.load(fileName)
funcGiftis.append(funcGiftisTemp)
numRows.append(funcGiftis[i].darrays[0].data.shape[0])
numCols.append(len(funcGiftis[i].darrays))
numRows = np.array(numRows)
numCols = np.array(numCols)
# Check if input func.gii files are same format
if np.var(numCols[~np.isnan(numCols)]) != 0:
sys.exit("Error: Number of columns is not the same.")
if np.var(numRows[~np.isnan(numRows)]) != 0:
sys.exit("Error: Number of vertices is not the same.")
# Determine the number of columns
if len(inputCol) == 0:
inputCol = [i for i in range(min(numCols))]
numrows = np.nanmean(numRows)
# Get the input column names
inputColumnNames = getGiftiColumnNames.getGiftiColumnNames(funcGiftis[0])
# Get main anatomical structure
anatStruct = getGiftiAnatomicalStruct.getGiftiAnatomicalStruct(funcGiftis[0])
# Determine output column names
if len(outColNames) == 0:
for col in range(len(giftiFileList)):
giftiFileNameExt = os.path.split(giftiFileList[col])[1]
giftiFileName = os.path.splitext(giftiFileNameExt)[0]
outColNames.append(str.format("{}".format(giftiFileName)))
# for i in range(len(inputCol)):
# outColNames.append(str.format("col{:02d}".format(i+1)))
# Reorder into new metric files
for file in range(len(inputCol)):
OutData = np.empty([int(numrows),int(len(funcGiftis))])*np.nan
SumData = np.empty([int(numrows),int(len(inputCol))])*np.nan
for col in range(len(funcGiftis)):
if len(funcGiftis[col].darrays[file].data) != 0:
OutData[:,col] = funcGiftis[col].darrays[inputCol[file]].data
if (len(outFileNames) == 0 or len(outFileNames)<file):
outFileNames.append(str.format("{}.func.gii".\
format(inputColumnNames[inputCol[file]])))
funcGiftiOut = makeFuncGifti.makeFuncGifti(OutData,\
columnNames=outColNames,\
anatomicalStruct=anatStruct)
nb.save(funcGiftiOut,outFileNames[file])
if groupStats == True:
SumData[:,file] = np.nanmean(OutData,axis=1)
elif groupStats == False:
SumData[:,file] = np.mean(OutData,axis=1)
# If Summary file name is given
if len(groupSummary) != 0:
groupSummaryGifti = makeFuncGifti.makeFuncGifti(SumData,columNames=outColNames,\
anatomicalStruct=anatStruct)
nb.save(groupSummaryGifti,groupSummary)
def smooth_surface(fileList,surfaceFile=[],kernelSigma=2.0,filePrefix='smooth'):
if not fileList:
sys.exit('Error: No fileList of .func.gii files provided.')
if not surfaceFile:
sys.exit('Error: No surfaceFile provided.')
with open(fileList, 'r') as f:
funcFileList = f.read()
funcFileList = funcFileList.split()
numFiles = len(funcFileList)
smoothedFileList = list()
for i in range(numFiles):
funcFilePath = os.path.split(funcFileList[i])
smoothedFileList.append(os.path.join(funcFilePath[0],'_'.join((filePrefix,funcFilePath[1]))))
subprocess.run(["wb_command","-metric-smoothing",surfaceFile,funcFileList[i],kernelSigma,smoothedFileList[i]])