Commit 619d23f1 authored by Christoph Arthofer's avatar Christoph Arthofer
Browse files

include function documentation

parent 6f74a38d
......@@ -41,7 +41,7 @@ Directory containing the defaced subjects/timepoints
#### `-t <path>, --tree <path>`
Path to FSL Filetree describing the subject-specific directory structure and selection of modalities.
The input file structure of the data (i.e. can be a timepoint or a subject) has to be defined in the FSL filetree located in `./tree/data.tree`.
The input file structure of the data (i.e. can be a timepoint or a subject) has to be defined in the FSL filetree located in `./config/data.tree`.
To construct a combined T1, T2 and DTI template the locations and filenames of e.g. whole-head, brain-extracted and brain masks with respect to
the timepoint's directory have to be specified. In the template construction code these will be accessed through Filetree keys,
which must not be altered or removed.
......@@ -50,7 +50,7 @@ Required keys for T1: T1_head, T1_brain, T1_brain_mask
Required keys for T1+T2: T1_head, T1_brain, T1_brain_mask, T2_head, T2_brain
Required keys for T1+T2+DTI: T1_head, T1_brain, T1_brain_mask, T2_head, T2_brain, DTI_scalar, DTI_tensor
For example to construct a combined T1, T2 and DTI template `./tree/data.tree` could look like:
For example to construct a combined T1, T2 and DTI template `./config/data.tree` could look like:
```bash
{sub_id}
......@@ -114,7 +114,7 @@ A typical command for within-subject template construction given multiple timepo
export MMORFDIR=/path/to/mmorf.sif
python run_template_construction.py
-i /full/path/to/subject/containing/timepoint/directories/
-t ./tree/MS_template.tree
-t ./config/MS_template.tree
-o /full/path/to/output/directory/
-aff True
-nln True
......
......@@ -4,6 +4,15 @@
# Author: Christoph Arthofer
# Copyright: FMRIB 2021
#
# run_template_construction.py - allows construction of multimodal templates
#
# 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.
"""
import os
import shutil
import pandas as pd
......@@ -18,10 +27,19 @@ import tempfile
import argparse
import sys
# use_mask_mov_scalar
# use_mask_mov_tensor
def writeConfig(step,mod,fpath):
"""! Writes the nonlinear registration parameters for a given resolution level and modalities to a file readable by MMORF.
@param step: Resolution level provided as integer
@param mod: Modalities provided as a dictionary
@param fpath: Output filepath
"""
# For future use of individual subject masks:
# use_mask_mov_scalar
# use_mask_mov_tensor
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
......@@ -256,6 +274,15 @@ def writeConfig(step,mod,fpath):
def correctBiasMidtransWrapper(aff_matrix_paths, temp_dir, ref_path, unbiasing_invmtx_path, unbiased_matrix_paths):
"""! Writes the nonlinear registration parameters for a given resolution level and modalities to a file readable by MMORF.
@param aff_matrix_paths: List of filepaths to affine transformations
@param temp_dir: Output directory
@param ref_path: Path to reference template
@param unbiasing_invmtx_path: Path to unbiasing matrix
@param unbiased_matrix_paths: List of filepaths to unbiased transformations
"""
separate_path = os.path.join(temp_dir, 'T1_to_unbiased')
command = 'midtrans -v --separate=' + separate_path + ' --template=' + ref_path + ' -o ' + unbiasing_invmtx_path + ' '
count = 0
......@@ -280,16 +307,20 @@ def correctBiasMidtransWrapper(aff_matrix_paths, temp_dir, ref_path, unbiasing_i
def soft_clamp(x, k):
# Piecewise function for soft intensity clamping of T1 images.
# Takes a single parameter k which defines the transition to the clamping part of the
# function
#
# f(x) = 0 | x <= 0
# f(x) = x | 0 < x <= k
# f(x) = 3k/4 + k/(2(1 + exp(-8(x - k)/k))) | x > k
# Date: 08/02/2021
# Author: Frederik J Lange
# Copyright: FMRIB 2021
"""! Piecewise function for soft intensity clamping of T1 images. Takes a single parameter k which defines the transition to the clamping part of the function.
f(x) = 0 | x <= 0
f(x) = x | 0 < x <= k
f(x) = 3k/4 + k/(2(1 + exp(-8(x - k)/k))) | x > k
@param x: Image as numpy array
@param k: Defines the transition to the clamping part of the function
Date: 08/02/2021
Author: Frederik J Lange
Copyright: FMRIB 2021
"""
return np.piecewise(x,
[x <= 0, (0 < x) & (x <= k), x > k],
......@@ -297,6 +328,13 @@ def soft_clamp(x, k):
def clampImage(img_path, out_path):
"""! Performs preprocessing steps and clamping on an image.
@param img_path: Path to input image
@param out_path: Path to clamped output image
"""
out_dir = os.path.split(out_path)[0]
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)
......@@ -313,6 +351,14 @@ def clampImage(img_path, out_path):
def averageImages(img_paths, out_path, norm_bool=False):
"""! 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
"""
n_exist = 0
n_imgs = len(img_paths)
for i, img_path in enumerate(img_paths):
......@@ -337,6 +383,17 @@ def averageImages(img_paths, out_path, norm_bool=False):
def applyWarpWrapper(img_path, ref_path, warped_path, warp_path, interp='spline', norm_bool=False):
"""! Wrapper for FSL applywarp - applies a warp (deformation field) to an image.
@param img_path: Path to input image
@param ref_path: Path to reference image
@param warped_path: Path to warped output image
@param warp_path: Path to warp (deformation field)
@param interp: Interpolation method (same options as FSL applywarp)
@param norm_bool: Normalise intensities of each image before averaging true or false
"""
print(img_path, warp_path)
if os.path.exists(img_path):
img_nib = nib.load(img_path)
......@@ -348,6 +405,21 @@ def applyWarpWrapper(img_path, ref_path, warped_path, warp_path, interp='spline'
def submitJob(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: Function can take path to a shell script, which contains one command per line - commands will be submitted as an array job
@param command: Alternatively function can take a command 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.
"""
cmd = 'fsl_sub'
if wait_for and any(job != '' for job in wait_for):
cmd += ' -j '
......@@ -382,6 +454,16 @@ def submitJob(name, log_dir, queue, wait_for=[], script=None, command=None, copr
def RMSdifference(img1_path, img2_path, mask1_path=None, mask2_path=None, rms_path=None):
"""! Calculates the difference between two images or warps as the root mean squared (RMS)
@param img1_path: Path to first image or deformation field
@param img2_path: Path to second image or deformation field
@param mask1_path: Path to mask for first image
@param mask2_path: Path to mask for second image
@param rms_path: Path to output text file that RMS is written to
"""
img1_arr = nib.load(img1_path).get_fdata()
img2_arr = nib.load(img2_path).get_fdata()
......@@ -416,6 +498,16 @@ def RMSdifference(img1_path, img2_path, mask1_path=None, mask2_path=None, rms_pa
def RMSstandardDeviation(img_paths, mean_img_path, mask_path, sd_img_out_path=None, rms_out_path=None):
"""! Calculates the standard deviation of images as the root mean squared (RMS) (== coefficient of variation)
@param img_paths: List of paths to images
@param mean_img_path: Path to average image
@param mask_path: Path to mask
@param sd_img_out_path: Path to standard deviation output image
@param rms_out_path: Path to output text file that RMS is written to
"""
mean_img_nib = nib.load(mean_img_path)
for i, path in enumerate(img_paths):
......@@ -448,11 +540,37 @@ def RMSstandardDeviation(img_paths, mean_img_path, mask_path, sd_img_out_path=No
f.write('{}'.format(rms))
def mmorfWrapper(mmorf_run_cmd, config_path, img_warp_space, img_ref_scalar, img_mov_scalar, aff_ref_scalar,
aff_mov_scalar, mask_ref_scalar,
mask_mov_scalar, img_ref_tensor, img_mov_tensor, aff_ref_tensor, aff_mov_tensor, mask_ref_tensor,
mask_mov_tensor,
def mmorfWrapper(mmorf_run_cmd, config_path, img_warp_space,
img_ref_scalar, img_mov_scalar, aff_ref_scalar, aff_mov_scalar,
mask_ref_scalar, mask_mov_scalar,
img_ref_tensor, img_mov_tensor, aff_ref_tensor, aff_mov_tensor,
mask_ref_tensor, mask_mov_tensor,
warp_out, jac_det_out, bias_out):
"""! Wrapper function for running MMORF.
@param mmorf_run_cmd: Singularity command to run MMORF
@param config_path: Path to config file with fixed parameters
@param img_warp_space: Path to image defining the space in which the warp field will be calculated
@param img_ref_scalar: List of paths to scalar reference images
@param img_mov_scalar: List of paths to scalar moving images
@param aff_ref_scalar: List of paths to affine transformations for scalar reference images
@param aff_mov_scalar: List of paths to affine transformations for scalar moving images
@param mask_ref_scalar: List of paths to masks in reference image spaces
@param mask_mov_scalar: List of paths to masks in moving image spaces
@param img_ref_tensor: List of paths to reference tensors
@param img_mov_tensor: List of paths to moving tensors
@param aff_ref_tensor: List of paths to affine transformations for reference tensors
@param aff_mov_tensor: List of paths to affine transformations for moving tensors
@param mask_ref_tensor: List of paths to masks in reference tensor spaces
@param mask_mov_tensor: List of paths to masks in moving tensor spaces
@param warp_out: Path to output warp field
@param jac_det_out: Path to output Jacobian determinant of final warp field
@param bias_out: Path to output bias field for scalar image pairs
@return The command as a string and a dictionary of environment variables.
"""
export_var = []
cmd = mmorf_run_cmd
cmd += ' --config ' + config_path
......@@ -528,6 +646,9 @@ def mmorfWrapper(mmorf_run_cmd, config_path, img_warp_space, img_ref_scalar, img
if __name__ == "__main__":
"""! Main function submitting the jobs.
"""
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')
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment