run_template_construction.py 100 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
17
18
import shlex
import subprocess
import sys
Christoph Arthofer's avatar
Christoph Arthofer committed
19
20
from fsl.wrappers import fslmaths,flirt,applyxfm,concatxfm,bet,fast,fslstats
from fsl.wrappers.fnirt import invwarp, applywarp, convertwarp
21
22
from file_tree import FileTree
# from fsl.utils.filetree import FileTree
Christoph Arthofer's avatar
Christoph Arthofer committed
23
24
25
26
from fsl.utils.fslsub import func_to_cmd
from operator import itemgetter
import tempfile
import argparse
27
import fsl_sub
Christoph Arthofer's avatar
Christoph Arthofer committed
28

Christoph Arthofer's avatar
Christoph Arthofer committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
56
            'use_mask_mov_scalar     = 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
            '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
96
            'use_mask_mov_scalar     = 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
            '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
136
            'use_mask_mov_scalar     = 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
            '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
176
            'use_mask_mov_scalar     = 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
            '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
216
            'use_mask_mov_scalar     = 1 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
            '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
256
            'use_mask_mov_scalar     = 1 1 1 1 1 1 1 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
            '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'

    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]
352
    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
353
    with tempfile.TemporaryDirectory(dir=out_dir) as tmpdirname:
354
355
        mask_path = os.path.join(tmpdirname, mask_name)
        bet(img_path, mask_path, robust=True)
Christoph Arthofer's avatar
Christoph Arthofer committed
356
357
358
359
360
361
362
363
364
365
        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)


366
def averageImages(img_paths, out_path, mod='average', norm_bool=False):
Christoph Arthofer's avatar
Christoph Arthofer committed
367
368
369
    """! Creates an average image from individual (non)normalised images.

    @param img_paths:             List of filepaths
370
    @param out_path:              Path to average/median output image
Christoph Arthofer's avatar
Christoph Arthofer committed
371
    @param mod:                   Choose between 'average' or 'median' image.
Christoph Arthofer's avatar
Christoph Arthofer committed
372
373
374
375
376
    @param norm_bool:             Normalise intensities of each image before averaging true or false

    """

    n_imgs = len(img_paths)
377
378
379
380
381
382
383
384
385
386
387
388
389
    n_exist = 0
    if mod == 'average':
        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
390
            else:
391
392
393
394
                print(i, ' ', img_path, ' does not exist!')

        if n_exist > 0:
            mean_img = fslmaths(sum_img).div(n_exist).run()
395
            mean_img.to_filename(out_path)
396
397
398
399
400
401
402
403
404
405
406
    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:
407
408
            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)
409
            median_nib.to_filename(out_path)
Christoph Arthofer's avatar
Christoph Arthofer committed
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434

    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
435
# https://git.fmrib.ox.ac.uk/fsl/fsl_sub
Christoph Arthofer's avatar
Christoph Arthofer committed
436
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):
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    coprocessor_class_strict = True if coprocessor_class is not None else False

    job_id = fsl_sub.submit(command=command,
                   array_task=array_task,
                   jobhold=wait_for,
                   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
                   )

    return job_id


# def submitJob(name, log_dir, queue, wait_for=[], script=None, command=None, coprocessor_class=None,
#                   coprocessor=None, export_var=None, debug=False):
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
458
#     """! Wrapper for fslsub - submits a job to the cluster. This function can be easily extended to work with other workload managers.
Christoph Arthofer's avatar
Christoph Arthofer committed
459
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
460
461
462
463
464
465
#     @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
466
#     @param coprocessor_class:     Coprocessor class
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
467
468
#     @param export_var:            Environment variables to be exported to the submission node
#     @param debug:                 If True, information about job will be written to output
Christoph Arthofer's avatar
Christoph Arthofer committed
469
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
470
471
472
#     @return  The job ID.
#     """
#     cmd = 'fsl_sub'
473
474
475
476
477
478
479
480
#
#     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):
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
481
#                 cmd += job.replace("\n", "")
482
#                 if j < len(wait_for_arr) - 1:
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
483
#                     cmd += ','
Christoph Arthofer's avatar
Christoph Arthofer committed
484
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
485
486
487
#     cmd += ' -N ' + name + \
#            ' -l ' + log_dir + \
#            ' -q ' + queue
Christoph Arthofer's avatar
Christoph Arthofer committed
488
#
489
490
491
492
493
#     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'
Christoph Arthofer's avatar
Christoph Arthofer committed
494
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
495
496
#     if export_var is not None :
#         cmd += ' --export ' + export_var
Christoph Arthofer's avatar
Christoph Arthofer committed
497
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
498
499
#     if debug:
#         cmd += ' --debug'
Christoph Arthofer's avatar
Christoph Arthofer committed
500
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
501
502
503
#     if script is not None and os.path.exists(script):
#         cmd += ' -t ' + script
#     elif command is not None :
504
505
#         cmd += ' ' + command + ' '
#         # cmd += ' "' + command + '"'
Christoph Arthofer's avatar
Christoph Arthofer committed
506
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
507
508
#     # stream = os.popen(cmd)
#     # job_id = stream.read()
Christoph Arthofer's avatar
Christoph Arthofer committed
509
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
510
#     try:
511
#         result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, check=True)
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
512
513
514
#     except subprocess.CalledProcessError as e:
#         print(str(e), file=sys.stderr)
#         return None
Christoph Arthofer's avatar
Christoph Arthofer committed
515
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
516
#     job_id = result.stdout.strip()
Christoph Arthofer's avatar
Christoph Arthofer committed
517
#
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
518
#     return job_id
Christoph Arthofer's avatar
Christoph Arthofer committed
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
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


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
711
712
713


if __name__ == "__main__":
714
715
716
    """! Main function submitting the jobs.
    """

Christoph Arthofer's avatar
Christoph Arthofer committed
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
760
761
762
763
764
765
766
767
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
    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

Christoph Arthofer's avatar
Christoph Arthofer committed
796
    job_ids = ['' for _ in range(100)]
Christoph Arthofer's avatar
Christoph Arthofer committed
797
798
    task_count = 0

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
799
800
    os.mkdir(base_dir, mode=0o770) if not os.path.exists(base_dir) else print(base_dir + ' exists')
    os.chmod(base_dir, 0o770)
Christoph Arthofer's avatar
Christoph Arthofer committed
801

802
    tree = FileTree.read(tree_path, top_level='')
Christoph Arthofer's avatar
Christoph Arthofer committed
803
804
805
    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
806
    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
807
    log_dir = tree.get('log_dir')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
808
    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
809
    misc_dir = tree.get('misc_dir')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
810
    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
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
    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'])

# Soft clamping of high skull intensities
        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
843
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
844
845
846
847
848
849
850
851
852
853
854
            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,
                                     clean="never")
                jobcmd = jobcmd + '\n'
855
                jobcmd = jobcmd + 'fslmaths ' + tree.get('data/lesion_mask_in_T1') + ' -bin ' + tree.get('inverse_lesion_mask_in_T1') + '\n'
Christoph Arthofer's avatar
Christoph Arthofer committed
856
                f.write(jobcmd)
857
858
        # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
859
860
861
862
863
864
        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
865
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
866
867
868
869
870
871
872
873
874
875
            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)
876
877
        # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
878
879
880
881
882
883
884
        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
885
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
886
887
888
889
890
891
                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)
892
            # job_ids[2] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
893
            job_ids[2] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=None, array_task=True)
894

Christoph Arthofer's avatar
Christoph Arthofer committed
895
896
897
898
899
900
901
            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
902
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
903
904
905
906
907
908
                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)
909
910
911
912
            # 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)

Christoph Arthofer's avatar
Christoph Arthofer committed
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
            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")
934
935
936
        # 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)

Christoph Arthofer's avatar
Christoph Arthofer committed
937
938
939
940
941
942
        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
943
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
944
945
946
947
948
949
            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)
950
951
952
        # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
953
954
955
956
957
958
959
        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
960
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
961
962
963
964
965
966
                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)
967
968
            # job_ids[6] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
            #                            wait_for=[job_ids[4]])
Christoph Arthofer's avatar
Christoph Arthofer committed
969
            job_ids[6] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=cpuq, wait_for=list(itemgetter(*[2,4])(job_ids)),
970
                                   array_task=True)
Christoph Arthofer's avatar
Christoph Arthofer committed
971
972
973
974
975
976
977
            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
978
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
979
980
981
982
983
984
                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)
985
986
987
988
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
989
990
991
992
993
994
995
996
997
998
999
            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')

1000
        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
1001
                             clean="never")
1002
1003
1004
        # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1005
1006
1007
1008
1009
1010
1011
1012
        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'
1013
1014
1015
        # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1016
1017
1018
1019
1020
1021
        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
1022
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1023
1024
1025
1026
1027
1028
            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)
1029
1030
1031
1032
        # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1033
1034
1035
1036
1037
1038
1039
        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
1040
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1041
1042
1043
1044
1045
1046
                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)
1047
1048
1049
1050
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1051
1052
1053
1054
1055
1056
1057
            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
1058
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1059
1060
1061
1062
1063
1064
                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)
1065
1066
1067
1068
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1069
1070
1071
1072
1073
1074
1075
            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
1076
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1077
1078
1079
1080
1081
1082
                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)
1083
1084
1085
1086
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1087
1088
1089
1090
1091
1092
1093
            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
1094
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1095
1096
1097
1098
1099
1100
1101
                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)
1102
1103
1104
1105
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1106
1107
1108
1109
1110
1111
1112
            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
1113
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1114
1115
1116
1117
1118
1119
                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)
1120
1121
1122
1123
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1124
1125
1126
1127
1128
1129
1130
            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
1131
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1132
1133
1134
1135
1136
1137
                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)
1138
1139
1140
1141
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1142
1143
1144
1145
1146
1147
1148
            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
1149
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1150
1151
1152
1153
1154
1155
                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)
1156
1157
1158
1159
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1160
1161
1162
1163
1164
1165
1166
            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
1167
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1168
1169
1170
1171
1172
1173
1174
1175
                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)
1176
1177
1178
1179
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
            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')

1192
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1193
                                 kwargs=None, clean="never")
1194
1195
1196
1197
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
            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')

1210
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'average', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1211
                                 kwargs=None, clean="never")
1212
1213
1214
1215
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1216
1217
1218
1219
            print('submitted: ' + task_name)

            task_name = '{:03d}_affT_create_weighted_brain_mask'.format(task_count)
            jobcmd = 'fslmaths ' + aff_template_path + ' -bin -mul 7 -add 1 -inm 1 ' + tree.get('T1_brain_mask_weighted_affine_template')
1220
1221
1222
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
            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')

1235
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1236
                                 kwargs=None, clean="never")
1237
1238
1239
1240
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
            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')

1253
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1254
                                 kwargs=None, clean="never")
1255
1256
1257
1258
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
            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')

1271
            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, 'median', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1272
                                 kwargs=None, clean="never")
1273
1274
1275
1276
            # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
            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]) + '"'}

1295
1296
1297
            # 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]],
1298
                                    array_task=False, export_var=[export_var_str['SINGULARITY_BIND']])
Christoph Arthofer's avatar
Christoph Arthofer committed
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
            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')
1320
                    img_ref_tensor_path = tree.get('DTI_tensor_affine_template')
Christoph Arthofer's avatar
Christoph Arthofer committed
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
                    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')
1334
                    img_ref_tensor_path = tree.get('DTI_tensor_nln_template')
Christoph Arthofer's avatar
Christoph Arthofer committed
1335
1336
1337
1338
1339
1340
1341
1342
1343
                    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
1344
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
                    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]
1381
                            mask_mov_scalar = [tree.get('data/inverse_lesion_mask_in_T1')]
Christoph Arthofer's avatar
Christoph Arthofer committed
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
                            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]) + '"'

1418
1419
1420
1421
1422
                # job_ids[28] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=gpuq,
                #                         wait_for=list(itemgetter(*[21, 23, 24, 25, 26, 27, 28, 44, 45, 46, 47, 48, 50])(job_ids)),
                #                         coprocessor_class=None, coprocessor='cuda',
                #                         export_var=export_var_str['SINGULARITY_BIND'], debug=False)
                job_ids[28] = submitJob(script_path, tag + '_' + task_name, log_dir, queue=gpuq,
Christoph Arthofer's avatar
Christoph Arthofer committed
1423
                                        wait_for=list(itemgetter(*[21, 23, 24, 25, 26, 27, 28, 44, 45, 46, 47, 48, 50])(job_ids)),
Christoph Arthofer's avatar
Christoph Arthofer committed
1424
                                        array_task=True, coprocessor='cuda', coprocessor_class=None, coprocessor_multi="1", threads=1, export_var=[export_var_str['SINGULARITY_BIND']])
Christoph Arthofer's avatar
Christoph Arthofer committed
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
                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')

1436
                jobcmd = func_to_cmd(averageImages, args=(warp_paths, avg_warp_path, 'average', False), tmp_dir=script_dir,
Christoph Arthofer's avatar
Christoph Arthofer committed
1437
                                     kwargs=None, clean="never")
1438
1439
1440
1441
                # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1442
1443
1444
1445
1446
1447
1448
1449
1450
                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'
1451
1452
1453
1454
                # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1455
1456
1457
1458
1459
1460
                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
1461
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1462
1463
1464
1465
1466
1467
1468
1469
1470
                    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')
1471
1472
1473
1474
                # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1475
1476
1477
1478
1479
                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
1480
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1481
1482
1483
1484
                    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')
1485
1486
1487
1488
                # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1489
1490
1491
1492
1493
1494
1495
                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
1496
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1497
1498
1499
1500
1501
1502
1503
1504
1505
                    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)
1506
1507
1508
1509
                # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1510
1511
1512
1513
1514
1515
1516
                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
1517
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1518
1519
1520
1521
1522
1523
1524
1525
1526
                        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)
1527
1528
1529
1530
                    # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1531
1532
1533
1534
1535
1536
1537
                    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
1538
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1539
1540
1541
1542
1543
1544
1545
1546
1547
                        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)
1548
1549
1550
1551
                    # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1552
1553
1554
1555
1556
1557
1558
                    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
1559
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1560
1561
1562
1563
1564
1565
1566
1567
1568
                        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)
1569
1570
1571
1572
                    # 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)
Christoph Arthofer's avatar
Christoph Arthofer committed
1573
1574
1575
1576
1577
1578
1579
1580
                    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
1581
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1582
1583
1584
1585
1586
1587
                        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=(
1588
                            img_path, img_ref_T1head_path, warped_path, warp_path, 'spline', False),
Christoph Arthofer's avatar
Christoph Arthofer committed
1589
1590
                                                 tmp_dir=script_dir, kwargs=None, clean="never")
                            f.write(jobcmd + '\n')
1591
1592
1593
1594
                    # job_ids[37] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,