-
Notifications
You must be signed in to change notification settings - Fork 4
/
full_pipeline.py
410 lines (329 loc) · 16.6 KB
/
full_pipeline.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
from nipype.pipeline.engine import Node, Workflow, MapNode
import nipype.interfaces.utility as util
import nipype.interfaces.io as nio
import nipype.interfaces.fsl as fsl
import nipype.interfaces.freesurfer as fs
import nipype.interfaces.nipy as nipy
import nipype.interfaces.afni as afni
import nipype.algorithms.rapidart as ra
from nipype.algorithms.misc import TSNR
import nipype.interfaces.ants as ants
from functions import strip_rois_func, get_info, median, motion_regressors, selectindex, fix_hdr, nilearn_denoise
from linear_coreg import create_coreg_pipeline
from nonlinear_coreg import create_nonlinear_pipeline
# FREESURFER
# FSL
# AFNI
# ANTSENV
# C3D
# DCMSTACK
# NILEARN
# source /scr/animals1/nipype_env/bin/activate
'''
------
Inputs
------
'''
# read in subjects and file names
subjects=['sub001'] #, 'sub002', 'sub003', 'sub004', 'sub005', 'sub006',
# 'sub007', 'sub008', 'sub009', 'sub010', 'sub011', 'sub012',
# 'sub013', 'sub014', 'sub015', 'sub016', 'sub017', 'sub018',
# 'sub019', 'sub020', 'sub021', 'sub022']
# sessions to loop over
sessions=['session_1']# ,'session_2']
# scans to loop over
scans=['rest_full_brain_1']#, 'rest_full_brain_2']
# directories
working_dir = '/scr/animals1/preproc7t/working_dir_test/'
data_dir= '/scr/animals1/preproc7t/data7t/'
out_dir = '/scr/animals1/preproc7t/resting_test/preprocessed/'
freesurfer_dir = '/scr/animals1/preproc7t/freesurfer/'
# set fsl output type to nii.gz
fsl.FSLCommand.set_default_output_type('NIFTI_GZ')
# number of processes to run in parallel with multiproc
n_proc = 1
# number of volumes to remove from the resting state timeseries
n_vol_remove = 5
'''
------------------
Construct workflow
------------------
'''
preproc = Workflow(name='func_preproc')
preproc.base_dir = working_dir
preproc.config['execution']['crashdump_dir'] = preproc.base_dir + "/crash_files"
# iterate over subjects
subject_infosource = Node(util.IdentityInterface(fields=['subject']),
name='subject_infosource')
subject_infosource.iterables=[('subject', subjects)]
# iterate over sessions
session_infosource = Node(util.IdentityInterface(fields=['session']),
name='session_infosource')
session_infosource.iterables=[('session', sessions)]
# iterate over scans
scan_infosource = Node(util.IdentityInterface(fields=['scan']),
name='scan_infosource')
scan_infosource.iterables=[('scan', scans)]
# select files
templates={'rest' : 'niftis/{subject}/{session}/{scan}.nii.gz',
'dicom':'dicoms_example/MR.2.25.130666515827674933471189335089197862909.dcm',
'uni_highres' : 'niftis/{subject}/{session}/MP2RAGE_UNI.nii.gz', # changed to lowres
't1_highres' : 'niftis/{subject}/{session}/MP2RAGE_T1.nii.gz', # changed to lowres
'brain_mask' : 'brainmasks/{subject}/ses-1/anat/*.nii.gz',
}
selectfiles = Node(nio.SelectFiles(templates, base_directory=data_dir),
name="selectfiles")
preproc.connect([(subject_infosource, selectfiles, [('subject', 'subject')]),
(session_infosource, selectfiles, [('session', 'session')]),
(scan_infosource, selectfiles, [('scan', 'scan')]),
])
'''
------------------------
Structural Preprocessing
------------------------
'''
# fix header of supplied brain mask
fixhdr = Node(util.Function(input_names=['data_file', 'header_file'],
output_names=['out_file'],
function=fix_hdr),
name='fixhdr')
preproc.connect([(selectfiles, fixhdr, [('brain_mask', 'data_file'),
('uni_highres', 'header_file')]),
])
# mask uni image with fixed brain mask
mask_uni = Node(fsl.ApplyMask(),name='mask_uni')
preproc.connect([(fixhdr, mask_uni, [('out_file', 'mask_file')]),
(selectfiles, mask_uni,[('uni_highres', 'in_file')])
])
# run reconall
#recon_all = Node(fs.ReconAll(args='-nuiterations 7 -no-isrunning'),
# name="recon_all")
#recon_all.plugin_args={'submit_specs': 'request_memory = 9000'}
#recon_all.inputs.subjects_dir=freesurfer_dir
# function to replace / in subject id string with a _
def sub_id(sub_id):
return sub_id.replace('/','_')
#preproc.connect([(mask_uni, recon_all, [('out_file', 'T1_files')]),
# (subject_infosource, recon_all, [(('subject', sub_id), 'subject_id')])
# ])
# Grab brain and T1 file and segmentation from Freesurfer
# to store denoised T1, create more precise brainmask and wmcsfmask
fs_import = Node(interface=nio.FreeSurferSource(),
name = 'fs_import')
preproc.connect([#(recon_all, fs_import, [('subject_id', 'subject_id'),
# ('subjects_dir', 'subjects_dir')])
(subject_infosource, fs_import, [(('subject', sub_id), 'subject_id')])
])
fs_import.inputs.subjects_dir=freesurfer_dir
# convert Freesurfer T1 file to nifti
head_convert=Node(fs.MRIConvert(out_type='niigz',
out_file='uni_lowres.nii.gz'),
name='head_convert')
preproc.connect([(fs_import, head_convert, [('T1', 'in_file')])])
def get_aparc_aseg(files):
for name in files:
if 'aparc+aseg' in name:
return name
# create brainmask from aparc+aseg with single dilation
brainmask = Node(fs.Binarize(min=0.5,
dilate=1,
out_type='nii.gz'),
name='brainmask')
preproc.connect([(fs_import, brainmask, [(('aparc_aseg', get_aparc_aseg), 'in_file')])])
# fill holes in mask
fillholes = Node(fsl.maths.MathsCommand(args='-fillh -s 3 -thr 0.1 -bin',
out_file='uni_lowres_brain_mask.nii.gz'),
name='fillholes')
preproc.connect([(brainmask, fillholes, [('binary_file', 'in_file')])])
# create wmcsf mask
wm_csf_mask = Node(fs.Binarize(wm_ven_csf = True,
erode = 2,
out_type = 'nii.gz',
binary_file='wmcsf_mask.nii.gz'),
name='wm_csf_mask')
preproc.connect([(fs_import, wm_csf_mask, [(('aparc_aseg', get_aparc_aseg), 'in_file')])
])
'''
------------------------
Functional Preprocessing
------------------------
'''
# remove first volumes
remove_vol = Node(util.Function(input_names=['in_file','t_min'],
output_names=["out_file"],
function=strip_rois_func),
name='remove_vol')
remove_vol.inputs.t_min = n_vol_remove
preproc.connect([(selectfiles, remove_vol, [('rest', 'in_file')])])
# get slice time information from example dicom
getinfo = Node(util.Function(input_names=['dicom_file'],
output_names=['TR', 'slice_times', 'slice_thickness'],
function=get_info),
name='getinfo')
preproc.connect([(selectfiles, getinfo, [('dicom', 'dicom_file')])])
# simultaneous slice time and motion correction
slicemoco = Node(nipy.SpaceTimeRealigner(),
name="spacetime_realign")
slicemoco.inputs.slice_info = 2
preproc.connect([(getinfo, slicemoco, [('slice_times', 'slice_times'),
('TR', 'tr')]),
(remove_vol, slicemoco, [('out_file', 'in_file')])])
# compute tsnr and detrend
tsnr = Node(TSNR(regress_poly=2),
name='tsnr')
preproc.connect([(slicemoco, tsnr, [('out_file', 'in_file')])])
# compute median of realigned timeseries for coregistration to anatomy
median = Node(util.Function(input_names=['in_files'],
output_names=['median_file'],
function=median),
name='median')
preproc.connect([(tsnr, median, [('detrended_file', 'in_files')])])
# make FOV mask for later nonlinear coregistration
fov = Node(fsl.maths.MathsCommand(args='-bin',
out_file='fov_mask.nii.gz'),
name='fov_mask')
preproc.connect([(median, fov, [('median_file', 'in_file')])])
# biasfield correction of median epi for better registration
biasfield = Node(ants.segmentation.N4BiasFieldCorrection(save_bias=True),
name='biasfield')
preproc.connect([(median, biasfield, [('median_file', 'input_image')])])
# perform linear coregistration in ONE step: median2lowres
coreg=create_coreg_pipeline()
coreg.inputs.inputnode.fs_subjects_dir = freesurfer_dir
preproc.connect([(selectfiles, coreg, [('uni_highres', 'inputnode.uni_highres')]),
(head_convert, coreg, [('out_file', 'inputnode.uni_lowres')]),
(biasfield, coreg, [('output_image', 'inputnode.epi_median')]),
(subject_infosource, coreg, [('subject', 'inputnode.fs_subject_id')])
])
# perform nonlinear coregistration
nonreg=create_nonlinear_pipeline()
preproc.connect([(selectfiles, nonreg, [('t1_highres', 'inputnode.t1_highres')]),
(fillholes, nonreg, [('out_file', 'inputnode.brain_mask')]),
(wm_csf_mask, nonreg, [('binary_file', 'inputnode.wmcsf_mask')]),
(fov, nonreg, [('out_file', 'inputnode.fov_mask')]),
(coreg, nonreg, [('outputnode.epi2highres_lin', 'inputnode.epi2highres_lin'),
('outputnode.epi2highres_lin_itk', 'inputnode.epi2highres_lin_itk'),
('outputnode.highres2lowres_itk', 'inputnode.highres2lowres_itk')])
])
# merge struct2func transforms into list
translist_inv = Node(util.Merge(2),name='translist_inv')
preproc.connect([(coreg, translist_inv, [('outputnode.epi2highres_lin_itk', 'in1')]),
(nonreg, translist_inv, [('outputnode.epi2highres_invwarp', 'in2')])])
# merge images into list
structlist = Node(util.Merge(2),name='structlist')
preproc.connect([(nonreg, structlist, [('outputnode.brainmask_highres', 'in1'),
('outputnode.wmcsfmask_highres', 'in2')]),
])
# project brain mask and wm/csf masks in functional space
struct2func = MapNode(ants.ApplyTransforms(dimension=3,
invert_transform_flags=[True, False],
interpolation = 'NearestNeighbor'),
iterfield=['input_image'],
name='struct2func')
preproc.connect([(structlist, struct2func, [('out', 'input_image')]),
(translist_inv, struct2func, [('out', 'transforms')]),
(median, struct2func, [('median_file', 'reference_image')]),
])
# perform artefact detection
artefact=Node(ra.ArtifactDetect(save_plot=True,
use_norm=True,
parameter_source='NiPy',
mask_type='file',
norm_threshold=1,
zintensity_threshold=3,
use_differences=[True,False]
),
name='artefact')
preproc.connect([(slicemoco, artefact, [('out_file', 'realigned_files'),
('par_file', 'realignment_parameters')]),
(struct2func, artefact, [(('output_image', selectindex, [0]), 'mask_file')]),
])
# calculate motion regressors
motreg = Node(util.Function(input_names=['motion_params', 'order','derivatives'],
output_names=['out_files'],
function=motion_regressors),
name='motion_regressors')
motreg.inputs.order=1
motreg.inputs.derivatives=1
preproc.connect([(slicemoco, motreg, [('par_file','motion_params')])])
# use Nilearn to calculate physiological nuissance regressors and clean
# time series using combined regressors
denoise = Node(util.Function(input_names=['in_file',
'brain_mask', 'wm_csf_mask',
'motreg_file',
'outlier_file',
'bandpass',
'tr'],
output_names=['denoised_file',
'confounds_file'],
function=nilearn_denoise),
name='denoise')
denoise.inputs.tr = 3.0
denoise.inputs.bandpass = [0.1, 0.01]
preproc.connect([(slicemoco, denoise, [('out_file', 'in_file')]),
(struct2func, denoise, [(('output_image', selectindex, [0]), 'brain_mask'),
(('output_image', selectindex, [1]), 'wm_csf_mask')]),
(motreg, denoise, [(('out_files',selectindex,[0]), 'motreg_file')]),
(artefact, denoise, [('outlier_files', 'outlier_file')])
])
'''
-------
Outputs
-------
'''
def make_basedir(out_dir, subject, session, scan):
return out_dir+subject+'/'+session+'/'+scan+'/'
makebase = Node(util.Function(input_names=['out_dir','subject',
'session', 'scan'],
output_names=['base_dir'],
function=make_basedir),
name='makebase')
makebase.inputs.out_dir = out_dir
preproc.connect([(subject_infosource, makebase, [('subject', 'subject')]),
(session_infosource, makebase, [('session', 'session')]),
(scan_infosource, makebase, [('scan', 'scan')])
])
sink = Node(nio.DataSink(parameterization=False),
name='sink')
sink.inputs.substitutions = [('transform0Warp', 'epi2highres_warp'),
('transform0InverseWarp', 'epi2highres_invwarp'),
('transform_Warped', 'epi2highres_nonlin')]
preproc.connect([(makebase, sink, [('base_dir', 'base_directory')]),
(head_convert, sink, [('out_file', 'registration.@anat_head')]),
(fillholes, sink, [('out_file', 'registration.@brain_mask')]),
(slicemoco, sink, [('out_file', 'realignment.@realigned_file'),
('par_file', 'confounds.@orig_motion')]),
(tsnr, sink, [('tsnr_file', 'realignment.@tsnr')]),
(median, sink, [('median_file', 'realignment.@median')]),
(biasfield, sink, [('output_image', 'realignment.@biasfield')]),
(coreg, sink, [('outputnode.epi2lowres', 'registration.@epi2lowres'),
('outputnode.epi2lowres_mat','registration.@epi2lowres_mat'),
('outputnode.epi2lowres_dat','registration.@epi2lowres_dat'),
('outputnode.highres2lowres', 'registration.@highres2lowres'),
('outputnode.highres2lowres_dat', 'registration.@highres2lowres_dat'),
('outputnode.highres2lowres_mat', 'registration.@highres2lowres_mat'),
('outputnode.epi2highres_lin', 'registration.@epi2highres_lin'),
('outputnode.epi2highres_lin_itk', 'registration.@epi2highres_lin_itk'),
('outputnode.epi2highres_lin_mat', 'registration.@epi2highres_lin_mat')]),
(nonreg, sink, [('outputnode.epi2highres_warp', 'registration.@epi2highres_warp'),
('outputnode.epi2highres_invwarp', 'registration.@epi2highres_invwarp'),
('outputnode.epi2highres_nonlin', 'registration.@epi2highres_nonlin'),
('outputnode.brainmask_highres', 'registration.@highres_brainmask')]),
(struct2func, sink, [(('output_image', selectindex, [0,1]), 'mask.@masks')]),
(artefact, sink, [('norm_files', 'confounds.@norm_motion'),
('outlier_files', 'confounds.@outlier_files'),
('intensity_files', 'confounds.@intensity_files'),
('statistic_files', 'confounds.@outlier_stats'),
('plot_files', 'confounds.@outlier_plots')]),
(motreg, sink, [('out_files', 'confounds.@motreg')]),
(denoise, sink, [('denoised_file', 'final.@final'),
('confounds_file', 'confounds.@all')])
])
'''
------------
Run workflow
------------
'''
#preproc.run()
#plugin='MultiProc', plugin_args={'n_procs' : n_proc})
preproc.run(plugin='CondorDAGMan', plugin_args = {'override_specs': 'request_memory = 20000'})