This repository has been archived by the owner on Dec 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
resting.py
193 lines (170 loc) · 7.99 KB
/
resting.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
"""
from resting import create_resting_preproc
TR = 3.0
wf = create_resting_preproc()
wf.inputs.inputspec.func = 'f3.nii'
wf.inputs.inputspec.num_noise_components = 6
wf.inputs.inputspec.highpass_sigma = 100/(2*TR)
wf.inputs.inputspec.lowpass_sigma = 12.5/(2*TR)
wf.write_graph()
wf.run() # doctest: +SKIP
"""
import nipype.interfaces.fsl as fsl # fsl
from nipype.algorithms.misc import TSNR
import nipype.interfaces.utility as util # utility
import nipype.pipeline.engine as pe # pypeline engine
def doPCA(realigned_file, noise_mask_file, num_components):
"""Derive components most reflective of physiological noise
"""
import os
from nibabel import load
import numpy as np
from scipy.signal import detrend
imgseries = load(realigned_file)
noise_mask = load(noise_mask_file)
idx = np.nonzero(noise_mask.get_data())
voxel_timecourses = detrend(imgseries.get_data()[idx[0], idx[1], idx[2], :],
axis=0, type='constant')
u,s,v = np.linalg.svd(voxel_timecourses)
components_file = os.path.join(os.getcwd(), 'noise_components.txt')
np.savetxt(components_file, v[:,:num_components])
return components_file
def pickvol(filename, which):
"""Return the middle index of a file
"""
from nibabel import load
import numpy as np
if which.lower() == 'first':
idx = 0
elif which.lower() == 'middle':
idx = int(np.ceil(load(filename).get_shape()[3]/2))
else:
raise Exception('unknown value for volume selection : %s'%which)
return idx
def create_realign_flow(name='realign'):
"""Realign a time series to the middle volume using spline interpolation
Uses MCFLIRT to realign the time series and ApplyWarp to apply the rigid
body transformations using spline interpolation (unknown order).
Example
-------
>>> from nipype.workflows.fsl import create_realign_flow
>>> import os
>>> wf = create_realign_flow()
>>> wf.inputs.inputspec.func = 'f3.nii'
>>> wf.run() # doctest: +SKIP
"""
realignflow = pe.Workflow(name=name)
inputnode = pe.Node(interface=util.IdentityInterface(fields=['func',
]),
name='inputspec')
outputnode = pe.Node(interface=util.IdentityInterface(fields=[
'realigned_file',
]),
name='outputspec')
realigner = pe.Node(fsl.MCFLIRT(save_mats=True, stats_imgs=True),
name='realigner')
splitter = pe.Node(fsl.Split(dimension='t'), name='splitter')
warper = pe.MapNode(fsl.ApplyWarp(interp='spline'),
iterfield=['in_file', 'premat'],
name='warper')
joiner = pe.Node(fsl.Merge(dimension='t'), name='joiner')
realignflow.connect(inputnode, 'func', realigner, 'in_file')
realignflow.connect(inputnode, ('func', pickvol, 'middle'),
realigner, 'ref_vol')
realignflow.connect(realigner, 'out_file', splitter, 'in_file')
realignflow.connect(realigner, 'mat_file', warper, 'premat')
realignflow.connect(realigner, 'variance_img', warper, 'ref_file')
realignflow.connect(splitter, 'out_files', warper, 'in_file')
realignflow.connect(warper, 'out_file', joiner, 'in_files')
realignflow.connect(joiner, 'merged_file', outputnode, 'realigned_file')
return realignflow
def create_resting_preproc(name='restpreproc'):
"""Create a "resting" time series preprocessing workflow
The noise removal is based on Behzadi et al. (2007)
Parameters
----------
name : name of workflow (default: restpreproc)
Inputs::
inputspec.func : functional run (filename or list of filenames)
Outputs::
outputspec.noise_mask_file : voxels used for PCA to derive noise components
outputspec.filtered_file : bandpass filtered and noise-reduced time series
Example
-------
>>> from nipype.workflows.fsl import create_resting_preproc
>>> TR = 3.0
>>> wf = create_resting_preproc()
>>> wf.inputs.inputspec.func = 'f3.nii'
>>> wf.inputs.inputspec.num_noise_components = 6
>>> wf.inputs.inputspec.highpass_sigma = 100/(2*TR)
>>> wf.inputs.inputspec.lowpass_sigma = 12.5/(2*TR)
>>> wf.write_graph()
>>> wf.run() # doctest: +SKIP
"""
restpreproc = pe.Workflow(name=name)
# Define nodes
inputnode = pe.Node(interface=util.IdentityInterface(fields=['func',
'num_noise_components',
'highpass_sigma',
'lowpass_sigma'
]),
name='inputspec')
outputnode = pe.Node(interface=util.IdentityInterface(fields=[
'noise_mask_file',
'filtered_file',
]),
name='outputspec')
slicetimer = pe.Node(fsl.SliceTimer(), name='slicetimer')
realigner = create_realign_flow()
tsnr = pe.Node(TSNR(regress_poly=2), name='tsnr')
getthresh = pe.Node(interface=fsl.ImageStats(op_string='-p 98'),
name='getthreshold')
threshold_stddev = pe.Node(fsl.Threshold(), name='threshold')
compcor = pe.Node(util.Function(input_names=['realigned_file',
'noise_mask_file',
'num_components'],
output_names=['noise_components'],
function=doPCA),
name='compcorr')
remove_noise = pe.Node(fsl.FilterRegressor(filter_all=True),
name='remove_noise')
bandpass_filter = pe.Node(fsl.TemporalFilter(),
name='bandpass_filter')
# Define connections
restpreproc.connect(inputnode, 'func', slicetimer, 'in_file')
restpreproc.connect(slicetimer, 'slice_time_corrected_file',
realigner, 'inputspec.func')
restpreproc.connect(realigner, 'outputspec.realigned_file', tsnr, 'in_file')
restpreproc.connect(tsnr, 'stddev_file', threshold_stddev, 'in_file')
restpreproc.connect(tsnr, 'stddev_file', getthresh, 'in_file')
restpreproc.connect(getthresh, 'out_stat', threshold_stddev, 'thresh')
restpreproc.connect(realigner, 'outputspec.realigned_file',
compcor, 'realigned_file')
restpreproc.connect(threshold_stddev, 'out_file',
compcor, 'noise_mask_file')
restpreproc.connect(inputnode, 'num_noise_components',
compcor, 'num_components')
restpreproc.connect(tsnr, 'detrended_file',
remove_noise, 'in_file')
restpreproc.connect(compcor, 'noise_components',
remove_noise, 'design_file')
restpreproc.connect(inputnode, 'highpass_sigma',
bandpass_filter, 'highpass_sigma')
restpreproc.connect(inputnode, 'lowpass_sigma',
bandpass_filter, 'lowpass_sigma')
restpreproc.connect(remove_noise, 'out_file', bandpass_filter, 'in_file')
restpreproc.connect(threshold_stddev, 'out_file',
outputnode, 'noise_mask_file')
restpreproc.connect(bandpass_filter, 'out_file',
outputnode, 'filtered_file')
return restpreproc
if __name__ == '__main__':
TR = 3.0
wf = create_resting_preproc()
wf.inputs.inputspec.func = 'f3.nii'
wf.inputs.inputspec.num_noise_components = 6
wf.inputs.inputspec.highpass_sigma = 100/(2*TR)
wf.inputs.inputspec.lowpass_sigma = 12.5/(2*TR)
wf.write_graph()
#wf.run() # doctest: +SKIP
#flow.run()