run_template_construction.py 91.2 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
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
27
# import fsl_sub
Christoph Arthofer's avatar
Christoph Arthofer committed
28
29

def writeConfig(step,mod,fpath):
30
31
32
33
34
35
36
37
    """! 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

    """

Christoph Arthofer's avatar
Christoph Arthofer committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    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' \
56
            'use_mask_mov_scalar     = 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
57
58
59
60
61
62
63
64
65
66
67
            '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' \
68
            'use_mask_mov_scalar     = 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
69
70
71
72
73
74
75
76
77
78
            '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' \
79
            'use_mask_mov_tensor     = 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
            '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' \
96
            'use_mask_mov_scalar     = 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
97
98
99
100
101
102
103
104
105
106
107
            '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' \
108
            'use_mask_mov_scalar     = 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
109
110
111
112
113
114
115
116
117
118
            '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' \
119
            'use_mask_mov_tensor     = 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
            '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' \
136
            'use_mask_mov_scalar     = 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
137
138
139
140
141
142
143
144
145
146
147
            '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' \
148
            'use_mask_mov_scalar     = 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
149
150
151
152
153
154
155
156
157
158
            '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' \
159
            'use_mask_mov_tensor     = 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
            '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' \
176
            'use_mask_mov_scalar     = 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
177
178
179
180
181
182
183
184
185
186
187
            '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' \
188
            'use_mask_mov_scalar     = 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
189
190
191
192
193
194
195
196
197
198
            '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' \
199
            'use_mask_mov_tensor     = 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
            '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' \
216
            'use_mask_mov_scalar     = 0 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
217
218
219
220
221
222
223
224
225
226
227
            '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' \
228
            'use_mask_mov_scalar     = 0 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
229
230
231
232
233
234
235
236
237
238
            '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' \
239
            'use_mask_mov_tensor     = 0 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
            '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' \
256
            'use_mask_mov_scalar     = 0 0 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
257
258
259
260
261
262
263
264
265
266
267
            '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' \
268
            'use_mask_mov_scalar     = 0 0 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
269
270
271
272
273
274
275
276
277
278
            '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' \
279
            'use_mask_mov_tensor     = 0 0 0 0 0 0 0 \n' \
Christoph Arthofer's avatar
Christoph Arthofer committed
280
281
282
283
            'fwhm_ref_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'fwhm_mov_tensor         = 8.0 8.0 4.0 2.0 1.0 0.5 0.25 \n' \
            'lambda_tensor           = 1 1 1 1 1 1 1 \n'

Christoph Arthofer's avatar
Christoph Arthofer committed
284
    f = open(fpath, 'w+')
Christoph Arthofer's avatar
Christoph Arthofer committed
285
286
287
288
289
    f.write(s)
    f.close()


def correctBiasMidtransWrapper(aff_matrix_paths, temp_dir, ref_path, unbiasing_invmtx_path, unbiased_matrix_paths):
290
291
292
293
294
295
296
297
298
    """! 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

    """
Christoph Arthofer's avatar
Christoph Arthofer committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
    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):
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    """! 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

    """
Christoph Arthofer's avatar
Christoph Arthofer committed
337
338
339
340
341
342
343

    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):
344
345
346
347
348
349
350
    """! Performs preprocessing steps and clamping on an image.

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

    """

Christoph Arthofer's avatar
Christoph Arthofer committed
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
    out_dir = os.path.split(out_path)[0]
    mask_path = os.path.splitext(os.path.splitext(os.path.basename(out_path))[0])[0] + '_brain.nii.gz'
    mask_path = os.path.join(out_dir, mask_path)
    bet(img_path, mask_path, robust=True)
    with tempfile.TemporaryDirectory(dir=out_dir) as tmpdirname:
        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)


def averageImages(img_paths, out_path, norm_bool=False):
367
368
369
370
371
372
373
374
    """! Creates an average image from individual (non)normalised images.

    @param img_paths:             List of filepaths
    @param out_path:              Path to average output image
    @param norm_bool:             Normalise intensities of each image before averaging true or false

    """

Christoph Arthofer's avatar
Christoph Arthofer committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
    n_exist = 0
    n_imgs = len(img_paths)
    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()
        else:
            print(i, ' ', img_path, ' does not exist!')

    if n_exist > 0:
        mean_img = fslmaths(sum_img).div(n_exist).run()
        mean_img.to_filename(out_path)

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


def applyWarpWrapper(img_path, ref_path, warped_path, warp_path, interp='spline', norm_bool=False):
399
400
401
402
403
404
405
406
407
408
409
    """! 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

    """

Christoph Arthofer's avatar
Christoph Arthofer committed
410
411
412
413
414
415
416
417
418
    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
fslsub    
Christoph Arthofer committed
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# def submitJob_fsl_sub(name, log_dir, queue, wait_for=[], script=None, command=None, coprocessor_class=None, export_var=None,
#                   debug=False):
#     """! Wrapper for fslsub - submits a job to the cluster. This function can be easily extended to work with other workload managers.
#
#     @param name:                  Job name
#     @param log_dir:               Directory where output log-files will be saved
#     @param queue:                 Name of queue to submit the job to
#     @param wait_for:              List of IDs of jobs required to finish before running this job.
#     @param script:                Path to a shell script, which contains one command per line - commands will be submitted as an array job
#     @param command:               Alternatively a single command can be provided as a string - command will be submitted as single job
#     @param coprocessor_class:     Coprocessor class, if not None cuda will be selected
#     @param export_var:            Environment variables to be exported to the submission node
#     @param debug:                 If True, information about job will be written to output
#
#     @return  The job ID.
#     """
#
#     fsl_sub.submit()
#
#     cmd = 'fsl_sub'
#     if wait_for and any(job != '' for job in wait_for):
#         cmd += ' -j '
#         for j, job in enumerate(wait_for):
#             if job != '':
#                 cmd += job.replace("\n", "")
#                 if j < len(wait_for) - 1:
#                     cmd += ','
#
#     cmd += ' -N ' + name + \
#            ' -l ' + log_dir + \
#            ' -q ' + queue
#
#     if coprocessor_class is not None :
#         cmd += ' --coprocessor cuda'
#
#     if export_var is not None :
#         cmd += ' --export ' + export_var
#
#     if debug:
#         cmd += ' --debug'
#
#     if script is not None and os.path.exists(script):
#         cmd += ' -t ' + script
#     elif command is not None :
#         cmd += shlex.split(command)
#
#     # stream = os.popen(cmd)
#     # job_id = stream.read()
#
#     try:
#         result = subprocess.run(command, capture_output, text=True, check=True)
#     except subprocess.CalledProcessError as e:
#         print(str(e), file=sys.stderr)
#         return None
#
#     job_id = result.stdout.strip()
#
#     return job_id


Christoph Arthofer's avatar
Christoph Arthofer committed
479
480
def submitJob(name, log_dir, queue, wait_for=[], script=None, command=None, coprocessor_class=None, export_var=None,
                  debug=False):
481
482
483
484
485
486
    """! Wrapper for fslsub - submits a job to the cluster. This function can be easily extended to work with other workload managers.

    @param name:                  Job name
    @param log_dir:               Directory where output log-files will be saved
    @param queue:                 Name of queue to submit the job to
    @param wait_for:              List of IDs of jobs required to finish before running this job.
487
488
    @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
489
490
491
492
493
494
    @param coprocessor_class:     Coprocessor class, if not None cuda will be selected
    @param export_var:            Environment variables to be exported to the submission node
    @param debug:                 If True, information about job will be written to output

    @return  The job ID.
    """
Christoph Arthofer's avatar
Christoph Arthofer committed
495
496
497
498
499
500
501
502
503
504
505
506
507
    cmd = 'fsl_sub'
    if wait_for and any(job != '' for job in wait_for):
        cmd += ' -j '
        for j, job in enumerate(wait_for):
            if job != '':
                cmd += job.replace("\n", "")
                if j < len(wait_for) - 1:
                    cmd += ','

    cmd += ' -N ' + name + \
           ' -l ' + log_dir + \
           ' -q ' + queue

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
508
    if coprocessor_class is not None :
Christoph Arthofer's avatar
Christoph Arthofer committed
509
510
        cmd += ' --coprocessor cuda'

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
511
    if export_var is not None :
Christoph Arthofer's avatar
Christoph Arthofer committed
512
513
514
515
516
        cmd += ' --export ' + export_var

    if debug:
        cmd += ' --debug'

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
517
    if script is not None and os.path.exists(script):
Christoph Arthofer's avatar
Christoph Arthofer committed
518
        cmd += ' -t ' + script
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
519
    elif command is not None :
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
520
        cmd += ' "' + command + '"'
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
521
522
523

    # stream = os.popen(cmd)
    # job_id = stream.read()
Christoph Arthofer's avatar
Christoph Arthofer committed
524

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
525
526
    print(cmd)

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
527
    try:
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
528
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, check=True)
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
529
530
531
532
533
    except subprocess.CalledProcessError as e:
        print(str(e), file=sys.stderr)
        return None

    job_id = result.stdout.strip()
Christoph Arthofer's avatar
Christoph Arthofer committed
534
535
536

    return job_id

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
537

Christoph Arthofer's avatar
Christoph Arthofer committed
538
def RMSdifference(img1_path, img2_path, mask1_path=None, mask2_path=None, rms_path=None):
539
540
541
542
543
544
545
546
547
548
    """! 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

    """

Christoph Arthofer's avatar
Christoph Arthofer committed
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
    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:
Christoph Arthofer's avatar
Christoph Arthofer committed
578
        with open(rms_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
579
580
581
582
            f.write('{}'.format(rms))


def RMSstandardDeviation(img_paths, mean_img_path, mask_path, sd_img_out_path=None, rms_out_path=None):
583
584
585
586
587
588
589
590
591
592
    """! 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

    """

Christoph Arthofer's avatar
Christoph Arthofer committed
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
    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:
Christoph Arthofer's avatar
Christoph Arthofer committed
621
        with open(rms_out_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
622
623
624
            f.write('{}'.format(rms))


625
626
627
628
629
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,
Christoph Arthofer's avatar
Christoph Arthofer committed
630
                 warp_out, jac_det_out, bias_out):
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
    """! 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.

    """

Christoph Arthofer's avatar
Christoph Arthofer committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
    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


if __name__ == "__main__":
731
732
733
    """! Main function submitting the jobs.
    """

Christoph Arthofer's avatar
Christoph Arthofer committed
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
    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

    job_ids = ['' for _ in range(100)]
    task_count = 0

Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
816
817
    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
818

819
    tree = FileTree.read(tree_path, top_level='')
Christoph Arthofer's avatar
Christoph Arthofer committed
820
821
822
    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
823
    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
824
    log_dir = tree.get('log_dir')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
825
    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
826
    misc_dir = tree.get('misc_dir')
Christoph Arthofer's avatar
fslsub    
Christoph Arthofer committed
827
    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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
    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
860
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
            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'
                f.write(jobcmd)
        job_ids[0] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
        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
880
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
            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)
        job_ids[1] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
        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
899
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
                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)
            job_ids[2] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
            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
914
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
                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)
            job_ids[3] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq)
            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")
        job_ids[4] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[1]])
        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
950
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
            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)
        job_ids[5] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                   wait_for=[job_ids[4]])
        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
966
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
                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)
            job_ids[6] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                       wait_for=[job_ids[4]])
            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
982
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
                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)
            job_ids[7] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                       wait_for=[job_ids[6]])
            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')

        jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, True), tmp_dir=script_dir, kwargs=None,
                             clean="never")
        job_ids[8] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[5]])
        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'
        job_ids[9] = submitJob(tag+'_'+task_name, log_dir, command=cmd, queue=cpuq, wait_for=[job_ids[8]])
        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
1020
        with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
            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)
        job_ids[10] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                    wait_for=[job_ids[9]])
        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
1036
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
                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)
            job_ids[12] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=[job_ids[9]])
            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
1052
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
                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)
            job_ids[14] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=[job_ids[9]])
            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
1068
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
                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)
            job_ids[15] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=[job_ids[10]])
            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
1084
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
                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)
            job_ids[16] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=[job_ids[10]])
            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
1101
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
                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)
            job_ids[17] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=list(itemgetter(*[0, 10])(job_ids)))
            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
1117
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
                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)
            job_ids[18] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=[job_ids[12]])
            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
1133
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
                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)
            job_ids[19] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=[job_ids[14]])
            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
1149
            with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
                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)
            job_ids[20] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                        wait_for=[job_ids[14]])
            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')

            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, True), tmp_dir=script_dir,
                                 kwargs=None, clean="never")
            job_ids[21] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                        wait_for=[job_ids[15]])
            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')

            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, False), tmp_dir=script_dir,
                                 kwargs=None, clean="never")
            job_ids[22] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                        wait_for=[job_ids[16]])
            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')
            job_ids[23] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq, wait_for=[job_ids[22]])
            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')

            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, True), tmp_dir=script_dir,
                                 kwargs=None, clean="never")
            job_ids[24] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                        wait_for=[job_ids[17]])
            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')

            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, True), tmp_dir=script_dir,
                                 kwargs=None, clean="never")
            job_ids[25] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                        wait_for=[job_ids[18]])
            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')

            jobcmd = func_to_cmd(averageImages, args=(img_paths, aff_template_path, True), tmp_dir=script_dir,
                                 kwargs=None, clean="never")
            job_ids[26] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                        wait_for=[job_ids[19]])
            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]) + '"'}

            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]])
            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')
1286
                    img_ref_tensor_path = tree.get('DTI_tensor_affine_template')
Christoph Arthofer's avatar
Christoph Arthofer committed
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
                    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')
1300
                    img_ref_tensor_path = tree.get('DTI_tensor_nln_template')
Christoph Arthofer's avatar
Christoph Arthofer committed
1301
1302
1303
1304
1305
1306
1307
1308
1309
                    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
1310
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
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
1381
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
1418
1419
1420
                    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]
                            mask_mov_scalar = ['NULL']
                            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]) + '"'

                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='P',
                                            export_var=export_var_str['SINGULARITY_BIND'], debug=False)
                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')

                jobcmd = func_to_cmd(averageImages, args=(warp_paths, avg_warp_path, False), tmp_dir=script_dir,
                                     kwargs=None, clean="never")
                job_ids[29] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                            wait_for=[job_ids[28]])
                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'
                job_ids[30] = submitJob(tag+'_'+task_name, log_dir, command=cmd, queue=cpuq,
                                            wait_for=[job_ids[29]])
                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
1421
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
                    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')
                job_ids[31] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                            wait_for=[job_ids[30]])
                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
1438
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
                    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')
                job_ids[32] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                            wait_for=[job_ids[31]])
                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
1452
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1453
1454
1455
1456
1457
1458
1459
1460
1461
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))
                        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)
                job_ids[33] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                            wait_for=[job_ids[32]])
                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
1471
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
                        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)
                    job_ids[34] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[32]])
                    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
1490
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
                        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)
                    job_ids[35] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[32]])
                    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
1509
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
                        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)
                    job_ids[36] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[32]])
                    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
1529
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1530
1531
1532
1533
1534
1535
                        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=(
1536
                            img_path, img_ref_T1head_path, warped_path, warp_path, 'spline', False),
Christoph Arthofer's avatar
Christoph Arthofer committed
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
                                                 tmp_dir=script_dir, kwargs=None, clean="never")
                            f.write(jobcmd + '\n')
                    job_ids[37] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[33]])
                    print('submitted: ' + task_name)

# T1 brain mask
                task_count += 1
                task_name = '{:03d}_nlnT_warp_T1_brain_mask'.format(task_count)
                script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1547
                with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1548
1549
1550
1551
1552
1553
                    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_mask_key'])
                        warped_path = tree.get('warped_T1brain_mask')
                        warp_path = tree.get('mmorf_warp_resampled_unbiased_full_T1brain')
                        jobcmd = func_to_cmd(applyWarpWrapper,
1554
                                             args=(img_path, img_ref_T1head_path, warped_path, warp_path, 'nn', False),
Christoph Arthofer's avatar
Christoph Arthofer committed
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
                                             tmp_dir=script_dir, kwargs=None, clean="never")
                        f.write(jobcmd + '\n')
                job_ids[38] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                            wait_for=list(itemgetter(*[33, 34])(job_ids)))
                print('submitted: ' + task_name)

# T1 head
                if mod['T1_head_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_warp_T1_head'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
                    if step == step_id[-1] and it == it_at_step_id[-1]:
                        T1_head_key_temp = mod['T1_head_key']
                    else:
                        T1_head_key_temp = 'T1_head_clamped'
Christoph Arthofer's avatar
Christoph Arthofer committed
1570
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1571
1572
1573
1574
1575
1576
                        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(T1_head_key_temp)
                            warped_path = tree.get('warped_T1head')
                            warp_path = tree.get('mmorf_warp_resampled_unbiased_full_T1head')
                            jobcmd = func_to_cmd(applyWarpWrapper, args=(
1577
                            img_path, img_ref_T1head_path, warped_path, warp_path, 'spline', False),
Christoph Arthofer's avatar
Christoph Arthofer committed
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
                                                 tmp_dir=script_dir, kwargs=None, clean="never")
                            f.write(jobcmd + '\n')
                    job_ids[39] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[34]])
                    print('submitted: ' + task_name)

# T2 head
                if mod['T2_head_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_warp_T2_head'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1589
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1590
1591
1592
1593
1594
1595
                        for id in ls_ids:
                            tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                            img_path = tree.get(mod['T2_head_key'])
                            warped_path = tree.get('warped_T2head')
                            warp_path = tree.get('mmorf_warp_resampled_unbiased_full_T2')
                            jobcmd = func_to_cmd(applyWarpWrapper, args=(
1596
                            img_path, img_ref_T1head_path, warped_path, warp_path, 'spline', False),
Christoph Arthofer's avatar
Christoph Arthofer committed
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
                                                 tmp_dir=script_dir, kwargs=None, clean="never")
                            f.write(jobcmd + '\n')
                    job_ids[40] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[35]])
                    print('submitted: ' + task_name)

# scalar DTI
                if mod['T2_head_key'] is not None and mod['DTI_scalar_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_warp_DTI_scalar'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1608
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
                        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['DTI_scalar_key'])
                            warped_path = tree.get('warped_DTIscalar')
                            warp_path = tree.get('mmorf_warp_resampled_unbiased_full_DTI')
                            jobcmd = func_to_cmd(applyWarpWrapper, args=(
                            img_path, img_ref_T1head_path, warped_path, warp_path, 'spline', True),
                                                 tmp_dir=script_dir, kwargs=None, clean="never")
                            f.write(jobcmd + '\n')
                    job_ids[42] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[36]])
                    print('submitted: ' + task_name)

# DTI tensor
                if mod['T2_head_key'] is not None and mod['DTI_tensor_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_warp_DTI_tensor'.format(task_count)
                    script_path = os.path.join(script_dir, task_name + '.sh')
Christoph Arthofer's avatar
Christoph Arthofer committed
1627
                    with open(script_path, 'w+') as f:
Christoph Arthofer's avatar
Christoph Arthofer committed
1628
1629
1630
                        for id in ls_ids:
                            tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                            cmd = 'vecreg -i ' + tree.get('data/DTI_tensor') + \
1631
                                  ' -r ' + img_ref_T1head_path + \
Christoph Arthofer's avatar
Christoph Arthofer committed
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
                                  ' -o ' + tree.get('warped_DTItensor') + \
                                  ' -w ' + tree.get('mmorf_warp_resampled_unbiased_full_DTI') + \
                                  ' --interp=spline \n'
                            f.write(cmd)
                    job_ids[43] = submitJob(tag+'_'+task_name, log_dir, script=script_path, queue=cpuq,
                                                wait_for=[job_ids[36]])
                    print('submitted: ' + task_name)

# Averaging transformed T1 brain images in template space
                if mod['T1_brain_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_average_T1_brain'.format(task_count)
                    img_paths = []
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        img_paths.append(tree.get('warped_T1brain'))
                    nln_template_path = tree.get('T1_brain_nln_template')

                    jobcmd = func_to_cmd(averageImages, args=(img_paths, nln_template_path, True), tmp_dir=script_dir,
                                         kwargs=None, clean="never")
                    job_ids[44] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                                wait_for=[job_ids[37]])
                    print('submitted: ' + task_name)

# Averaging transformed T1 whole-head images in template space
                if mod['T1_head_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_average_T1_head'.format(task_count)
                    img_paths = []
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        img_paths.append(tree.get('warped_T1head'))
                    nln_template_path = tree.get('T1_head_nln_template')

                    jobcmd = func_to_cmd(averageImages, args=(img_paths, nln_template_path, True), tmp_dir=script_dir,
                                         kwargs=None, clean="never")
                    job_ids[45] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                                wait_for=[job_ids[39]])
                    print('submitted: ' + task_name)

# Averaging transformed T2 whole-head images in template space
                if mod['T2_head_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_average_T2_head'.format(task_count)
                    img_paths = []
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        img_paths.append(tree.get('warped_T2head'))
                    nln_template_path = tree.get('T2_head_nln_template')

                    jobcmd = func_to_cmd(averageImages, args=(img_paths, nln_template_path, True), tmp_dir=script_dir,
                                         kwargs=None, clean="never")
                    job_ids[46] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                                wait_for=[job_ids[40]])
                    print('submitted: ' + task_name)

# Averaging transformed DTI images in template space
                if mod['T2_head_key'] is not None and mod['DTI_scalar_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_average_DTI_scalar'.format(task_count)
                    img_paths = []
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        img_paths.append(tree.get('warped_DTIscalar'))
                    nln_template_path = tree.get('DTI_nln_template')

                    jobcmd = func_to_cmd(averageImages, args=(img_paths, nln_template_path, True), tmp_dir=script_dir,
                                         kwargs=None, clean="never")
                    job_ids[47] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                                wait_for=[job_ids[42]])
                    print('submitted: ' + task_name)

# Averaging transformed DTI tensors in template space
                if mod['T2_head_key'] is not None and mod['DTI_tensor_key'] is not None:
                    task_count += 1
                    task_name = '{:03d}_nlnT_average_DTI_tensor'.format(task_count)
                    export_paths = []
                    cmd = mmorf_exec_cmd + ' tensor_average' + ' -i '
                    for id in ls_ids:
                        tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                        cmd += tree.get('warped_DTItensor') + ' '
                        export_paths.append(tree.get('warped_DTItensor'))
                    cmd += '-o ' + tree.get('DTI_tensor_nln_template')
                    export_paths.append(tree.get('DTI_tensor_nln_template'))

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

                    job_ids[48] = submitJob(tag+'_'+task_name, log_dir, command=cmd, queue=cpuq,
                                                export_var=export_var_str['SINGULARITY_BIND'], wait_for=[job_ids[43]])
                    print('submitted: ' + task_name)

# Averaging transformed T1 brain masks in template space
                task_count += 1
                task_name = '{:03d}_nlnT_average_T1_brain_mask'.format(task_count)
                img_paths = []
                for id in ls_ids:
                    tree = tree.update(sub_id=id, step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                    img_paths.append(tree.get('warped_T1brain_mask'))
                nln_template_path = tree.get('T1_brain_mask_nln_template')

                jobcmd = func_to_cmd(averageImages, args=(img_paths, nln_template_path, False), tmp_dir=script_dir,
                                     kwargs=None, clean="never")
                job_ids[49] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                            wait_for=[job_ids[38]])
                print('submitted: ' + task_name)

                task_count += 1
                task_name = '{:03d}_nlnT_average_T1_brain_mask_weighted'.format(task_count)
                jobcmd = 'fslmaths ' + nln_template_path + ' -bin -mul 7 -add 1 -inm 1 ' + tree.get(
                    'T1_brain_mask_weighted_nln_template')
                job_ids[50] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                            wait_for=[job_ids[49]])
                print('submitted: ' + task_name)

# Convergence monitoring
# Difference in average warp between consecutive iterations
                if it_total > 1:
                    task_count += 1
                    task_name = '{:03d}_nlnT_average_warp_diff'.format(task_count)
                    tree = tree.update(step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                    avgwarp_curr_it_path = tree.get('avg_warp')
                    avgmask_curr_it_path = tree.get('T1_brain_mask_nln_template')
                    jobcmd = func_to_cmd(RMSdifference, args=(
                    avgwarp_curr_it_path, avgwarp_prev_it_path, avgmask_curr_it_path, avgmask_prev_it_path,
                    tree.get('delta_avgwarp_output')),
                                         tmp_dir=script_dir, kwargs=None,
                                         clean="never")
                    job_ids[51] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
                                                wait_for=list(itemgetter(*[29, 49])(job_ids)))
                    print('submitted: ' + task_name)

# Difference in template intensity between consecutive iterations
                if it_total > 1:
                    task_count += 1
                    task_name = '{:03d}_nlnT_temp_intensity_diff'.format(task_count)
                    tree = tree.update(step_id='{:02d}'.format(step), it_id='{:02d}'.format(it))
                    nln_template_curr_it_path = tree.get('T1_brain_nln_template')
                    avgmask_curr_it_path = tree.get('T1_brain_mask_nln_template')
                    jobcmd = func_to_cmd(RMSdifference, args=(
                    nln_template_curr_it_path, img_ref_T1brain_path, avgmask_curr_it_path, avgmask_prev_it_path,
                    tree.get('delta_intensity_output')),
                                         tmp_dir=script_dir, kwargs=None,
                                         clean="never")
                    job_ids[52] = submitJob(tag+'_'+task_name, log_dir, command=jobcmd, queue=cpuq,
1777
                                                wait_for=list(itemgetter(*[44,49])(job_ids)))
Christoph Arthofer's avatar
Christoph Arthofer committed
1778
1779
1780
1781