run_template_construction.py 102 KB
Newer Older
Christoph Arthofer's avatar
Christoph Arthofer committed
1
#!/usr/bin/env python
2
#
Christoph Arthofer's avatar
Christoph Arthofer committed
3
# run_template_construction.py - Constructs multimodal templates
4
5
6
7
8
9
10
#
# Author: Christoph Arthofer <c.arthofer@gmail.com>
# Copyright: FMRIB 2021
#
"""! This script allows the construction of an unbiased, multimodal template from T1, T1+T2 or T1+T2+DTI modalities.
"""

Christoph Arthofer's avatar
Christoph Arthofer committed
11
12
13
14
15
import os
import shutil
import pandas as pd
import nibabel as nib
import numpy as np
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
16
import sys
Christoph Arthofer's avatar
Christoph Arthofer committed
17
18
from fsl.wrappers import fslmaths,flirt,applyxfm,concatxfm,bet,fast,fslstats
from fsl.wrappers.fnirt import invwarp, applywarp, convertwarp
19
from file_tree import FileTree
Christoph Arthofer's avatar
Christoph Arthofer committed
20
21
22
23
from fsl.utils.fslsub import func_to_cmd
from operator import itemgetter
import tempfile
import argparse
24
25
import fsl_sub
import logging
Christoph Arthofer's avatar
Christoph Arthofer committed
26

Christoph Arthofer's avatar
Christoph Arthofer committed
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
def writeConfig(step,mod,fpath):
    """! Writes the nonlinear registration parameters for a given resolution level and modalities to a file readable by MMORF.

    @param step:          Resolution level provided as integer
    @param mod:           Modalities provided as a dictionary
    @param fpath:         Output filepath

    """

    T1_head = True if mod['T1_head_key'] is not None else False
    T2_head = True if mod['T2_head_key'] is not None else False
    DTI = True if mod['DTI_tensor_key'] is not None else False

# This will be defined in a separate file in the future and,
# I know, this could be implemented more efficiently but for the sake of easy readability:
    if step == 1:
        s = 'warp_res_init           = 32 \n' \
            'warp_scaling            = 1 1 \n' \
            'lambda_reg              = 4.0e5 3.7e-1 \n' \
            'hires                   = 3.9 \n' \
            'optimiser_max_it_lowres = 5 \n' \
            'optimiser_max_it_hires  = 5 \n'
        if T1_head:
            s += '\n' \
            '; Whole-head T1 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
54
            'use_mask_mov_scalar     = 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
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
            'fwhm_ref_scalar         = 8.0 8.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 \n' \
            'lambda_scalar           = 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 \n'
        if T2_head:
            s += '\n' \
            '; Whole-head T2 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 0 0 \n' \
            'use_mask_mov_scalar     = 0 0 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 \n' \
            'lambda_scalar           = 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 \n'
        if DTI:
            s += '\n' \
            '; DTI \n' \
            'use_mask_ref_tensor     = 0 0 \n' \
            'use_mask_mov_tensor     = 0 0 \n' \
            'fwhm_ref_tensor         = 8.0 8.0 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 \n' \
            'lambda_tensor           = 1 1 \n'

    elif step == 2:
        s = 'warp_res_init           = 32 \n' \
            'warp_scaling            = 1 1 2 \n' \
            'lambda_reg              = 4.0e5 3.7e-1 3.1e-1 \n' \
            'hires                   = 3.9 \n' \
            'optimiser_max_it_lowres = 5 \n' \
            'optimiser_max_it_hires  = 5 \n'
        if T1_head:
            s += '\n' \
            '; Whole-head T1 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
94
            'use_mask_mov_scalar     = 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
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
            'fwhm_ref_scalar         = 8.0 8.0 4.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 \n' \
            'lambda_scalar           = 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 \n'
        if T2_head:
            s += '\n' \
            '; Whole-head T2 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 0 0 0 \n' \
            'use_mask_mov_scalar     = 0 0 0 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 4.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 \n' \
            'lambda_scalar           = 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 \n'
        if DTI:
            s += '\n' \
            '; DTI \n' \
            'use_mask_ref_tensor     = 0 0 0 \n' \
            'use_mask_mov_tensor     = 0 0 0 \n' \
            'fwhm_ref_tensor         = 8.0 8.0 4.0 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 4.0 \n' \
            'lambda_tensor           = 1 1 1 \n'

    elif step == 3:
        s = 'warp_res_init           = 32 \n' \
            'warp_scaling            = 1 1 2 2 \n' \
            'lambda_reg              = 4.0e5 3.7e-1 3.1e-1 2.6e-1 \n' \
            'hires                   = 3.9 \n' \
            'optimiser_max_it_lowres = 5 \n' \
            'optimiser_max_it_hires  = 5 \n'
        if T1_head:
            s += '\n' \
            '; Whole-head T1 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
134
            'use_mask_mov_scalar     = 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
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
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 \n' \
            'lambda_scalar           = 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 \n'
        if T2_head:
            s += '\n' \
            '; Whole-head T2 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 0 0 0 0 \n' \
            'use_mask_mov_scalar     = 0 0 0 0 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 \n' \
            'lambda_scalar           = 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 \n'
        if DTI:
            s += '\n' \
            '; DTI \n' \
            'use_mask_ref_tensor     = 0 0 0 0 \n' \
            'use_mask_mov_tensor     = 0 0 0 0 \n' \
            'fwhm_ref_tensor         = 8.0 8.0 4.0 2.0 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 4.0 2.0 \n' \
            'lambda_tensor           = 1 1 1 1 \n'

    elif step == 4:
        s = 'warp_res_init           = 32 \n' \
            'warp_scaling            = 1 1 2 2 2 \n' \
            'lambda_reg              = 4.0e5 3.7e-1 3.1e-1 2.6e-1 2.2e-1 \n' \
            'hires                   = 3.9 \n' \
            'optimiser_max_it_lowres = 5 \n' \
            'optimiser_max_it_hires  = 5 \n'
        if T1_head:
            s += '\n' \
            '; Whole-head T1 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
174
            'use_mask_mov_scalar     = 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
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
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 \n' \
            'lambda_scalar           = 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 \n'
        if T2_head:
            s += '\n' \
            '; Whole-head T2 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 0 0 0 0 0 \n' \
            'use_mask_mov_scalar     = 0 0 0 0 0 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 \n' \
            'lambda_scalar           = 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 \n'
        if DTI:
            s += '\n'\
            '; DTI \n' \
            'use_mask_ref_tensor     = 0 0 0 0 0 \n' \
            'use_mask_mov_tensor     = 0 0 0 0 0 \n' \
            'fwhm_ref_tensor         = 8.0 8.0 4.0 2.0 1.0 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 4.0 2.0 1.0 \n' \
            'lambda_tensor           = 1 1 1 1 1 \n'

    elif step == 5:
        s = 'warp_res_init           = 32 \n' \
            'warp_scaling            = 1 1 2 2 2 2 \n' \
            'lambda_reg              = 4.0e5 3.7e-1 3.1e-1 2.6e-1 2.2e-1 1.8e-1 \n' \
            'hires                   = 3.9 \n' \
            'optimiser_max_it_lowres = 5 \n' \
            'optimiser_max_it_hires  = 5 \n'
        if T1_head:
            s += '\n' \
            '; Whole-head T1 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 1 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
214
            'use_mask_mov_scalar     = 1 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
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
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 \n' \
            'lambda_scalar           = 1 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 1e9 \n'
        if T2_head:
            s += '\n' \
            '; Whole-head T2 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 0 0 0 0 0 0 \n' \
            'use_mask_mov_scalar     = 0 0 0 0 0 0 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 \n' \
            'lambda_scalar           = 1 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 1e9 \n'
        if DTI:
            s += '\n' \
            '; DTI \n' \
            'use_mask_ref_tensor     = 0 0 0 0 0 0 \n' \
            'use_mask_mov_tensor     = 0 0 0 0 0 0 \n' \
            'fwhm_ref_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 \n' \
            'lambda_tensor           = 1 1 1 1 1 1 \n'

    elif step == 6:
        s = 'warp_res_init           = 32 \n' \
            'warp_scaling            = 1 1 2 2 2 2 2 \n' \
            'lambda_reg              = 4.0e5 3.7e-1 3.1e-1 2.6e-1 2.2e-1 1.8e-1 1.5e-1 \n' \
            'hires                   = 3.9 \n' \
            'optimiser_max_it_lowres = 5 \n' \
            'optimiser_max_it_hires  = 5 \n'
        if T1_head:
            s += '\n' \
            '; Whole-head T1 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 1 1 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
254
            'use_mask_mov_scalar     = 1 1 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
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
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'lambda_scalar           = 1 1 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 1e9 1e9 \n'
        if T2_head:
            s += '\n' \
            '; Whole-head T2 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 0 0 0 0 0 0 0 \n' \
            'use_mask_mov_scalar     = 0 0 0 0 0 0 0 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'lambda_scalar           = 1 1 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 1e9 1e9 \n'
        if DTI:
            s += '\n' \
            '; DTI \n' \
            'use_mask_ref_tensor     = 0 0 0 0 0 0 0 \n' \
            'use_mask_mov_tensor     = 0 0 0 0 0 0 0 \n' \
            'fwhm_ref_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'lambda_tensor           = 1 1 1 1 1 1 1 \n'

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
    elif step == 7:
        s = 'warp_res_init           = 32 \n' \
            'warp_scaling            = 1 1 2 2 2 2 2 \n' \
            'lambda_reg              = 4.0e5 3.7e-1 3.1e-1 2.6e-1 2.2e-1 1.8e-1 1.5e-1 \n' \
            'hires                   = 3.9 \n' \
            'optimiser_max_it_lowres = 5 \n' \
            'optimiser_max_it_hires  = 5 \n'
        if T1_head:
            s += '\n' \
            '; Whole-head T1 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 1 1 1 1 1 1 1 \n' \
            'use_mask_mov_scalar     = 1 1 1 1 1 1 1 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'lambda_scalar           = 1 1 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 1e9 1e9 \n'
        if T2_head:
            s += '\n' \
            '; Whole-head T2 \n' \
            'use_implicit_mask       = 0 \n' \
            'use_mask_ref_scalar     = 0 0 0 0 0 0 0 \n' \
            'use_mask_mov_scalar     = 0 0 0 0 0 0 0 \n' \
            'fwhm_ref_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'fwhm_mov_scalar         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'lambda_scalar           = 1 1 1 1 1 1 1 \n' \
            'estimate_bias           = 1 \n' \
            'bias_res_init           = 32 \n' \
            'lambda_bias_reg         = 1e9 1e9 1e9 1e9 1e9 1e9 1e9 \n'
        if DTI:
            s += '\n' \
            '; DTI \n' \
            'use_mask_ref_tensor     = 0 0 0 0 0 0 0 \n' \
            'use_mask_mov_tensor     = 0 0 0 0 0 0 0 \n' \
            'fwhm_ref_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'lambda_tensor           = 1 1 1 1 1 1 1 \n'

Christoph Arthofer's avatar
Christoph Arthofer committed
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
    f = open(fpath, 'w+')
    f.write(s)
    f.close()


def correctBiasMidtransWrapper(aff_matrix_paths, temp_dir, ref_path, unbiasing_invmtx_path, unbiased_matrix_paths):
    """! Writes the nonlinear registration parameters for a given resolution level and modalities to a file readable by MMORF.

    @param aff_matrix_paths:              List of filepaths to affine transformations
    @param temp_dir:                      Output directory
    @param ref_path:                      Path to reference template
    @param unbiasing_invmtx_path:         Path to unbiasing matrix
    @param unbiased_matrix_paths:         List of filepaths to unbiased transformations

    """
    separate_path = os.path.join(temp_dir, 'T1_to_unbiased')
    command = 'midtrans -v --separate=' + separate_path + ' --template=' + ref_path + ' -o ' + unbiasing_invmtx_path + ' '
    count = 0
    for omat_path in aff_matrix_paths:
        if os.path.exists(omat_path):
            count += 1
            print(count, ' ', omat_path)
            command += omat_path + ' '

    stream = os.popen(command)
    output = stream.read()
    print(output)

    # Renaming matrices
    for i, sub_unbiasing_mat in enumerate(unbiased_matrix_paths):
        sub_unbiasing_mat_temp = os.path.join(temp_dir, 'T1_to_unbiased%04d.mat' % (i + 1))

        os.rename(sub_unbiasing_mat_temp, sub_unbiasing_mat)
        print(i, ' ', sub_unbiasing_mat_temp, ' renamed to ', sub_unbiasing_mat)

    print('T1 unbiasing matrices constructed!')


def soft_clamp(x, k):
    """! Piecewise function for soft intensity clamping of T1 images. Takes a single parameter k which defines the transition to the clamping part of the function.

    f(x) = 0                                  | x <= 0
    f(x) = x                                  | 0 < x <= k
    f(x) = 3k/4 + k/(2(1 + exp(-8(x - k)/k))) | x > k

    @param x:              Image as numpy array
    @param k:              Defines the transition to the clamping part of the function

    Date: 08/02/2021
    Author: Frederik J Lange
    Copyright: FMRIB 2021

    """

    return np.piecewise(x,
                        [x <= 0, (0 < x) & (x <= k), x > k],
                        [lambda x: 0, lambda x: x, lambda x: k / (2 * (1 + np.exp(-8 * (x - k) / k))) + 0.75 * k])


def clampImage(img_path, out_path):
    """! Performs preprocessing steps and clamping on an image.

    @param img_path:              Path to input image
    @param out_path:              Path to clamped output image

    """

    out_dir = os.path.split(out_path)[0]
390
    mask_name = os.path.splitext(os.path.splitext(os.path.basename(out_path))[0])[0] + '_brain.nii.gz'
Christoph Arthofer's avatar
Christoph Arthofer committed
391
    with tempfile.TemporaryDirectory(dir=out_dir) as tmpdirname:
392
393
        mask_path = os.path.join(tmpdirname, mask_name)
        bet(img_path, mask_path, robust=True)
Christoph Arthofer's avatar
Christoph Arthofer committed
394
395
396
397
398
399
400
401
402
        fast(mask_path, tmpdirname + '/fast', iter=0, N=True, g=True, v=False)
        wm_intensity_mean = fslstats(mask_path).k(tmpdirname + '/fast_seg_2').M.run()
        print('White matter mean intensity is: ', wm_intensity_mean)

    img_nib = nib.load(img_path)
    img_clamped_np = soft_clamp(img_nib.get_fdata(), wm_intensity_mean)
    img_clamped_nib = nib.Nifti1Image(img_clamped_np, affine=img_nib.affine, header=img_nib.header)
    img_clamped_nib.to_filename(out_path)

403
404
405
def maskPreprocessing(tree):
    fslmaths(tree.get('data/T1_brain_mask')).thr(0.1).bin().mul(7).add(1).inm(1).run(tree.get('T1_weighted_brain_mask'))
    fslmaths(tree.get('data/lesion_mask_in_T1')).binv().mul(tree.get('T1_weighted_brain_mask')).run(tree.get('inverse_lesion_and_brain_mask_in_T1'))
Christoph Arthofer's avatar
Christoph Arthofer committed
406

407
def averageImages(img_paths, out_path, mod='mean', norm_bool=False):
Christoph Arthofer's avatar
Christoph Arthofer committed
408
409
410
    """! Creates an average image from individual (non)normalised images.

    @param img_paths:             List of filepaths
411
    @param out_path:              Path to average/median output image
412
    @param mod:                   Choose between 'mean' or 'median' image.
Christoph Arthofer's avatar
Christoph Arthofer committed
413
414
415
416
417
    @param norm_bool:             Normalise intensities of each image before averaging true or false

    """

    n_imgs = len(img_paths)
418
    n_exist = 0
419
    if mod == 'mean':
420
421
422
423
424
425
426
427
428
429
430
        for i, img_path in enumerate(img_paths):
            if os.path.exists(img_path):
                n_exist += 1
                print(i, ' ', img_path)
                img_nib = nib.load(img_path)
                if norm_bool:
                    img_nib = fslmaths(img_nib).inm(1000).run()
                if i == 0:
                    sum_img = img_nib
                else:
                    sum_img = fslmaths(sum_img).add(img_nib).run()
Christoph Arthofer's avatar
Christoph Arthofer committed
431
            else:
432
433
434
                print(i, ' ', img_path, ' does not exist!')

        if n_exist > 0:
435
            fslmaths(sum_img).div(n_exist).run(out_path)
436
437
438
439
440
441
442
443
444
445
446
    elif mod == 'median':
        images = []
        for i, img_path in enumerate(img_paths):
            if os.path.exists(img_path):
                n_exist += 1
                print(i, ' ', img_path)
                img_nib = nib.load(img_path)
                if norm_bool:
                    img_nib = fslmaths(img_nib).inm(1000).run()
                images.append(img_nib.get_fdata())
        if n_exist > 0:
447
448
            median_img = np.median(np.array(images),axis=0)
            median_nib = nib.Nifti1Image(np.squeeze(median_img), affine=img_nib.affine, header=img_nib.header)
449
            median_nib.to_filename(out_path)
Christoph Arthofer's avatar
Christoph Arthofer committed
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

    assert n_exist == n_imgs, "Not all images available!"


def applyWarpWrapper(img_path, ref_path, warped_path, warp_path, interp='spline', norm_bool=False):
    """! Wrapper for FSL applywarp - applies a warp (deformation field) to an image.

    @param img_path:              Path to input image
    @param ref_path:              Path to reference image
    @param warped_path:           Path to warped output image
    @param warp_path:             Path to warp (deformation field)
    @param interp:                Interpolation method (same options as FSL applywarp)
    @param norm_bool:             Normalise intensities of each image before averaging true or false

    """

    print(img_path, warp_path)
    if os.path.exists(img_path):
        img_nib = nib.load(img_path)
        if norm_bool:
            img_nib = fslmaths(img_nib).inm(1000).run()
        print('applywarp(src=img_nib,ref=ref_path,out=warped_path,warp=warp_path,interp=interp)')
        applywarp(src=img_nib, ref=ref_path, out=warped_path, warp=warp_path, interp=interp)


Christoph Arthofer's avatar
Christoph Arthofer committed
475
# https://git.fmrib.ox.ac.uk/fsl/fsl_sub
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
def submitJob(command, name, log_dir, queue, wait_for=None, array_task=False, coprocessor=None, coprocessor_class=None, coprocessor_multi="1", threads=1, export_var=None, jobram=None, jobtime=None):
    coprocessor_class_strict = True if coprocessor_class is not None else False

    hold_ids = []
    if wait_for is not None:
        for job_id in wait_for:
            if len(job_id) > 0:
                hold_ids.append(job_id)

    job_id = fsl_sub.submit(command=command,
                   array_task=array_task,
                   jobhold=hold_ids,
                   name=name,
                   logdir=log_dir,
                   queue=queue,
                   coprocessor=coprocessor,
                   coprocessor_class=coprocessor_class,
                   coprocessor_class_strict=coprocessor_class_strict,
                   coprocessor_multi=coprocessor_multi,
                   threads=threads,
                   export_vars=export_var,
                   jobram=jobram,
                   jobtime=jobtime
                   )

    return str(job_id)



# def submitJob(name, log_dir, queue, wait_for=[], script=None, command=None, coprocessor_class=None,
#                   coprocessor=None, export_var=None, debug=False):
#     """! Wrapper for fslsub - submits a job to the cluster. This function can be easily extended to work with other workload managers.
#
#     @param name:                  Job name
#     @param log_dir:               Directory where output log-files will be saved
#     @param queue:                 Name of queue to submit the job to
#     @param wait_for:              List of IDs of jobs required to finish before running this job.
#     @param script:                Path to a shell script, which contains one command per line - commands will be submitted as an array job
#     @param command:               Alternatively a single command can be provided as a string - command will be submitted as single job
#     @param coprocessor_class:     Coprocessor class
#     @param export_var:            Environment variables to be exported to the submission node
#     @param debug:                 If True, information about job will be written to output
#
#     @return  The job ID.
#     """
#     cmd = 'fsl_sub'
#
#     if wait_for:
#         job_ids_bool = [job != '' for job in wait_for]
#         if any(job_ids_bool):
#             cmd += ' -j '
#             wait_for_arr = np.array(wait_for)
#             wait_for_arr = wait_for_arr[job_ids_bool]
#             for j, job in enumerate(wait_for_arr):
#                 cmd += job.replace("\n", "")
#                 if j < len(wait_for_arr) - 1:
#                     cmd += ','
#
#     cmd += ' -N ' + name + \
#            ' -l ' + log_dir + \
#            ' -q ' + queue
#
#     if coprocessor_class is not None:
#         cmd += ' --coprocessor_class ' + coprocessor_class
#         cmd += ' --coprocessor_class_strict '
#     if coprocessor is not None:
#         cmd += ' --coprocessor ' + coprocessor + ' -R 32'
#
#     if export_var is not None :
#         cmd += ' --export ' + export_var
#
#     if debug:
#         cmd += ' --debug'
Christoph Arthofer's avatar
Christoph Arthofer committed
549
#
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#     if script is not None and os.path.exists(script):
#         cmd += ' -t ' + script
#     elif command is not None :
#         cmd += ' ' + command + ' '
#         # cmd += ' "' + command + '"'
#
#     # stream = os.popen(cmd)
#     # job_id = stream.read()
#
#     try:
#         result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, check=True)
#     except subprocess.CalledProcessError as e:
#         print(str(e), file=sys.stderr)
#         return None
#
#     job_id = result.stdout.strip()
Christoph Arthofer's avatar
Christoph Arthofer committed
566
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
567
#     return job_id
568
#
569

Christoph Arthofer's avatar
Christoph Arthofer committed
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
def RMSdifference(img1_path, img2_path, mask1_path=None, mask2_path=None, rms_path=None):
    """! Calculates the difference between two images or warps as the root mean squared (RMS)

    @param img1_path:                 Path to first image or deformation field
    @param img2_path:                 Path to second image or deformation field
    @param mask1_path:                Path to mask for first image
    @param mask2_path:                Path to mask for second image
    @param rms_path:                  Path to output text file that RMS is written to

    """

    img1_arr = nib.load(img1_path).get_fdata()
    img2_arr = nib.load(img2_path).get_fdata()

    if mask1_path is not None and mask2_path is not None:
        mask1_arr = nib.load(mask1_path).get_fdata()
        mask2_arr = nib.load(mask2_path).get_fdata()

        if len(img1_arr.shape) > 3:
            n_dim = img1_arr.shape[-1]
            img1_mask_stack_arr = np.stack((mask1_arr,) * n_dim, -1)
            n_dim = img2_arr.shape[-1]
            img2_mask_stack_arr = np.stack((mask2_arr,) * n_dim, -1)
        else:
            img1_mask_stack_arr = mask1_arr
            img2_mask_stack_arr = mask2_arr

        img_mask_stack_arr = np.logical_or(img1_mask_stack_arr, img2_mask_stack_arr)
        img1_masked_arr = img1_arr[img_mask_stack_arr > 0]
        img2_masked_arr = img2_arr[img_mask_stack_arr > 0]

        diff_img = img1_masked_arr - img2_masked_arr
    else:
        diff_img = img1_arr - img2_arr

    dim = np.prod(diff_img.shape)
    rms = np.sqrt((diff_img ** 2).sum() / dim)

    print('RMS difference between {} and {}: {}'.format(img1_path, img2_path, rms))
    if rms_path is not None:
        with open(rms_path, 'w+') as f:
            f.write('{}'.format(rms))


def RMSstandardDeviation(img_paths, mean_img_path, mask_path, sd_img_out_path=None, rms_out_path=None):
    """! Calculates the standard deviation of images as the root mean squared (RMS) (== coefficient of variation)

    @param img_paths:                     List of paths to images
    @param mean_img_path:                 Path to average image
    @param mask_path:                     Path to mask
    @param sd_img_out_path:               Path to standard deviation output image
    @param rms_out_path:                  Path to output text file that RMS is written to

    """

    mean_img_nib = nib.load(mean_img_path)

    for i, path in enumerate(img_paths):
        print(i, ' ', path)
        diff_img = fslmaths(path).inm(1000).sub(mean_img_nib).run()
        if i == 0:
            diffsum_img = fslmaths(diff_img).mul(diff_img).run()
        else:
            diffsum_img = fslmaths(diff_img).mul(diff_img).add(diffsum_img).run()

    stdtemp_img = fslmaths(diffsum_img).div(len(img_paths)).run()
    stdtemp_img_np = np.sqrt(stdtemp_img.get_fdata())
    if sd_img_out_path is not None:
        std_img = nib.Nifti1Image(stdtemp_img_np, affine=stdtemp_img.affine, header=stdtemp_img.header)
        std_img.to_filename(sd_img_out_path)

    mask_np = nib.load(mask_path).get_fdata()
    mean_img_np = mean_img_nib.get_fdata()

    stdtemp_img_masked_np = stdtemp_img_np[mask_np > 0]
    mean_img_masked_np = mean_img_np[mask_np > 0]

    cv = stdtemp_img_masked_np / mean_img_masked_np  # coefficient of variation
    dim = np.prod(cv.shape)
    rms = np.sqrt((cv ** 2).sum() / dim)

    print('RMS standard deviation: {}'.format(rms))
    if rms_out_path is not None:
        with open(rms_out_path, 'w+') as f:
            f.write('{}'.format(rms))


def mmorfWrapper(mmorf_run_cmd, config_path, img_warp_space,
                 img_ref_scalar, img_mov_scalar, aff_ref_scalar, aff_mov_scalar,
                 mask_ref_scalar, mask_mov_scalar,
                 img_ref_tensor, img_mov_tensor, aff_ref_tensor, aff_mov_tensor,
                 mask_ref_tensor, mask_mov_tensor,
                 warp_out, jac_det_out, bias_out):
    """! Wrapper function for running MMORF.

    @param mmorf_run_cmd:                     Singularity command to run MMORF
    @param config_path:                       Path to config file with fixed parameters
    @param img_warp_space:                    Path to image defining the space in which the warp field will be calculated
    @param img_ref_scalar:                    List of paths to scalar reference images
    @param img_mov_scalar:                    List of paths to scalar moving images
    @param aff_ref_scalar:                    List of paths to affine transformations for scalar reference images
    @param aff_mov_scalar:                    List of paths to affine transformations for scalar moving images
    @param mask_ref_scalar:                   List of paths to masks in reference image spaces
    @param mask_mov_scalar:                   List of paths to masks in moving image spaces
    @param img_ref_tensor:                    List of paths to reference tensors
    @param img_mov_tensor:                    List of paths to moving tensors
    @param aff_ref_tensor:                    List of paths to affine transformations for reference tensors
    @param aff_mov_tensor:                    List of paths to affine transformations for moving tensors
    @param mask_ref_tensor:                   List of paths to masks in reference tensor spaces
    @param mask_mov_tensor:                   List of paths to masks in moving tensor spaces
    @param warp_out:                          Path to output warp field
    @param jac_det_out:                       Path to output Jacobian determinant of final warp field
    @param bias_out:                          Path to output bias field for scalar image pairs

    @return  The command as a string and a dictionary of environment variables.

    """

    export_var = []
    cmd = mmorf_run_cmd
    cmd += ' --config ' + config_path
    split = os.path.split(config_path)
    export_var.append(split[0])
    cmd += ' --img_warp_space ' + img_warp_space
    split = os.path.split(img_warp_space)
    export_var.append(split[0])
    for path in img_ref_scalar:
        cmd += ' --img_ref_scalar ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in img_mov_scalar:
        cmd += ' --img_mov_scalar ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in aff_ref_scalar:
        cmd += ' --aff_ref_scalar ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in aff_mov_scalar:
        cmd += ' --aff_mov_scalar ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in mask_ref_scalar:
        cmd += ' --mask_ref_scalar ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in mask_mov_scalar:
        cmd += ' --mask_mov_scalar ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in img_ref_tensor:
        cmd += ' --img_ref_tensor ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in img_mov_tensor:
        cmd += ' --img_mov_tensor ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in aff_ref_tensor:
        cmd += ' --aff_ref_tensor ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in aff_mov_tensor:
        cmd += ' --aff_mov_tensor ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in mask_ref_tensor:
        cmd += ' --mask_ref_tensor ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    for path in mask_mov_tensor:
        cmd += ' --mask_mov_tensor ' + path
        split = os.path.split(path)
        export_var.append(split[0])
    cmd += ' --warp_out ' + warp_out
    split = os.path.split(warp_out)
    export_var.append(split[0])
    cmd += ' --jac_det_out ' + jac_det_out
    split = os.path.split(jac_det_out)
    export_var.append(split[0])
    cmd += ' --bias_out ' + bias_out
    split = os.path.split(bias_out)
    export_var.append(split[0])

    cmd += '\n'

    export_var = list(filter(None, list(set(export_var))))
    export_var = {'SINGULARITY_BIND': export_var}

    return cmd, export_var
Christoph Arthofer's avatar
Christoph Arthofer committed
760
761
762


if __name__ == "__main__":
763
764
    """! Main function submitting the jobs.
    """
765
766
    logging.basicConfig()
    logging.getLogger('fsl.wrappers').setLevel(logging.DEBUG)
767

Christoph Arthofer's avatar
Christoph Arthofer committed
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
    mni_path = os.getenv('FSLDIR')+'/data/standard/MNI152lin_T1_1mm_brain.nii.gz'
    identity_path = os.getenv('FSLDIR')+'/etc/flirtsch/ident.mat'
    mmorf_path = os.getenv('MMORFDIR')
    mmorf_run_cmd = 'singularity run --nv ' + mmorf_path
    mmorf_exec_cmd = 'singularity exec ' + mmorf_path

    flags_required = {
        'input': [('-i', '--input'),'<dir>'],
        'tree': [('-t', '--tree'),'<path>'],
        'output': [('-o', '--output'),'<dir>']
    }
    help_required = {
        'input': 'Directory containing the subjects/timepoints',
        'tree': 'Path to FSL Filetree describing the subject-specific directory structure',
        'output': 'Output directory',
    }

    flags_optional = {
        'subids': [('-s', '--subids'),'<path>'],
        'affine': [('-aff', '--affine'),'[True,False]'],
        'nonlinear': [('-nln', '--nonlinear'),'[True,False]'],
        'n_resolutions': [('-nres', '--n_resolutions'),'<int>'],
        'n_iterations': [('-nit', '--n_iterations'),'<int>'],
        'cpuq': [('-c', '--cpuq'),'<string>'],
        'gpuq': [('-g', '--gpuq'), '<string>']
    }
    help_optional = {
        'subids': 'Path to .csv file containing one subject ID per row: subject IDs have to indentify the sub-directories of the \'input\' argument (optional)'
                  'if not provided all sub-directories of the \'input\' argument will be used',
        'affine': 'Run affine template construction (required for affine)',
        'nonlinear': 'Run nonlinear template construction (required for nonlinear)',
        'n_resolutions': 'Number of resolution levels (has to be <= number of resolutions defined in the MMORF config (required for nonlinear template construction)',
        'n_iterations': 'Number of iterations per resolution level (required for nonlinear template construction)',
        'cpuq': 'Name of cluster queue to submit CPU jobs to (required for affine and nonlinear template construction)',
        'gpuq': 'Name of cluster queue to submit GPU jobs to (required for nonlinear template construction)'
    }

    parser = argparse.ArgumentParser(description='Constructs a multimodal template from T1, T1+T2 or T1+T2+DTI data.',
                                     usage='\npython run_template_construction.py -i <inputdir> -t <filetree> -o <outputdir> -aff True --cpuq short.qc\n'
                                           'python run_template_construction.py -i <inputdir> -t <filetree> -o <outputdir> -aff True -nln True -nres 2 -nit 1 --cpuq short.qc --gpuq gpu8.q\n'
                                           'python run_template_construction.py -i <inputdir> -t <filetree> -o <outputdir> -nln True -nres 2 -nit 1 --cpuq short.qc --gpuq gpu8.q\n')
    for key in flags_required.keys():
        parser.add_argument(*flags_required[key][0], help=help_required[key], metavar=flags_required[key][1], required=True)
    for key in flags_optional.keys():
        parser.add_argument(*flags_optional[key][0], help=help_optional[key], metavar=flags_optional[key][1])
    args = parser.parse_args()

    data_dir = args.input
    tag = os.path.basename(os.path.abspath(args.output))
    base_dir = args.output
    tree_path = args.tree
    if args.subids is not None:
        id_path = args.subids
        df_ids = pd.read_csv(id_path, header=None, names=['subject_ID'], dtype={'subject_ID': str})
        ls_ids = df_ids['subject_ID'].tolist()
    else:
        ls_ids = [f.name for f in os.scandir(args.input) if f.is_dir()]
        ls_ids.sort()

    affine_on = args.affine == 'True'
    nln_on = args.nonlinear == 'True'
    if nln_on:
        if args.n_resolutions is None or args.n_iterations is None:
            sys.exit('No \'n_resolutions\' or \'n_iterations\' provided')
        else:
            step_id = np.arange(int(args.n_resolutions))+1
            it_at_step_id = np.arange(int(args.n_iterations))+1
        if args.cpuq is None or args.gpuq is None:
            sys.exit('No CPU or GPU queue provided')
        else:
            cpuq = args.cpuq
            gpuq = args.gpuq

    if affine_on:
        if args.cpuq is None:
            sys.exit('No CPU queue provided')
        else:
            cpuq = args.cpuq

847
848
849
850
851
852
853

    jobram_low = 4
    jobram_hi = 12

    jobtime_low = 15
    jobtime_high = 60

Christoph Arthofer's avatar
Christoph Arthofer committed
854
    job_ids = ['' for _ in range(100)]
Christoph Arthofer's avatar
Christoph Arthofer committed
855
856
    task_count = 0

857
    os.makedirs(base_dir, mode=0o770) if not os.path.exists(base_dir) else print(base_dir + ' exists')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
858
    os.chmod(base_dir, 0o770)
Christoph Arthofer's avatar
Christoph Arthofer committed
859

860
    tree = FileTree.read(tree_path, top_level='')
Christoph Arthofer's avatar
Christoph Arthofer committed
861
862
863
    tree = tree.update(data_dir=data_dir, template_dir=base_dir)

    script_dir = tree.get('script_dir')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
864
    os.mkdir(script_dir, mode=0o770) if not os.path.exists(script_dir) else print(script_dir + ' exists')
Christoph Arthofer's avatar
Christoph Arthofer committed
865
    log_dir = tree.get('log_dir')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
866
    os.mkdir(log_dir, mode=0o770) if not os.path.exists(log_dir) else print(log_dir + ' exists')
Christoph Arthofer's avatar
Christoph Arthofer committed
867
    misc_dir = tree.get('misc_dir')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
868
    os.mkdir(misc_dir, mode=0o770) if not os.path.exists(misc_dir) else print(misc_dir + ' exists')
Christoph Arthofer's avatar
Christoph Arthofer committed
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
    shutil.copyfile(identity_path,tree.get('identity_mat'))

    ref_idx = 0

    filetree_keys = tree.template_keys()
    mod = {'T1_brain_key': None,
           'T1_head_key': None,
           'T2_brain_key': None,
           'T2_head_key': None,
           'DTI_tensor_key': None,
           'DTI_scalar_key': None
           }
    if 'data/T1_head' in filetree_keys:
        mod['T1_head_key'] = 'data/T1_head'
        mod['T1_brain_key'] = 'data/T1_brain'
        mod['T1_brain_mask_key'] = 'data/T1_brain_mask'
    if 'data/T2_head' in filetree_keys:
        mod['T2_head_key'] = 'data/T2_head'
        mod['T2_brain_key'] = 'data/T2_brain'
    if 'data/DTI_tensor' in filetree_keys:
        mod['DTI_tensor_key'] = 'data/DTI_tensor'
        mod['DTI_scalar_key'] = 'data/DTI_scalar'

# Affine template construction
    if affine_on:
        aff_ref_id = ls_ids[ref_idx]
        tree = tree.update(sub_id=aff_ref_id, ref_id=aff_ref_id)
        affine_ref_path = tree.get(mod['T1_brain_key'])

898
# Soft clamping of high skull intensities and mask preprocessing
Christoph Arthofer's avatar
Christoph Arthofer committed
899
900
        task_name = '{:03d}_prep_clamping'.format(task_count)
        script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
901
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
902
903
904
905
906
907
908
909
910
            for id in ls_ids:
                tree = tree.update(sub_id=id)
                T1_head_path = tree.get(mod['T1_head_key'])
                T1_clamped_path = tree.get('T1_head_clamped', make_dir=True)

                jobcmd = func_to_cmd(clampImage,
                                     args=(T1_head_path, T1_clamped_path),
                                     tmp_dir=script_dir,
                                     kwargs=None,
911
912
913
914
915
916
                                     clean="never") + '\n'
                jobcmd += func_to_cmd(maskPreprocessing,
                                      args=(tree,),
                                      tmp_dir=script_dir,
                                      kwargs=None,
                                      clean="never") + '\n'
Christoph Arthofer's avatar
Christoph Arthofer committed
917
                f.write(jobcmd)
918
919
        # job_ids[0] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
        job_ids[0] = submitJob(script_path, tag+'_'+task_name, log_dir, queue=cpuq, wait_for=None, array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
920
921
922
923
924
925
        print('submitted: ' + task_name)

# Register all individual images to one reference image
        task_count += 1
        task_name = '{:03d}_affT_registrations_2_ref'.format(task_count)
        script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
926
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
927
928
929
930
931
932
933
934
935
936
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)

                if id == aff_ref_id:
                    shutil.copyfile(tree.get('identity_mat'), tree.get('T1_to_ref_mat', make_dir=True))
                else:
                    cmd = flirt(tree.get(mod['T1_brain_key']), affine_ref_path,
                                omat=tree.get('T1_to_ref_mat', make_dir=True), dof=6, cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
937
938
        # job_ids[1] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
        job_ids[1] = submitJob(script_path, tag+'_'+task_name, log_dir, queue=cpuq, wait_for=None, array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
939
940
941
942
943
944
945
        print('submitted: ' + task_name)

# Register T2 images to corresponding T1 images
        if mod['T2_brain_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_registrations_T2_2_T1'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
946
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
947
948
949
950
951
952
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=id)
                    cmd = flirt(tree.get(mod['T2_brain_key']), tree.get(mod['T1_brain_key']), omat=tree.get('T2_to_T1_mat'),
                                dof=6, cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
953
954
            # job_ids[2] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
            job_ids[2] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=None, array_task=True, jobram=jobram_low, jobtime=jobtime_low)
955

Christoph Arthofer's avatar
Christoph Arthofer committed
956
957
958
959
960
961
962
            print('submitted: ' + task_name)

# Register DTI images to corresponding T2 images
        if mod['T2_brain_key'] is not None and mod['DTI_scalar_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_registrations_DTI_2_T2'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
963
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
964
965
966
967
968
969
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=id)
                    cmd = flirt(tree.get(mod['DTI_scalar_key']), tree.get(mod['T2_brain_key']), omat=tree.get('DTI_to_T2_mat'),
                                dof=6, cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
970
971
            # job_ids[3] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
            job_ids[3] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=None, array_task=True, jobram=jobram_low, jobtime=jobtime_low)
972

Christoph Arthofer's avatar
Christoph Arthofer committed
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
            print('submitted: ' + task_name)

# Unbiasing of T1 images
        task_count += 1
        task_name = '{:03d}_affT_correct_bias'.format(task_count)
        aff_matrix_paths = []
        unbiased_matrix_paths = []
        for id in ls_ids:
            tree = tree.update(sub_id=id, ref_id=aff_ref_id)
            aff_matrix_paths.append(tree.get('T1_to_ref_mat'))
            unbiased_matrix_paths.append(tree.get('T1_to_unbiased_mat'))

        temp_dir = tree.get('affine_it1_dir')
        unbiasing_invmtx_path = tree.get('T1_unbiasing_affine_matrix', make_dir=True)

        jobcmd = func_to_cmd(correctBiasMidtransWrapper,
                             args=(
                             aff_matrix_paths, temp_dir, affine_ref_path, unbiasing_invmtx_path, unbiased_matrix_paths),
                             tmp_dir=script_dir,
                             kwargs=None,
                             clean="never")
994
995
        # job_ids[4] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[1]])
        job_ids[4] = submitJob(jobcmd, tag+'_'+task_name, log_dir, queue=cpuq, wait_for=[job_ids[1]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
996

Christoph Arthofer's avatar
Christoph Arthofer committed
997
998
999
1000
1001
1002
        print('submitted: ' + task_name)

# Apply unbiased matrix to T1 images
        task_count += 1
        task_name = '{:03d}_affT_unbiased_transform_of_T1'.format(task_count)
        script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1003
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1004
1005
1006
1007
1008
1009
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                cmd = applyxfm(src=tree.get(mod['T1_brain_key']), ref=affine_ref_path, mat=tree.get('T1_to_unbiased_mat'),
                               out=tree.get('T1_to_unbiased_img'), interp='spline', cmdonly=True)
                cmd = ' '.join(cmd) + '\n'
                f.write(cmd)
1010
1011
        # job_ids[5] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[4]])
        job_ids[5] = submitJob(script_path, tag+'_'+task_name, log_dir, queue=cpuq, wait_for=[job_ids[4]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1012
1013
1014
1015
1016
1017
1018
        print('submitted: ' + task_name)

# Concat T2_to_T1 and T1_to_unbiased
        if mod['T2_head_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_concat_T2_and_unbiased'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1019
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1020
1021
1022
1023
1024
1025
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = concatxfm(tree.get('T2_to_T1_mat'), tree.get('T1_to_unbiased_mat'),
                                    tree.get('T2_to_unbiased_mat'), cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1026
1027
            # job_ids[6] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[4]])
            job_ids[6] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=list(itemgetter(*[2,4])(job_ids)), array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1028
1029
1030
1031
1032
1033
1034
            print('submitted: ' + task_name)

# Concat DTI_to_T2 and T2_to_unbiased
        if mod['T2_head_key'] is not None and mod['DTI_scalar_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_concat_DTI_and_unbiased'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1035
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1036
1037
1038
1039
1040
1041
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = concatxfm(tree.get('DTI_to_T2_mat'), tree.get('T2_to_unbiased_mat'),
                                    tree.get('DTI_to_unbiased_mat'), cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1042
1043
            # job_ids[7] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[6]])
            job_ids[7] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[6]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
            print('submitted: ' + task_name)

# Averaging unbiased T1 images
        task_count += 1
        task_name = '{:03d}_affT_average_unbiased_T1'.format(task_count)
        img_paths = []
        for id in ls_ids:
            tree = tree.update(sub_id=id, ref_id=aff_ref_id)
            img_paths.append(tree.get('T1_to_unbiased_img'))
        aff_template_path = tree.get('T1_unbiased_affine_template')

1055
        jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir, kwargs=None,
Christoph Arthofer's avatar
Christoph Arthofer committed
1056
                             clean="never")
1057
1058
        # job_ids[8] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[5]])
        job_ids[8] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[5]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1059
1060
1061
1062
1063
1064
1065
1066
        print('submitted: ' + task_name)

# Register unbiased template to MNI space with 6 dof
        task_count += 1
        task_name = '{:03d}_affT_unbiased_T1_template_to_MNI'.format(task_count)
        cmd = flirt(aff_template_path, mni_path, omat=tree.get('T1_unbiased_affine_template_to_MNI_mat'),
                    out=tree.get('T1_unbiased_affine_template_to_MNI_img'), dof=6, cmdonly=True)
        cmd = ' '.join(cmd) + '\n'
1067
1068
        # job_ids[9] = submitJob(tag+'_'+task_name, log_dir, command=cmd, queue=cpuq, wait_for=[job_ids[8]])
        job_ids[9] = submitJob(cmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[8]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1069
1070
1071
1072
1073
1074
        print('submitted: ' + task_name)

# Concatenate individual affine transformations (T1 brain to unbiased T1 and the rigid transformation to MNI)
        task_count += 1
        task_name = '{:03d}_affT_concat_T1_brain_to_MNI'.format(task_count)
        script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1075
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1076
1077
1078
1079
1080
1081
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                cmd = concatxfm(tree.get('T1_to_unbiased_mat'), tree.get('T1_unbiased_affine_template_to_MNI_mat'),
                                tree.get('T1_to_MNI_mat', make_dir=True), cmdonly=True)
                cmd = ' '.join(cmd) + '\n'
                f.write(cmd)
1082
1083
        # job_ids[10] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[9]])
        job_ids[10] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[9]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1084
1085
1086
1087
1088
1089
1090
        print('submitted: ' + task_name)

# Concatenate individual affine transformations (T2 brain to unbiased T2 and the rigid transformation to MNI)
        if mod['T2_head_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_concat_T2_brain_to_MNI'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1091
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1092
1093
1094
1095
1096
1097
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = concatxfm(tree.get('T2_to_unbiased_mat'), tree.get('T1_unbiased_affine_template_to_MNI_mat'),
                                    tree.get('T2_to_MNI_mat'), cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1098
1099
            # job_ids[12] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[9]])
            job_ids[12] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[9]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1100
1101
1102
1103
1104
1105
1106
            print('submitted: ' + task_name)

# Concatenate individual affine transformations (DTI to unbiased T2 and the rigid transformation to MNI)
        if mod['T2_head_key'] is not None and mod['DTI_scalar_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_concat_DTI_to_MNI'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1107
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1108
1109
1110
1111
1112
1113
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = concatxfm(tree.get('DTI_to_unbiased_mat'), tree.get('T1_unbiased_affine_template_to_MNI_mat'),
                                    tree.get('DTI_to_MNI_mat'), cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1114
1115
            # job_ids[14] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[9]])
            job_ids[14] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[9]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1116
1117
1118
1119
1120
1121
1122
            print('submitted: ' + task_name)

# Transform individual T1 brain images to MNI space
        if mod['T1_brain_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_transform_T1_brain_to_MNI'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1123
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1124
1125
1126
1127
1128
1129
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = applyxfm(src=tree.get(mod['T1_brain_key']), ref=mni_path, mat=tree.get('T1_to_MNI_mat'),
                                   out=tree.get('T1_brain_to_MNI_img'), interp='spline', cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1130
1131
            # job_ids[15] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[10]])
            job_ids[15] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[10]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1132
1133
1134
1135
1136
1137
1138
            print('submitted: ' + task_name)

# Transform individual T1 brain masks to MNI space
        if mod['T1_brain_mask_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_transform_T1_brain_masks_to_MNI'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1139
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1140
1141
1142
1143
1144
1145
1146
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = applyxfm(src=tree.get(mod['T1_brain_mask_key']), ref=mni_path,
                                   mat=tree.get('T1_to_MNI_mat'),
                                   out=tree.get('T1_brain_mask_to_MNI_img'), interp='trilinear', cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1147
1148
            # job_ids[16] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[10]])
            job_ids[16] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[10]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1149
1150
1151
1152
1153
1154
1155
            print('submitted: ' + task_name)

# Transform individual T1 head images to MNI space
        if mod['T1_head_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_transform_T1_head_to_MNI'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1156
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1157
1158
1159
1160
1161
1162
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = applyxfm(src=tree.get('T1_head_clamped'), ref=mni_path, mat=tree.get('T1_to_MNI_mat'),
                                   out=tree.get('T1_head_to_MNI_img'), interp='spline', cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1163
1164
            # job_ids[17] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=list(itemgetter(*[0, 10])(job_ids)))
            job_ids[17] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=list(itemgetter(*[0, 10])(job_ids)), array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1165
1166
1167
1168
1169
1170
1171
            print('submitted: ' + task_name)

# Transform individual T2 head images to MNI space
        task_count += 1
        task_name = '{:03d}_affT_transform_T2_head_to_MNI'.format(task_count)
        script_path = os.path.join(script_dir, task_name + '.sh')
        if mod['T2_head_key'] is not None:
Christoph Arthofer's avatar
Christoph Arthofer committed
1172
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1173
1174
1175
1176
1177
1178
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = applyxfm(src=tree.get(mod['T2_head_key']), ref=mni_path, mat=tree.get('T2_to_MNI_mat'),
                                   out=tree.get('T2_head_to_MNI_img'), interp='spline', cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1179
1180
            # job_ids[18] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[12]])
            job_ids[18] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[12]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1181
1182
1183
1184
1185
1186
1187
            print('submitted: ' + task_name)

# Transform individual DTI images to MNI space
        if mod['T2_head_key'] is not None and mod['DTI_scalar_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_transform_DTI_scalar_to_MNI'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1188
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1189
1190
1191
1192
1193
1194
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = applyxfm(src=tree.get(mod['DTI_scalar_key']), ref=mni_path, mat=tree.get('DTI_to_MNI_mat'),
                                   out=tree.get('DTI_to_MNI_img'), interp='spline', cmdonly=True)
                    cmd = ' '.join(cmd) + '\n'
                    f.write(cmd)
1195
1196
            # job_ids[19] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[14]])
            job_ids[19] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[14]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1197
1198
1199
1200
1201
1202
1203
            print('submitted: ' + task_name)

# Transform individual DTI tensors to MNI space
        if mod['T2_head_key'] is not None and mod['DTI_tensor_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_transform_DTI_tensor_to_MNI'.format(task_count)
            script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1204
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1205
1206
1207
1208
1209
1210
1211
1212
                for id in ls_ids:
                    tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                    cmd = 'vecreg -i ' + tree.get(mod['DTI_tensor_key']) + \
                          ' -r ' + mni_path + \
                          ' -o ' + tree.get('DTI_tensor_to_MNI') + \
                          ' -t ' + tree.get('DTI_to_MNI_mat') + \
                          ' --interp=spline \n'
                    f.write(cmd)
1213
1214
            # job_ids[20] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[14]])
            job_ids[20] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[14]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
            print('submitted: ' + task_name)

# Averaging transformed T1 brain images in MNI space
        if mod['T1_brain_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_average_T1_brain_in_MNI'.format(task_count)
            img_paths = []
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                img_paths.append(tree.get('T1_brain_to_MNI_img'))
            aff_template_path = tree.get('T1_brain_affine_template')

1227
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1228
                                 kwargs=None, clean="never")
1229
1230
            # job_ids[21] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[15]])
            job_ids[21] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[15]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
            print('submitted: ' + task_name)

# Averaging transformed T1 brain masks in MNI space
        if mod['T1_brain_mask_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_average_T1_brain_masks_in_MNI'.format(task_count)
            img_paths = []
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                img_paths.append(tree.get('T1_brain_mask_to_MNI_img'))
            aff_template_path = tree.get('T1_brain_mask_affine_template')

1243
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'mean', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1244
                                 kwargs=None, clean="never")
1245
1246
            # job_ids[22] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[16]])
            job_ids[22] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[16]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1247
1248
1249
            print('submitted: ' + task_name)

            task_name = '{:03d}_affT_create_weighted_brain_mask'.format(task_count)
Christoph Arthofer's avatar
Christoph Arthofer committed
1250
            jobcmd = 'fslmaths ' + aff_template_path + ' -thr 0.1 -bin -mul 7 -add 1 -inm 1 ' + tree.get('T1_brain_mask_weighted_affine_template')
1251
1252
            # job_ids[23] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[22]])
            job_ids[23] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[22]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
            print('submitted: ' + task_name)

# Averaging transformed T1 non-defaced whole-head images in MNI space
        if mod['T1_head_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_average_T1_head_in_MNI'.format(task_count)
            img_paths = []
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                img_paths.append(tree.get('T1_head_to_MNI_img'))
            aff_template_path = tree.get('T1_head_affine_template')

1265
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1266
                                 kwargs=None, clean="never")
1267
1268
            # job_ids[24] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[17]])
            job_ids[24] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[17]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
            print('submitted: ' + task_name)

# Averaging transformed T2 non-defaced whole-head images in MNI space
        if mod['T2_head_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_average_T2_head_in_MNI'.format(task_count)
            img_paths = []
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                img_paths.append(tree.get('T2_head_to_MNI_img'))
            aff_template_path = tree.get('T2_head_affine_template')

1281
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1282
                                 kwargs=None, clean="never")
1283
1284
            # job_ids[25] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[18]])
            job_ids[25] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[18]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
            print('submitted: ' + task_name)

# Averaging transformed DTI images in MNI space
        if mod['T2_head_key'] is not None and mod['DTI_scalar_key'] is not None:
            task_count += 1
            task_name = '{:03d}_affT_average_DTI_scalar_in_MNI'.format(task_count)
            img_paths = []
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                img_paths.append(tree.get('DTI_to_MNI_img'))
            aff_template_path = tree.get('DTI_affine_template')

1297
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1298
                                 kwargs=None, clean="never")
1299
1300
            # job_ids[26] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[19]])
            job_ids[26] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[19]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
            print('submitted: ' + task_name)

# Averaging transformed DTI tensors in MNI space
        if mod['T2_head_key'] is not None and mod['DTI_tensor_key']:
            task_count += 1
            task_name = '{:03d}_affT_average_DTI_tensor_in_MNI'.format(task_count)
            export_paths = []
            cmd = mmorf_exec_cmd + ' tensor_average' + ' -i '
            for id in ls_ids:
                tree = tree.update(sub_id=id, ref_id=aff_ref_id)
                cmd += tree.get('DTI_tensor_to_MNI') + ' '
                export_paths.append(tree.get('DTI_tensor_to_MNI'))
            cmd += '-o ' + tree.get('DTI_tensor_affine_template')
            export_paths.append(tree.get('DTI_tensor_affine_template'))

            common_path = os.path.commonpath(export_paths)
            export_var_str = {'SINGULARITY_BIND': '"SINGULARITY_BIND=' + ','.join([common_path]) + '"'}

1319
1320
            # job_ids[27] = submitJob(tag+'_'+task_name, log_dir, command=cmd, queue=cpuq, export_var=export_var_str['SINGULARITY_BIND'], wait_for=[job_ids[20]])
            job_ids[27] = submitJob(cmd, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[20]], array_task=False, export_var=[export_var_str['SINGULARITY_BIND']], jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
            print('submitted: ' + task_name)

    # Nonlinear template construction
    if nln_on:
        it_total = 0

        for s, step in enumerate(step_id):
            tree = tree.update(step_id='{:02d}'.format(step))
            config_path = tree.get('mmorf_params', make_dir=True)
            writeConfig(step, mod, config_path)

            for i, it in enumerate(it_at_step_id):
                print('Step ID: ', step)
                print('Iteration ID: ', it)
                it_total += 1

                if it_total == 1:
                    tree = tree.update(step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                    img_ref_T1brain_path = tree.get('T1_brain_affine_template')
                    img_ref_T1head_path = tree.get('T1_head_affine_template')
                    img_ref_T2head_path = tree.get('T2_head_affine_template')
1342
                    img_ref_tensor_path = tree.get('DTI_tensor_affine_template')
Christoph Arthofer's avatar
Christoph Arthofer committed
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
                    img_ref_T1brain_mask_path = tree.get('T1_brain_mask_weighted_affine_template')
                else:
                    if it == 1:
                        prev_it = it_at_step_id[-1]
                        prev_step = step - 1
                    elif it > 1:
                        prev_it = it - 1
                        prev_step = step

                    tree = tree.update(step_id='{:02d}'.format(prev_step), it_id='{:02d}'.format(prev_it))
                    img_ref_T1brain_path = tree.get('T1_brain_nln_template')
                    img_ref_T1head_path = tree.get('T1_head_nln_template')
                    img_ref_T2head_path = tree.get('T2_head_nln_template')
1356
                    img_ref_tensor_path = tree.get('DTI_tensor_nln_template')
Christoph Arthofer's avatar
Christoph Arthofer committed
1357
1358
1359
1360
1361
1362
1363
1364
1365
                    img_ref_T1brain_mask_path = tree.get('T1_brain_mask_weighted_nln_template')
                    avgwarp_prev_it_path = tree.get('avg_warp')
                    avgmask_prev_it_path = tree.get('T1_brain_mask_nln_template')

                task_count += 1
                task_name = '{:03d}_nlnT_mmorf'.format(task_count)

# Nonlinear registration to template from previous iteration
                script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1366
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
                    export_vars = {}
                    for i, id in enumerate(ls_ids):
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        if mod['T1_head_key'] is not None and mod['T2_head_key'] is not None and mod['DTI_tensor_key'] is not None:
                            img_warp_space = img_ref_T1head_path
                            img_ref_scalar = [img_ref_T1head_path, img_ref_T2head_path]
                            img_mov_scalar = [tree.get('T1_head_clamped'), tree.get(mod['T2_head_key'])]
                            aff_ref_scalar = [tree.get('identity_mat'), tree.get('identity_mat')]
                            aff_mov_scalar = [tree.get('T1_to_MNI_mat'), tree.get('T2_to_MNI_mat')]
                            mask_ref_scalar = [img_ref_T1brain_mask_path, 'NULL']
                            mask_mov_scalar = ['NULL', 'NULL']
                            img_ref_tensor = [img_ref_tensor_path]
                            img_mov_tensor = [tree.get(mod['DTI_tensor_key'])]
                            aff_ref_tensor = [tree.get('identity_mat')]
                            aff_mov_tensor = [tree.get('DTI_to_MNI_mat')]
                            mask_tensor = ['NULL']
                        elif mod['T1_head_key'] is not None and mod['T2_head_key'] is not None:
                            img_warp_space = img_ref_T1head_path
                            img_ref_scalar = [img_ref_T1head_path, img_ref_T2head_path]
                            img_mov_scalar = [tree.get('T1_head_clamped'), tree.get(mod['T2_head_key'])]
                            aff_ref_scalar = [tree.get('identity_mat'), tree.get('identity_mat')]
                            aff_mov_scalar = [tree.get('T1_to_MNI_mat'), tree.get('T2_to_MNI_mat')]
                            mask_ref_scalar = [img_ref_T1brain_mask_path, 'NULL']
                            mask_mov_scalar = ['NULL', 'NULL']
                            img_ref_tensor = []
                            img_mov_tensor = []
                            aff_ref_tensor = []
                            aff_mov_tensor = []
                            mask_tensor = []
                        elif mod['T1_head_key'] is not None:
                            img_warp_space = img_ref_T1head_path
                            img_ref_scalar = [img_ref_T1head_path]
                            img_mov_scalar = [tree.get('T1_head_clamped')]
                            aff_ref_scalar = [tree.get('identity_mat')]
                            aff_mov_scalar = [tree.get('T1_to_MNI_mat')]
                            mask_ref_scalar = [img_ref_T1brain_mask_path]
1403
                            mask_mov_scalar = [tree.get('inverse_lesion_and_brain_mask_in_T1')]
Christoph Arthofer's avatar
Christoph Arthofer committed
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
                            img_ref_tensor = []
                            img_mov_tensor = []
                            aff_ref_tensor = []
                            aff_mov_tensor = []
                            mask_tensor = []

                        mmorf_script, export_var = mmorfWrapper(mmorf_run_cmd, config_path,
                                                                img_warp_space=img_warp_space,
                                                                img_ref_scalar=img_ref_scalar,
                                                                img_mov_scalar=img_mov_scalar,
                                                                aff_ref_scalar=aff_ref_scalar,
                                                                aff_mov_scalar=aff_mov_scalar,
                                                                mask_ref_scalar=mask_ref_scalar,
                                                                mask_mov_scalar=mask_mov_scalar,
                                                                img_ref_tensor=img_ref_tensor,
                                                                img_mov_tensor=img_mov_tensor,
                                                                aff_ref_tensor=aff_ref_tensor,
                                                                aff_mov_tensor=aff_mov_tensor,
                                                                mask_ref_tensor=mask_tensor,
                                                                mask_mov_tensor=mask_tensor,
                                                                warp_out=tree.get('mmorf_warp', make_dir=True),
                                                                jac_det_out=tree.get('mmorf_jac'),
                                                                bias_out=tree.get('mmorf_bias'))
                        f.write(mmorf_script)

                        for key, value in export_var.items():
                            if i == 0:
                                export_vars[key] = value
                            else:
                                export_vars[key] = export_vars[key] + value

                    export_var_str = {}
                    for key, value in export_vars.items():
                        common_path = os.path.commonpath(value)
                        export_var_str[key] = '"' + key + '=' + ','.join([common_path]) + '"'

1440
1441
1442
                if affine_on:
                    job_ids[28] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=gpuq,
                                            wait_for=list(itemgetter(*[21, 23, 24, 25, 26, 27, 28, 44, 45, 46, 47, 48, 50])(job_ids)),
1443
                                            array_task=True, coprocessor='cuda', coprocessor_class=None, coprocessor_multi="1", threads=1, export_var=[export_var_str['SINGULARITY_BIND']], jobram=32, jobtime=jobtime_high)
1444
1445
1446
                else:
                    job_ids[28] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=gpuq,
                                            wait_for=list(itemgetter(*[44, 45, 46, 47, 48, 50])(job_ids)),
1447
                                            array_task=True, coprocessor='cuda', coprocessor_class=None, coprocessor_multi="1", threads=1, export_var=[export_var_str['SINGULARITY_BIND']], jobram=32, jobtime=jobtime_high)
1448

Christoph Arthofer's avatar
Christoph Arthofer committed
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
                print('submitted: ' + task_name)

# Averaging warps
                task_count += 1
                task_name = '{:03d}_nlnT_average_warps'.format(task_count)
                warp_paths = []
                for id in ls_ids:
                    tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                    warp_paths.append(tree.get('mmorf_warp'))
                avg_warp_path = tree.get('avg_warp')

1460
                jobcmd = func_to_cmd(averageImages, args=(warp_paths, avg_warp_path, 'mean', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1461
                                     kwargs=None, clean="never")
1462
1463
                # job_ids[29] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[28]])
                job_ids[29] = submitJob(jobcmd, tag + '_' + task_name, log_dir, queue=cpuq,wait_for=[job_ids[28]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1464
1465
1466
1467
1468
1469
1470
1471
1472
                print('submitted: ' + task_name)

# Inverse average warp
                task_count += 1
                task_name = '{:03d}_nlnT_invert_average_warp'.format(task_count)
                avg_warp_path = tree.get('avg_warp')
                inv_avg_warp_path = tree.get('inv_avg_warp')
                cmd = invwarp(warp=avg_warp_path, ref=img_ref_T1head_path, out=inv_avg_warp_path, cmdonly=True)
                cmd = ' '.join(cmd) + '\n'
1473
1474
                # job_ids[30] = submitJob(tag+'_'+task_name, log_dir, command=cmd, queue=cpuq, wait_for=[job_ids[29]])
                job_ids[30] = submitJob(cmd, tag + '_' + task_name, log_dir, queue=cpuq,wait_for=[job_ids[29]], array_task=False, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1475
1476
1477
1478
1479
1480
                print('submitted: ' + task_name)

# Create unbiased warps: (1) resample forward warp with inverse average warp and (2) add inverse average warp to resulting composition
                task_count += 1
                task_name = '{:03d}_nlnT_resample_warps'.format(task_count)
                script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1481
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1482
1483
1484
1485
1486
1487
1488
1489
1490
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        warp_path = tree.get('mmorf_warp')
                        resampled_path = tree.get('mmorf_warp_resampled')
                        inv_avg_warp_path = tree.get('inv_avg_warp')
                        jobcmd = func_to_cmd(applyWarpWrapper, args=(
                        warp_path, img_ref_T1head_path, resampled_path, inv_avg_warp_path, 'spline', False),
                                             tmp_dir=script_dir, kwargs=None, clean="never")
                        f.write(jobcmd + '\n')
1491
1492
                # job_ids[31] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[30]])
                job_ids[31] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[30]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1493
1494
1495
1496
1497
                print('submitted: ' + task_name)

                task_count += 1
                task_name = '{:03d}_nlnT_unbias_warps'.format(task_count)
                script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1498
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1499
1500
1501
1502
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        f.write('fslmaths ' + tree.get('mmorf_warp_resampled') + ' -add ' + tree.get(
                            'inv_avg_warp') + ' ' + tree.get('mmorf_warp_resampled_unbiased') + '\n')
1503
1504
                # job_ids[32] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[31]])
                job_ids[32] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[31]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1505
1506
1507
1508
1509
1510
1511
                print('submitted: ' + task_name)

# Concatenate corresponding affine transforms and unbiased warps
# T1 brain
                task_count += 1
                task_name = '{:03d}_nlnT_concat_unbiased_warps_T1_brain'.format(task_count)
                script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1512
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1513
1514
1515
1516
1517
1518
1519
1520
1521
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        full_resampled_path = tree.get('mmorf_warp_resampled_unbiased_full_T1brain')
                        premat_path = tree.get('T1_to_MNI_mat')
                        warp_path = tree.get('mmorf_warp_resampled_unbiased')
                        cmd = convertwarp(out=full_resampled_path, ref=img_ref_T1head_path, premat=premat_path,
                                          warp1=warp_path, cmdonly=True)
                        cmd = ' '.join(cmd) + '\n'
                        f.write(cmd)
1522
1523
                # job_ids[33] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[32]])
                job_ids[33] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[32]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1524
1525
1526
1527
1528
1529
1530
                print('submitted: ' + task_name)

# T1 head
                if mod['T1_head_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_concat_unbiased_warps_T1_head'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1531
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1532
1533
1534
1535
1536
1537
1538
1539
1540
                        for id in ls_ids:
                            tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                            full_resampled_path = tree.get('mmorf_warp_resampled_unbiased_full_T1head')
                            premat_path = tree.get('T1_to_MNI_mat')
                            warp_path = tree.get('mmorf_warp_resampled_unbiased')
                            cmd = convertwarp(out=full_resampled_path, ref=img_ref_T1head_path, premat=premat_path,
                                              warp1=warp_path, cmdonly=True)
                            cmd = ' '.join(cmd) + '\n'
                            f.write(cmd)
1541
1542
                    # job_ids[34] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[32]])
                    job_ids[34] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[32]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1543
1544
1545
1546
1547
1548
1549
                    print('submitted: ' + task_name)

# T2 head
                if mod['T2_head_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_concat_unbiased_warps_T2_head'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1550
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1551
1552
1553
1554
1555
1556
1557
1558
1559
                        for id in ls_ids:
                            tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                            full_resampled_path = tree.get('mmorf_warp_resampled_unbiased_full_T2')
                            premat_path = tree.get('T2_to_MNI_mat')
                            warp_path = tree.get('mmorf_warp_resampled_unbiased')
                            cmd = convertwarp(out=full_resampled_path, ref=img_ref_T1head_path, premat=premat_path,
                                              warp1=warp_path, cmdonly=True)
                            cmd = ' '.join(cmd) + '\n'
                            f.write(cmd)
1560
1561
                    # job_ids[35] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[32]])
                    job_ids[35] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[32]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1562
1563
1564
1565
1566
1567
1568
                    print('submitted: ' + task_name)

# DTI
                if mod['T2_head_key'] is not None and mod['DTI_tensor_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_concat_unbiased_warps_DTI'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1569
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1570
1571
1572
1573
1574
1575
1576
1577
1578
                        for id in ls_ids:
                            tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                            full_resampled_path = tree.get('mmorf_warp_resampled_unbiased_full_DTI')
                            premat_path = tree.get('DTI_to_MNI_mat')
                            warp_path = tree.get('mmorf_warp_resampled_unbiased')
                            cmd = convertwarp(out=full_resampled_path, ref=img_ref_T1head_path, premat=premat_path,
                                              warp1=warp_path, cmdonly=True)
                            cmd = ' '.join(cmd) + '\n'
                            f.write(cmd)
1579
1580
                    # job_ids[36] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[32]])
                    job_ids[36] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[32]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)
Christoph Arthofer's avatar
Christoph Arthofer committed
1581
1582
1583
1584
1585
1586
1587
1588
                    print('submitted: ' + task_name)

# Apply warps to images
# T1 brain
                if mod['T1_brain_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_warp_T1_brain'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1589
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1590
1591
1592
1593
1594
1595
                        for id in ls_ids:
                            tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                            img_path = tree.get(mod['T1_brain_key'])
                            warped_path = tree.get('warped_T1brain')
                            warp_path = tree.get('mmorf_warp_resampled_unbiased_full_T1brain')
                            jobcmd = func_to_cmd(applyWarpWrapper, args=(
1596
                            img_path, img_ref_T1head_path, warped_path, warp_path, 'spline', False),
Christoph Arthofer's avatar
Christoph Arthofer committed
1597
1598
                                                 tmp_dir=script_dir, kwargs=None, clean="never")
                            f.write(jobcmd + '\n')
1599
1600
                    # job_ids[37] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq, wait_for=[job_ids[33]])
                    job_ids[37] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=[job_ids[33]], array_task=True, jobram=jobram_low, jobtime=jobtime_low)