-
Notifications
You must be signed in to change notification settings - Fork 10
/
spm_batch_ds105.py
executable file
·325 lines (287 loc) · 10.9 KB
/
spm_batch_ds105.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
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
''' Single subject analysis script for SPM / Open FMRI ds105
https://openfmri.org/dataset/ds000105
Download and extract the ds105 archive to some directory.
Run this script with::
process_ds105.py ~/data/ds105
where ``~/data/ds105`` is the directory containing the ds105 data.
The example uses the very basic MATLAB / SPM interface routines in NIPY.
If you need more than very basic use, please consider using nipype. nipype has
extended capabilities to interface with external tools and for dataflow
management. nipype can handle vanilla SPM in MATLAB or SPM run through the
MATLAB common runtime (free from MATLAB Licensing).
'''
import sys
from copy import deepcopy
from os.path import join as pjoin, abspath, splitext, isfile
from glob import glob
from warnings import warn
import gzip
import numpy as np
import matlab as nimat
from spm import (spm_info, make_job, scans_for_fnames,
run_jobdef, fnames_presuffix, fname_presuffix,
fltcols)
# The batch scripts currently need SPM5
nimat.matlab_cmd = 'matlab-spm8 -nodesktop -nosplash'
# This definition is partly for slice timing. We can't do slice timing for this
# dataset because the slice dimension is the first, and SPM assumes it is the
# last.
N_SLICES = 40 # X slices
STUDY_DEF = dict(
TR = 2.5,
n_slices = N_SLICES,
time_to_space = range(1, N_SLICES, 2) + range(2, N_SLICES, 2)
)
def _sorted_prefer_nii(file_list):
""" Strip any filanames ending nii.gz if matching .nii filename in list
"""
preferred = []
for fname in file_list:
if not fname.endswith('.gz'):
preferred.append(fname)
else:
nogz, ext = splitext(fname)
if not nogz in file_list:
preferred.append(fname)
return sorted(preferred)
def get_data(data_path, subj_id):
data_path = abspath(data_path)
data_def = {}
subject_path = pjoin(data_path, 'sub%03d' % subj_id)
functionals = _sorted_prefer_nii(
glob(pjoin(subject_path, 'BOLD', 'task*', 'bold*.nii*')))
anatomicals = _sorted_prefer_nii(
glob(pjoin(subject_path, 'anatomy', 'highres001.nii*')))
for flist in (anatomicals, functionals):
for i, fname in enumerate(flist):
nogz, gz_ext = splitext(fname)
if gz_ext == '.gz':
if not isfile(nogz):
contents = gzip.open(fname, 'rb').read()
with open(nogz, 'wb') as fobj:
fobj.write(contents)
flist[i] = nogz
if len(anatomicals) == 0:
data_def['anatomical'] = None
else:
data_def['anatomical'] = anatomicals[0]
data_def['functionals'] = functionals
return data_def
def default_ta(tr, nslices):
slice_time = tr / float(nslices)
return slice_time * (nslices - 1)
class SPMSubjectAnalysis(object):
""" Class to preprocess single subject in SPM
"""
def __init__(self, data_def, study_def, ana_def):
self.data_def = deepcopy(data_def)
self.study_def = self.add_study_defaults(study_def)
self.ana_def = self.add_ana_defaults(deepcopy(ana_def))
def add_study_defaults(self, study_def):
full_study_def = deepcopy(study_def)
if 'TA' not in full_study_def:
full_study_def['TA'] = default_ta(
full_study_def['TR'], full_study_def['n_slices'])
return full_study_def
def add_ana_defaults(self, ana_def):
full_ana_def = deepcopy(ana_def)
if 'fwhm' not in full_ana_def:
full_ana_def['fwhm'] = 8.0
return full_ana_def
def slicetime(self, in_prefix='', out_prefix='a'):
sess_scans = scans_for_fnames(
fnames_presuffix(self.data_def['functionals'], in_prefix))
sdef = self.study_def
stinfo = make_job('temporal', 'st', {
'scans': sess_scans,
'so': sdef['time_to_space'],
'tr': sdef['TR'],
'ta': sdef['TA'],
'nslices': float(sdef['n_slices']),
'refslice':1,
'prefix': out_prefix,
})
run_jobdef(stinfo)
return out_prefix + in_prefix
def realign(self, in_prefix=''):
sess_scans = scans_for_fnames(
fnames_presuffix(self.data_def['functionals'], in_prefix))
rinfo = make_job('spatial', 'realign', [{
'estimate':{
'data':sess_scans,
'eoptions':{
'quality': 0.9,
'sep': 4.0,
'fwhm': 5.0,
'rtm': True,
'interp': 2.0,
'wrap': [0.0,0.0,0.0],
'weight': []
}
}
}])
run_jobdef(rinfo)
return in_prefix
def reslice(self, in_prefix='', out_prefix='r', out=('1..n', 'mean')):
which = [0, 0]
if 'mean' in out:
which[1] = 1
if '1..n' in out or 'all' in out:
which[0] = 2
elif '2..n' in out:
which[0] = 1
sess_scans = scans_for_fnames(
fnames_presuffix(self.data_def['functionals'], in_prefix))
rsinfo = make_job('spatial', 'realign', [{
'write':{
'data': np.vstack(sess_scans.flat),
'roptions':{
'which': which,
'interp':4.0,
'wrap':[0.0,0.0,0.0],
'mask':True,
'prefix': out_prefix
}
}
}])
run_jobdef(rsinfo)
return out_prefix + in_prefix
def coregister(self, in_prefix=''):
func1 = self.data_def['functionals'][0]
mean_fname = fname_presuffix(func1, 'mean' + in_prefix)
crinfo = make_job('spatial', 'coreg', [{
'estimate':{
'ref': np.asarray(mean_fname, dtype=object),
'source': np.asarray(self.data_def['anatomical'],
dtype=object),
'other': [''],
'eoptions':{
'cost_fun':'nmi',
'sep':[4.0, 2.0],
'tol':np.array(
[0.02,0.02,0.02,
0.001,0.001,0.001,
0.01,0.01,0.01,
0.001,0.001,0.001]).reshape(1,12),
'fwhm':[7.0, 7.0]
}
}
}])
run_jobdef(crinfo)
return in_prefix
def seg_norm(self, in_prefix=''):
def_tpms = np.zeros((3,1), dtype=np.object)
spm_path = spm_info.spm_path
def_tpms[0] = pjoin(spm_path, 'tpm', 'grey.nii'),
def_tpms[1] = pjoin(spm_path, 'tpm', 'white.nii'),
def_tpms[2] = pjoin(spm_path, 'tpm', 'csf.nii')
data = np.zeros((1,), dtype=object)
data[0] = self.data_def['anatomical']
sninfo = make_job('spatial', 'preproc', {
'data': data,
'output':{
'GM':fltcols([0,0,1]),
'WM':fltcols([0,0,1]),
'CSF':fltcols([0,0,0]),
'biascor':1.0,
'cleanup':False,
},
'opts':{
'tpm':def_tpms,
'ngaus':fltcols([2,2,2,4]),
'regtype':'mni',
'warpreg':1.0,
'warpco':25.0,
'biasreg':0.0001,
'biasfwhm':60.0,
'samp':3.0,
'msk':np.array([], dtype=object),
}
})
run_jobdef(sninfo)
return in_prefix
def norm_write(self, in_prefix='', out_prefix='w'):
sess_scans = scans_for_fnames(
fnames_presuffix(self.data_def['functionals'], in_prefix))
matname = fname_presuffix(self.data_def['anatomical'],
suffix='_seg_sn.mat',
use_ext=False)
subj = {
'matname': np.zeros((1,), dtype=object),
'resample': np.vstack(sess_scans.flat),
}
subj['matname'][0] = matname
roptions = {
'preserve':False,
'bb':np.array([[-78,-112, -50],[78,76,85.0]]),
'vox':fltcols([2.0,2.0,2.0]),
'interp':1.0,
'wrap':[0.0,0.0,0.0],
'prefix': out_prefix,
}
nwinfo = make_job('spatial', 'normalise', [{
'write':{
'subj': subj,
'roptions': roptions,
}
}])
run_jobdef(nwinfo)
# knock out the list of images, replacing with only one
subj['resample'] = np.zeros((1,), dtype=object)
subj['resample'][0] = self.data_def['anatomical']
roptions['interp'] = 4.0
run_jobdef(nwinfo)
return out_prefix + in_prefix
def smooth(self, in_prefix='', out_prefix='s'):
fwhm = self.ana_def['fwhm']
try:
len(fwhm)
except TypeError:
fwhm = [fwhm] * 3
fwhm = np.asarray(fwhm, dtype=np.float).reshape(1,3)
sess_scans = scans_for_fnames(
fnames_presuffix(self.data_def['functionals'], in_prefix))
sinfo = make_job('spatial', 'smooth',
{'data':np.vstack(sess_scans.flat),
'fwhm':fwhm,
'dtype':0})
run_jobdef(sinfo)
return out_prefix + in_prefix
def process_subject(ddef, study_def, ana_def):
""" Process subject from subject data dict `ddef`
"""
if not ddef['anatomical']:
warn("No anatomical, aborting processing")
return
ana = SPMSubjectAnalysis(ddef, study_def, ana_def)
# st_prefix = ana.slicetime('') # We can't run slice timing
st_prefix = ''
ana.realign(in_prefix=st_prefix)
ana.reslice(in_prefix=st_prefix, out=('mean',))
ana.coregister(in_prefix=st_prefix)
ana.seg_norm()
n_st_prefix = ana.norm_write(st_prefix)
ana.smooth(n_st_prefix)
def get_subjects(data_path, subj_ids, study_def, ana_def):
ddefs = []
for subj_id in subj_ids:
ddefs.append(get_data(data_path, subj_id))
return ddefs
def main():
try:
data_path = sys.argv[1]
except IndexError:
raise OSError('Need ds105 data path as input')
if len(sys.argv) > 2:
subj_ids = [int(id) for id in sys.argv[2:]]
else:
subj_ids = range(1, 7)
for subj_id in subj_ids:
ddef = get_data(data_path, subj_id)
assert len(ddef['functionals']) in (11, 12)
process_subject(ddef, STUDY_DEF, {})
if __name__ == '__main__':
main()