diff --git a/CHANGES b/CHANGES index 933b22cb25..73f4566e95 100644 --- a/CHANGES +++ b/CHANGES @@ -4,6 +4,8 @@ Upcoming release (0.14.1) * FIX: Robustly handled outputs of 3dFWHMx across different versions of AFNI (https://github.com/nipy/nipype/pull/2373) * FIX: Cluster threshold in randomise + change default prefix (https://github.com/nipy/nipype/pull/2369) * MAINT: Cleaning / simplify ``Node`` (https://github.com/nipy/nipype/pull/#2325) +* STY: Cleanup of PEP8 violations (https://github.com/nipy/nipype/pull/2358) +* STY: Cleanup of trailing spaces and adding of missing newlines at end of files (https://github.com/nipy/nipype/pull/2355) 0.14.0 (November 29, 2017) ========================== diff --git a/build_docs.py b/build_docs.py index e2ae75b7b9..c39a8da473 100644 --- a/build_docs.py +++ b/build_docs.py @@ -8,7 +8,8 @@ python setup.py build_sphinx """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open, str # Standard library imports @@ -28,7 +29,7 @@ DOC_BUILD_DIR = os.path.join('doc', '_build', 'html') DOC_DOCTREES_DIR = os.path.join('doc', '_build', 'doctrees') -################################################################################ +############################################################################### # Distutils Command class for installing nipype to a temporary location. @@ -63,7 +64,7 @@ def finalize_options(self): pass -################################################################################ +############################################################################### # Distutils Command class for API generation class APIDocs(TempInstall): description = \ @@ -93,7 +94,7 @@ def run(self): os.chdir('..') -################################################################################ +############################################################################### # Code to copy the sphinx-generated html docs in the distribution. def relative_path(filename): """ Return the relative path to the file, assuming the file is @@ -103,7 +104,7 @@ def relative_path(filename): return os.path.abspath(filename)[length:] -################################################################################ +############################################################################### # Distutils Command class build the docs # Sphinx import. try: @@ -165,7 +166,7 @@ def finalize_options(self): self.build_dir = os.path.join(*DOC_BUILD_DIR.split(os.sep)[:-1]) BuildDoc.finalize_options(self) -################################################################################ +############################################################################### # Distutils Command class to clean diff --git a/doc/sphinxext/autosummary_generate.py b/doc/sphinxext/autosummary_generate.py index d30edf6aec..658c50e4a4 100755 --- a/doc/sphinxext/autosummary_generate.py +++ b/doc/sphinxext/autosummary_generate.py @@ -39,9 +39,9 @@ def main(): help="Phantom import modules from a file") p.add_option("-o", "--output-dir", action="store", type="string", dest="output_dir", default=None, - help=("Write all output files to the given directory (instead " - "of writing them as specified in the autosummary:: " - "directives)")) + help=("Write all output files to the given directory " + "(instead of writing them as specified in the " + "autosummary:: directives)")) options, args = p.parse_args() if len(args) == 0: @@ -161,9 +161,12 @@ def get_documented_in_lines(lines, module=None, filename=None): """ title_underline_re = re.compile("^[-=*_^#]{3,}\s*$") - autodoc_re = re.compile(".. auto(function|method|attribute|class|exception|module)::\s*([A-Za-z0-9_.]+)\s*$") + autodoc_re = re.compile( + ".. auto(function|method|attribute|class|exception|module)::" + "\s*([A-Za-z0-9_.]+)\s*$") autosummary_re = re.compile(r'^\.\.\s+autosummary::\s*') - module_re = re.compile(r'^\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') + module_re = re.compile( + r'^\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') autosummary_item_re = re.compile(r'^\s+([_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$') @@ -189,7 +192,8 @@ def get_documented_in_lines(lines, module=None, filename=None): m = autosummary_item_re.match(line) if m: name = m.group(1).strip() - if current_module and not name.startswith(current_module + '.'): + if current_module and not name.startswith( + current_module + '.'): name = "%s.%s" % (current_module, name) documented.setdefault(name, []).append( (filename, current_title, 'autosummary', toctree)) @@ -210,7 +214,8 @@ def get_documented_in_lines(lines, module=None, filename=None): current_module = name documented.update(get_documented_in_docstring( name, filename=filename)) - elif current_module and not name.startswith(current_module + '.'): + elif current_module and not name.startswith( + current_module + '.'): name = "%s.%s" % (current_module, name) documented.setdefault(name, []).append( (filename, current_title, "auto" + m.group(1), None)) @@ -230,5 +235,6 @@ def get_documented_in_lines(lines, module=None, filename=None): return documented + if __name__ == "__main__": main() diff --git a/doc/sphinxext/ipython_console_highlighting.py b/doc/sphinxext/ipython_console_highlighting.py index 6720056dc8..a400d3c9c1 100644 --- a/doc/sphinxext/ipython_console_highlighting.py +++ b/doc/sphinxext/ipython_console_highlighting.py @@ -59,7 +59,6 @@ class IPythonConsoleLexer(Lexer): def get_tokens_unprocessed(self, text): pylexer = PythonLexer(**self.options) - tblexer = PythonTracebackLexer(**self.options) curcode = '' insertions = [] @@ -72,21 +71,22 @@ def get_tokens_unprocessed(self, text): insertions.append((len(curcode), [(0, Comment, line)])) elif input_prompt is not None: - insertions.append((len(curcode), - [(0, Generic.Prompt, input_prompt.group())])) + insertions.append((len( + curcode), [(0, Generic.Prompt, input_prompt.group())])) curcode += line[input_prompt.end():] elif continue_prompt is not None: - insertions.append((len(curcode), - [(0, Generic.Prompt, continue_prompt.group())])) + insertions.append((len( + curcode), [(0, Generic.Prompt, continue_prompt.group())])) curcode += line[continue_prompt.end():] elif output_prompt is not None: - insertions.append((len(curcode), - [(0, Generic.Output, output_prompt.group())])) + insertions.append((len( + curcode), [(0, Generic.Output, output_prompt.group())])) curcode += line[output_prompt.end():] else: if curcode: for item in do_insertions(insertions, - pylexer.get_tokens_unprocessed(curcode)): + pylexer.get_tokens_unprocessed( + curcode)): yield item curcode = '' insertions = [] diff --git a/doc/sphinxext/numpy_ext/docscrape.py b/doc/sphinxext/numpy_ext/docscrape.py index a4ff432715..28e3b30948 100644 --- a/doc/sphinxext/numpy_ext/docscrape.py +++ b/doc/sphinxext/numpy_ext/docscrape.py @@ -295,7 +295,8 @@ def _parse(self): for (section, content) in self._read_sections(): if not section.startswith('..'): - section = ' '.join([s.capitalize() for s in section.split(' ')]) + section = ' '.join([s.capitalize() + for s in section.split(' ')]) if section in ('Parameters', 'Returns', 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) @@ -443,7 +444,7 @@ def __init__(self, func, role='func', doc=None, config={}): argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*', '\*') signature = '%s%s' % (func_name, argspec) - except TypeError as e: + except TypeError: signature = '%s()' % func_name self['Signature'] = signature @@ -459,7 +460,6 @@ def __str__(self): out = '' func, func_name = self.get_func() - signature = self['Signature'].replace('*', '\*') roles = {'func': 'function', 'meth': 'method'} diff --git a/doc/sphinxext/numpy_ext/numpydoc.py b/doc/sphinxext/numpy_ext/numpydoc.py index ccce7aad03..c21ada71e6 100644 --- a/doc/sphinxext/numpy_ext/numpydoc.py +++ b/doc/sphinxext/numpy_ext/numpydoc.py @@ -11,7 +11,7 @@ - Convert Parameters etc. sections to field lists. - Convert See Also section to a See also entry. - Renumber references. -- Extract the signature from the docstring, if it can't be determined otherwise. +- Extract signature from docstring, if it can't be determined otherwise. .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt diff --git a/examples/dmri_camino_dti.py b/examples/dmri_camino_dti.py index 3a9528bf10..eaf9b4ff95 100755 --- a/examples/dmri_camino_dti.py +++ b/examples/dmri_camino_dti.py @@ -18,15 +18,14 @@ Import necessary modules from nipype. """ -import os # system functions -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine +import os # system functions +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine import nipype.interfaces.camino as camino import nipype.interfaces.fsl as fsl import nipype.interfaces.camino2trackvis as cam2trk import nipype.algorithms.misc as misc - """ We use the following functions to scrape the voxel and data dimensions of the input images. This allows the pipeline to be flexible enough to accept and process images of varying size. The SPM Face tutorial @@ -62,21 +61,20 @@ def get_affine(volume): nii = nb.load(volume, mmap=NUMPY_MMAP) return nii.affine + subject_list = ['subj1'] fsl.FSLCommand.set_default_output_type('NIFTI') - - """ Map field names to individual subject runs """ -info = dict(dwi=[['subject_id', 'data']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + dwi=[['subject_id', 'data']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -87,7 +85,6 @@ def get_affine(volume): """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -96,9 +93,10 @@ def get_affine(volume): functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" @@ -109,13 +107,13 @@ def get_affine(volume): datasource.inputs.field_template = dict(dwi='%s/%s.nii.gz') datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """ An inputnode is used to pass the data obtained by the data grabber to the actual processing functions """ -inputnode = pe.Node(interface=util.IdentityInterface(fields=["dwi", "bvecs", "bvals"]), name="inputnode") - +inputnode = pe.Node( + interface=util.IdentityInterface(fields=["dwi", "bvecs", "bvals"]), + name="inputnode") """ Setup for Diffusion Tensor Computation -------------------------------------- @@ -126,13 +124,11 @@ def get_affine(volume): image2voxel = pe.Node(interface=camino.Image2Voxel(), name="image2voxel") fsl2scheme = pe.Node(interface=camino.FSL2Scheme(), name="fsl2scheme") fsl2scheme.inputs.usegradmod = True - """ Second, diffusion tensors are fit to the voxel-order data. """ dtifit = pe.Node(interface=camino.DTIFit(), name='dtifit') - """ Next, a lookup table is generated from the schemefile and the signal-to-noise ratio (SNR) of the unweighted (q=0) data. @@ -141,7 +137,6 @@ def get_affine(volume): dtlutgen = pe.Node(interface=camino.DTLUTGen(), name="dtlutgen") dtlutgen.inputs.snr = 16.0 dtlutgen.inputs.inversion = 1 - """ In this tutorial we implement probabilistic tractography using the PICo algorithm. PICo tractography requires an estimate of the fibre direction and a model of its @@ -150,21 +145,18 @@ def get_affine(volume): picopdfs = pe.Node(interface=camino.PicoPDFs(), name="picopdfs") picopdfs.inputs.inputmodel = 'dt' - """ An FSL BET node creates a brain mask is generated from the diffusion image for seeding the PICo tractography. """ bet = pe.Node(interface=fsl.BET(), name="bet") bet.inputs.mask = True - """ Finally, tractography is performed. First DT streamline tractography. """ trackdt = pe.Node(interface=camino.TrackDT(), name="trackdt") - """ Now camino's Probablistic Index of connectivity algorithm. In this tutorial, we will use only 1 iteration for time-saving purposes. @@ -172,7 +164,6 @@ def get_affine(volume): trackpico = pe.Node(interface=camino.TrackPICo(), name="trackpico") trackpico.inputs.iterations = 1 - """ Currently, the best program for visualizing tracts is TrackVis. For this reason, a node is included to convert the raw tract data to .trk format. Solely for testing purposes, another node is added to perform the reverse. @@ -182,21 +173,20 @@ def get_affine(volume): cam2trk_dt.inputs.min_length = 30 cam2trk_dt.inputs.voxel_order = 'LAS' -cam2trk_pico = pe.Node(interface=cam2trk.Camino2Trackvis(), name="cam2trk_pico") +cam2trk_pico = pe.Node( + interface=cam2trk.Camino2Trackvis(), name="cam2trk_pico") cam2trk_pico.inputs.min_length = 30 cam2trk_pico.inputs.voxel_order = 'LAS' trk2camino = pe.Node(interface=cam2trk.Trackvis2Camino(), name="trk2camino") - """ Tracts can also be converted to VTK and OOGL formats, for use in programs such as GeomView and Paraview, using the following two nodes. For VTK use VtkStreamlines. """ -procstreamlines = pe.Node(interface=camino.ProcStreamlines(), name="procstreamlines") +procstreamlines = pe.Node( + interface=camino.ProcStreamlines(), name="procstreamlines") procstreamlines.inputs.outputtracts = 'oogl' - - """ We can also produce a variety of scalar values from our fitted tensors. The following nodes generate the fractional anisotropy and diffusivity trace maps and their associated headers. @@ -206,13 +196,13 @@ def get_affine(volume): trace = pe.Node(interface=camino.ComputeTensorTrace(), name='trace') dteig = pe.Node(interface=camino.ComputeEigensystem(), name='dteig') -analyzeheader_fa = pe.Node(interface=camino.AnalyzeHeader(), name="analyzeheader_fa") +analyzeheader_fa = pe.Node( + interface=camino.AnalyzeHeader(), name="analyzeheader_fa") analyzeheader_fa.inputs.datatype = "double" analyzeheader_trace = analyzeheader_fa.clone('analyzeheader_trace') fa2nii = pe.Node(interface=misc.CreateNifti(), name='fa2nii') trace2nii = fa2nii.clone("trace2nii") - """ Since we have now created all our nodes, we can now define our workflow and start making connections. """ @@ -220,31 +210,25 @@ def get_affine(volume): tractography = pe.Workflow(name='tractography') tractography.connect([(inputnode, bet, [("dwi", "in_file")])]) - """ File format conversion """ tractography.connect([(inputnode, image2voxel, [("dwi", "in_file")]), (inputnode, fsl2scheme, [("bvecs", "bvec_file"), - ("bvals", "bval_file")]) - ]) - + ("bvals", "bval_file")])]) """ Tensor fitting """ tractography.connect([(image2voxel, dtifit, [['voxel_order', 'in_file']]), - (fsl2scheme, dtifit, [['scheme', 'scheme_file']]) - ]) - + (fsl2scheme, dtifit, [['scheme', 'scheme_file']])]) """ Workflow for applying DT streamline tractogpahy """ tractography.connect([(bet, trackdt, [("mask_file", "seed_file")])]) tractography.connect([(dtifit, trackdt, [("tensor_fitted", "in_file")])]) - """ Workflow for applying PICo """ @@ -257,8 +241,6 @@ def get_affine(volume): # ProcStreamlines might throw memory errors - comment this line out in such case tractography.connect([(trackdt, procstreamlines, [("tracked", "in_file")])]) - - """ Connecting the Fractional Anisotropy and Trace nodes is simple, as they obtain their input from the tensor fitting. @@ -270,32 +252,35 @@ def get_affine(volume): tractography.connect([(dtifit, fa, [("tensor_fitted", "in_file")])]) tractography.connect([(fa, analyzeheader_fa, [("fa", "in_file")])]) -tractography.connect([(inputnode, analyzeheader_fa, [(('dwi', get_vox_dims), 'voxel_dims'), - (('dwi', get_data_dims), 'data_dims')])]) +tractography.connect([(inputnode, analyzeheader_fa, + [(('dwi', get_vox_dims), 'voxel_dims'), + (('dwi', get_data_dims), 'data_dims')])]) tractography.connect([(fa, fa2nii, [('fa', 'data_file')])]) tractography.connect([(inputnode, fa2nii, [(('dwi', get_affine), 'affine')])]) tractography.connect([(analyzeheader_fa, fa2nii, [('header', 'header_file')])]) - tractography.connect([(dtifit, trace, [("tensor_fitted", "in_file")])]) tractography.connect([(trace, analyzeheader_trace, [("trace", "in_file")])]) -tractography.connect([(inputnode, analyzeheader_trace, [(('dwi', get_vox_dims), 'voxel_dims'), - (('dwi', get_data_dims), 'data_dims')])]) +tractography.connect([(inputnode, analyzeheader_trace, + [(('dwi', get_vox_dims), 'voxel_dims'), + (('dwi', get_data_dims), 'data_dims')])]) tractography.connect([(trace, trace2nii, [('trace', 'data_file')])]) -tractography.connect([(inputnode, trace2nii, [(('dwi', get_affine), 'affine')])]) -tractography.connect([(analyzeheader_trace, trace2nii, [('header', 'header_file')])]) +tractography.connect([(inputnode, trace2nii, [(('dwi', get_affine), + 'affine')])]) +tractography.connect([(analyzeheader_trace, trace2nii, [('header', + 'header_file')])]) tractography.connect([(dtifit, dteig, [("tensor_fitted", "in_file")])]) tractography.connect([(trackpico, cam2trk_pico, [('tracked', 'in_file')])]) tractography.connect([(trackdt, cam2trk_dt, [('tracked', 'in_file')])]) -tractography.connect([(inputnode, cam2trk_pico, [(('dwi', get_vox_dims), 'voxel_dims'), - (('dwi', get_data_dims), 'data_dims')])]) - -tractography.connect([(inputnode, cam2trk_dt, [(('dwi', get_vox_dims), 'voxel_dims'), - (('dwi', get_data_dims), 'data_dims')])]) - +tractography.connect([(inputnode, cam2trk_pico, + [(('dwi', get_vox_dims), 'voxel_dims'), + (('dwi', get_data_dims), 'data_dims')])]) +tractography.connect([(inputnode, cam2trk_dt, + [(('dwi', get_vox_dims), 'voxel_dims'), + (('dwi', get_data_dims), 'data_dims')])]) """ Finally, we create another higher-level workflow to connect our tractography workflow with the info and datagrabbing nodes declared at the beginning. Our tutorial can is now extensible to any arbitrary number of subjects by simply adding @@ -305,11 +290,9 @@ def get_affine(volume): workflow = pe.Workflow(name="workflow") workflow.base_dir = os.path.abspath('camino_dti_tutorial') workflow.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, tractography, [('dwi', 'inputnode.dwi'), - ('bvals', 'inputnode.bvals'), - ('bvecs', 'inputnode.bvecs') - ]) - ]) + (datasource, tractography, + [('dwi', 'inputnode.dwi'), ('bvals', 'inputnode.bvals'), + ('bvecs', 'inputnode.bvecs')])]) """ The following functions run the whole workflow and produce a .dot and .png graph of the processing pipeline. """ @@ -317,7 +300,6 @@ def get_affine(volume): if __name__ == '__main__': workflow.run() workflow.write_graph() - """ You can choose the format of the experted graph with the ``format`` option. For example ``workflow.write_graph(format='eps')`` diff --git a/examples/dmri_connectivity.py b/examples/dmri_connectivity.py index 5ebbbb77d5..fc5b51c362 100755 --- a/examples/dmri_connectivity.py +++ b/examples/dmri_connectivity.py @@ -49,18 +49,17 @@ import inspect -import os.path as op # system functions -import cmp # connectome mapper -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine +import os.path as op # system functions +import cmp # connectome mapper +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine import nipype.interfaces.camino as camino import nipype.interfaces.fsl as fsl import nipype.interfaces.camino2trackvis as cam2trk -import nipype.interfaces.freesurfer as fs # freesurfer +import nipype.interfaces.freesurfer as fs # freesurfer import nipype.interfaces.cmtk as cmtk import nipype.algorithms.misc as misc - """ We define the following functions to scrape the voxel and data dimensions of the input images. This allows the pipeline to be flexible enough to accept and process images of varying size. The SPM Face tutorial @@ -114,6 +113,7 @@ def select_aparc_annot(list_of_files): idx = list_of_files.index(in_file) return list_of_files[idx] + """ These need to point to the main Freesurfer directory as well as the freesurfer subjects directory. No assumptions are made about where the directory of subjects is placed. @@ -123,7 +123,6 @@ def select_aparc_annot(list_of_files): fs_dir = op.abspath('/usr/local/freesurfer') subjects_dir = op.abspath(op.join(op.curdir, './subjects')) fsl.FSLCommand.set_default_output_type('NIFTI') - """ This needs to point to the fdt folder you can find after extracting http://www.fmrib.ox.ac.uk/fslcourse/fsl_course_data2.tar.gz @@ -132,7 +131,6 @@ def select_aparc_annot(list_of_files): data_dir = op.abspath('fsl_course_data/fdt/') fs.FSCommand.set_default_subjects_dir(subjects_dir) subject_list = ['subj1'] - """ An infosource node is used to loop through the subject list and define the input files. For our purposes, these are the diffusion-weighted MR image, b vectors, and b values. @@ -140,22 +138,24 @@ def select_aparc_annot(list_of_files): the 4D nifti diffusion image is stored in the FSL course data as data.nii.gz. """ -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), name="infosource") +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") infosource.iterables = ('subject_id', subject_list) -info = dict(dwi=[['subject_id', 'data']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']]) - +info = dict( + dwi=[['subject_id', 'data']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']]) """ A datasource node is used to perform the actual data grabbing. Templates for the associated images are used to obtain the correct images. The data are assumed to lie in data_dir/subject_id/. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" datasource.inputs.base_directory = data_dir @@ -163,7 +163,6 @@ def select_aparc_annot(list_of_files): datasource.inputs.template_args = info datasource.inputs.base_directory = data_dir datasource.inputs.sort_filelist = True - """ FreeSurferSource nodes are used to retrieve a number of image files that were automatically generated by the recon-all process. @@ -173,14 +172,15 @@ def select_aparc_annot(list_of_files): FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(), name='fssource') FreeSurferSource.inputs.subjects_dir = subjects_dir -FreeSurferSourceLH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceLH') +FreeSurferSourceLH = pe.Node( + interface=nio.FreeSurferSource(), name='fssourceLH') FreeSurferSourceLH.inputs.subjects_dir = subjects_dir FreeSurferSourceLH.inputs.hemi = 'lh' -FreeSurferSourceRH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceRH') +FreeSurferSourceRH = pe.Node( + interface=nio.FreeSurferSource(), name='fssourceRH') FreeSurferSourceRH.inputs.subjects_dir = subjects_dir FreeSurferSourceRH.inputs.hemi = 'rh' - """ Since the b values and b vectors come from the FSL course, we must convert it to a scheme file for use in Camino. @@ -188,13 +188,11 @@ def select_aparc_annot(list_of_files): fsl2scheme = pe.Node(interface=camino.FSL2Scheme(), name="fsl2scheme") fsl2scheme.inputs.usegradmod = True - """ FSL's Brain Extraction tool is used to create a mask from the b0 image """ b0Strip = pe.Node(interface=fsl.BET(mask=True), name='bet_b0') - """ FSL's FLIRT function is used to coregister the b0 mask and the structural image. A convert_xfm node is then used to obtain the inverse of the transformation matrix. @@ -212,7 +210,6 @@ def select_aparc_annot(list_of_files): inverse_AparcAseg = pe.Node(interface=fsl.FLIRT(), name='inverse_AparcAseg') inverse_AparcAseg.inputs.interp = ('nearestneighbour') - """ A number of conversion operations are required to obtain NIFTI files from the FreesurferSource for each subject. Nodes are used to convert the following: @@ -225,7 +222,8 @@ def select_aparc_annot(list_of_files): * Parcellated annotation files for the left and right hemispheres are also converted to GIFTI """ -mri_convert_Brain = pe.Node(interface=fs.MRIConvert(), name='mri_convert_Brain') +mri_convert_Brain = pe.Node( + interface=fs.MRIConvert(), name='mri_convert_Brain') mri_convert_Brain.inputs.out_type = 'nii' mri_convert_WMParc = mri_convert_Brain.clone('mri_convert_WMParc') @@ -242,13 +240,14 @@ def select_aparc_annot(list_of_files): mris_convertLHsphere = mris_convertLH.clone('mris_convertLHsphere') mris_convertLHlabels = mris_convertLH.clone('mris_convertLHlabels') mris_convertRHlabels = mris_convertLH.clone('mris_convertRHlabels') - """ An inputnode is used to pass the data obtained by the data grabber to the actual processing functions """ -inputnode = pe.Node(interface=util.IdentityInterface(fields=["dwi", "bvecs", "bvals", "subject_id"]), name="inputnode") - +inputnode = pe.Node( + interface=util.IdentityInterface( + fields=["dwi", "bvecs", "bvals", "subject_id"]), + name="inputnode") """ In this section we create the nodes necessary for diffusion analysis. First, the diffusion image is converted to voxel order, since this is the format in which Camino does @@ -256,14 +255,12 @@ def select_aparc_annot(list_of_files): """ image2voxel = pe.Node(interface=camino.Image2Voxel(), name="image2voxel") - """ Second, diffusion tensors are fit to the voxel-order data. If desired, these tensors can be converted to a Nifti tensor image using the DT2NIfTI interface. """ dtifit = pe.Node(interface=camino.DTIFit(), name='dtifit') - """ Next, a lookup table is generated from the schemefile and the signal-to-noise ratio (SNR) of the unweighted (q=0) data. @@ -272,7 +269,6 @@ def select_aparc_annot(list_of_files): dtlutgen = pe.Node(interface=camino.DTLUTGen(), name="dtlutgen") dtlutgen.inputs.snr = 16.0 dtlutgen.inputs.inversion = 1 - """ In this tutorial we implement probabilistic tractography using the PICo algorithm. PICo tractography requires an estimate of the fibre direction and a model of its uncertainty in each voxel; @@ -281,7 +277,6 @@ def select_aparc_annot(list_of_files): picopdfs = pe.Node(interface=camino.PicoPDFs(), name="picopdfs") picopdfs.inputs.inputmodel = 'dt' - """ Finally, tractography is performed. In this tutorial, we will use only one iteration for time-saving purposes. It is important to note that we use the TrackPICo interface here. This interface now expects the files required @@ -291,27 +286,26 @@ def select_aparc_annot(list_of_files): track = pe.Node(interface=camino.TrackPICo(), name="track") track.inputs.iterations = 1 - - """ Currently, the best program for visualizing tracts is TrackVis. For this reason, a node is included to convert the raw tract data to .trk format. Solely for testing purposes, another node is added to perform the reverse. """ -camino2trackvis = pe.Node(interface=cam2trk.Camino2Trackvis(), name="camino2trk") +camino2trackvis = pe.Node( + interface=cam2trk.Camino2Trackvis(), name="camino2trk") camino2trackvis.inputs.min_length = 30 camino2trackvis.inputs.voxel_order = 'LAS' trk2camino = pe.Node(interface=cam2trk.Trackvis2Camino(), name="trk2camino") - """ Tracts can also be converted to VTK and OOGL formats, for use in programs such as GeomView and Paraview, using the following two nodes. """ -vtkstreamlines = pe.Node(interface=camino.VtkStreamlines(), name="vtkstreamlines") -procstreamlines = pe.Node(interface=camino.ProcStreamlines(), name="procstreamlines") +vtkstreamlines = pe.Node( + interface=camino.VtkStreamlines(), name="vtkstreamlines") +procstreamlines = pe.Node( + interface=camino.ProcStreamlines(), name="procstreamlines") procstreamlines.inputs.outputtracts = 'oogl' - """ We can easily produce a variety of scalar values from our fitted tensors. The following nodes generate the fractional anisotropy and diffusivity trace maps and their associated headers, and then merge them back @@ -322,14 +316,15 @@ def select_aparc_annot(list_of_files): trace = pe.Node(interface=camino.ComputeTensorTrace(), name='trace') dteig = pe.Node(interface=camino.ComputeEigensystem(), name='dteig') -analyzeheader_fa = pe.Node(interface=camino.AnalyzeHeader(), name='analyzeheader_fa') +analyzeheader_fa = pe.Node( + interface=camino.AnalyzeHeader(), name='analyzeheader_fa') analyzeheader_fa.inputs.datatype = 'double' -analyzeheader_trace = pe.Node(interface=camino.AnalyzeHeader(), name='analyzeheader_trace') +analyzeheader_trace = pe.Node( + interface=camino.AnalyzeHeader(), name='analyzeheader_trace') analyzeheader_trace.inputs.datatype = 'double' fa2nii = pe.Node(interface=misc.CreateNifti(), name='fa2nii') trace2nii = fa2nii.clone("trace2nii") - """ This section adds the Connectome Mapping Toolkit (CMTK) nodes. These interfaces are fairly experimental and may not function properly. @@ -342,11 +337,12 @@ def select_aparc_annot(list_of_files): """ roigen = pe.Node(interface=cmtk.ROIGen(), name="ROIGen") -cmp_config = cmp.configuration.PipelineConfiguration(parcellation_scheme="NativeFreesurfer") +cmp_config = cmp.configuration.PipelineConfiguration( + parcellation_scheme="NativeFreesurfer") cmp_config.parcellation_scheme = "NativeFreesurfer" -roigen.inputs.LUT_file = cmp_config.get_freeview_lut("NativeFreesurfer")['freesurferaparc'] +roigen.inputs.LUT_file = cmp_config.get_freeview_lut("NativeFreesurfer")[ + 'freesurferaparc'] roigen_structspace = roigen.clone('ROIGen_structspace') - """ The CreateMatrix interface takes in the remapped aparc+aseg image as well as the label dictionary and fiber tracts and outputs a number of different files. The most important of which is the connectivity network itself, which is stored @@ -359,8 +355,8 @@ def select_aparc_annot(list_of_files): creatematrix = pe.Node(interface=cmtk.CreateMatrix(), name="CreateMatrix") creatematrix.inputs.count_region_intersections = True createnodes = pe.Node(interface=cmtk.CreateNodes(), name="CreateNodes") -createnodes.inputs.resolution_network_file = cmp_config.parcellation['freesurferaparc']['node_information_graphml'] - +createnodes.inputs.resolution_network_file = cmp_config.parcellation[ + 'freesurferaparc']['node_information_graphml'] """ Here we define the endpoint of this tutorial, which is the CFFConverter node, as well as a few nodes which use the Nipype Merge utility. These are useful for passing lists of the files we want packaged in our CFF file. @@ -373,65 +369,73 @@ def select_aparc_annot(list_of_files): niftiVolumes = pe.Node(interface=util.Merge(3), name="NiftiVolumes") fiberDataArrays = pe.Node(interface=util.Merge(4), name="FiberDataArrays") gpickledNetworks = pe.Node(interface=util.Merge(1), name="NetworkFiles") - """ Since we have now created all our nodes, we can define our workflow and start making connections. """ mapping = pe.Workflow(name='mapping') - """ First, we connect the input node to the early conversion functions. FreeSurfer input nodes: """ -mapping.connect([(inputnode, FreeSurferSource, [("subject_id", "subject_id")])]) -mapping.connect([(inputnode, FreeSurferSourceLH, [("subject_id", "subject_id")])]) -mapping.connect([(inputnode, FreeSurferSourceRH, [("subject_id", "subject_id")])]) - +mapping.connect([(inputnode, FreeSurferSource, [("subject_id", + "subject_id")])]) +mapping.connect([(inputnode, FreeSurferSourceLH, [("subject_id", + "subject_id")])]) +mapping.connect([(inputnode, FreeSurferSourceRH, [("subject_id", + "subject_id")])]) """ Required conversions for processing in Camino: """ mapping.connect([(inputnode, image2voxel, [("dwi", "in_file")]), - (inputnode, fsl2scheme, [("bvecs", "bvec_file"), - ("bvals", "bval_file")]), - (image2voxel, dtifit, [['voxel_order', 'in_file']]), - (fsl2scheme, dtifit, [['scheme', 'scheme_file']]) - ]) - + (inputnode, fsl2scheme, + [("bvecs", "bvec_file"), + ("bvals", "bval_file")]), (image2voxel, dtifit, + [['voxel_order', 'in_file']]), + (fsl2scheme, dtifit, [['scheme', 'scheme_file']])]) """ Nifti conversions for the parcellated white matter image (used in Camino's conmap), and the subject's stripped brain image from Freesurfer: """ -mapping.connect([(FreeSurferSource, mri_convert_WMParc, [('wmparc', 'in_file')])]) -mapping.connect([(FreeSurferSource, mri_convert_Brain, [('brain', 'in_file')])]) - +mapping.connect([(FreeSurferSource, mri_convert_WMParc, [('wmparc', + 'in_file')])]) +mapping.connect([(FreeSurferSource, mri_convert_Brain, [('brain', + 'in_file')])]) """ Surface conversions to GIFTI (pial, white, inflated, and sphere for both hemispheres) """ mapping.connect([(FreeSurferSourceLH, mris_convertLH, [('pial', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRH, [('pial', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite, [('white', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite, [('white', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated, [('inflated', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated, [('inflated', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere, [('sphere', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere, [('sphere', 'in_file')])]) - +mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite, [('white', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite, [('white', + 'in_file')])]) +mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated, [('inflated', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated, [('inflated', + 'in_file')])]) +mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere, [('sphere', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere, [('sphere', + 'in_file')])]) """ The annotation files are converted using the pial surface as a map via the MRIsConvert interface. One of the functions defined earlier is used to select the lh.aparc.annot and rh.aparc.annot files specifically (rather than i.e. rh.aparc.a2009s.annot) from the output list given by the FreeSurferSource. """ -mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [('pial', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [('pial', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) - +mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [('pial', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [('pial', + 'in_file')])]) +mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, + [(('annot', select_aparc_annot), 'annot_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, + [(('annot', select_aparc_annot), 'annot_file')])]) """ This section coregisters the diffusion-weighted and parcellated white-matter / whole brain images. At present the conmap node connection is left commented, as there have been recent changes in Camino @@ -445,7 +449,6 @@ def select_aparc_annot(list_of_files): mapping.connect([(b0Strip, inverse, [('out_file', 'reference')])]) mapping.connect([(convertxfm, inverse, [('out_file', 'in_matrix_file')])]) mapping.connect([(mri_convert_WMParc, inverse, [('out_file', 'in_file')])]) - """ The tractography pipeline consists of the following nodes. Further information about the tractography can be found in nipype/examples/dmri_camino_dti.py. @@ -456,7 +459,6 @@ def select_aparc_annot(list_of_files): mapping.connect([(dtlutgen, picopdfs, [("dtLUT", "luts")])]) mapping.connect([(dtifit, picopdfs, [("tensor_fitted", "in_file")])]) mapping.connect([(picopdfs, track, [("pdfs", "in_file")])]) - """ Connecting the Fractional Anisotropy and Trace nodes is simple, as they obtain their input from the tensor fitting. This is also where our voxel- and data-grabbing functions come in. We pass these functions, @@ -466,23 +468,24 @@ def select_aparc_annot(list_of_files): mapping.connect([(dtifit, fa, [("tensor_fitted", "in_file")])]) mapping.connect([(fa, analyzeheader_fa, [("fa", "in_file")])]) -mapping.connect([(inputnode, analyzeheader_fa, [(('dwi', get_vox_dims), 'voxel_dims'), - (('dwi', get_data_dims), 'data_dims')])]) +mapping.connect([(inputnode, analyzeheader_fa, + [(('dwi', get_vox_dims), 'voxel_dims'), + (('dwi', get_data_dims), 'data_dims')])]) mapping.connect([(fa, fa2nii, [('fa', 'data_file')])]) mapping.connect([(inputnode, fa2nii, [(('dwi', get_affine), 'affine')])]) mapping.connect([(analyzeheader_fa, fa2nii, [('header', 'header_file')])]) - mapping.connect([(dtifit, trace, [("tensor_fitted", "in_file")])]) mapping.connect([(trace, analyzeheader_trace, [("trace", "in_file")])]) -mapping.connect([(inputnode, analyzeheader_trace, [(('dwi', get_vox_dims), 'voxel_dims'), - (('dwi', get_data_dims), 'data_dims')])]) +mapping.connect([(inputnode, analyzeheader_trace, + [(('dwi', get_vox_dims), 'voxel_dims'), + (('dwi', get_data_dims), 'data_dims')])]) mapping.connect([(trace, trace2nii, [('trace', 'data_file')])]) mapping.connect([(inputnode, trace2nii, [(('dwi', get_affine), 'affine')])]) -mapping.connect([(analyzeheader_trace, trace2nii, [('header', 'header_file')])]) +mapping.connect([(analyzeheader_trace, trace2nii, [('header', + 'header_file')])]) mapping.connect([(dtifit, dteig, [("tensor_fitted", "in_file")])]) - """ The output tracts are converted to Trackvis format (and back). Here we also use the voxel- and data-grabbing functions defined at the beginning of the pipeline. @@ -490,11 +493,10 @@ def select_aparc_annot(list_of_files): mapping.connect([(track, camino2trackvis, [('tracked', 'in_file')]), (track, vtkstreamlines, [['tracked', 'in_file']]), - (camino2trackvis, trk2camino, [['trackvis', 'in_file']]) - ]) -mapping.connect([(inputnode, camino2trackvis, [(('dwi', get_vox_dims), 'voxel_dims'), - (('dwi', get_data_dims), 'data_dims')])]) - + (camino2trackvis, trk2camino, [['trackvis', 'in_file']])]) +mapping.connect([(inputnode, camino2trackvis, + [(('dwi', get_vox_dims), 'voxel_dims'), + (('dwi', get_data_dims), 'data_dims')])]) """ Here the CMTK connectivity mapping nodes are connected. The original aparc+aseg image is converted to NIFTI, then registered to @@ -502,22 +504,30 @@ def select_aparc_annot(list_of_files): original tracts, and label file are then given to CreateMatrix. """ -mapping.connect(createnodes, 'node_network', - creatematrix, 'resolution_network_file') -mapping.connect([(FreeSurferSource, mri_convert_AparcAseg, [(('aparc_aseg', select_aparc), 'in_file')])]) +mapping.connect(createnodes, 'node_network', creatematrix, + 'resolution_network_file') +mapping.connect([(FreeSurferSource, mri_convert_AparcAseg, + [(('aparc_aseg', select_aparc), 'in_file')])]) mapping.connect([(b0Strip, inverse_AparcAseg, [('out_file', 'reference')])]) -mapping.connect([(convertxfm, inverse_AparcAseg, [('out_file', 'in_matrix_file')])]) -mapping.connect([(mri_convert_AparcAseg, inverse_AparcAseg, [('out_file', 'in_file')])]) -mapping.connect([(mri_convert_AparcAseg, roigen_structspace, [('out_file', 'aparc_aseg_file')])]) -mapping.connect([(roigen_structspace, createnodes, [("roi_file", "roi_file")])]) - -mapping.connect([(inverse_AparcAseg, roigen, [("out_file", "aparc_aseg_file")])]) +mapping.connect([(convertxfm, inverse_AparcAseg, [('out_file', + 'in_matrix_file')])]) +mapping.connect([(mri_convert_AparcAseg, inverse_AparcAseg, [('out_file', + 'in_file')])]) +mapping.connect([(mri_convert_AparcAseg, roigen_structspace, + [('out_file', 'aparc_aseg_file')])]) +mapping.connect([(roigen_structspace, createnodes, [("roi_file", + "roi_file")])]) + +mapping.connect([(inverse_AparcAseg, roigen, [("out_file", + "aparc_aseg_file")])]) mapping.connect([(roigen, creatematrix, [("roi_file", "roi_file")])]) -mapping.connect([(camino2trackvis, creatematrix, [("trackvis", "tract_file")])]) -mapping.connect([(inputnode, creatematrix, [("subject_id", "out_matrix_file")])]) -mapping.connect([(inputnode, creatematrix, [("subject_id", "out_matrix_mat_file")])]) - +mapping.connect([(camino2trackvis, creatematrix, [("trackvis", + "tract_file")])]) +mapping.connect([(inputnode, creatematrix, [("subject_id", + "out_matrix_file")])]) +mapping.connect([(inputnode, creatematrix, [("subject_id", + "out_matrix_mat_file")])]) """ The merge nodes defined earlier are used here to create lists of the files which are destined for the CFFConverter. @@ -529,10 +539,14 @@ def select_aparc_annot(list_of_files): mapping.connect([(mris_convertRH, giftiSurfaces, [("converted", "in2")])]) mapping.connect([(mris_convertLHwhite, giftiSurfaces, [("converted", "in3")])]) mapping.connect([(mris_convertRHwhite, giftiSurfaces, [("converted", "in4")])]) -mapping.connect([(mris_convertLHinflated, giftiSurfaces, [("converted", "in5")])]) -mapping.connect([(mris_convertRHinflated, giftiSurfaces, [("converted", "in6")])]) -mapping.connect([(mris_convertLHsphere, giftiSurfaces, [("converted", "in7")])]) -mapping.connect([(mris_convertRHsphere, giftiSurfaces, [("converted", "in8")])]) +mapping.connect([(mris_convertLHinflated, giftiSurfaces, [("converted", + "in5")])]) +mapping.connect([(mris_convertRHinflated, giftiSurfaces, [("converted", + "in6")])]) +mapping.connect([(mris_convertLHsphere, giftiSurfaces, [("converted", + "in7")])]) +mapping.connect([(mris_convertRHsphere, giftiSurfaces, [("converted", + "in8")])]) mapping.connect([(mris_convertLHlabels, giftiLabels, [("converted", "in1")])]) mapping.connect([(mris_convertRHlabels, giftiLabels, [("converted", "in2")])]) @@ -542,10 +556,12 @@ def select_aparc_annot(list_of_files): mapping.connect([(mri_convert_Brain, niftiVolumes, [("out_file", "in3")])]) mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file", "in1")])]) -mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm", "in2")])]) -mapping.connect([(creatematrix, fiberDataArrays, [("fiber_length_file", "in3")])]) -mapping.connect([(creatematrix, fiberDataArrays, [("fiber_label_file", "in4")])]) - +mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm", + "in2")])]) +mapping.connect([(creatematrix, fiberDataArrays, [("fiber_length_file", + "in3")])]) +mapping.connect([(creatematrix, fiberDataArrays, [("fiber_label_file", + "in4")])]) """ This block actually connects the merged lists to the CFF converter. We pass the surfaces and volumes that are to be included, as well as the tracts and the network itself. The currently @@ -554,15 +570,17 @@ def select_aparc_annot(list_of_files): product. """ -CFFConverter.inputs.script_files = op.abspath(inspect.getfile(inspect.currentframe())) +CFFConverter.inputs.script_files = op.abspath( + inspect.getfile(inspect.currentframe())) mapping.connect([(giftiSurfaces, CFFConverter, [("out", "gifti_surfaces")])]) mapping.connect([(giftiLabels, CFFConverter, [("out", "gifti_labels")])]) -mapping.connect([(gpickledNetworks, CFFConverter, [("out", "gpickled_networks")])]) +mapping.connect([(gpickledNetworks, CFFConverter, [("out", + "gpickled_networks")])]) mapping.connect([(niftiVolumes, CFFConverter, [("out", "nifti_volumes")])]) mapping.connect([(fiberDataArrays, CFFConverter, [("out", "data_files")])]) -mapping.connect([(creatematrix, CFFConverter, [("filtered_tractographies", "tract_files")])]) +mapping.connect([(creatematrix, CFFConverter, [("filtered_tractographies", + "tract_files")])]) mapping.connect([(inputnode, CFFConverter, [("subject_id", "title")])]) - """ Finally, we create another higher-level workflow to connect our mapping workflow with the info and datagrabbing nodes declared at the beginning. Our tutorial can is now extensible to any arbitrary number of subjects by simply adding @@ -571,15 +589,12 @@ def select_aparc_annot(list_of_files): connectivity = pe.Workflow(name="connectivity") connectivity.base_dir = op.abspath('dmri_connectivity') -connectivity.connect([ - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, mapping, [('dwi', 'inputnode.dwi'), - ('bvals', 'inputnode.bvals'), - ('bvecs', 'inputnode.bvecs') - ]), - (infosource, mapping, [('subject_id', 'inputnode.subject_id')]) -]) - +connectivity.connect([(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, mapping, + [('dwi', 'inputnode.dwi'), ('bvals', 'inputnode.bvals'), + ('bvecs', 'inputnode.bvecs')]), + (infosource, mapping, [('subject_id', + 'inputnode.subject_id')])]) """ The following functions run the whole workflow and produce graphs describing the processing pipeline. By default, write_graph outputs a .dot file and a .png image, but here we set it to output the image @@ -589,7 +604,6 @@ def select_aparc_annot(list_of_files): if __name__ == '__main__': connectivity.run() connectivity.write_graph(format='eps') - """ The output CFF file of this pipeline can be loaded in the `Connectome Viewer `_. After loading the network into memory it can be examined in 3D or as a connectivity matrix diff --git a/examples/dmri_connectivity_advanced.py b/examples/dmri_connectivity_advanced.py index b1d3ae692f..1c97eab5cb 100755 --- a/examples/dmri_connectivity_advanced.py +++ b/examples/dmri_connectivity_advanced.py @@ -46,18 +46,18 @@ Import necessary modules from nipype. """ -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine import nipype.interfaces.fsl as fsl -import nipype.interfaces.freesurfer as fs # freesurfer +import nipype.interfaces.freesurfer as fs # freesurfer import nipype.interfaces.mrtrix as mrtrix import nipype.algorithms.misc as misc import nipype.interfaces.cmtk as cmtk import nipype.interfaces.dipy as dipy import inspect import os -import os.path as op # system functions +import os.path as op # system functions from nipype.workflows.dmri.fsl.dti import create_eddy_correct_pipeline from nipype.workflows.dmri.camino.connectivity_mapping import select_aparc_annot from nipype.utils.misc import package_check @@ -71,7 +71,6 @@ warnings.warn('cmp not installed') else: import cmp - """ This needs to point to the freesurfer subjects directory (Recon-all must have been run on subj1 from the FSL course data) Alternatively, the reconstructed subject data can be downloaded from: @@ -86,7 +85,6 @@ fs_dir = os.environ['FREESURFER_HOME'] lookup_file = op.join(fs_dir, 'FreeSurferColorLUT.txt') - """ This needs to point to the fdt folder you can find after extracting @@ -96,40 +94,43 @@ data_dir = op.abspath(op.join(op.curdir, 'exdata/')) subject_list = ['subj1'] - """ Use infosource node to loop through the subject list and define the input files. For our purposes, these are the diffusion-weighted MR image, b vectors, and b values. """ -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), name="infosource") +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") infosource.iterables = ('subject_id', subject_list) -info = dict(dwi=[['subject_id', 'data']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']]) - +info = dict( + dwi=[['subject_id', 'data']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']]) """ Use datasource node to perform the actual data grabbing. Templates for the associated images are used to obtain the correct images. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" datasource.inputs.base_directory = data_dir datasource.inputs.field_template = dict(dwi='%s/%s.nii.gz') datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """ The input node and Freesurfer sources declared here will be the main conduits for the raw data to the rest of the processing pipeline. """ -inputnode = pe.Node(interface=util.IdentityInterface(fields=["subject_id", "dwi", "bvecs", "bvals", "subjects_dir"]), name="inputnode") +inputnode = pe.Node( + interface=util.IdentityInterface( + fields=["subject_id", "dwi", "bvecs", "bvals", "subjects_dir"]), + name="inputnode") inputnode.inputs.subjects_dir = subjects_dir FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(), name='fssource') @@ -137,7 +138,6 @@ FreeSurferSourceLH.inputs.hemi = 'lh' FreeSurferSourceRH = FreeSurferSource.clone('fssourceRH') FreeSurferSourceRH.inputs.hemi = 'rh' - """ Creating the workflow's nodes ============================= @@ -154,7 +154,8 @@ """ -mri_convert_Brain = pe.Node(interface=fs.MRIConvert(), name='mri_convert_Brain') +mri_convert_Brain = pe.Node( + interface=fs.MRIConvert(), name='mri_convert_Brain') mri_convert_Brain.inputs.out_type = 'nii' mri_convert_ROI_scale500 = mri_convert_Brain.clone('mri_convert_ROI_scale500') @@ -169,7 +170,6 @@ mris_convertLHsphere = mris_convertLH.clone('mris_convertLHsphere') mris_convertLHlabels = mris_convertLH.clone('mris_convertLHlabels') mris_convertRHlabels = mris_convertLH.clone('mris_convertRHlabels') - """ Diffusion processing nodes -------------------------- @@ -188,7 +188,6 @@ """ fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix') - """ Distortions induced by eddy currents are corrected prior to fitting the tensors. The first image is used as a reference for which to warp the others. @@ -196,7 +195,6 @@ eddycorrect = create_eddy_correct_pipeline(name='eddycorrect') eddycorrect.inputs.inputnode.ref_num = 1 - """ Tensors are fitted to each voxel in the diffusion-weighted image and from these three maps are created: @@ -207,11 +205,12 @@ dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(), name='dwi2tensor') tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(), name='tensor2vector') -tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(), name='tensor2adc') -tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(), name='tensor2fa') +tensor2adc = pe.Node( + interface=mrtrix.Tensor2ApparentDiffusion(), name='tensor2adc') +tensor2fa = pe.Node( + interface=mrtrix.Tensor2FractionalAnisotropy(), name='tensor2fa') MRconvert_fa = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert_fa') MRconvert_fa.inputs.extension = 'nii' - """ These nodes are used to create a rough brain mask from the b0 image. @@ -224,7 +223,6 @@ MRconvert.inputs.extract_at_coordinate = [0] threshold_b0 = pe.Node(interface=mrtrix.Threshold(), name='threshold_b0') median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3d') - """ The brain mask is also used to help identify single-fiber voxels. This is done by passing the brain mask through two erosion steps, @@ -232,13 +230,14 @@ thresholding the result to obtain some highly anisotropic within-brain voxels. """ -erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_firstpass') -erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_secondpass') +erode_mask_firstpass = pe.Node( + interface=mrtrix.Erode(), name='erode_mask_firstpass') +erode_mask_secondpass = pe.Node( + interface=mrtrix.Erode(), name='erode_mask_secondpass') MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply') MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge') threshold_FA = pe.Node(interface=mrtrix.Threshold(), name='threshold_FA') threshold_FA.inputs.absolute_threshold_value = 0.7 - """ For whole-brain tracking we also require a broad white-matter seed mask. This is created by generating a white matter mask, given a brainmask, and @@ -246,10 +245,11 @@ """ bet = pe.Node(interface=fsl.BET(mask=True), name='bet_b0') -gen_WM_mask = pe.Node(interface=mrtrix.GenerateWhiteMatterMask(), name='gen_WM_mask') -threshold_wmmask = pe.Node(interface=mrtrix.Threshold(), name='threshold_wmmask') +gen_WM_mask = pe.Node( + interface=mrtrix.GenerateWhiteMatterMask(), name='gen_WM_mask') +threshold_wmmask = pe.Node( + interface=mrtrix.Threshold(), name='threshold_wmmask') threshold_wmmask.inputs.absolute_threshold_value = 0.4 - """ The spherical deconvolution step depends on the estimate of the response function in the highly anisotropic voxels we obtained above. @@ -260,17 +260,20 @@ """ -estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') +estimateresponse = pe.Node( + interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') estimateresponse.inputs.maximum_harmonic_order = 6 -csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') +csdeconv = pe.Node( + interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') csdeconv.inputs.maximum_harmonic_order = 6 - """ Finally, we track probabilistically using the orientation distribution functions obtained earlier. The tracts are then used to generate a tract-density image, and they are also converted to TrackVis format. """ -probCSDstreamtrack = pe.Node(interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(), name='probCSDstreamtrack') +probCSDstreamtrack = pe.Node( + interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(), + name='probCSDstreamtrack') probCSDstreamtrack.inputs.inputmodel = 'SD_PROB' probCSDstreamtrack.inputs.desired_number_of_tracks = 150000 tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(), name='tracks2prob') @@ -278,7 +281,6 @@ MRconvert_tracks2prob = MRconvert_fa.clone(name='MRconvert_tracks2prob') tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk') trk2tdi = pe.Node(interface=dipy.TrackDensityMap(), name='trk2tdi') - """ Structural segmentation nodes ----------------------------- @@ -290,7 +292,6 @@ coregister = pe.Node(interface=fsl.FLIRT(dof=6), name='coregister') coregister.inputs.cost = ('normmi') - """ Parcellation is performed given the aparc+aseg image from Freesurfer. The CMTK Parcellation step subdivides these regions to return a higher-resolution parcellation scheme. @@ -300,7 +301,6 @@ parcellation_name = 'scale500' parcellate = pe.Node(interface=cmtk.Parcellate(), name="Parcellate") parcellate.inputs.parcellation_name = parcellation_name - """ The CreateMatrix interface takes in the remapped aparc+aseg image as well as the label dictionary and fiber tracts and outputs a number of different files. The most important of which is the connectivity network itself, which is stored @@ -316,11 +316,11 @@ cmp_config = cmp.configuration.PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" createnodes = pe.Node(interface=cmtk.CreateNodes(), name="CreateNodes") -createnodes.inputs.resolution_network_file = cmp_config._get_lausanne_parcellation('Lausanne2008')[parcellation_name]['node_information_graphml'] +createnodes.inputs.resolution_network_file = cmp_config._get_lausanne_parcellation( + 'Lausanne2008')[parcellation_name]['node_information_graphml'] creatematrix = pe.Node(interface=cmtk.CreateMatrix(), name="CreateMatrix") creatematrix.inputs.count_region_intersections = True - """ Next we define the endpoint of this tutorial, which is the CFFConverter node, as well as a few nodes which use the Nipype Merge utility. These are useful for passing lists of the files we want packaged in our CFF file. @@ -329,13 +329,13 @@ """ CFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="CFFConverter") -CFFConverter.inputs.script_files = op.abspath(inspect.getfile(inspect.currentframe())) +CFFConverter.inputs.script_files = op.abspath( + inspect.getfile(inspect.currentframe())) giftiSurfaces = pe.Node(interface=util.Merge(9), name="GiftiSurfaces") giftiLabels = pe.Node(interface=util.Merge(2), name="GiftiLabels") niftiVolumes = pe.Node(interface=util.Merge(3), name="NiftiVolumes") fiberDataArrays = pe.Node(interface=util.Merge(4), name="FiberDataArrays") gpickledNetworks = pe.Node(interface=util.Merge(2), name="NetworkFiles") - """ We also create a workflow to calculate several network metrics on our resulting file, and another CFF converter which will be used to package these networks into a single file. @@ -343,12 +343,13 @@ networkx = create_networkx_pipeline(name='networkx') cmats_to_csv = create_cmats_to_csv_pipeline(name='cmats_to_csv') -NxStatsCFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="NxStatsCFFConverter") -NxStatsCFFConverter.inputs.script_files = op.abspath(inspect.getfile(inspect.currentframe())) +NxStatsCFFConverter = pe.Node( + interface=cmtk.CFFConverter(), name="NxStatsCFFConverter") +NxStatsCFFConverter.inputs.script_files = op.abspath( + inspect.getfile(inspect.currentframe())) tessflow = create_tessellation_flow(name='tessflow', out_format='gii') tessflow.inputs.inputspec.lookup_file = lookup_file - """ Connecting the workflow ======================= @@ -359,58 +360,72 @@ """ mapping = pe.Workflow(name='mapping') - """ First, we connect the input node to the FreeSurfer input nodes. """ -mapping.connect([(inputnode, FreeSurferSource, [("subjects_dir", "subjects_dir")])]) -mapping.connect([(inputnode, FreeSurferSource, [("subject_id", "subject_id")])]) +mapping.connect([(inputnode, FreeSurferSource, [("subjects_dir", + "subjects_dir")])]) +mapping.connect([(inputnode, FreeSurferSource, [("subject_id", + "subject_id")])]) -mapping.connect([(inputnode, FreeSurferSourceLH, [("subjects_dir", "subjects_dir")])]) -mapping.connect([(inputnode, FreeSurferSourceLH, [("subject_id", "subject_id")])]) +mapping.connect([(inputnode, FreeSurferSourceLH, [("subjects_dir", + "subjects_dir")])]) +mapping.connect([(inputnode, FreeSurferSourceLH, [("subject_id", + "subject_id")])]) -mapping.connect([(inputnode, FreeSurferSourceRH, [("subjects_dir", "subjects_dir")])]) -mapping.connect([(inputnode, FreeSurferSourceRH, [("subject_id", "subject_id")])]) +mapping.connect([(inputnode, FreeSurferSourceRH, [("subjects_dir", + "subjects_dir")])]) +mapping.connect([(inputnode, FreeSurferSourceRH, [("subject_id", + "subject_id")])]) -mapping.connect([(inputnode, tessflow, [("subjects_dir", "inputspec.subjects_dir")])]) -mapping.connect([(inputnode, tessflow, [("subject_id", "inputspec.subject_id")])]) +mapping.connect([(inputnode, tessflow, [("subjects_dir", + "inputspec.subjects_dir")])]) +mapping.connect([(inputnode, tessflow, [("subject_id", + "inputspec.subject_id")])]) mapping.connect([(inputnode, parcellate, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode, parcellate, [("subject_id", "subject_id")])]) -mapping.connect([(parcellate, mri_convert_ROI_scale500, [('roi_file', 'in_file')])]) - +mapping.connect([(parcellate, mri_convert_ROI_scale500, [('roi_file', + 'in_file')])]) """ Nifti conversion for subject's stripped brain image from Freesurfer: """ -mapping.connect([(FreeSurferSource, mri_convert_Brain, [('brain', 'in_file')])]) - +mapping.connect([(FreeSurferSource, mri_convert_Brain, [('brain', + 'in_file')])]) """ Surface conversions to GIFTI (pial, white, inflated, and sphere for both hemispheres) """ mapping.connect([(FreeSurferSourceLH, mris_convertLH, [('pial', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRH, [('pial', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite, [('white', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite, [('white', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated, [('inflated', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated, [('inflated', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere, [('sphere', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere, [('sphere', 'in_file')])]) - +mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite, [('white', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite, [('white', + 'in_file')])]) +mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated, [('inflated', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated, [('inflated', + 'in_file')])]) +mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere, [('sphere', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere, [('sphere', + 'in_file')])]) """ The annotation files are converted using the pial surface as a map via the MRIsConvert interface. One of the functions defined earlier is used to select the lh.aparc.annot and rh.aparc.annot files specifically (rather than e.g. rh.aparc.a2009s.annot) from the output list given by the FreeSurferSource. """ -mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [('pial', 'in_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [('pial', 'in_file')])]) -mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) -mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) - - +mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [('pial', + 'in_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [('pial', + 'in_file')])]) +mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, + [(('annot', select_aparc_annot), 'annot_file')])]) +mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, + [(('annot', select_aparc_annot), 'annot_file')])]) """ Diffusion Processing -------------------- @@ -420,93 +435,110 @@ mapping.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"), ("bvals", "bval_file")])]) mapping.connect([(inputnode, eddycorrect, [("dwi", "inputnode.in_file")])]) -mapping.connect([(eddycorrect, dwi2tensor, [("outputnode.eddy_corrected", "in_file")])]) -mapping.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file", "encoding_file")])]) - -mapping.connect([(dwi2tensor, tensor2vector, [['tensor', 'in_file']]), - (dwi2tensor, tensor2adc, [['tensor', 'in_file']]), - (dwi2tensor, tensor2fa, [['tensor', 'in_file']]), - ]) +mapping.connect([(eddycorrect, dwi2tensor, [("outputnode.eddy_corrected", + "in_file")])]) +mapping.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file", + "encoding_file")])]) + +mapping.connect([ + (dwi2tensor, tensor2vector, [['tensor', 'in_file']]), + (dwi2tensor, tensor2adc, [['tensor', 'in_file']]), + (dwi2tensor, tensor2fa, [['tensor', 'in_file']]), +]) mapping.connect([(tensor2fa, MRmult_merge, [("FA", "in1")])]) mapping.connect([(tensor2fa, MRconvert_fa, [("FA", "in_file")])]) - """ This block creates the rough brain mask to be multiplied, mulitplies it with the fractional anisotropy image, and thresholds it to get the single-fiber voxels. """ -mapping.connect([(eddycorrect, MRconvert, [("outputnode.eddy_corrected", "in_file")])]) +mapping.connect([(eddycorrect, MRconvert, [("outputnode.eddy_corrected", + "in_file")])]) mapping.connect([(MRconvert, threshold_b0, [("converted", "in_file")])]) mapping.connect([(threshold_b0, median3d, [("out_file", "in_file")])]) mapping.connect([(median3d, erode_mask_firstpass, [("out_file", "in_file")])]) -mapping.connect([(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])]) +mapping.connect([(erode_mask_firstpass, erode_mask_secondpass, [("out_file", + "in_file")])]) mapping.connect([(erode_mask_secondpass, MRmult_merge, [("out_file", "in2")])]) mapping.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])]) mapping.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])]) - """ Here the thresholded white matter mask is created for seeding the tractography. """ -mapping.connect([(eddycorrect, bet, [("outputnode.eddy_corrected", "in_file")])]) -mapping.connect([(eddycorrect, gen_WM_mask, [("outputnode.eddy_corrected", "in_file")])]) +mapping.connect([(eddycorrect, bet, [("outputnode.eddy_corrected", + "in_file")])]) +mapping.connect([(eddycorrect, gen_WM_mask, [("outputnode.eddy_corrected", + "in_file")])]) mapping.connect([(bet, gen_WM_mask, [("mask_file", "binary_mask")])]) -mapping.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file", "encoding_file")])]) -mapping.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap", "in_file")])]) - +mapping.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file", + "encoding_file")])]) +mapping.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap", + "in_file")])]) """ Next we estimate the fiber response distribution. """ -mapping.connect([(eddycorrect, estimateresponse, [("outputnode.eddy_corrected", "in_file")])]) -mapping.connect([(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])]) -mapping.connect([(threshold_FA, estimateresponse, [("out_file", "mask_image")])]) - +mapping.connect([(eddycorrect, estimateresponse, [("outputnode.eddy_corrected", + "in_file")])]) +mapping.connect([(fsl2mrtrix, estimateresponse, [("encoding_file", + "encoding_file")])]) +mapping.connect([(threshold_FA, estimateresponse, [("out_file", + "mask_image")])]) """ Run constrained spherical deconvolution. """ -mapping.connect([(eddycorrect, csdeconv, [("outputnode.eddy_corrected", "in_file")])]) -mapping.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap", "mask_image")])]) -mapping.connect([(estimateresponse, csdeconv, [("response", "response_file")])]) +mapping.connect([(eddycorrect, csdeconv, [("outputnode.eddy_corrected", + "in_file")])]) +mapping.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap", + "mask_image")])]) +mapping.connect([(estimateresponse, csdeconv, [("response", + "response_file")])]) mapping.connect([(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")])]) - """ Connect the tractography and compute the tract density image. """ -mapping.connect([(threshold_wmmask, probCSDstreamtrack, [("out_file", "seed_file")])]) -mapping.connect([(csdeconv, probCSDstreamtrack, [("spherical_harmonics_image", "in_file")])]) +mapping.connect([(threshold_wmmask, probCSDstreamtrack, [("out_file", + "seed_file")])]) +mapping.connect([(csdeconv, probCSDstreamtrack, [("spherical_harmonics_image", + "in_file")])]) mapping.connect([(probCSDstreamtrack, tracks2prob, [("tracked", "in_file")])]) -mapping.connect([(eddycorrect, tracks2prob, [("outputnode.eddy_corrected", "template_file")])]) -mapping.connect([(tracks2prob, MRconvert_tracks2prob, [("tract_image", "in_file")])]) - +mapping.connect([(eddycorrect, tracks2prob, [("outputnode.eddy_corrected", + "template_file")])]) +mapping.connect([(tracks2prob, MRconvert_tracks2prob, [("tract_image", + "in_file")])]) """ Structural Processing --------------------- First, we coregister the diffusion image to the structural image """ -mapping.connect([(eddycorrect, coregister, [("outputnode.eddy_corrected", "in_file")])]) +mapping.connect([(eddycorrect, coregister, [("outputnode.eddy_corrected", + "in_file")])]) mapping.connect([(mri_convert_Brain, coregister, [('out_file', 'reference')])]) - """ The MRtrix-tracked fibers are converted to TrackVis format (with voxel and data dimensions grabbed from the DWI). The connectivity matrix is created with the transformed .trk fibers and the parcellation file. """ -mapping.connect([(eddycorrect, tck2trk, [("outputnode.eddy_corrected", "image_file")])]) -mapping.connect([(mri_convert_Brain, tck2trk, [("out_file", "registration_image_file")])]) +mapping.connect([(eddycorrect, tck2trk, [("outputnode.eddy_corrected", + "image_file")])]) +mapping.connect([(mri_convert_Brain, tck2trk, [("out_file", + "registration_image_file")])]) mapping.connect([(coregister, tck2trk, [("out_matrix_file", "matrix_file")])]) mapping.connect([(probCSDstreamtrack, tck2trk, [("tracked", "in_file")])]) mapping.connect([(tck2trk, creatematrix, [("out_file", "tract_file")])]) mapping.connect([(tck2trk, trk2tdi, [("out_file", "in_file")])]) -mapping.connect([(inputnode, creatematrix, [("subject_id", "out_matrix_file")])]) -mapping.connect([(inputnode, creatematrix, [("subject_id", "out_matrix_mat_file")])]) +mapping.connect([(inputnode, creatematrix, [("subject_id", + "out_matrix_file")])]) +mapping.connect([(inputnode, creatematrix, [("subject_id", + "out_matrix_mat_file")])]) mapping.connect([(parcellate, creatematrix, [("roi_file", "roi_file")])]) mapping.connect([(parcellate, createnodes, [("roi_file", "roi_file")])]) -mapping.connect([(createnodes, creatematrix, [("node_network", "resolution_network_file")])]) - +mapping.connect([(createnodes, creatematrix, [("node_network", + "resolution_network_file")])]) """ The merge nodes defined earlier are used here to create lists of the files which are destined for the CFFConverter. @@ -516,24 +548,31 @@ mapping.connect([(mris_convertRH, giftiSurfaces, [("converted", "in2")])]) mapping.connect([(mris_convertLHwhite, giftiSurfaces, [("converted", "in3")])]) mapping.connect([(mris_convertRHwhite, giftiSurfaces, [("converted", "in4")])]) -mapping.connect([(mris_convertLHinflated, giftiSurfaces, [("converted", "in5")])]) -mapping.connect([(mris_convertRHinflated, giftiSurfaces, [("converted", "in6")])]) -mapping.connect([(mris_convertLHsphere, giftiSurfaces, [("converted", "in7")])]) -mapping.connect([(mris_convertRHsphere, giftiSurfaces, [("converted", "in8")])]) +mapping.connect([(mris_convertLHinflated, giftiSurfaces, [("converted", + "in5")])]) +mapping.connect([(mris_convertRHinflated, giftiSurfaces, [("converted", + "in6")])]) +mapping.connect([(mris_convertLHsphere, giftiSurfaces, [("converted", + "in7")])]) +mapping.connect([(mris_convertRHsphere, giftiSurfaces, [("converted", + "in8")])]) mapping.connect([(tessflow, giftiSurfaces, [("outputspec.meshes", "in9")])]) mapping.connect([(mris_convertLHlabels, giftiLabels, [("converted", "in1")])]) mapping.connect([(mris_convertRHlabels, giftiLabels, [("converted", "in2")])]) mapping.connect([(parcellate, niftiVolumes, [("roi_file", "in1")])]) -mapping.connect([(eddycorrect, niftiVolumes, [("outputnode.eddy_corrected", "in2")])]) +mapping.connect([(eddycorrect, niftiVolumes, [("outputnode.eddy_corrected", + "in2")])]) mapping.connect([(mri_convert_Brain, niftiVolumes, [("out_file", "in3")])]) mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file", "in1")])]) -mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm", "in2")])]) -mapping.connect([(creatematrix, fiberDataArrays, [("fiber_length_file", "in3")])]) -mapping.connect([(creatematrix, fiberDataArrays, [("fiber_label_file", "in4")])]) - +mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm", + "in2")])]) +mapping.connect([(creatematrix, fiberDataArrays, [("fiber_length_file", + "in3")])]) +mapping.connect([(creatematrix, fiberDataArrays, [("fiber_label_file", + "in4")])]) """ This block actually connects the merged lists to the CFF converter. We pass the surfaces and volumes that are to be included, as well as the tracts and the network itself. The currently @@ -544,29 +583,38 @@ mapping.connect([(giftiSurfaces, CFFConverter, [("out", "gifti_surfaces")])]) mapping.connect([(giftiLabels, CFFConverter, [("out", "gifti_labels")])]) -mapping.connect([(creatematrix, CFFConverter, [("matrix_files", "gpickled_networks")])]) +mapping.connect([(creatematrix, CFFConverter, [("matrix_files", + "gpickled_networks")])]) mapping.connect([(niftiVolumes, CFFConverter, [("out", "nifti_volumes")])]) mapping.connect([(fiberDataArrays, CFFConverter, [("out", "data_files")])]) -mapping.connect([(creatematrix, CFFConverter, [("filtered_tractographies", "tract_files")])]) +mapping.connect([(creatematrix, CFFConverter, [("filtered_tractographies", + "tract_files")])]) mapping.connect([(inputnode, CFFConverter, [("subject_id", "title")])]) - """ The graph theoretical metrics are computed using the networkx workflow and placed in another CFF file """ -mapping.connect([(inputnode, networkx, [("subject_id", "inputnode.extra_field")])]) -mapping.connect([(creatematrix, networkx, [("intersection_matrix_file", "inputnode.network_file")])]) - -mapping.connect([(networkx, NxStatsCFFConverter, [("outputnode.network_files", "gpickled_networks")])]) -mapping.connect([(giftiSurfaces, NxStatsCFFConverter, [("out", "gifti_surfaces")])]) -mapping.connect([(giftiLabels, NxStatsCFFConverter, [("out", "gifti_labels")])]) -mapping.connect([(niftiVolumes, NxStatsCFFConverter, [("out", "nifti_volumes")])]) -mapping.connect([(fiberDataArrays, NxStatsCFFConverter, [("out", "data_files")])]) +mapping.connect([(inputnode, networkx, [("subject_id", + "inputnode.extra_field")])]) +mapping.connect([(creatematrix, networkx, [("intersection_matrix_file", + "inputnode.network_file")])]) + +mapping.connect([(networkx, NxStatsCFFConverter, [("outputnode.network_files", + "gpickled_networks")])]) +mapping.connect([(giftiSurfaces, NxStatsCFFConverter, [("out", + "gifti_surfaces")])]) +mapping.connect([(giftiLabels, NxStatsCFFConverter, [("out", + "gifti_labels")])]) +mapping.connect([(niftiVolumes, NxStatsCFFConverter, [("out", + "nifti_volumes")])]) +mapping.connect([(fiberDataArrays, NxStatsCFFConverter, [("out", + "data_files")])]) mapping.connect([(inputnode, NxStatsCFFConverter, [("subject_id", "title")])]) -mapping.connect([(inputnode, cmats_to_csv, [("subject_id", "inputnode.extra_field")])]) -mapping.connect([(creatematrix, cmats_to_csv, [("matlab_matrix_files", "inputnode.matlab_matrix_files")])]) - +mapping.connect([(inputnode, cmats_to_csv, [("subject_id", + "inputnode.extra_field")])]) +mapping.connect([(creatematrix, cmats_to_csv, + [("matlab_matrix_files", "inputnode.matlab_matrix_files")])]) """ Create a higher-level workflow ------------------------------ @@ -578,15 +626,12 @@ connectivity = pe.Workflow(name="connectivity") connectivity.base_dir = op.abspath('dmri_connectivity_advanced') -connectivity.connect([ - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, mapping, [('dwi', 'inputnode.dwi'), - ('bvals', 'inputnode.bvals'), - ('bvecs', 'inputnode.bvecs') - ]), - (infosource, mapping, [('subject_id', 'inputnode.subject_id')]) -]) - +connectivity.connect([(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, mapping, + [('dwi', 'inputnode.dwi'), ('bvals', 'inputnode.bvals'), + ('bvecs', 'inputnode.bvecs')]), + (infosource, mapping, [('subject_id', + 'inputnode.subject_id')])]) """ The following functions run the whole workflow and produce a .dot and .png graph of the processing pipeline. """ diff --git a/examples/dmri_dtk_dti.py b/examples/dmri_dtk_dti.py index 4a5e2676cf..2946e305cc 100755 --- a/examples/dmri_dtk_dti.py +++ b/examples/dmri_dtk_dti.py @@ -13,21 +13,20 @@ More details can be found at http://www.fmrib.ox.ac.uk/fslcourse/lectures/practicals/fdt/index.htm -In order to run this tutorial you need to have Diffusion Toolkit and FSL tools installed and -accessible from matlab/command line. Check by calling fslinfo and dtk from the command -line. +In order to run this tutorial you need to have Diffusion Toolkit and FSL tools +installed and accessible from matlab/command line. Check by calling fslinfo and +dtk from the command line. Tell python where to find the appropriate functions. """ -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.fsl as fsl # fsl +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.fsl as fsl # fsl import nipype.interfaces.diffusion_toolkit as dtk -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import os # system functions +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import os # system functions from nipype.workflows.dmri.fsl.dti import create_eddy_correct_pipeline - """ Confirm package dependencies are installed. (This is only for the tutorial, rarely would you put this in your own code.) @@ -38,8 +37,6 @@ package_check('numpy', '1.3', 'tutorial1') package_check('scipy', '0.7', 'tutorial1') package_check('IPython', '0.10', 'tutorial1') - - """ Setting up workflows -------------------- @@ -51,8 +48,8 @@ The nipype tutorial contains data for two subjects. Subject data is in two subdirectories, ``dwis1`` and ``dwis2``. Each subject directory -contains each of the following files: bvec, bval, diffusion weighted data, a set of target masks, -a seed file, and a transformation matrix. +contains each of the following files: bvec, bval, diffusion weighted data, a +set of target masks, a seed file, and a transformation matrix. Below we set some variables to inform the ``datasource`` about the layout of our data. We specify the location of the data, the subject @@ -64,19 +61,17 @@ """ subject_list = ['subj1'] - - """ Map field names to individual subject runs """ -info = dict(dwi=[['subject_id', 'data']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + dwi=[['subject_id', 'data']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -87,7 +82,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -96,9 +90,10 @@ functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" @@ -109,8 +104,6 @@ datasource.inputs.field_template = dict(dwi='%s/%s.nii.gz') datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - - """ Setup for Diffusion Tensor Computation -------------------------------------- @@ -118,7 +111,6 @@ """ computeTensor = pe.Workflow(name='computeTensor') - """ extract the volume with b=0 (nodif_brain) """ @@ -126,7 +118,6 @@ fslroi = pe.Node(interface=fsl.ExtractROI(), name='fslroi') fslroi.inputs.t_min = 0 fslroi.inputs.t_size = 1 - """ create a brain mask from the nodif_brain """ @@ -134,30 +125,24 @@ bet = pe.Node(interface=fsl.BET(), name='bet') bet.inputs.mask = True bet.inputs.frac = 0.34 - """ correct the diffusion weighted images for eddy_currents """ eddycorrect = create_eddy_correct_pipeline('eddycorrect') eddycorrect.inputs.inputnode.ref_num = 0 - """ compute the diffusion tensor in each voxel """ dtifit = pe.Node(interface=dtk.DTIRecon(), name='dtifit') - """ connect all the nodes for this workflow """ -computeTensor.connect([ - (fslroi, bet, [('roi_file', 'in_file')]), - (eddycorrect, dtifit, [('outputnode.eddy_corrected', 'DWI')]) -]) - - +computeTensor.connect([(fslroi, bet, [('roi_file', 'in_file')]), + (eddycorrect, dtifit, [('outputnode.eddy_corrected', + 'DWI')])]) """ Setup for Tracktography ----------------------- @@ -175,11 +160,8 @@ connect all the nodes for this workflow """ -tractography.connect([ - (dtk_tracker, smooth_trk, [('track_file', 'track_file')]) -]) - - +tractography.connect([(dtk_tracker, smooth_trk, [('track_file', + 'track_file')])]) """ Setup data storage area """ @@ -189,26 +171,26 @@ def getstripdir(subject_id): - return os.path.join(os.path.abspath('data/workingdir/dwiproc'), '_subject_id_%s' % subject_id) + return os.path.join( + os.path.abspath('data/workingdir/dwiproc'), + '_subject_id_%s' % subject_id) """ -Setup the pipeline that combines the two workflows: tractography and computeTensor ----------------------------------------------------------------------------------- +Setup the pipeline that combines the 2 workflows: tractography & computeTensor +------------------------------------------------------------------------------ """ dwiproc = pe.Workflow(name="dwiproc") dwiproc.base_dir = os.path.abspath('dtk_dti_tutorial') -dwiproc.connect([ - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, computeTensor, [('dwi', 'fslroi.in_file'), - ('bvals', 'dtifit.bvals'), - ('bvecs', 'dtifit.bvecs'), - ('dwi', 'eddycorrect.inputnode.in_file')]), - (computeTensor, tractography, [('bet.mask_file', 'dtk_tracker.mask1_file'), - ('dtifit.tensor', 'dtk_tracker.tensor_file') - ]) -]) +dwiproc.connect([(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, computeTensor, + [('dwi', 'fslroi.in_file'), ('bvals', 'dtifit.bvals'), + ('bvecs', 'dtifit.bvecs'), + ('dwi', 'eddycorrect.inputnode.in_file')]), + (computeTensor, tractography, + [('bet.mask_file', 'dtk_tracker.mask1_file'), + ('dtifit.tensor', 'dtk_tracker.tensor_file')])]) if __name__ == '__main__': dwiproc.run() diff --git a/examples/dmri_dtk_odf.py b/examples/dmri_dtk_odf.py index b4fb978dd0..14367668b6 100755 --- a/examples/dmri_dtk_odf.py +++ b/examples/dmri_dtk_odf.py @@ -13,21 +13,20 @@ More details can be found at http://www.fmrib.ox.ac.uk/fslcourse/lectures/practicals/fdt/index.htm -In order to run this tutorial you need to have Diffusion Toolkit and FSL tools installed and -accessible from matlab/command line. Check by calling fslinfo and dtk from the command -line. +In order to run this tutorial you need to have Diffusion Toolkit and FSL tools +installed and accessible from matlab/command line. Check by calling fslinfo and +dtk from the command line. Tell python where to find the appropriate functions. """ -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.fsl as fsl # fsl +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.fsl as fsl # fsl import nipype.interfaces.diffusion_toolkit as dtk -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import os # system functions +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import os # system functions from nipype.workflows.dmri.fsl.dti import create_eddy_correct_pipeline - """ Confirm package dependencies are installed. (This is only for the tutorial, rarely would you put this in your own code.) @@ -38,8 +37,6 @@ package_check('numpy', '1.3', 'tutorial1') package_check('scipy', '0.7', 'tutorial1') package_check('IPython', '0.10', 'tutorial1') - - """ Setting up workflows -------------------- @@ -51,8 +48,8 @@ The nipype tutorial contains data for two subjects. Subject data is in two subdirectories, ``dwis1`` and ``dwis2``. Each subject directory -contains each of the following files: bvec, bval, diffusion weighted data, a set of target masks, -a seed file, and a transformation matrix. +contains each of the following files: bvec, bval, diffusion weighted data, a +set of target masks, a seed file, and a transformation matrix. Below we set some variables to inform the ``datasource`` about the layout of our data. We specify the location of the data, the subject @@ -64,19 +61,17 @@ """ subject_list = ['siemens_hardi_test'] - - """ Map field names to individual subject runs """ -info = dict(dwi=[['subject_id', 'siemens_hardi_test_data']], - bvecs=[['subject_id', 'siemens_hardi_test_data.bvec']], - bvals=[['subject_id', 'siemens_hardi_test_data.bval']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + dwi=[['subject_id', 'siemens_hardi_test_data']], + bvecs=[['subject_id', 'siemens_hardi_test_data.bvec']], + bvals=[['subject_id', 'siemens_hardi_test_data.bval']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -87,7 +82,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -96,9 +90,10 @@ functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" @@ -109,8 +104,6 @@ datasource.inputs.field_template = dict(dwi='%s/%s.nii') datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - - """ Setup for ODF Computation -------------------------------------- @@ -118,7 +111,6 @@ """ compute_ODF = pe.Workflow(name='compute_ODF') - """ extract the volume with b=0 (nodif_brain) """ @@ -126,7 +118,6 @@ fslroi = pe.Node(interface=fsl.ExtractROI(), name='fslroi') fslroi.inputs.t_min = 0 fslroi.inputs.t_size = 1 - """ create a brain mask from the nodif_brain """ @@ -134,7 +125,6 @@ bet = pe.Node(interface=fsl.BET(), name='bet') bet.inputs.mask = True bet.inputs.frac = 0.34 - """ correct the diffusion weighted images for eddy_currents """ @@ -142,23 +132,19 @@ eddycorrect = create_eddy_correct_pipeline('eddycorrect') eddycorrect.inputs.inputnode.ref_num = 0 - hardi_mat = pe.Node(interface=dtk.HARDIMat(), name='hardi_mat') odf_recon = pe.Node(interface=dtk.ODFRecon(), name='odf_recon') - """ connect all the nodes for this workflow """ -compute_ODF.connect([ - (fslroi, bet, [('roi_file', 'in_file')]), - (eddycorrect, odf_recon, [('outputnode.eddy_corrected', 'DWI')]), - (eddycorrect, hardi_mat, [('outputnode.eddy_corrected', 'reference_file')]), - (hardi_mat, odf_recon, [('out_file', 'matrix')]) -]) - - +compute_ODF.connect( + [(fslroi, bet, [('roi_file', 'in_file')]), + (eddycorrect, odf_recon, [('outputnode.eddy_corrected', 'DWI')]), + (eddycorrect, hardi_mat, + [('outputnode.eddy_corrected', + 'reference_file')]), (hardi_mat, odf_recon, [('out_file', 'matrix')])]) """ Setup for Tracktography ----------------------- @@ -175,29 +161,24 @@ connect all the nodes for this workflow """ -tractography.connect([ - (odf_tracker, smooth_trk, [('track_file', 'track_file')]) -]) - - +tractography.connect([(odf_tracker, smooth_trk, [('track_file', + 'track_file')])]) """ -Setup the pipeline that combines the two workflows: tractography and compute_ODF ----------------------------------------------------------------------------------- +Setup the pipeline that combines the 2 workflows: tractography and compute_ODF +------------------------------------------------------------------------------ """ dwiproc = pe.Workflow(name="dwiproc") dwiproc.base_dir = os.path.abspath('dtk_odf_tutorial') -dwiproc.connect([ - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, compute_ODF, [('dwi', 'fslroi.in_file'), - ('bvals', 'hardi_mat.bvals'), - ('bvecs', 'hardi_mat.bvecs'), - ('dwi', 'eddycorrect.inputnode.in_file')]), - (compute_ODF, tractography, [('bet.mask_file', 'odf_tracker.mask1_file'), - ('odf_recon.ODF', 'odf_tracker.ODF'), - ('odf_recon.max', 'odf_tracker.max') - ]) -]) +dwiproc.connect([(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, compute_ODF, + [('dwi', 'fslroi.in_file'), ('bvals', 'hardi_mat.bvals'), + ('bvecs', 'hardi_mat.bvecs'), + ('dwi', 'eddycorrect.inputnode.in_file')]), + (compute_ODF, tractography, + [('bet.mask_file', 'odf_tracker.mask1_file'), + ('odf_recon.ODF', 'odf_tracker.ODF'), + ('odf_recon.max', 'odf_tracker.max')])]) dwiproc.inputs.compute_ODF.hardi_mat.oblique_correction = True dwiproc.inputs.compute_ODF.odf_recon.n_directions = 31 diff --git a/examples/dmri_fsl_dti.py b/examples/dmri_fsl_dti.py index 05891a8727..1ac833a98d 100755 --- a/examples/dmri_fsl_dti.py +++ b/examples/dmri_fsl_dti.py @@ -20,14 +20,13 @@ Tell python where to find the appropriate functions. """ -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.fsl as fsl # fsl -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import os # system functions +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.fsl as fsl # fsl +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import os # system functions from nipype.workflows.dmri.fsl.dti import create_eddy_correct_pipeline,\ create_bedpostx_pipeline - """ Confirm package dependencies are installed. (This is only for the tutorial, rarely would you put this in your own code.) @@ -38,8 +37,6 @@ package_check('numpy', '1.3', 'tutorial1') package_check('scipy', '0.7', 'tutorial1') package_check('IPython', '0.10', 'tutorial1') - - """ Setting up workflows -------------------- @@ -64,27 +61,26 @@ """ subject_list = ['subj1'] - - """ Map field names to individual subject runs """ -info = dict(dwi=[['subject_id', 'data']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']], - seed_file=[['subject_id', 'MASK_average_thal_right']], - target_masks=[['subject_id', ['MASK_average_M1_right', - 'MASK_average_S1_right', - 'MASK_average_occipital_right', - 'MASK_average_pfc_right', - 'MASK_average_pmc_right', - 'MASK_average_ppc_right', - 'MASK_average_temporal_right']]]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + dwi=[['subject_id', 'data']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']], + seed_file=[['subject_id', 'MASK_average_thal_right']], + target_masks=[[ + 'subject_id', [ + 'MASK_average_M1_right', 'MASK_average_S1_right', + 'MASK_average_occipital_right', 'MASK_average_pfc_right', + 'MASK_average_pmc_right', 'MASK_average_ppc_right', + 'MASK_average_temporal_right' + ] + ]]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """ Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The @@ -96,7 +92,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -105,9 +100,10 @@ functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" @@ -115,12 +111,12 @@ # http://www.fmrib.ox.ac.uk/fslcourse/fsl_course_data2.tar.gz datasource.inputs.base_directory = os.path.abspath('fsl_course_data/fdt/') -datasource.inputs.field_template = dict(dwi='%s/%s.nii.gz', - seed_file="%s.bedpostX/%s.nii.gz", - target_masks="%s.bedpostX/%s.nii.gz") +datasource.inputs.field_template = dict( + dwi='%s/%s.nii.gz', + seed_file="%s.bedpostX/%s.nii.gz", + target_masks="%s.bedpostX/%s.nii.gz") datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """ Setup for Diffusion Tensor Computation -------------------------------------- @@ -129,7 +125,6 @@ """ computeTensor = pe.Workflow(name='computeTensor') - """ extract the volume with b=0 (nodif_brain) """ @@ -137,7 +132,6 @@ fslroi = pe.Node(interface=fsl.ExtractROI(), name='fslroi') fslroi.inputs.t_min = 0 fslroi.inputs.t_size = 1 - """ create a brain mask from the nodif_brain """ @@ -145,32 +139,26 @@ bet = pe.Node(interface=fsl.BET(), name='bet') bet.inputs.mask = True bet.inputs.frac = 0.34 - """ correct the diffusion weighted images for eddy_currents """ eddycorrect = create_eddy_correct_pipeline('eddycorrect') eddycorrect.inputs.inputnode.ref_num = 0 - """ compute the diffusion tensor in each voxel """ dtifit = pe.Node(interface=fsl.DTIFit(), name='dtifit') - """ connect all the nodes for this workflow """ -computeTensor.connect([ - (fslroi, bet, [('roi_file', 'in_file')]), - (eddycorrect, dtifit, [('outputnode.eddy_corrected', 'dwi')]), - (infosource, dtifit, [['subject_id', 'base_name']]), - (bet, dtifit, [('mask_file', 'mask')]) -]) - - +computeTensor.connect( + [(fslroi, bet, [('roi_file', 'in_file')]), + (eddycorrect, dtifit, [('outputnode.eddy_corrected', 'dwi')]), + (infosource, dtifit, + [['subject_id', 'base_name']]), (bet, dtifit, [('mask_file', 'mask')])]) """ Setup for Tracktography ----------------------- @@ -181,7 +169,6 @@ tractography = pe.Workflow(name='tractography') tractography.base_dir = os.path.abspath('fsl_dti_tutorial') - """ estimate the diffusion parameters: phi, theta, and so on """ @@ -189,11 +176,9 @@ bedpostx = create_bedpostx_pipeline() bedpostx.get_node("xfibres").iterables = ("n_fibres", [1, 2]) - flirt = pe.Node(interface=fsl.FLIRT(), name='flirt') flirt.inputs.in_file = fsl.Info.standard_image('MNI152_T1_2mm_brain.nii.gz') flirt.inputs.dof = 12 - """ perform probabilistic tracktography """ @@ -207,29 +192,22 @@ probtrackx.inputs.opd = True probtrackx.inputs.os2t = True probtrackx.inputs.loop_check = True - - """ perform hard segmentation on the output of probtrackx """ findthebiggest = pe.Node(interface=fsl.FindTheBiggest(), name='findthebiggest') - - """ connect all the nodes for this workflow """ tractography.add_nodes([bedpostx, flirt]) -tractography.connect([(bedpostx, probtrackx, [('outputnode.thsamples', 'thsamples'), - ('outputnode.phsamples', 'phsamples'), - ('outputnode.fsamples', 'fsamples') - ]), +tractography.connect([(bedpostx, probtrackx, + [('outputnode.thsamples', + 'thsamples'), ('outputnode.phsamples', 'phsamples'), + ('outputnode.fsamples', 'fsamples')]), (probtrackx, findthebiggest, [('targets', 'in_files')]), - (flirt, probtrackx, [('out_matrix_file', 'xfm')]) - ]) - - + (flirt, probtrackx, [('out_matrix_file', 'xfm')])]) """ Setup data storage area """ @@ -240,35 +218,36 @@ def getstripdir(subject_id): import os - return os.path.join(os.path.abspath('data/workingdir/dwiproc'), '_subject_id_%s' % subject_id) + return os.path.join( + os.path.abspath('data/workingdir/dwiproc'), + '_subject_id_%s' % subject_id) """ -Setup the pipeline that combines the two workflows: tractography and computeTensor ----------------------------------------------------------------------------------- +Setup the pipeline that combines the 2 workflows: tractography & computeTensor +------------------------------------------------------------------------------ """ dwiproc = pe.Workflow(name="dwiproc") dwiproc.base_dir = os.path.abspath('fsl_dti_tutorial') -dwiproc.connect([ - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, computeTensor, [('dwi', 'fslroi.in_file'), - ('bvals', 'dtifit.bvals'), - ('bvecs', 'dtifit.bvecs'), - ('dwi', 'eddycorrect.inputnode.in_file')]), - (datasource, tractography, [('bvals', 'bedpostx.inputnode.bvals'), - ('bvecs', 'bedpostx.inputnode.bvecs'), - ('seed_file', 'probtrackx.seed'), - ('target_masks', 'probtrackx.target_masks') - ]), - (computeTensor, tractography, [('eddycorrect.outputnode.eddy_corrected', 'bedpostx.inputnode.dwi'), - ('bet.mask_file', 'bedpostx.inputnode.mask'), - ('bet.mask_file', 'probtrackx.mask'), - ('fslroi.roi_file', 'flirt.reference')]), - (infosource, datasink, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (tractography, datasink, [('findthebiggest.out_file', 'fbiggest.@biggestsegmentation')]) -]) +dwiproc.connect( + [(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, computeTensor, + [('dwi', 'fslroi.in_file'), ('bvals', 'dtifit.bvals'), + ('bvecs', 'dtifit.bvecs'), ('dwi', 'eddycorrect.inputnode.in_file')]), + (datasource, tractography, + [('bvals', 'bedpostx.inputnode.bvals'), + ('bvecs', 'bedpostx.inputnode.bvecs'), ('seed_file', 'probtrackx.seed'), + ('target_masks', 'probtrackx.target_masks')]), + (computeTensor, tractography, + [('eddycorrect.outputnode.eddy_corrected', 'bedpostx.inputnode.dwi'), + ('bet.mask_file', 'bedpostx.inputnode.mask'), ('bet.mask_file', + 'probtrackx.mask'), + ('fslroi.roi_file', 'flirt.reference')]), (infosource, datasink, [ + ('subject_id', 'container'), (('subject_id', getstripdir), + 'strip_dir') + ]), (tractography, datasink, [('findthebiggest.out_file', + 'fbiggest.@biggestsegmentation')])]) if __name__ == '__main__': dwiproc.run() diff --git a/examples/dmri_group_connectivity_camino.py b/examples/dmri_group_connectivity_camino.py index afb2ad1e60..b244adee86 100644 --- a/examples/dmri_group_connectivity_camino.py +++ b/examples/dmri_group_connectivity_camino.py @@ -54,13 +54,14 @@ """ import nipype.interfaces.fsl as fsl -import nipype.interfaces.freesurfer as fs # freesurfer -import os.path as op # system functions +import nipype.interfaces.freesurfer as fs # freesurfer +import os.path as op # system functions import cmp from nipype.workflows.dmri.camino.group_connectivity import create_group_connectivity_pipeline -from nipype.workflows.dmri.connectivity.group_connectivity import (create_merge_networks_by_group_workflow, - create_merge_group_networks_workflow, create_average_networks_by_group_workflow) - +from nipype.workflows.dmri.connectivity.group_connectivity import ( + create_merge_networks_by_group_workflow, + create_merge_group_networks_workflow, + create_average_networks_by_group_workflow) """ Set the proper directories -------------------------- @@ -72,7 +73,6 @@ data_dir = op.abspath('groupcondatapackage/data/') fs.FSCommand.set_default_subjects_dir(subjects_dir) fsl.FSLCommand.set_default_output_type('NIFTI') - """ Define the groups ----------------- @@ -84,14 +84,12 @@ group_list = {} group_list['controls'] = ['cont17'] group_list['parkinsons'] = ['pat10', 'pat20'] - """ The output directory must be named as well. """ global output_dir output_dir = op.abspath('dmri_group_connectivity_camino') - """ Main processing loop ==================== @@ -122,46 +120,49 @@ """ - title = '' for idx, group_id in enumerate(group_list.keys()): title += group_id if not idx == len(list(group_list.keys())) - 1: title += '-' - info = dict(dwi=[['subject_id', 'dti']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']]) + info = dict( + dwi=[['subject_id', 'dti']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']]) - l1pipeline = create_group_connectivity_pipeline(group_list, group_id, data_dir, subjects_dir, output_dir, info) + l1pipeline = create_group_connectivity_pipeline( + group_list, group_id, data_dir, subjects_dir, output_dir, info) # Here we define the parcellation scheme and the number of tracks to produce parcellation_scheme = 'NativeFreesurfer' cmp_config = cmp.configuration.PipelineConfiguration() cmp_config.parcellation_scheme = parcellation_scheme - l1pipeline.inputs.connectivity.inputnode.resolution_network_file = cmp_config._get_lausanne_parcellation(parcellation_scheme)['freesurferaparc']['node_information_graphml'] + l1pipeline.inputs.connectivity.inputnode.resolution_network_file = cmp_config._get_lausanne_parcellation( + parcellation_scheme)['freesurferaparc']['node_information_graphml'] l1pipeline.run() l1pipeline.write_graph(format='eps', graph2use='flat') # The second-level pipeline is created here - l2pipeline = create_merge_networks_by_group_workflow(group_list, group_id, data_dir, subjects_dir, output_dir) + l2pipeline = create_merge_networks_by_group_workflow( + group_list, group_id, data_dir, subjects_dir, output_dir) l2pipeline.run() l2pipeline.write_graph(format='eps', graph2use='flat') - """ Now that the for loop is complete there are two grouped CFF files each containing the appropriate subjects. It is also convenient to have every subject in a single CFF file, so that is what the third-level pipeline does. """ -l3pipeline = create_merge_group_networks_workflow(group_list, data_dir, subjects_dir, output_dir, title) +l3pipeline = create_merge_group_networks_workflow( + group_list, data_dir, subjects_dir, output_dir, title) l3pipeline.run() l3pipeline.write_graph(format='eps', graph2use='flat') - """ The fourth and final workflow averages the networks and saves them in another CFF file """ -l4pipeline = create_average_networks_by_group_workflow(group_list, data_dir, subjects_dir, output_dir, title) +l4pipeline = create_average_networks_by_group_workflow( + group_list, data_dir, subjects_dir, output_dir, title) l4pipeline.run() l4pipeline.write_graph(format='eps', graph2use='flat') diff --git a/examples/dmri_group_connectivity_mrtrix.py b/examples/dmri_group_connectivity_mrtrix.py index 4bdc0ae2b2..e709b9ade9 100644 --- a/examples/dmri_group_connectivity_mrtrix.py +++ b/examples/dmri_group_connectivity_mrtrix.py @@ -54,12 +54,14 @@ """ import nipype.interfaces.fsl as fsl -import nipype.interfaces.freesurfer as fs # freesurfer -import os.path as op # system functions +import nipype.interfaces.freesurfer as fs # freesurfer +import os.path as op # system functions import cmp from nipype.workflows.dmri.mrtrix.group_connectivity import create_group_connectivity_pipeline -from nipype.workflows.dmri.connectivity.group_connectivity import (create_merge_network_results_by_group_workflow, create_merge_group_network_results_workflow, create_average_networks_by_group_workflow) - +from nipype.workflows.dmri.connectivity.group_connectivity import ( + create_merge_network_results_by_group_workflow, + create_merge_group_network_results_workflow, + create_average_networks_by_group_workflow) """ Set the proper directories -------------------------- @@ -70,7 +72,6 @@ data_dir = op.abspath('groupcondatapackage/data/') fs.FSCommand.set_default_subjects_dir(subjects_dir) fsl.FSLCommand.set_default_output_type('NIFTI') - """ Define the groups ----------------- @@ -82,14 +83,12 @@ group_list = {} group_list['controls'] = ['cont17'] group_list['parkinsons'] = ['pat10', 'pat20'] - """ The output directory must be named as well. """ global output_dir output_dir = op.abspath('dmri_group_connectivity_mrtrix') - """ Main processing loop ==================== @@ -134,11 +133,13 @@ if not idx == len(list(group_list.keys())) - 1: title += '-' - info = dict(dwi=[['subject_id', 'dti']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']]) + info = dict( + dwi=[['subject_id', 'dti']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']]) - l1pipeline = create_group_connectivity_pipeline(group_list, group_id, data_dir, subjects_dir, output_dir, info) + l1pipeline = create_group_connectivity_pipeline( + group_list, group_id, data_dir, subjects_dir, output_dir, info) # Here with invert the b-vectors in the Y direction and set the maximum harmonic order of the # spherical deconvolution step @@ -150,31 +151,34 @@ l1pipeline.inputs.connectivity.mapping.Parcellate.parcellation_name = parcellation_name cmp_config = cmp.configuration.PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" - l1pipeline.inputs.connectivity.mapping.inputnode_within.resolution_network_file = cmp_config._get_lausanne_parcellation('Lausanne2008')[parcellation_name]['node_information_graphml'] + l1pipeline.inputs.connectivity.mapping.inputnode_within.resolution_network_file = cmp_config._get_lausanne_parcellation( + 'Lausanne2008')[parcellation_name]['node_information_graphml'] l1pipeline.inputs.connectivity.mapping.probCSDstreamtrack.desired_number_of_tracks = 100000 l1pipeline.run() l1pipeline.write_graph(format='eps', graph2use='flat') # The second-level pipeline is created here - l2pipeline = create_merge_network_results_by_group_workflow(group_list, group_id, data_dir, subjects_dir, output_dir) - l2pipeline.inputs.l2inputnode.network_file = cmp_config._get_lausanne_parcellation('Lausanne2008')[parcellation_name]['node_information_graphml'] + l2pipeline = create_merge_network_results_by_group_workflow( + group_list, group_id, data_dir, subjects_dir, output_dir) + l2pipeline.inputs.l2inputnode.network_file = cmp_config._get_lausanne_parcellation( + 'Lausanne2008')[parcellation_name]['node_information_graphml'] l2pipeline.run() l2pipeline.write_graph(format='eps', graph2use='flat') - """ Now that the for loop is complete there are two grouped CFF files each containing the appropriate subjects. It is also convenient to have every subject in a single CFF file, so that is what the third-level pipeline does. """ -l3pipeline = create_merge_group_network_results_workflow(group_list, data_dir, subjects_dir, output_dir, title) +l3pipeline = create_merge_group_network_results_workflow( + group_list, data_dir, subjects_dir, output_dir, title) l3pipeline.run() l3pipeline.write_graph(format='eps', graph2use='flat') - """ The fourth and final workflow averages the networks and saves them in another CFF file """ -l4pipeline = create_average_networks_by_group_workflow(group_list, data_dir, subjects_dir, output_dir, title) +l4pipeline = create_average_networks_by_group_workflow( + group_list, data_dir, subjects_dir, output_dir, title) l4pipeline.run() l4pipeline.write_graph(format='eps', graph2use='flat') diff --git a/examples/dmri_mrtrix_dti.py b/examples/dmri_mrtrix_dti.py index 36b8f5508e..065c5ac99f 100755 --- a/examples/dmri_mrtrix_dti.py +++ b/examples/dmri_mrtrix_dti.py @@ -19,17 +19,16 @@ Import necessary modules from nipype. """ -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine import nipype.interfaces.mrtrix as mrtrix # <---- The important new part! import nipype.interfaces.fsl as fsl import nipype.algorithms.misc as misc import os -import os.path as op # system functions +import os.path as op # system functions fsl.FSLCommand.set_default_output_type('NIFTI') - """ This needs to point to the fdt folder you can find after extracting @@ -39,40 +38,41 @@ data_dir = op.abspath(op.join(op.curdir, 'exdata/')) subject_list = ['subj1'] - """ Use infosource node to loop through the subject list and define the input files. For our purposes, these are the diffusion-weighted MR image, b vectors, and b values. """ -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), name="infosource") +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") infosource.iterables = ('subject_id', subject_list) -info = dict(dwi=[['subject_id', 'data']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']]) - +info = dict( + dwi=[['subject_id', 'data']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']]) """ Use datasource node to perform the actual data grabbing. Templates for the associated images are used to obtain the correct images. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" datasource.inputs.base_directory = data_dir datasource.inputs.field_template = dict(dwi='%s/%s.nii.gz') datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """ An inputnode is used to pass the data obtained by the data grabber to the actual processing functions """ -inputnode = pe.Node(interface=util.IdentityInterface(fields=["dwi", "bvecs", "bvals"]), name="inputnode") - +inputnode = pe.Node( + interface=util.IdentityInterface(fields=["dwi", "bvecs", "bvals"]), + name="inputnode") """ Diffusion processing nodes -------------------------- @@ -89,7 +89,6 @@ """ fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix') - """ Tensors are fitted to each voxel in the diffusion-weighted image and from these three maps are created: * Major eigenvector in each voxel @@ -101,9 +100,10 @@ gunzip = pe.Node(interface=misc.Gunzip(), name='gunzip') dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(), name='dwi2tensor') tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(), name='tensor2vector') -tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(), name='tensor2adc') -tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(), name='tensor2fa') - +tensor2adc = pe.Node( + interface=mrtrix.Tensor2ApparentDiffusion(), name='tensor2adc') +tensor2fa = pe.Node( + interface=mrtrix.Tensor2FractionalAnisotropy(), name='tensor2fa') """ These nodes are used to create a rough brain mask from the b0 image. The b0 image is extracted from the original diffusion-weighted image, @@ -115,7 +115,6 @@ MRconvert.inputs.extract_at_coordinate = [0] threshold_b0 = pe.Node(interface=mrtrix.Threshold(), name='threshold_b0') median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3d') - """ The brain mask is also used to help identify single-fiber voxels. This is done by passing the brain mask through two erosion steps, @@ -123,13 +122,14 @@ thresholding the result to obtain some highly anisotropic within-brain voxels. """ -erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_firstpass') -erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_secondpass') +erode_mask_firstpass = pe.Node( + interface=mrtrix.Erode(), name='erode_mask_firstpass') +erode_mask_secondpass = pe.Node( + interface=mrtrix.Erode(), name='erode_mask_secondpass') MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply') MRmult_merge = pe.Node(interface=util.Merge(2), name="MRmultiply_merge") threshold_FA = pe.Node(interface=mrtrix.Threshold(), name='threshold_FA') threshold_FA.inputs.absolute_threshold_value = 0.7 - """ For whole-brain tracking we also require a broad white-matter seed mask. This is created by generating a white matter mask, given a brainmask, and @@ -137,10 +137,11 @@ """ bet = pe.Node(interface=fsl.BET(mask=True), name='bet_b0') -gen_WM_mask = pe.Node(interface=mrtrix.GenerateWhiteMatterMask(), name='gen_WM_mask') -threshold_wmmask = pe.Node(interface=mrtrix.Threshold(), name='threshold_wmmask') +gen_WM_mask = pe.Node( + interface=mrtrix.GenerateWhiteMatterMask(), name='gen_WM_mask') +threshold_wmmask = pe.Node( + interface=mrtrix.Threshold(), name='threshold_wmmask') threshold_wmmask.inputs.absolute_threshold_value = 0.4 - """ The spherical deconvolution step depends on the estimate of the response function in the highly anisotropic voxels we obtained above. @@ -151,23 +152,25 @@ """ -estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') +estimateresponse = pe.Node( + interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') estimateresponse.inputs.maximum_harmonic_order = 6 -csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') +csdeconv = pe.Node( + interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') csdeconv.inputs.maximum_harmonic_order = 6 - """ Finally, we track probabilistically using the orientation distribution functions obtained earlier. The tracts are then used to generate a tract-density image, and they are also converted to TrackVis format. """ -probCSDstreamtrack = pe.Node(interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(), name='probCSDstreamtrack') +probCSDstreamtrack = pe.Node( + interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(), + name='probCSDstreamtrack') probCSDstreamtrack.inputs.inputmodel = 'SD_PROB' probCSDstreamtrack.inputs.maximum_number_of_tracks = 150000 tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(), name='tracks2prob') tracks2prob.inputs.colour = True tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk') - """ Creating the workflow --------------------- @@ -180,14 +183,15 @@ ("bvals", "bval_file")])]) tractography.connect([(inputnode, gunzip, [("dwi", "in_file")])]) tractography.connect([(gunzip, dwi2tensor, [("out_file", "in_file")])]) -tractography.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file", "encoding_file")])]) +tractography.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file", + "encoding_file")])]) -tractography.connect([(dwi2tensor, tensor2vector, [['tensor', 'in_file']]), - (dwi2tensor, tensor2adc, [['tensor', 'in_file']]), - (dwi2tensor, tensor2fa, [['tensor', 'in_file']]), - ]) +tractography.connect([ + (dwi2tensor, tensor2vector, [['tensor', 'in_file']]), + (dwi2tensor, tensor2adc, [['tensor', 'in_file']]), + (dwi2tensor, tensor2fa, [['tensor', 'in_file']]), +]) tractography.connect([(tensor2fa, MRmult_merge, [("FA", "in1")])]) - """ This block creates the rough brain mask to be multiplied, mulitplies it with the fractional anisotropy image, and thresholds it to get the single-fiber voxels. @@ -196,12 +200,14 @@ tractography.connect([(gunzip, MRconvert, [("out_file", "in_file")])]) tractography.connect([(MRconvert, threshold_b0, [("converted", "in_file")])]) tractography.connect([(threshold_b0, median3d, [("out_file", "in_file")])]) -tractography.connect([(median3d, erode_mask_firstpass, [("out_file", "in_file")])]) -tractography.connect([(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])]) -tractography.connect([(erode_mask_secondpass, MRmult_merge, [("out_file", "in2")])]) +tractography.connect([(median3d, erode_mask_firstpass, [("out_file", + "in_file")])]) +tractography.connect([(erode_mask_firstpass, erode_mask_secondpass, + [("out_file", "in_file")])]) +tractography.connect([(erode_mask_secondpass, MRmult_merge, [("out_file", + "in2")])]) tractography.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])]) tractography.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])]) - """ Here the thresholded white matter mask is created for seeding the tractography. """ @@ -209,38 +215,44 @@ tractography.connect([(gunzip, bet, [("out_file", "in_file")])]) tractography.connect([(gunzip, gen_WM_mask, [("out_file", "in_file")])]) tractography.connect([(bet, gen_WM_mask, [("mask_file", "binary_mask")])]) -tractography.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file", "encoding_file")])]) -tractography.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap", "in_file")])]) - +tractography.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file", + "encoding_file")])]) +tractography.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap", + "in_file")])]) """ Next we estimate the fiber response distribution. """ tractography.connect([(gunzip, estimateresponse, [("out_file", "in_file")])]) -tractography.connect([(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])]) -tractography.connect([(threshold_FA, estimateresponse, [("out_file", "mask_image")])]) - +tractography.connect([(fsl2mrtrix, estimateresponse, [("encoding_file", + "encoding_file")])]) +tractography.connect([(threshold_FA, estimateresponse, [("out_file", + "mask_image")])]) """ Run constrained spherical deconvolution. """ tractography.connect([(gunzip, csdeconv, [("out_file", "in_file")])]) -tractography.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap", "mask_image")])]) -tractography.connect([(estimateresponse, csdeconv, [("response", "response_file")])]) -tractography.connect([(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")])]) - +tractography.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap", + "mask_image")])]) +tractography.connect([(estimateresponse, csdeconv, [("response", + "response_file")])]) +tractography.connect([(fsl2mrtrix, csdeconv, [("encoding_file", + "encoding_file")])]) """ Connect the tractography and compute the tract density image. """ -tractography.connect([(threshold_wmmask, probCSDstreamtrack, [("out_file", "seed_file")])]) -tractography.connect([(csdeconv, probCSDstreamtrack, [("spherical_harmonics_image", "in_file")])]) -tractography.connect([(probCSDstreamtrack, tracks2prob, [("tracked", "in_file")])]) +tractography.connect([(threshold_wmmask, probCSDstreamtrack, [("out_file", + "seed_file")])]) +tractography.connect([(csdeconv, probCSDstreamtrack, + [("spherical_harmonics_image", "in_file")])]) +tractography.connect([(probCSDstreamtrack, tracks2prob, [("tracked", + "in_file")])]) tractography.connect([(gunzip, tracks2prob, [("out_file", "template_file")])]) tractography.connect([(gunzip, tck2trk, [("out_file", "image_file")])]) tractography.connect([(probCSDstreamtrack, tck2trk, [("tracked", "in_file")])]) - """ Finally, we create another higher-level workflow to connect our tractography workflow with the info and datagrabbing nodes declared at the beginning. Our tutorial is now extensible to any arbitrary number of subjects by simply adding @@ -249,13 +261,10 @@ dwiproc = pe.Workflow(name="dwiproc") dwiproc.base_dir = os.path.abspath('dmri_mrtrix_dti') -dwiproc.connect([ - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, tractography, [('dwi', 'inputnode.dwi'), - ('bvals', 'inputnode.bvals'), - ('bvecs', 'inputnode.bvecs') - ]) -]) +dwiproc.connect([(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, tractography, + [('dwi', 'inputnode.dwi'), ('bvals', 'inputnode.bvals'), + ('bvecs', 'inputnode.bvecs')])]) if __name__ == '__main__': dwiproc.run() diff --git a/examples/dmri_preprocessing.py b/examples/dmri_preprocessing.py index d814e4facc..21d594d3b7 100644 --- a/examples/dmri_preprocessing.py +++ b/examples/dmri_preprocessing.py @@ -1,7 +1,6 @@ # coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ =================== dMRI: Preprocessing @@ -22,17 +21,15 @@ Import necessary modules from nipype. """ -import os # system functions -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.utility as niu # utility +import os # system functions +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.utility as niu # utility import nipype.algorithms.misc as misc -import nipype.pipeline.engine as pe # pypeline engine +import nipype.pipeline.engine as pe # pypeline engine from nipype.interfaces import fsl from nipype.interfaces import ants - - """ Load specific nipype's workflows for preprocessing of dMRI data: :class:`nipype.workflows.dmri.preprocess.epi.all_peb_pipeline`, @@ -42,24 +39,22 @@ """ from nipype.workflows.dmri.fsl.artifacts import all_fsl_pipeline, remove_bias - """ Map field names into individual subject runs """ -info = dict(dwi=[['subject_id', 'dwidata']], - bvecs=[['subject_id', 'bvecs']], - bvals=[['subject_id', 'bvals']], - dwi_rev=[['subject_id', 'nodif_PA']]) +info = dict( + dwi=[['subject_id', 'dwidata']], + bvecs=[['subject_id', 'bvecs']], + bvals=[['subject_id', 'bvals']], + dwi_rev=[['subject_id', 'nodif_PA']]) -infosource = pe.Node(interface=niu.IdentityInterface(fields=['subject_id']), - name="infosource") +infosource = pe.Node( + interface=niu.IdentityInterface(fields=['subject_id']), name="infosource") # Set the subject 1 identifier in subject_list, # we choose the preproc dataset as it contains uncorrected files. subject_list = ['subj1_preproc'] - - """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -70,8 +65,6 @@ """ infosource.iterables = ('subject_id', subject_list) - - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -80,29 +73,27 @@ functionality. """ -datasource = pe.Node(nio.DataGrabber(infields=['subject_id'], - outfields=list(info.keys())), name='datasource') +datasource = pe.Node( + nio.DataGrabber(infields=['subject_id'], outfields=list(info.keys())), + name='datasource') datasource.inputs.template = "%s/%s" # This needs to point to the fdt folder you can find after extracting # http://www.fmrib.ox.ac.uk/fslcourse/fsl_course_data2.tar.gz datasource.inputs.base_directory = os.path.abspath('fdt1') -datasource.inputs.field_template = dict(dwi='%s/%s.nii.gz', - dwi_rev='%s/%s.nii.gz') +datasource.inputs.field_template = dict( + dwi='%s/%s.nii.gz', dwi_rev='%s/%s.nii.gz') datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - - """ An inputnode is used to pass the data obtained by the data grabber to the actual processing functions """ -inputnode = pe.Node(niu.IdentityInterface(fields=["dwi", "bvecs", "bvals", - "dwi_rev"]), name="inputnode") - - +inputnode = pe.Node( + niu.IdentityInterface(fields=["dwi", "bvecs", "bvals", "dwi_rev"]), + name="inputnode") """ Setup for dMRI preprocessing @@ -128,8 +119,6 @@ epi_AP = {'echospacing': 66.5e-3, 'enc_dir': 'y-'} epi_PA = {'echospacing': 66.5e-3, 'enc_dir': 'y'} prep = all_fsl_pipeline(epi_params=epi_AP, altepi_params=epi_PA) - - """ Bias field correction @@ -141,8 +130,6 @@ """ bias = remove_bias() - - """ Connect nodes in workflow ========================= @@ -154,18 +141,13 @@ wf = pe.Workflow(name="dMRI_Preprocessing") wf.base_dir = os.path.abspath('preprocessing_dmri_tutorial') -wf.connect([ - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, prep, [('dwi', 'inputnode.in_file'), - ('dwi_rev', 'inputnode.alt_file'), - ('bvals', 'inputnode.in_bval'), - ('bvecs', 'inputnode.in_bvec')]), - (prep, bias, [('outputnode.out_file', 'inputnode.in_file'), - ('outputnode.out_mask', 'inputnode.in_mask')]), - (datasource, bias, [('bvals', 'inputnode.in_bval')]) -]) - - +wf.connect([(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, prep, + [('dwi', 'inputnode.in_file'), ('dwi_rev', 'inputnode.alt_file'), + ('bvals', 'inputnode.in_bval'), ('bvecs', 'inputnode.in_bvec')]), + (prep, bias, [('outputnode.out_file', 'inputnode.in_file'), + ('outputnode.out_mask', 'inputnode.in_mask')]), + (datasource, bias, [('bvals', 'inputnode.in_bval')])]) """ Run the workflow as command line executable """ diff --git a/examples/dmri_tbss_nki.py b/examples/dmri_tbss_nki.py index 67f3719b2f..5f2f3d5a01 100755 --- a/examples/dmri_tbss_nki.py +++ b/examples/dmri_tbss_nki.py @@ -12,19 +12,17 @@ from nipype.workflows.dmri.fsl.dti import create_eddy_correct_pipeline from nipype.workflows.dmri.fsl.tbss import create_tbss_non_FA, create_tbss_all - """ Tell python where to find the appropriate functions. """ -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.fsl as fsl # fsl -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import os # system functions +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.fsl as fsl # fsl +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import os # system functions fsl.FSLCommand.set_default_output_type('NIFTI') - """ You can get the data from: @@ -33,25 +31,28 @@ dataDir = os.path.abspath('nki_rs_data') workingdir = './tbss_example' -subjects_list = ['2475376', '3313349', '3808535', '3893245', '8735778', - '9630905'] +subjects_list = [ + '2475376', '3313349', '3808535', '3893245', '8735778', '9630905' +] gen_fa = pe.Workflow(name="gen_fa") gen_fa.base_dir = os.path.join(os.path.abspath(workingdir), 'l1') -subject_id_infosource = pe.Node(util.IdentityInterface(fields=['subject_id']), - name='subject_id_infosource') +subject_id_infosource = pe.Node( + util.IdentityInterface(fields=['subject_id']), + name='subject_id_infosource') subject_id_infosource.iterables = ('subject_id', subjects_list) -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['dwi', 'bvec', - 'bval']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['dwi', 'bvec', 'bval']), + name='datasource') datasource.inputs.base_directory = os.path.abspath(dataDir) datasource.inputs.template = '%s/session2/DTI_mx_137/dti.%s' -datasource.inputs.template_args = dict(dwi=[['subject_id', 'nii.gz']], - bvec=[['subject_id', 'bvec']], - bval=[['subject_id', 'bval']]) +datasource.inputs.template_args = dict( + dwi=[['subject_id', 'nii.gz']], + bvec=[['subject_id', 'bvec']], + bval=[['subject_id', 'bval']]) datasource.inputs.sort_filelist = True gen_fa.connect(subject_id_infosource, 'subject_id', datasource, 'subject_id') @@ -72,8 +73,8 @@ gen_fa.connect(datasource, 'bval', dtifit, 'bvals') datasink = pe.Node(interface=nio.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.join(os.path.abspath(workingdir), - 'l1_results') +datasink.inputs.base_directory = os.path.join( + os.path.abspath(workingdir), 'l1_results') datasink.inputs.parameterization = False gen_fa.connect(dtifit, 'FA', datasink, 'FA') gen_fa.connect(dtifit, 'MD', datasink, 'MD') @@ -81,21 +82,19 @@ if __name__ == '__main__': gen_fa.write_graph() gen_fa.run() - - """ Here we get the FA list including all the subjects. """ -tbss_source = pe.Node(interface=nio.DataGrabber(outfiles=['fa_list', - 'md_list']), - name='tbss_source') +tbss_source = pe.Node( + interface=nio.DataGrabber(outfiles=['fa_list', 'md_list']), + name='tbss_source') tbss_source.inputs.base_directory = datasink.inputs.base_directory tbss_source.inputs.template = '%s/%s_%s.nii' -tbss_source.inputs.template_args = dict(fa_list=[['FA', subjects_list, 'FA']], - md_list=[['MD', subjects_list, 'MD']]) +tbss_source.inputs.template_args = dict( + fa_list=[['FA', subjects_list, 'FA']], + md_list=[['MD', subjects_list, 'MD']]) tbss_source.inputs.sort_filelist = True - """ TBSS analysis """ @@ -110,17 +109,15 @@ tbss_MD = create_tbss_non_FA(name='tbss_MD') tbss_MD.inputs.inputnode.skeleton_thresh = tbss_all.inputs.inputnode.skeleton_thresh -tbssproc.connect([(tbss_all, tbss_MD, [('tbss2.outputnode.field_list', - 'inputnode.field_list'), - ('tbss3.outputnode.groupmask', - 'inputnode.groupmask'), - ('tbss3.outputnode.meanfa_file', - 'inputnode.meanfa_file'), - ('tbss4.outputnode.distance_map', - 'inputnode.distance_map')]), - (tbss_source, tbss_MD, [('md_list', - 'inputnode.file_list')]), - ]) +tbssproc.connect([ + (tbss_all, tbss_MD, + [('tbss2.outputnode.field_list', 'inputnode.field_list'), + ('tbss3.outputnode.groupmask', 'inputnode.groupmask'), + ('tbss3.outputnode.meanfa_file', + 'inputnode.meanfa_file'), ('tbss4.outputnode.distance_map', + 'inputnode.distance_map')]), + (tbss_source, tbss_MD, [('md_list', 'inputnode.file_list')]), +]) if __name__ == '__main__': tbssproc.write_graph() diff --git a/examples/fmri_ants_openfmri.py b/examples/fmri_ants_openfmri.py index ee6ddee3f9..458d065075 100755 --- a/examples/fmri_ants_openfmri.py +++ b/examples/fmri_ants_openfmri.py @@ -38,18 +38,16 @@ create_fixed_effects_flow) from nipype.utils import NUMPY_MMAP - config.enable_provenance() version = 0 -if (fsl.Info.version() and LooseVersion(fsl.Info.version()) > LooseVersion('5.0.6')): +if (fsl.Info.version() + and LooseVersion(fsl.Info.version()) > LooseVersion('5.0.6')): version = 507 fsl.FSLCommand.set_default_output_type('NIFTI_GZ') imports = [ - 'import os', - 'import nibabel as nb', - 'import numpy as np', + 'import os', 'import nibabel as nb', 'import numpy as np', 'import scipy as sp', 'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename', 'from scipy.special import legendre' @@ -80,22 +78,19 @@ def create_reg_workflow(name='registration'): register = pe.Workflow(name=name) - inputnode = pe.Node(interface=niu.IdentityInterface(fields=['source_files', - 'mean_image', - 'anatomical_image', - 'target_image', - 'target_image_brain', - 'config_file']), - name='inputspec') - outputnode = pe.Node(interface=niu.IdentityInterface(fields=['func2anat_transform', - 'anat2target_transform', - 'transformed_files', - 'transformed_mean', - 'anat2target', - 'mean2anat_mask' - ]), - name='outputspec') - + inputnode = pe.Node( + interface=niu.IdentityInterface(fields=[ + 'source_files', 'mean_image', 'anatomical_image', 'target_image', + 'target_image_brain', 'config_file' + ]), + name='inputspec') + outputnode = pe.Node( + interface=niu.IdentityInterface(fields=[ + 'func2anat_transform', 'anat2target_transform', + 'transformed_files', 'transformed_mean', 'anat2target', + 'mean2anat_mask' + ]), + name='outputspec') """ Estimate the tissue classes from the anatomical image. But use spm's segment as FSL appears to be breaking. @@ -105,17 +100,15 @@ def create_reg_workflow(name='registration'): register.connect(inputnode, 'anatomical_image', stripper, 'in_file') fast = pe.Node(fsl.FAST(), name='fast') register.connect(stripper, 'out_file', fast, 'in_files') - """ Binarize the segmentation """ - binarize = pe.Node(fsl.ImageMaths(op_string='-nan -thr 0.5 -bin'), - name='binarize') + binarize = pe.Node( + fsl.ImageMaths(op_string='-nan -thr 0.5 -bin'), name='binarize') pickindex = lambda x, i: x[i] - register.connect(fast, ('partial_volume_files', pickindex, 2), - binarize, 'in_file') - + register.connect(fast, ('partial_volume_files', pickindex, 2), binarize, + 'in_file') """ Calculate rigid transform from mean image to anatomical image """ @@ -124,7 +117,6 @@ def create_reg_workflow(name='registration'): mean2anat.inputs.dof = 6 register.connect(inputnode, 'mean_image', mean2anat, 'in_file') register.connect(stripper, 'out_file', mean2anat, 'reference') - """ Now use bbr cost function to improve the transform """ @@ -132,33 +124,30 @@ def create_reg_workflow(name='registration'): mean2anatbbr = pe.Node(fsl.FLIRT(), name='mean2anatbbr') mean2anatbbr.inputs.dof = 6 mean2anatbbr.inputs.cost = 'bbr' - mean2anatbbr.inputs.schedule = os.path.join(os.getenv('FSLDIR'), - 'etc/flirtsch/bbr.sch') + mean2anatbbr.inputs.schedule = os.path.join( + os.getenv('FSLDIR'), 'etc/flirtsch/bbr.sch') register.connect(inputnode, 'mean_image', mean2anatbbr, 'in_file') register.connect(binarize, 'out_file', mean2anatbbr, 'wm_seg') register.connect(inputnode, 'anatomical_image', mean2anatbbr, 'reference') - register.connect(mean2anat, 'out_matrix_file', - mean2anatbbr, 'in_matrix_file') - + register.connect(mean2anat, 'out_matrix_file', mean2anatbbr, + 'in_matrix_file') """ Create a mask of the median image coregistered to the anatomical image """ mean2anat_mask = Node(fsl.BET(mask=True), name='mean2anat_mask') register.connect(mean2anatbbr, 'out_file', mean2anat_mask, 'in_file') - """ Convert the BBRegister transformation to ANTS ITK format """ - convert2itk = pe.Node(C3dAffineTool(), - name='convert2itk') + convert2itk = pe.Node(C3dAffineTool(), name='convert2itk') convert2itk.inputs.fsl2ras = True convert2itk.inputs.itk_transform = True - register.connect(mean2anatbbr, 'out_matrix_file', convert2itk, 'transform_file') + register.connect(mean2anatbbr, 'out_matrix_file', convert2itk, + 'transform_file') register.connect(inputnode, 'mean_image', convert2itk, 'source_file') register.connect(stripper, 'out_file', convert2itk, 'reference_file') - """ Compute registration between the subject's structural and MNI template This is currently set to perform a very quick registration. However, the @@ -171,8 +160,10 @@ def create_reg_workflow(name='registration'): reg = pe.Node(ants.Registration(), name='antsRegister') reg.inputs.output_transform_prefix = "output_" reg.inputs.transforms = ['Rigid', 'Affine', 'SyN'] - reg.inputs.transform_parameters = [(0.1,), (0.1,), (0.2, 3.0, 0.0)] - reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[100, 30, 20]] + reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)] + reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[ + 100, 30, 20 + ]] reg.inputs.dimension = 3 reg.inputs.write_composite_transform = True reg.inputs.collapse_output_transforms = True @@ -194,52 +185,48 @@ def create_reg_workflow(name='registration'): reg.inputs.args = '--float' reg.inputs.output_warped_image = 'output_warped_image.nii.gz' reg.inputs.num_threads = 4 - reg.plugin_args = {'qsub_args': '-pe orte 4', - 'sbatch_args': '--mem=6G -c 4'} + reg.plugin_args = { + 'qsub_args': '-pe orte 4', + 'sbatch_args': '--mem=6G -c 4' + } register.connect(stripper, 'out_file', reg, 'moving_image') register.connect(inputnode, 'target_image_brain', reg, 'fixed_image') - """ Concatenate the affine and ants transforms into a list """ - pickfirst = lambda x: x[0] - merge = pe.Node(niu.Merge(2), iterfield=['in2'], name='mergexfm') register.connect(convert2itk, 'itk_transform', merge, 'in2') register.connect(reg, 'composite_transform', merge, 'in1') - """ Transform the mean image. First to anatomical and then to target """ - warpmean = pe.Node(ants.ApplyTransforms(), - name='warpmean') + warpmean = pe.Node(ants.ApplyTransforms(), name='warpmean') warpmean.inputs.input_image_type = 0 warpmean.inputs.interpolation = 'Linear' warpmean.inputs.invert_transform_flags = [False, False] warpmean.terminal_output = 'file' - register.connect(inputnode, 'target_image_brain', warpmean, 'reference_image') + register.connect(inputnode, 'target_image_brain', warpmean, + 'reference_image') register.connect(inputnode, 'mean_image', warpmean, 'input_image') register.connect(merge, 'out', warpmean, 'transforms') - """ Transform the remaining images. First to anatomical and then to target """ - warpall = pe.MapNode(ants.ApplyTransforms(), - iterfield=['input_image'], - name='warpall') + warpall = pe.MapNode( + ants.ApplyTransforms(), iterfield=['input_image'], name='warpall') warpall.inputs.input_image_type = 0 warpall.inputs.interpolation = 'Linear' warpall.inputs.invert_transform_flags = [False, False] warpall.terminal_output = 'file' - register.connect(inputnode, 'target_image_brain', warpall, 'reference_image') + register.connect(inputnode, 'target_image_brain', warpall, + 'reference_image') register.connect(inputnode, 'source_files', warpall, 'input_image') register.connect(merge, 'out', warpall, 'transforms') - """ Assign all the output files """ @@ -247,12 +234,11 @@ def create_reg_workflow(name='registration'): register.connect(reg, 'warped_image', outputnode, 'anat2target') register.connect(warpmean, 'output_image', outputnode, 'transformed_mean') register.connect(warpall, 'output_image', outputnode, 'transformed_files') - register.connect(mean2anatbbr, 'out_matrix_file', - outputnode, 'func2anat_transform') - register.connect(mean2anat_mask, 'mask_file', - outputnode, 'mean2anat_mask') - register.connect(reg, 'composite_transform', - outputnode, 'anat2target_transform') + register.connect(mean2anatbbr, 'out_matrix_file', outputnode, + 'func2anat_transform') + register.connect(mean2anat_mask, 'mask_file', outputnode, 'mean2anat_mask') + register.connect(reg, 'composite_transform', outputnode, + 'anat2target_transform') return register @@ -289,40 +275,33 @@ def create_fs_reg_workflow(name='registration'): register = Workflow(name=name) - inputnode = Node(interface=IdentityInterface(fields=['source_files', - 'mean_image', - 'subject_id', - 'subjects_dir', - 'target_image']), - name='inputspec') - - outputnode = Node(interface=IdentityInterface(fields=['func2anat_transform', - 'out_reg_file', - 'anat2target_transform', - 'transforms', - 'transformed_mean', - 'transformed_files', - 'min_cost_file', - 'anat2target', - 'aparc', - 'mean2anat_mask' - ]), - name='outputspec') + inputnode = Node( + interface=IdentityInterface(fields=[ + 'source_files', 'mean_image', 'subject_id', 'subjects_dir', + 'target_image' + ]), + name='inputspec') + + outputnode = Node( + interface=IdentityInterface(fields=[ + 'func2anat_transform', 'out_reg_file', 'anat2target_transform', + 'transforms', 'transformed_mean', 'transformed_files', + 'min_cost_file', 'anat2target', 'aparc', 'mean2anat_mask' + ]), + name='outputspec') # Get the subject's freesurfer source directory - fssource = Node(FreeSurferSource(), - name='fssource') + fssource = Node(FreeSurferSource(), name='fssource') fssource.run_without_submitting = True register.connect(inputnode, 'subject_id', fssource, 'subject_id') register.connect(inputnode, 'subjects_dir', fssource, 'subjects_dir') - convert = Node(freesurfer.MRIConvert(out_type='nii'), - name="convert") + convert = Node(freesurfer.MRIConvert(out_type='nii'), name="convert") register.connect(fssource, 'T1', convert, 'in_file') # Coregister the median to the surface - bbregister = Node(freesurfer.BBRegister(registered_file=True), - name='bbregister') + bbregister = Node( + freesurfer.BBRegister(registered_file=True), name='bbregister') bbregister.inputs.init = 'fsl' bbregister.inputs.contrast_type = 't2' bbregister.inputs.out_fsl_file = True @@ -334,31 +313,31 @@ def create_fs_reg_workflow(name='registration'): # Create a mask of the median coregistered to the anatomical image mean2anat_mask = Node(fsl.BET(mask=True), name='mean2anat_mask') register.connect(bbregister, 'registered_file', mean2anat_mask, 'in_file') - """ use aparc+aseg's brain mask """ - binarize = Node(fs.Binarize(min=0.5, out_type="nii.gz", dilate=1), name="binarize_aparc") - register.connect(fssource, ("aparc_aseg", get_aparc_aseg), binarize, "in_file") + binarize = Node( + fs.Binarize(min=0.5, out_type="nii.gz", dilate=1), + name="binarize_aparc") + register.connect(fssource, ("aparc_aseg", get_aparc_aseg), binarize, + "in_file") stripper = Node(fsl.ApplyMask(), name='stripper') register.connect(binarize, "binary_file", stripper, "mask_file") register.connect(convert, 'out_file', stripper, 'in_file') - """ Apply inverse transform to aparc file """ - aparcxfm = Node(freesurfer.ApplyVolTransform(inverse=True, - interp='nearest'), - name='aparc_inverse_transform') + aparcxfm = Node( + freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), + name='aparc_inverse_transform') register.connect(inputnode, 'subjects_dir', aparcxfm, 'subjects_dir') register.connect(bbregister, 'out_reg_file', aparcxfm, 'reg_file') - register.connect(fssource, ('aparc_aseg', get_aparc_aseg), - aparcxfm, 'target_file') + register.connect(fssource, ('aparc_aseg', get_aparc_aseg), aparcxfm, + 'target_file') register.connect(inputnode, 'mean_image', aparcxfm, 'source_file') - """ Convert the BBRegister transformation to ANTS ITK format """ @@ -369,7 +348,6 @@ def create_fs_reg_workflow(name='registration'): register.connect(bbregister, 'out_fsl_file', convert2itk, 'transform_file') register.connect(inputnode, 'mean_image', convert2itk, 'source_file') register.connect(stripper, 'out_file', convert2itk, 'reference_file') - """ Compute registration between the subject's structural and MNI template This is currently set to perform a very quick registration. However, the @@ -382,8 +360,10 @@ def create_fs_reg_workflow(name='registration'): reg = Node(ants.Registration(), name='antsRegister') reg.inputs.output_transform_prefix = "output_" reg.inputs.transforms = ['Rigid', 'Affine', 'SyN'] - reg.inputs.transform_parameters = [(0.1,), (0.1,), (0.2, 3.0, 0.0)] - reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[100, 30, 20]] + reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)] + reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[ + 100, 30, 20 + ]] reg.inputs.dimension = 3 reg.inputs.write_composite_transform = True reg.inputs.collapse_output_transforms = True @@ -405,21 +385,19 @@ def create_fs_reg_workflow(name='registration'): reg.inputs.float = True reg.inputs.output_warped_image = 'output_warped_image.nii.gz' reg.inputs.num_threads = 4 - reg.plugin_args = {'qsub_args': '-pe orte 4', - 'sbatch_args': '--mem=6G -c 4'} + reg.plugin_args = { + 'qsub_args': '-pe orte 4', + 'sbatch_args': '--mem=6G -c 4' + } register.connect(stripper, 'out_file', reg, 'moving_image') register.connect(inputnode, 'target_image', reg, 'fixed_image') - """ Concatenate the affine and ants transforms into a list """ - pickfirst = lambda x: x[0] - merge = Node(Merge(2), iterfield=['in2'], name='mergexfm') register.connect(convert2itk, 'itk_transform', merge, 'in2') register.connect(reg, 'composite_transform', merge, 'in1') - """ Transform the mean image. First to anatomical and then to target """ @@ -432,14 +410,12 @@ def create_fs_reg_workflow(name='registration'): warpmean.inputs.args = '--float' # warpmean.inputs.num_threads = 4 # warpmean.plugin_args = {'sbatch_args': '--mem=4G -c 4'} - """ Transform the remaining images. First to anatomical and then to target """ - warpall = pe.MapNode(ants.ApplyTransforms(), - iterfield=['input_image'], - name='warpall') + warpall = pe.MapNode( + ants.ApplyTransforms(), iterfield=['input_image'], name='warpall') warpall.inputs.input_image_type = 0 warpall.inputs.interpolation = 'Linear' warpall.inputs.invert_transform_flags = [False, False] @@ -447,7 +423,6 @@ def create_fs_reg_workflow(name='registration'): warpall.inputs.args = '--float' warpall.inputs.num_threads = 2 warpall.plugin_args = {'sbatch_args': '--mem=6G -c 2'} - """ Assign all the output files """ @@ -461,24 +436,19 @@ def create_fs_reg_workflow(name='registration'): register.connect(inputnode, 'target_image', warpall, 'reference_image') register.connect(inputnode, 'source_files', warpall, 'input_image') register.connect(merge, 'out', warpall, 'transforms') - """ Assign all the output files """ register.connect(reg, 'warped_image', outputnode, 'anat2target') - register.connect(aparcxfm, 'transformed_file', - outputnode, 'aparc') - register.connect(bbregister, 'out_fsl_file', - outputnode, 'func2anat_transform') - register.connect(bbregister, 'out_reg_file', - outputnode, 'out_reg_file') - register.connect(bbregister, 'min_cost_file', - outputnode, 'min_cost_file') - register.connect(mean2anat_mask, 'mask_file', - outputnode, 'mean2anat_mask') - register.connect(reg, 'composite_transform', - outputnode, 'anat2target_transform') + register.connect(aparcxfm, 'transformed_file', outputnode, 'aparc') + register.connect(bbregister, 'out_fsl_file', outputnode, + 'func2anat_transform') + register.connect(bbregister, 'out_reg_file', outputnode, 'out_reg_file') + register.connect(bbregister, 'min_cost_file', outputnode, 'min_cost_file') + register.connect(mean2anat_mask, 'mask_file', outputnode, 'mean2anat_mask') + register.connect(reg, 'composite_transform', outputnode, + 'anat2target_transform') register.connect(merge, 'out', outputnode, 'transforms') return register @@ -532,41 +502,51 @@ def get_subjectinfo(subject_id, base_dir, task_id, model_id): raise ValueError('Task id %d does not exist' % task_id) for idx in range(n_tasks): taskidx = np.where(taskinfo[:, 0] == 'task%03d' % (idx + 1)) - conds.append([condition.replace(' ', '_') for condition - in taskinfo[taskidx[0], 2]]) # if 'junk' not in condition]) - files = sorted(glob(os.path.join(base_dir, - subject_id, - 'BOLD', - 'task%03d_run*' % (idx + 1)))) + conds.append([ + condition.replace(' ', '_') + for condition in taskinfo[taskidx[0], 2] + ]) # if 'junk' not in condition]) + files = sorted( + glob( + os.path.join(base_dir, subject_id, 'BOLD', + 'task%03d_run*' % (idx + 1)))) runs = [int(val[-3:]) for val in files] run_ids.insert(idx, runs) - json_info = os.path.join(base_dir, subject_id, 'BOLD', - 'task%03d_run%03d' % (task_id, run_ids[task_id - 1][0]), - 'bold_scaninfo.json') + json_info = os.path.join(base_dir, subject_id, 'BOLD', 'task%03d_run%03d' % + (task_id, + run_ids[task_id - 1][0]), 'bold_scaninfo.json') if os.path.exists(json_info): import json with open(json_info, 'rt') as fp: data = json.load(fp) TR = data['global']['const']['RepetitionTime'] / 1000. else: - task_scan_key = os.path.join(base_dir, subject_id, 'BOLD', - 'task%03d_run%03d' % (task_id, run_ids[task_id - 1][0]), - 'scan_key.txt') + task_scan_key = os.path.join( + base_dir, subject_id, 'BOLD', 'task%03d_run%03d' % + (task_id, run_ids[task_id - 1][0]), 'scan_key.txt') if os.path.exists(task_scan_key): TR = np.genfromtxt(task_scan_key)[1] else: TR = np.genfromtxt(os.path.join(base_dir, 'scan_key.txt'))[1] return run_ids[task_id - 1], conds[task_id - 1], TR + """ Analyzes an open fmri dataset """ -def analyze_openfmri_dataset(data_dir, subject=None, model_id=None, - task_id=None, output_dir=None, subj_prefix='*', - hpcutoff=120., use_derivatives=True, - fwhm=6.0, subjects_dir=None, target=None): +def analyze_openfmri_dataset(data_dir, + subject=None, + model_id=None, + task_id=None, + output_dir=None, + subj_prefix='*', + hpcutoff=120., + use_derivatives=True, + fwhm=6.0, + subjects_dir=None, + target=None): """Analyzes an open fmri dataset Parameters @@ -578,7 +558,6 @@ def analyze_openfmri_dataset(data_dir, subject=None, model_id=None, work_dir : str Nipype working directory (defaults to cwd) """ - """ Load nipype workflows """ @@ -590,43 +569,41 @@ def analyze_openfmri_dataset(data_dir, subject=None, model_id=None, registration = create_fs_reg_workflow() else: registration = create_reg_workflow() - """ Remove the plotting connection so that plot iterables don't propagate to the model stage """ - preproc.disconnect(preproc.get_node('plot_motion'), 'out_file', - preproc.get_node('outputspec'), 'motion_plots') - + preproc.disconnect( + preproc.get_node('plot_motion'), 'out_file', + preproc.get_node('outputspec'), 'motion_plots') """ Set up openfmri data specific components """ - subjects = sorted([path.split(os.path.sep)[-1] for path in - glob(os.path.join(data_dir, subj_prefix))]) + subjects = sorted([ + path.split(os.path.sep)[-1] + for path in glob(os.path.join(data_dir, subj_prefix)) + ]) - infosource = pe.Node(niu.IdentityInterface(fields=['subject_id', - 'model_id', - 'task_id']), - name='infosource') + infosource = pe.Node( + niu.IdentityInterface(fields=['subject_id', 'model_id', 'task_id']), + name='infosource') if len(subject) == 0: infosource.iterables = [('subject_id', subjects), - ('model_id', [model_id]), - ('task_id', task_id)] + ('model_id', [model_id]), ('task_id', task_id)] else: - infosource.iterables = [('subject_id', - [subjects[subjects.index(subj)] for subj in subject]), - ('model_id', [model_id]), - ('task_id', task_id)] - - subjinfo = pe.Node(niu.Function(input_names=['subject_id', 'base_dir', - 'task_id', 'model_id'], - output_names=['run_id', 'conds', 'TR'], - function=get_subjectinfo), - name='subjectinfo') + infosource.iterables = [('subject_id', [ + subjects[subjects.index(subj)] for subj in subject + ]), ('model_id', [model_id]), ('task_id', task_id)] + + subjinfo = pe.Node( + niu.Function( + input_names=['subject_id', 'base_dir', 'task_id', 'model_id'], + output_names=['run_id', 'conds', 'TR'], + function=get_subjectinfo), + name='subjectinfo') subjinfo.inputs.base_dir = data_dir - """ Return data components as anat, bold and behav """ @@ -635,43 +612,49 @@ def analyze_openfmri_dataset(data_dir, subject=None, model_id=None, 'task_contrasts.txt') has_contrast = os.path.exists(contrast_file) if has_contrast: - datasource = pe.Node(nio.DataGrabber(infields=['subject_id', 'run_id', - 'task_id', 'model_id'], - outfields=['anat', 'bold', 'behav', - 'contrasts']), - name='datasource') + datasource = pe.Node( + nio.DataGrabber( + infields=['subject_id', 'run_id', 'task_id', 'model_id'], + outfields=['anat', 'bold', 'behav', 'contrasts']), + name='datasource') else: - datasource = pe.Node(nio.DataGrabber(infields=['subject_id', 'run_id', - 'task_id', 'model_id'], - outfields=['anat', 'bold', 'behav']), - name='datasource') + datasource = pe.Node( + nio.DataGrabber( + infields=['subject_id', 'run_id', 'task_id', 'model_id'], + outfields=['anat', 'bold', 'behav']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '*' if has_contrast: - datasource.inputs.field_template = {'anat': '%s/anatomy/T1_001.nii.gz', - 'bold': '%s/BOLD/task%03d_r*/bold.nii.gz', - 'behav': ('%s/model/model%03d/onsets/task%03d_' - 'run%03d/cond*.txt'), - 'contrasts': ('models/model%03d/' - 'task_contrasts.txt')} - datasource.inputs.template_args = {'anat': [['subject_id']], - 'bold': [['subject_id', 'task_id']], - 'behav': [['subject_id', 'model_id', - 'task_id', 'run_id']], - 'contrasts': [['model_id']]} + datasource.inputs.field_template = { + 'anat': '%s/anatomy/T1_001.nii.gz', + 'bold': '%s/BOLD/task%03d_r*/bold.nii.gz', + 'behav': ('%s/model/model%03d/onsets/task%03d_' + 'run%03d/cond*.txt'), + 'contrasts': ('models/model%03d/' + 'task_contrasts.txt') + } + datasource.inputs.template_args = { + 'anat': [['subject_id']], + 'bold': [['subject_id', 'task_id']], + 'behav': [['subject_id', 'model_id', 'task_id', 'run_id']], + 'contrasts': [['model_id']] + } else: - datasource.inputs.field_template = {'anat': '%s/anatomy/T1_001.nii.gz', - 'bold': '%s/BOLD/task%03d_r*/bold.nii.gz', - 'behav': ('%s/model/model%03d/onsets/task%03d_' - 'run%03d/cond*.txt')} - datasource.inputs.template_args = {'anat': [['subject_id']], - 'bold': [['subject_id', 'task_id']], - 'behav': [['subject_id', 'model_id', - 'task_id', 'run_id']]} + datasource.inputs.field_template = { + 'anat': '%s/anatomy/T1_001.nii.gz', + 'bold': '%s/BOLD/task%03d_r*/bold.nii.gz', + 'behav': ('%s/model/model%03d/onsets/task%03d_' + 'run%03d/cond*.txt') + } + datasource.inputs.template_args = { + 'anat': [['subject_id']], + 'bold': [['subject_id', 'task_id']], + 'behav': [['subject_id', 'model_id', 'task_id', 'run_id']] + } datasource.inputs.sort_filelist = True - """ Create meta workflow """ @@ -684,18 +667,21 @@ def analyze_openfmri_dataset(data_dir, subject=None, model_id=None, wf.connect(infosource, 'model_id', datasource, 'model_id') wf.connect(infosource, 'task_id', datasource, 'task_id') wf.connect(subjinfo, 'run_id', datasource, 'run_id') - wf.connect([(datasource, preproc, [('bold', 'inputspec.func')]), - ]) + wf.connect([ + (datasource, preproc, [('bold', 'inputspec.func')]), + ]) def get_highpass(TR, hpcutoff): return hpcutoff / (2. * TR) - gethighpass = pe.Node(niu.Function(input_names=['TR', 'hpcutoff'], - output_names=['highpass'], - function=get_highpass), - name='gethighpass') + + gethighpass = pe.Node( + niu.Function( + input_names=['TR', 'hpcutoff'], + output_names=['highpass'], + function=get_highpass), + name='gethighpass') wf.connect(subjinfo, 'TR', gethighpass, 'TR') wf.connect(gethighpass, 'highpass', preproc, 'inputspec.highpass') - """ Setup a basic set of contrasts, a t-test per condition """ @@ -706,13 +692,18 @@ def get_contrasts(contrast_file, task_id, conds): contrast_def = [] if os.path.exists(contrast_file): with open(contrast_file, 'rt') as fp: - contrast_def.extend([np.array(row.split()) for row in fp.readlines() if row.strip()]) + contrast_def.extend([ + np.array(row.split()) for row in fp.readlines() + if row.strip() + ]) contrasts = [] for row in contrast_def: if row[0] != 'task%03d' % task_id: continue - con = [row[1], 'T', ['cond%03d' % (i + 1) for i in range(len(conds))], - row[2:].astype(float).tolist()] + con = [ + row[1], 'T', ['cond%03d' % (i + 1) for i in range(len(conds))], + row[2:].astype(float).tolist() + ] contrasts.append(con) # add auto contrasts for each column for i, cond in enumerate(conds): @@ -720,24 +711,25 @@ def get_contrasts(contrast_file, task_id, conds): contrasts.append(con) return contrasts - contrastgen = pe.Node(niu.Function(input_names=['contrast_file', - 'task_id', 'conds'], - output_names=['contrasts'], - function=get_contrasts), - name='contrastgen') - - art = pe.MapNode(interface=ra.ArtifactDetect(use_differences=[True, False], - use_norm=True, - norm_threshold=1, - zintensity_threshold=3, - parameter_source='FSL', - mask_type='file'), - iterfield=['realigned_files', 'realignment_parameters', - 'mask_file'], - name="art") - - modelspec = pe.Node(interface=model.SpecifyModel(), - name="modelspec") + contrastgen = pe.Node( + niu.Function( + input_names=['contrast_file', 'task_id', 'conds'], + output_names=['contrasts'], + function=get_contrasts), + name='contrastgen') + + art = pe.MapNode( + interface=ra.ArtifactDetect( + use_differences=[True, False], + use_norm=True, + norm_threshold=1, + zintensity_threshold=3, + parameter_source='FSL', + mask_type='file'), + iterfield=['realigned_files', 'realignment_parameters', 'mask_file'], + name="art") + + modelspec = pe.Node(interface=model.SpecifyModel(), name="modelspec") modelspec.inputs.input_units = 'secs' def check_behav_list(behav, run_id, conds): @@ -750,10 +742,12 @@ def check_behav_list(behav, run_id, conds): return behav_array.reshape(int(num_elements / num_conds), num_conds).tolist() - reshape_behav = pe.Node(niu.Function(input_names=['behav', 'run_id', 'conds'], - output_names=['behav'], - function=check_behav_list), - name='reshape_behav') + reshape_behav = pe.Node( + niu.Function( + input_names=['behav', 'run_id', 'conds'], + output_names=['behav'], + function=check_behav_list), + name='reshape_behav') wf.connect(subjinfo, 'TR', modelspec, 'time_repetition') wf.connect(datasource, 'behav', reshape_behav, 'behav') @@ -770,21 +764,18 @@ def check_behav_list(behav, run_id, conds): wf.connect(infosource, 'task_id', contrastgen, 'task_id') wf.connect(contrastgen, 'contrasts', modelfit, 'inputspec.contrasts') - wf.connect([(preproc, art, [('outputspec.motion_parameters', - 'realignment_parameters'), - ('outputspec.realigned_files', - 'realigned_files'), - ('outputspec.mask', 'mask_file')]), - (preproc, modelspec, [('outputspec.highpassed_files', - 'functional_runs'), - ('outputspec.motion_parameters', - 'realignment_parameters')]), - (art, modelspec, [('outlier_files', 'outlier_files')]), - (modelspec, modelfit, [('session_info', - 'inputspec.session_info')]), - (preproc, modelfit, [('outputspec.highpassed_files', - 'inputspec.functional_data')]) - ]) + wf.connect([(preproc, art, + [('outputspec.motion_parameters', 'realignment_parameters'), + ('outputspec.realigned_files', + 'realigned_files'), ('outputspec.mask', 'mask_file')]), + (preproc, modelspec, + [('outputspec.highpassed_files', 'functional_runs'), + ('outputspec.motion_parameters', 'realignment_parameters')]), + (art, modelspec, + [('outlier_files', 'outlier_files')]), (modelspec, modelfit, [ + ('session_info', 'inputspec.session_info') + ]), (preproc, modelfit, [('outputspec.highpassed_files', + 'inputspec.functional_data')])]) # Comute TSNR on realigned data regressing polynomials upto order 2 tsnr = MapNode(TSNR(regress_poly=2), iterfield=['in_file'], name='tsnr') @@ -793,7 +784,6 @@ def check_behav_list(behav, run_id, conds): # Compute the median image across runs calc_median = Node(CalculateMedian(), name='median') wf.connect(tsnr, 'detrended_file', calc_median, 'in_files') - """ Reorder the copes so that now it combines across runs """ @@ -807,45 +797,51 @@ def sort_copes(copes, varcopes, contrasts): n_runs = len(copes) all_copes = np.array(copes).flatten() all_varcopes = np.array(varcopes).flatten() - outcopes = all_copes.reshape(int(len(all_copes) / num_copes), - num_copes).T.tolist() - outvarcopes = all_varcopes.reshape(int(len(all_varcopes) / num_copes), - num_copes).T.tolist() + outcopes = all_copes.reshape( + int(len(all_copes) / num_copes), num_copes).T.tolist() + outvarcopes = all_varcopes.reshape( + int(len(all_varcopes) / num_copes), num_copes).T.tolist() return outcopes, outvarcopes, n_runs - cope_sorter = pe.Node(niu.Function(input_names=['copes', 'varcopes', - 'contrasts'], - output_names=['copes', 'varcopes', - 'n_runs'], - function=sort_copes), - name='cope_sorter') + cope_sorter = pe.Node( + niu.Function( + input_names=['copes', 'varcopes', 'contrasts'], + output_names=['copes', 'varcopes', 'n_runs'], + function=sort_copes), + name='cope_sorter') pickfirst = lambda x: x[0] wf.connect(contrastgen, 'contrasts', cope_sorter, 'contrasts') - wf.connect([(preproc, fixed_fx, [(('outputspec.mask', pickfirst), - 'flameo.mask_file')]), - (modelfit, cope_sorter, [('outputspec.copes', 'copes')]), + wf.connect([(preproc, fixed_fx, + [(('outputspec.mask', pickfirst), + 'flameo.mask_file')]), (modelfit, cope_sorter, + [('outputspec.copes', 'copes')]), (modelfit, cope_sorter, [('outputspec.varcopes', 'varcopes')]), - (cope_sorter, fixed_fx, [('copes', 'inputspec.copes'), - ('varcopes', 'inputspec.varcopes'), - ('n_runs', 'l2model.num_copes')]), - (modelfit, fixed_fx, [('outputspec.dof_file', - 'inputspec.dof_files'), - ]) - ]) + (cope_sorter, fixed_fx, + [('copes', 'inputspec.copes'), ('varcopes', + 'inputspec.varcopes'), + ('n_runs', 'l2model.num_copes')]), (modelfit, fixed_fx, [ + ('outputspec.dof_file', 'inputspec.dof_files'), + ])]) - wf.connect(calc_median, 'median_file', registration, 'inputspec.mean_image') + wf.connect(calc_median, 'median_file', registration, + 'inputspec.mean_image') if subjects_dir: - wf.connect(infosource, 'subject_id', registration, 'inputspec.subject_id') + wf.connect(infosource, 'subject_id', registration, + 'inputspec.subject_id') registration.inputs.inputspec.subjects_dir = subjects_dir - registration.inputs.inputspec.target_image = fsl.Info.standard_image('MNI152_T1_2mm_brain.nii.gz') + registration.inputs.inputspec.target_image = fsl.Info.standard_image( + 'MNI152_T1_2mm_brain.nii.gz') if target: registration.inputs.inputspec.target_image = target else: - wf.connect(datasource, 'anat', registration, 'inputspec.anatomical_image') - registration.inputs.inputspec.target_image = fsl.Info.standard_image('MNI152_T1_2mm.nii.gz') - registration.inputs.inputspec.target_image_brain = fsl.Info.standard_image('MNI152_T1_2mm_brain.nii.gz') + wf.connect(datasource, 'anat', registration, + 'inputspec.anatomical_image') + registration.inputs.inputspec.target_image = fsl.Info.standard_image( + 'MNI152_T1_2mm.nii.gz') + registration.inputs.inputspec.target_image_brain = fsl.Info.standard_image( + 'MNI152_T1_2mm_brain.nii.gz') registration.inputs.inputspec.config_file = 'T1_2_MNI152_2mm' def merge_files(copes, varcopes, zstats): @@ -859,16 +855,17 @@ def merge_files(copes, varcopes, zstats): splits.append(len(zstats)) return out_files, splits - mergefunc = pe.Node(niu.Function(input_names=['copes', 'varcopes', - 'zstats'], - output_names=['out_files', 'splits'], - function=merge_files), - name='merge_files') - wf.connect([(fixed_fx.get_node('outputspec'), mergefunc, - [('copes', 'copes'), - ('varcopes', 'varcopes'), - ('zstats', 'zstats'), - ])]) + mergefunc = pe.Node( + niu.Function( + input_names=['copes', 'varcopes', 'zstats'], + output_names=['out_files', 'splits'], + function=merge_files), + name='merge_files') + wf.connect([(fixed_fx.get_node('outputspec'), mergefunc, [ + ('copes', 'copes'), + ('varcopes', 'varcopes'), + ('zstats', 'zstats'), + ])]) wf.connect(mergefunc, 'out_files', registration, 'inputspec.source_files') def split_files(in_files, splits): @@ -877,28 +874,35 @@ def split_files(in_files, splits): zstats = in_files[(splits[0] + splits[1]):] return copes, varcopes, zstats - splitfunc = pe.Node(niu.Function(input_names=['in_files', 'splits'], - output_names=['copes', 'varcopes', - 'zstats'], - function=split_files), - name='split_files') + splitfunc = pe.Node( + niu.Function( + input_names=['in_files', 'splits'], + output_names=['copes', 'varcopes', 'zstats'], + function=split_files), + name='split_files') wf.connect(mergefunc, 'splits', splitfunc, 'splits') - wf.connect(registration, 'outputspec.transformed_files', - splitfunc, 'in_files') + wf.connect(registration, 'outputspec.transformed_files', splitfunc, + 'in_files') if subjects_dir: - get_roi_mean = pe.MapNode(fs.SegStats(default_color_table=True), - iterfield=['in_file'], name='get_aparc_means') + get_roi_mean = pe.MapNode( + fs.SegStats(default_color_table=True), + iterfield=['in_file'], + name='get_aparc_means') get_roi_mean.inputs.avgwf_txt_file = True - wf.connect(fixed_fx.get_node('outputspec'), 'copes', get_roi_mean, 'in_file') - wf.connect(registration, 'outputspec.aparc', get_roi_mean, 'segmentation_file') - - get_roi_tsnr = pe.MapNode(fs.SegStats(default_color_table=True), - iterfield=['in_file'], name='get_aparc_tsnr') + wf.connect( + fixed_fx.get_node('outputspec'), 'copes', get_roi_mean, 'in_file') + wf.connect(registration, 'outputspec.aparc', get_roi_mean, + 'segmentation_file') + + get_roi_tsnr = pe.MapNode( + fs.SegStats(default_color_table=True), + iterfield=['in_file'], + name='get_aparc_tsnr') get_roi_tsnr.inputs.avgwf_txt_file = True wf.connect(tsnr, 'tsnr_file', get_roi_tsnr, 'in_file') - wf.connect(registration, 'outputspec.aparc', get_roi_tsnr, 'segmentation_file') - + wf.connect(registration, 'outputspec.aparc', get_roi_tsnr, + 'segmentation_file') """ Connect to a datasink """ @@ -918,14 +922,12 @@ def get_subs(subject_id, conds, run_id, model_id, task_id): subs.append(('_flameo%d/zstat1.' % i, 'zstat%02d.' % (i + 1))) subs.append(('_flameo%d/tstat1.' % i, 'tstat%02d.' % (i + 1))) subs.append(('_flameo%d/res4d.' % i, 'res4d%02d.' % (i + 1))) - subs.append(('_warpall%d/cope1_warp.' % i, - 'cope%02d.' % (i + 1))) + subs.append(('_warpall%d/cope1_warp.' % i, 'cope%02d.' % (i + 1))) subs.append(('_warpall%d/varcope1_warp.' % (len(conds) + i), 'varcope%02d.' % (i + 1))) subs.append(('_warpall%d/zstat1_warp.' % (2 * len(conds) + i), 'zstat%02d.' % (i + 1))) - subs.append(('_warpall%d/cope1_trans.' % i, - 'cope%02d.' % (i + 1))) + subs.append(('_warpall%d/cope1_trans.' % i, 'cope%02d.' % (i + 1))) subs.append(('_warpall%d/varcope1_trans.' % (len(conds) + i), 'varcope%02d.' % (i + 1))) subs.append(('_warpall%d/zstat1_trans.' % (2 * len(conds) + i), @@ -946,15 +948,17 @@ def get_subs(subject_id, conds, run_id, model_id, task_id): subs.append(('median_bbreg_brain_mask', 'median_brain_mask')) return subs - subsgen = pe.Node(niu.Function(input_names=['subject_id', 'conds', 'run_id', - 'model_id', 'task_id'], - output_names=['substitutions'], - function=get_subs), - name='subsgen') + subsgen = pe.Node( + niu.Function( + input_names=[ + 'subject_id', 'conds', 'run_id', 'model_id', 'task_id' + ], + output_names=['substitutions'], + function=get_subs), + name='subsgen') wf.connect(subjinfo, 'run_id', subsgen, 'run_id') - datasink = pe.Node(interface=nio.DataSink(), - name="datasink") + datasink = pe.Node(interface=nio.DataSink(), name="datasink") wf.connect(infosource, 'subject_id', datasink, 'container') wf.connect(infosource, 'subject_id', subsgen, 'subject_id') wf.connect(infosource, 'model_id', subsgen, 'model_id') @@ -962,44 +966,47 @@ def get_subs(subject_id, conds, run_id, model_id, task_id): wf.connect(contrastgen, 'contrasts', subsgen, 'conds') wf.connect(subsgen, 'substitutions', datasink, 'substitutions') wf.connect([(fixed_fx.get_node('outputspec'), datasink, - [('res4d', 'res4d'), - ('copes', 'copes'), - ('varcopes', 'varcopes'), - ('zstats', 'zstats'), - ('tstats', 'tstats')]) - ]) - wf.connect([(modelfit.get_node('modelgen'), datasink, - [('design_cov', 'qa.model'), - ('design_image', 'qa.model.@matrix_image'), - ('design_file', 'qa.model.@matrix'), - ])]) + [('res4d', 'res4d'), ('copes', 'copes'), ('varcopes', + 'varcopes'), + ('zstats', 'zstats'), ('tstats', 'tstats')])]) + wf.connect([(modelfit.get_node('modelgen'), datasink, [ + ('design_cov', 'qa.model'), + ('design_image', 'qa.model.@matrix_image'), + ('design_file', 'qa.model.@matrix'), + ])]) wf.connect([(preproc, datasink, [('outputspec.motion_parameters', - 'qa.motion'), - ('outputspec.motion_plots', - 'qa.motion.plots'), + 'qa.motion'), ('outputspec.motion_plots', + 'qa.motion.plots'), ('outputspec.mask', 'qa.mask')])]) - wf.connect(registration, 'outputspec.mean2anat_mask', datasink, 'qa.mask.mean2anat') + wf.connect(registration, 'outputspec.mean2anat_mask', datasink, + 'qa.mask.mean2anat') wf.connect(art, 'norm_files', datasink, 'qa.art.@norm') wf.connect(art, 'intensity_files', datasink, 'qa.art.@intensity') wf.connect(art, 'outlier_files', datasink, 'qa.art.@outlier_files') - wf.connect(registration, 'outputspec.anat2target', datasink, 'qa.anat2target') + wf.connect(registration, 'outputspec.anat2target', datasink, + 'qa.anat2target') wf.connect(tsnr, 'tsnr_file', datasink, 'qa.tsnr.@map') if subjects_dir: - wf.connect(registration, 'outputspec.min_cost_file', datasink, 'qa.mincost') + wf.connect(registration, 'outputspec.min_cost_file', datasink, + 'qa.mincost') wf.connect([(get_roi_tsnr, datasink, [('avgwf_txt_file', 'qa.tsnr'), - ('summary_file', 'qa.tsnr.@summary')])]) + ('summary_file', + 'qa.tsnr.@summary')])]) wf.connect([(get_roi_mean, datasink, [('avgwf_txt_file', 'copes.roi'), - ('summary_file', 'copes.roi.@summary')])]) - wf.connect([(splitfunc, datasink, - [('copes', 'copes.mni'), - ('varcopes', 'varcopes.mni'), - ('zstats', 'zstats.mni'), - ])]) + ('summary_file', + 'copes.roi.@summary')])]) + wf.connect([(splitfunc, datasink, [ + ('copes', 'copes.mni'), + ('varcopes', 'varcopes.mni'), + ('zstats', 'zstats.mni'), + ])]) wf.connect(calc_median, 'median_file', datasink, 'mean') - wf.connect(registration, 'outputspec.transformed_mean', datasink, 'mean.mni') - wf.connect(registration, 'outputspec.func2anat_transform', datasink, 'xfm.mean2anat') - wf.connect(registration, 'outputspec.anat2target_transform', datasink, 'xfm.anat2target') - + wf.connect(registration, 'outputspec.transformed_mean', datasink, + 'mean.mni') + wf.connect(registration, 'outputspec.func2anat_transform', datasink, + 'xfm.mean2anat') + wf.connect(registration, 'outputspec.anat2target_transform', datasink, + 'xfm.anat2target') """ Set processing parameters """ @@ -1014,6 +1021,7 @@ def get_subs(subject_id, conds, run_id, model_id, task_id): datasink.inputs.base_directory = output_dir return wf + """ The following functions run the whole workflow. """ @@ -1021,39 +1029,60 @@ def get_subs(subject_id, conds, run_id, model_id, task_id): if __name__ == '__main__': import argparse defstr = ' (default %(default)s)' - parser = argparse.ArgumentParser(prog='fmri_openfmri.py', - description=__doc__) + parser = argparse.ArgumentParser( + prog='fmri_openfmri.py', description=__doc__) parser.add_argument('-d', '--datasetdir', required=True) - parser.add_argument('-s', '--subject', default=[], - nargs='+', type=str, - help="Subject name (e.g. 'sub001')") - parser.add_argument('-m', '--model', default=1, - help="Model index" + defstr) - parser.add_argument('-x', '--subjectprefix', default='sub*', - help="Subject prefix" + defstr) - parser.add_argument('-t', '--task', default=1, # nargs='+', - type=int, help="Task index" + defstr) - parser.add_argument('--hpfilter', default=120., - type=float, help="High pass filter cutoff (in secs)" + defstr) - parser.add_argument('--fwhm', default=6., - type=float, help="Spatial FWHM" + defstr) - parser.add_argument('--derivatives', action="store_true", - help="Use derivatives" + defstr) - parser.add_argument("-o", "--output_dir", dest="outdir", - help="Output directory base") - parser.add_argument("-w", "--work_dir", dest="work_dir", - help="Output directory base") - parser.add_argument("-p", "--plugin", dest="plugin", - default='Linear', - help="Plugin to use") - parser.add_argument("--plugin_args", dest="plugin_args", - help="Plugin arguments") - parser.add_argument("--sd", dest="subjects_dir", - help="FreeSurfer subjects directory (if available)") - parser.add_argument("--target", dest="target_file", - help=("Target in MNI space. Best to use the MindBoggle " - "template - only used with FreeSurfer" - "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz")) + parser.add_argument( + '-s', + '--subject', + default=[], + nargs='+', + type=str, + help="Subject name (e.g. 'sub001')") + parser.add_argument( + '-m', '--model', default=1, help="Model index" + defstr) + parser.add_argument( + '-x', + '--subjectprefix', + default='sub*', + help="Subject prefix" + defstr) + parser.add_argument( + '-t', + '--task', + default=1, # nargs='+', + type=int, + help="Task index" + defstr) + parser.add_argument( + '--hpfilter', + default=120., + type=float, + help="High pass filter cutoff (in secs)" + defstr) + parser.add_argument( + '--fwhm', default=6., type=float, help="Spatial FWHM" + defstr) + parser.add_argument( + '--derivatives', action="store_true", help="Use derivatives" + defstr) + parser.add_argument( + "-o", "--output_dir", dest="outdir", help="Output directory base") + parser.add_argument( + "-w", "--work_dir", dest="work_dir", help="Output directory base") + parser.add_argument( + "-p", + "--plugin", + dest="plugin", + default='Linear', + help="Plugin to use") + parser.add_argument( + "--plugin_args", dest="plugin_args", help="Plugin arguments") + parser.add_argument( + "--sd", + dest="subjects_dir", + help="FreeSurfer subjects directory (if available)") + parser.add_argument( + "--target", + dest="target_file", + help=("Target in MNI space. Best to use the MindBoggle " + "template - only used with FreeSurfer" + "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz")) args = parser.parse_args() outdir = args.outdir work_dir = os.getcwd() @@ -1068,17 +1097,18 @@ def get_subs(subject_id, conds, run_id, model_id, task_id): derivatives = args.derivatives if derivatives is None: derivatives = False - wf = analyze_openfmri_dataset(data_dir=os.path.abspath(args.datasetdir), - subject=args.subject, - model_id=int(args.model), - task_id=[int(args.task)], - subj_prefix=args.subjectprefix, - output_dir=outdir, - hpcutoff=args.hpfilter, - use_derivatives=derivatives, - fwhm=args.fwhm, - subjects_dir=args.subjects_dir, - target=args.target_file) + wf = analyze_openfmri_dataset( + data_dir=os.path.abspath(args.datasetdir), + subject=args.subject, + model_id=int(args.model), + task_id=[int(args.task)], + subj_prefix=args.subjectprefix, + output_dir=outdir, + hpcutoff=args.hpfilter, + use_derivatives=derivatives, + fwhm=args.fwhm, + subjects_dir=args.subjects_dir, + target=args.target_file) # wf.config['execution']['remove_unnecessary_outputs'] = False wf.base_dir = work_dir diff --git a/examples/fmri_freesurfer_smooth.py b/examples/fmri_freesurfer_smooth.py index b33235efd3..69545b59c0 100755 --- a/examples/fmri_freesurfer_smooth.py +++ b/examples/fmri_freesurfer_smooth.py @@ -43,17 +43,16 @@ from builtins import str from builtins import range -import os # system functions - -import nipype.algorithms.modelgen as model # model generation -import nipype.algorithms.rapidart as ra # artifact detection -import nipype.interfaces.freesurfer as fs # freesurfer -import nipype.interfaces.io as nio # i/o routines -import nipype.interfaces.matlab as mlab # how to run matlab -import nipype.interfaces.spm as spm # spm -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine +import os # system functions +import nipype.algorithms.modelgen as model # model generation +import nipype.algorithms.rapidart as ra # artifact detection +import nipype.interfaces.freesurfer as fs # freesurfer +import nipype.interfaces.io as nio # i/o routines +import nipype.interfaces.matlab as mlab # how to run matlab +import nipype.interfaces.spm as spm # spm +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine """ Preliminaries ------------- @@ -76,8 +75,6 @@ mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") # If SPM is not in your MATLAB path you should add it here mlab.MatlabCommand.set_default_paths('/software/spm8') - - """ Setup preprocessing workflow ---------------------------- @@ -86,8 +83,6 @@ """ preproc = pe.Workflow(name='preproc') - - """ Use :class:`nipype.interfaces.spm.Realign` for motion correction and register all images to the mean image. @@ -95,7 +90,6 @@ realign = pe.Node(interface=spm.Realign(), name="realign") realign.inputs.register_to_mean = True - """ Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in @@ -109,7 +103,6 @@ art.inputs.zintensity_threshold = 3 art.inputs.mask_type = 'file' art.inputs.parameter_source = 'SPM' - """ Use :class:`nipype.interfaces.freesurfer.BBRegister` to coregister the mean functional image generated by realign to the subjects' surfaces. @@ -118,23 +111,19 @@ surfregister = pe.Node(interface=fs.BBRegister(), name='surfregister') surfregister.inputs.init = 'fsl' surfregister.inputs.contrast_type = 't2' - """ Use :class:`nipype.interfaces.io.FreeSurferSource` to retrieve various image files that are automatically generated by the recon-all process. """ FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(), name='fssource') - """ Use :class:`nipype.interfaces.freesurfer.ApplyVolTransform` to convert the brainmask generated by freesurfer into the realigned functional space. """ -ApplyVolTransform = pe.Node(interface=fs.ApplyVolTransform(), - name='applyreg') +ApplyVolTransform = pe.Node(interface=fs.ApplyVolTransform(), name='applyreg') ApplyVolTransform.inputs.inverse = True - """ Use :class:`nipype.interfaces.freesurfer.Binarize` to extract a binary brain mask. @@ -143,7 +132,6 @@ Threshold = pe.Node(interface=fs.Binarize(), name='threshold') Threshold.inputs.min = 10 Threshold.inputs.out_type = 'nii' - """ Two different types of functional data smoothing are performed in this workflow. The volume smoothing option performs a standard SPM smoothin. using @@ -165,27 +153,27 @@ """ volsmooth = pe.Node(interface=spm.Smooth(), name="volsmooth") -surfsmooth = pe.MapNode(interface=fs.Smooth(proj_frac_avg=(0, 1, 0.1)), name="surfsmooth", - iterfield=['in_file']) - +surfsmooth = pe.MapNode( + interface=fs.Smooth(proj_frac_avg=(0, 1, 0.1)), + name="surfsmooth", + iterfield=['in_file']) """ We connect up the different nodes to implement the preprocessing workflow. """ -preproc.connect([(realign, surfregister, [('mean_image', 'source_file')]), - (FreeSurferSource, ApplyVolTransform, [('brainmask', 'target_file')]), - (surfregister, ApplyVolTransform, [('out_reg_file', 'reg_file')]), - (realign, ApplyVolTransform, [('mean_image', 'source_file')]), - (ApplyVolTransform, Threshold, [('transformed_file', 'in_file')]), - (realign, art, [('realignment_parameters', 'realignment_parameters'), - ('realigned_files', 'realigned_files')]), - (Threshold, art, [('binary_file', 'mask_file')]), - (realign, volsmooth, [('realigned_files', 'in_files')]), - (realign, surfsmooth, [('realigned_files', 'in_file')]), - (surfregister, surfsmooth, [('out_reg_file', 'reg_file')]), - ]) - - +preproc.connect([ + (realign, surfregister, [('mean_image', 'source_file')]), + (FreeSurferSource, ApplyVolTransform, [('brainmask', 'target_file')]), + (surfregister, ApplyVolTransform, [('out_reg_file', 'reg_file')]), + (realign, ApplyVolTransform, [('mean_image', 'source_file')]), + (ApplyVolTransform, Threshold, [('transformed_file', 'in_file')]), + (realign, art, [('realignment_parameters', 'realignment_parameters'), + ('realigned_files', 'realigned_files')]), + (Threshold, art, [('binary_file', 'mask_file')]), + (realign, volsmooth, [('realigned_files', 'in_files')]), + (realign, surfsmooth, [('realigned_files', 'in_file')]), + (surfregister, surfsmooth, [('out_reg_file', 'reg_file')]), +]) """ Set up volume analysis workflow ------------------------------- @@ -193,7 +181,6 @@ """ volanalysis = pe.Workflow(name='volanalysis') - """ Generate SPM-specific design information using :class:`nipype.interfaces.spm.SpecifyModel`. @@ -201,7 +188,6 @@ modelspec = pe.Node(interface=model.SpecifySPMModel(), name="modelspec") modelspec.inputs.concatenate_runs = True - """ Generate a first level SPM.mat file for analysis :class:`nipype.interfaces.spm.Level1Design`. @@ -209,7 +195,6 @@ level1design = pe.Node(interface=spm.Level1Design(), name="level1design") level1design.inputs.bases = {'hrf': {'derivs': [0, 0]}} - """ Use :class:`nipype.interfaces.spm.EstimateModel` to determine the parameters of the model. @@ -217,21 +202,21 @@ level1estimate = pe.Node(interface=spm.EstimateModel(), name="level1estimate") level1estimate.inputs.estimation_method = {'Classical': 1} - """ Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the first level contrasts specified in a few steps above. """ -contrastestimate = pe.Node(interface=spm.EstimateContrast(), name="contrastestimate") - -volanalysis.connect([(modelspec, level1design, [('session_info', 'session_info')]), - (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), - (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - ]) +contrastestimate = pe.Node( + interface=spm.EstimateContrast(), name="contrastestimate") +volanalysis.connect([ + (modelspec, level1design, [('session_info', 'session_info')]), + (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), + (level1estimate, contrastestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', 'beta_images'), + ('residual_image', 'residual_image')]), +]) """ Set up surface analysis workflow -------------------------------- @@ -240,8 +225,6 @@ """ surfanalysis = volanalysis.clone(name='surfanalysis') - - """ Set up volume normalization workflow ------------------------------------ @@ -251,7 +234,6 @@ """ volnorm = pe.Workflow(name='volnormconimages') - """ Use :class:`nipype.interfaces.freesurfer.MRIConvert` to convert the brainmask, an mgz file and the contrast images (nifti-1 img/hdr pairs), to single volume @@ -259,10 +241,10 @@ """ convert = pe.Node(interface=fs.MRIConvert(out_type='nii'), name='convert2nii') -convert2 = pe.MapNode(interface=fs.MRIConvert(out_type='nii'), - iterfield=['in_file'], - name='convertimg2nii') - +convert2 = pe.MapNode( + interface=fs.MRIConvert(out_type='nii'), + iterfield=['in_file'], + name='convertimg2nii') """ Use :class:`nipype.interfaces.spm.Segment` to segment the structural image and generate the transformation file to MNI space. @@ -274,34 +256,31 @@ """ segment = pe.Node(interface=spm.Segment(), name='segment') - """ Use :class:`nipype.interfaces.freesurfer.ApplyVolTransform` to convert contrast images into freesurfer space. """ -normwreg = pe.MapNode(interface=fs.ApplyVolTransform(), - iterfield=['source_file'], - name='applyreg2con') - +normwreg = pe.MapNode( + interface=fs.ApplyVolTransform(), + iterfield=['source_file'], + name='applyreg2con') """ Use :class:`nipype.interfaces.spm.Normalize` to normalize the contrast images to MNI space """ -normalize = pe.Node(interface=spm.Normalize(jobtype='write'), - name='norm2mni') - +normalize = pe.Node(interface=spm.Normalize(jobtype='write'), name='norm2mni') """ Connect up the volume normalization components """ -volnorm.connect([(convert, segment, [('out_file', 'data')]), - (convert2, normwreg, [('out_file', 'source_file')]), - (segment, normalize, [('transformation_mat', 'parameter_file')]), - (normwreg, normalize, [('transformed_file', 'apply_to_files')]), - ]) - +volnorm.connect([ + (convert, segment, [('out_file', 'data')]), + (convert2, normwreg, [('out_file', 'source_file')]), + (segment, normalize, [('transformation_mat', 'parameter_file')]), + (normwreg, normalize, [('transformed_file', 'apply_to_files')]), +]) """ Preproc + Analysis + VolumeNormalization workflow ------------------------------------------------- @@ -316,56 +295,51 @@ information for the functional runs and the contrasts to be evaluated. """ -inputnode = pe.Node(interface=util.IdentityInterface(fields=['func', - 'subject_id', - 'session_info', - 'contrasts']), - name='inputnode') - +inputnode = pe.Node( + interface=util.IdentityInterface( + fields=['func', 'subject_id', 'session_info', 'contrasts']), + name='inputnode') """ Connect the components into an integrated workflow. """ l1pipeline = pe.Workflow(name='firstlevel') -l1pipeline.connect([(inputnode, preproc, [('func', 'realign.in_files'), - ('subject_id', 'surfregister.subject_id'), - ('subject_id', 'fssource.subject_id'), - ]), - (inputnode, volanalysis, [('session_info', 'modelspec.subject_info'), - ('contrasts', 'contrastestimate.contrasts')]), - (inputnode, surfanalysis, [('session_info', 'modelspec.subject_info'), - ('contrasts', 'contrastestimate.contrasts')]), - ]) +l1pipeline.connect([ + (inputnode, preproc, [ + ('func', 'realign.in_files'), + ('subject_id', 'surfregister.subject_id'), + ('subject_id', 'fssource.subject_id'), + ]), + (inputnode, volanalysis, [('session_info', 'modelspec.subject_info'), + ('contrasts', 'contrastestimate.contrasts')]), + (inputnode, surfanalysis, [('session_info', 'modelspec.subject_info'), + ('contrasts', 'contrastestimate.contrasts')]), +]) # attach volume and surface model specification and estimation components -l1pipeline.connect([(preproc, volanalysis, [('realign.realignment_parameters', - 'modelspec.realignment_parameters'), - ('volsmooth.smoothed_files', - 'modelspec.functional_runs'), - ('art.outlier_files', - 'modelspec.outlier_files'), - ('threshold.binary_file', - 'level1design.mask_image')]), - (preproc, surfanalysis, [('realign.realignment_parameters', - 'modelspec.realignment_parameters'), - ('surfsmooth.smoothed_file', - 'modelspec.functional_runs'), - ('art.outlier_files', - 'modelspec.outlier_files'), - ('threshold.binary_file', - 'level1design.mask_image')]) - ]) +l1pipeline.connect( + [(preproc, volanalysis, + [('realign.realignment_parameters', 'modelspec.realignment_parameters'), + ('volsmooth.smoothed_files', 'modelspec.functional_runs'), + ('art.outlier_files', + 'modelspec.outlier_files'), ('threshold.binary_file', + 'level1design.mask_image')]), + (preproc, surfanalysis, + [('realign.realignment_parameters', 'modelspec.realignment_parameters'), + ('surfsmooth.smoothed_file', 'modelspec.functional_runs'), + ('art.outlier_files', + 'modelspec.outlier_files'), ('threshold.binary_file', + 'level1design.mask_image')])]) # attach volume contrast normalization components -l1pipeline.connect([(preproc, volnorm, [('fssource.orig', 'convert2nii.in_file'), - ('surfregister.out_reg_file', 'applyreg2con.reg_file'), - ('fssource.orig', 'applyreg2con.target_file')]), - (volanalysis, volnorm, [('contrastestimate.con_images', - 'convertimg2nii.in_file'), - ]) - ]) - - +l1pipeline.connect([(preproc, volnorm, + [('fssource.orig', 'convert2nii.in_file'), + ('surfregister.out_reg_file', 'applyreg2con.reg_file'), + ('fssource.orig', 'applyreg2con.target_file')]), + (volanalysis, volnorm, [ + ('contrastestimate.con_images', + 'convertimg2nii.in_file'), + ])]) """ Data specific components ------------------------ @@ -392,11 +366,12 @@ # Specify the subject directories subject_list = ['s1', 's3'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), name="infosource") +info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -407,7 +382,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -416,15 +390,14 @@ functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - - """ Set preprocessing parameters ---------------------------- @@ -434,8 +407,6 @@ l1pipeline.inputs.preproc.volsmooth.fwhm = 4 l1pipeline.inputs.preproc.surfsmooth.surface_fwhm = 5 l1pipeline.inputs.preproc.surfsmooth.vol_fwhm = 4 - - """ Experimental paradigm specific components ----------------------------------------- @@ -457,12 +428,14 @@ def subjectinfo(subject_id): for r in range(4): onsets = [list(range(15, 240, 60)), list(range(45, 240, 60))] output.insert(r, - Bunch(conditions=names, - onsets=deepcopy(onsets), - durations=[[15] for s in names], - )) + Bunch( + conditions=names, + onsets=deepcopy(onsets), + durations=[[15] for s in names], + )) return output + """Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - [Name,Stat,[list of condition names],[weights on @@ -473,7 +446,6 @@ def subjectinfo(subject_id): cont1 = ('Task>Baseline', 'T', ['Task-Odd', 'Task-Even'], [0.5, 0.5]) cont2 = ('Task-Odd>Task-Even', 'T', ['Task-Odd', 'Task-Even'], [1, -1]) contrasts = [cont1, cont2] - """ Set up node specific inputs --------------------------- @@ -501,8 +473,6 @@ def subjectinfo(subject_id): l1designref.interscan_interval = modelspecref.time_repetition l1pipeline.inputs.inputnode.contrasts = contrasts - - """ Setup the pipeline ------------------ @@ -519,14 +489,13 @@ def subjectinfo(subject_id): level1 = pe.Workflow(name="level1") level1.base_dir = os.path.abspath('volsurf_tutorial/workingdir') -level1.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, l1pipeline, [('func', 'inputnode.func')]), - (infosource, l1pipeline, [('subject_id', 'inputnode.subject_id'), - (('subject_id', subjectinfo), - 'inputnode.session_info')]), - ]) - - +level1.connect([ + (infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, l1pipeline, [('func', 'inputnode.func')]), + (infosource, l1pipeline, [('subject_id', 'inputnode.subject_id'), + (('subject_id', subjectinfo), + 'inputnode.session_info')]), +]) """ Store the output ---------------- @@ -543,16 +512,15 @@ def getsubs(subject_id): subs = [('_subject_id_%s/' % subject_id, '')] return subs + # store relevant outputs from various stages of the 1st level analysis level1.connect([(infosource, datasink, [('subject_id', 'container'), - (('subject_id', getsubs), 'substitutions') - ]), - (l1pipeline, datasink, [('surfanalysis.contrastestimate.con_images', 'contrasts'), - ('preproc.surfregister.out_reg_file', 'registrations'), - ]) - ]) - - + (('subject_id', getsubs), + 'substitutions')]), + (l1pipeline, datasink, [ + ('surfanalysis.contrastestimate.con_images', 'contrasts'), + ('preproc.surfregister.out_reg_file', 'registrations'), + ])]) """ Run the analysis pipeline and also create a dot+png (if graphviz is available) that visually represents the workflow. @@ -561,8 +529,6 @@ def getsubs(subject_id): if __name__ == '__main__': level1.run() level1.write_graph(graph2use='flat') - - """ Level2 surface-based pipeline ----------------------------- @@ -572,39 +538,36 @@ def getsubs(subject_id): l2flow = pe.Workflow(name='l2out') l2flow.base_dir = os.path.abspath('volsurf_tutorial') - """ Setup a dummy node to iterate over contrasts and hemispheres """ -l2inputnode = pe.Node(interface=util.IdentityInterface(fields=['contrasts', - 'hemi']), - name='inputnode') -l2inputnode.iterables = [('contrasts', list(range(1, len(contrasts) + 1))), +l2inputnode = pe.Node( + interface=util.IdentityInterface(fields=['contrasts', 'hemi']), + name='inputnode') +l2inputnode.iterables = [('contrasts', list(range(1, + len(contrasts) + 1))), ('hemi', ['lh', 'rh'])] - """ Use a datagrabber node to collect contrast images and registration files """ -l2source = pe.Node(interface=nio.DataGrabber(infields=['con_id'], - outfields=['con', 'reg']), - name='l2source') +l2source = pe.Node( + interface=nio.DataGrabber(infields=['con_id'], outfields=['con', 'reg']), + name='l2source') l2source.inputs.base_directory = os.path.abspath('volsurf_tutorial/l1out') l2source.inputs.template = '*' -l2source.inputs.field_template = dict(con='*/contrasts/con_%04d.img', - reg='*/registrations/*.dat') +l2source.inputs.field_template = dict( + con='*/contrasts/con_%04d.img', reg='*/registrations/*.dat') l2source.inputs.template_args = dict(con=[['con_id']], reg=[[]]) l2source.inputs.sort_filelist = True l2flow.connect(l2inputnode, 'contrasts', l2source, 'con_id') - """ Merge contrast images and registration files """ -mergenode = pe.Node(interface=util.Merge(2, axis='hstack'), - name='merge') +mergenode = pe.Node(interface=util.Merge(2, axis='hstack'), name='merge') def ordersubjects(files, subj_list): @@ -617,9 +580,11 @@ def ordersubjects(files, subj_list): print(outlist) return outlist -l2flow.connect(l2source, ('con', ordersubjects, subject_list), mergenode, 'in1') -l2flow.connect(l2source, ('reg', ordersubjects, subject_list), mergenode, 'in2') +l2flow.connect(l2source, ('con', ordersubjects, subject_list), mergenode, + 'in1') +l2flow.connect(l2source, ('reg', ordersubjects, subject_list), mergenode, + 'in2') """ Concatenate contrast images projected to fsaverage """ @@ -631,16 +596,16 @@ def ordersubjects(files, subj_list): def list2tuple(listoflist): return [tuple(x) for x in listoflist] + + l2flow.connect(l2inputnode, 'hemi', l2concat, 'hemi') l2flow.connect(mergenode, ('out', list2tuple), l2concat, 'vol_measure_file') - """ Perform a one sample t-test """ l2ttest = pe.Node(interface=fs.OneSampleTTest(), name='onesample') l2flow.connect(l2concat, 'out_file', l2ttest, 'in_file') - """ Run the analysis pipeline and also create a dot+png (if graphviz is available) that visually represents the workflow. diff --git a/examples/fmri_fsl.py b/examples/fmri_fsl.py index 9772290200..9d4ab71423 100755 --- a/examples/fmri_fsl.py +++ b/examples/fmri_fsl.py @@ -20,16 +20,14 @@ from builtins import str from builtins import range -import os # system functions - -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.fsl as fsl # fsl -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.modelgen as model # model generation -import nipype.algorithms.rapidart as ra # artifact detection - +import os # system functions +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.fsl as fsl # fsl +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.modelgen as model # model generation +import nipype.algorithms.rapidart as ra # artifact detection """ Preliminaries ------------- @@ -39,7 +37,6 @@ """ fsl.FSLCommand.set_default_output_type('NIFTI_GZ') - """ Setting up workflows -------------------- @@ -58,34 +55,32 @@ """ preproc = pe.Workflow(name='preproc') - """ Set up a node to define all inputs required for the preprocessing workflow """ -inputnode = pe.Node(interface=util.IdentityInterface(fields=['func', - 'struct', ]), - name='inputspec') - +inputnode = pe.Node( + interface=util.IdentityInterface(fields=[ + 'func', + 'struct', + ]), + name='inputspec') """ Convert functional images to float representation. Since there can be more than one functional run we use a MapNode to convert each run. """ -img2float = pe.MapNode(interface=fsl.ImageMaths(out_data_type='float', - op_string='', - suffix='_dtype'), - iterfield=['in_file'], - name='img2float') +img2float = pe.MapNode( + interface=fsl.ImageMaths( + out_data_type='float', op_string='', suffix='_dtype'), + iterfield=['in_file'], + name='img2float') preproc.connect(inputnode, 'func', img2float, 'in_file') - """ Extract the middle volume of the first run as the reference """ -extract_ref = pe.Node(interface=fsl.ExtractROI(t_size=1), - name='extractref') - +extract_ref = pe.Node(interface=fsl.ExtractROI(t_size=1), name='extractref') """ Define a function to pick the first file from a list of files """ @@ -97,8 +92,8 @@ def pickfirst(files): else: return files -preproc.connect(img2float, ('out_file', pickfirst), extract_ref, 'in_file') +preproc.connect(img2float, ('out_file', pickfirst), extract_ref, 'in_file') """ Define a function to return the 1 based index of the middle volume """ @@ -113,80 +108,71 @@ def getmiddlevolume(func): _, _, _, timepoints = load(funcfile, mmap=NUMPY_MMAP).shape return int(timepoints / 2) - 1 -preproc.connect(inputnode, ('func', getmiddlevolume), extract_ref, 't_min') +preproc.connect(inputnode, ('func', getmiddlevolume), extract_ref, 't_min') """ Realign the functional runs to the middle volume of the first run """ -motion_correct = pe.MapNode(interface=fsl.MCFLIRT(save_mats=True, - save_plots=True), - name='realign', - iterfield=['in_file']) +motion_correct = pe.MapNode( + interface=fsl.MCFLIRT(save_mats=True, save_plots=True), + name='realign', + iterfield=['in_file']) preproc.connect(img2float, 'out_file', motion_correct, 'in_file') preproc.connect(extract_ref, 'roi_file', motion_correct, 'ref_file') - - """ Plot the estimated motion parameters """ -plot_motion = pe.MapNode(interface=fsl.PlotMotionParams(in_source='fsl'), - name='plot_motion', - iterfield=['in_file']) +plot_motion = pe.MapNode( + interface=fsl.PlotMotionParams(in_source='fsl'), + name='plot_motion', + iterfield=['in_file']) plot_motion.iterables = ('plot_type', ['rotations', 'translations']) preproc.connect(motion_correct, 'par_file', plot_motion, 'in_file') - """ Extract the mean volume of the first functional run """ -meanfunc = pe.Node(interface=fsl.ImageMaths(op_string='-Tmean', - suffix='_mean'), - name='meanfunc') +meanfunc = pe.Node( + interface=fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), + name='meanfunc') preproc.connect(motion_correct, ('out_file', pickfirst), meanfunc, 'in_file') - """ Strip the skull from the mean functional to generate a mask """ -meanfuncmask = pe.Node(interface=fsl.BET(mask=True, - no_output=True, - frac=0.3), - name='meanfuncmask') +meanfuncmask = pe.Node( + interface=fsl.BET(mask=True, no_output=True, frac=0.3), + name='meanfuncmask') preproc.connect(meanfunc, 'out_file', meanfuncmask, 'in_file') - """ Mask the functional runs with the extracted mask """ -maskfunc = pe.MapNode(interface=fsl.ImageMaths(suffix='_bet', - op_string='-mas'), - iterfield=['in_file'], - name='maskfunc') +maskfunc = pe.MapNode( + interface=fsl.ImageMaths(suffix='_bet', op_string='-mas'), + iterfield=['in_file'], + name='maskfunc') preproc.connect(motion_correct, 'out_file', maskfunc, 'in_file') preproc.connect(meanfuncmask, 'mask_file', maskfunc, 'in_file2') - - """ Determine the 2nd and 98th percentile intensities of each functional run """ -getthresh = pe.MapNode(interface=fsl.ImageStats(op_string='-p 2 -p 98'), - iterfield=['in_file'], - name='getthreshold') +getthresh = pe.MapNode( + interface=fsl.ImageStats(op_string='-p 2 -p 98'), + iterfield=['in_file'], + name='getthreshold') preproc.connect(maskfunc, 'out_file', getthresh, 'in_file') - - """ Threshold the first run of the functional data at 10% of the 98th percentile """ -threshold = pe.Node(interface=fsl.ImageMaths(out_data_type='char', - suffix='_thresh'), - name='threshold') +threshold = pe.Node( + interface=fsl.ImageMaths(out_data_type='char', suffix='_thresh'), + name='threshold') preproc.connect(maskfunc, ('out_file', pickfirst), threshold, 'in_file') - """ Define a function to get 10% of the intensity """ @@ -194,67 +180,62 @@ def getmiddlevolume(func): def getthreshop(thresh): return '-thr %.10f -Tmin -bin' % (0.1 * thresh[0][1]) -preproc.connect(getthresh, ('out_stat', getthreshop), threshold, 'op_string') + +preproc.connect(getthresh, ('out_stat', getthreshop), threshold, 'op_string') """ Determine the median value of the functional runs using the mask """ -medianval = pe.MapNode(interface=fsl.ImageStats(op_string='-k %s -p 50'), - iterfield=['in_file'], - name='medianval') +medianval = pe.MapNode( + interface=fsl.ImageStats(op_string='-k %s -p 50'), + iterfield=['in_file'], + name='medianval') preproc.connect(motion_correct, 'out_file', medianval, 'in_file') preproc.connect(threshold, 'out_file', medianval, 'mask_file') - """ Dilate the mask """ -dilatemask = pe.Node(interface=fsl.ImageMaths(suffix='_dil', - op_string='-dilF'), - name='dilatemask') +dilatemask = pe.Node( + interface=fsl.ImageMaths(suffix='_dil', op_string='-dilF'), + name='dilatemask') preproc.connect(threshold, 'out_file', dilatemask, 'in_file') - """ Mask the motion corrected functional runs with the dilated mask """ -maskfunc2 = pe.MapNode(interface=fsl.ImageMaths(suffix='_mask', - op_string='-mas'), - iterfield=['in_file'], - name='maskfunc2') +maskfunc2 = pe.MapNode( + interface=fsl.ImageMaths(suffix='_mask', op_string='-mas'), + iterfield=['in_file'], + name='maskfunc2') preproc.connect(motion_correct, 'out_file', maskfunc2, 'in_file') preproc.connect(dilatemask, 'out_file', maskfunc2, 'in_file2') - """ Determine the mean image from each functional run """ -meanfunc2 = pe.MapNode(interface=fsl.ImageMaths(op_string='-Tmean', - suffix='_mean'), - iterfield=['in_file'], - name='meanfunc2') +meanfunc2 = pe.MapNode( + interface=fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), + iterfield=['in_file'], + name='meanfunc2') preproc.connect(maskfunc2, 'out_file', meanfunc2, 'in_file') - """ Merge the median values with the mean functional images into a coupled list """ -mergenode = pe.Node(interface=util.Merge(2, axis='hstack'), - name='merge') +mergenode = pe.Node(interface=util.Merge(2, axis='hstack'), name='merge') preproc.connect(meanfunc2, 'out_file', mergenode, 'in1') preproc.connect(medianval, 'out_stat', mergenode, 'in2') - - """ Smooth each run using SUSAN with the brightness threshold set to 75% of the median value for each run and a mask constituting the mean functional """ -smooth = pe.MapNode(interface=fsl.SUSAN(), - iterfield=['in_file', 'brightness_threshold', 'usans'], - name='smooth') - +smooth = pe.MapNode( + interface=fsl.SUSAN(), + iterfield=['in_file', 'brightness_threshold', 'usans'], + name='smooth') """ Define a function to get the brightness threshold for SUSAN """ @@ -267,30 +248,30 @@ def getbtthresh(medianvals): def getusans(x): return [[tuple([val[0], 0.75 * val[1]])] for val in x] + preproc.connect(maskfunc2, 'out_file', smooth, 'in_file') -preproc.connect(medianval, ('out_stat', getbtthresh), smooth, 'brightness_threshold') +preproc.connect(medianval, ('out_stat', getbtthresh), smooth, + 'brightness_threshold') preproc.connect(mergenode, ('out', getusans), smooth, 'usans') - """ Mask the smoothed data with the dilated mask """ -maskfunc3 = pe.MapNode(interface=fsl.ImageMaths(suffix='_mask', - op_string='-mas'), - iterfield=['in_file'], - name='maskfunc3') +maskfunc3 = pe.MapNode( + interface=fsl.ImageMaths(suffix='_mask', op_string='-mas'), + iterfield=['in_file'], + name='maskfunc3') preproc.connect(smooth, 'smoothed_file', maskfunc3, 'in_file') preproc.connect(dilatemask, 'out_file', maskfunc3, 'in_file2') - """ Scale each volume of the run so that the median value of the run is set to 10000 """ -intnorm = pe.MapNode(interface=fsl.ImageMaths(suffix='_intnorm'), - iterfield=['in_file', 'op_string'], - name='intnorm') +intnorm = pe.MapNode( + interface=fsl.ImageMaths(suffix='_intnorm'), + iterfield=['in_file', 'op_string'], + name='intnorm') preproc.connect(maskfunc3, 'out_file', intnorm, 'in_file') - """ Define a function to get the scaling factor for intensity normalization """ @@ -298,65 +279,62 @@ def getusans(x): def getinormscale(medianvals): return ['-mul %.10f' % (10000. / val) for val in medianvals] -preproc.connect(medianval, ('out_stat', getinormscale), intnorm, 'op_string') + +preproc.connect(medianval, ('out_stat', getinormscale), intnorm, 'op_string') """ Perform temporal highpass filtering on the data """ -highpass = pe.MapNode(interface=fsl.ImageMaths(suffix='_tempfilt'), - iterfield=['in_file'], - name='highpass') +highpass = pe.MapNode( + interface=fsl.ImageMaths(suffix='_tempfilt'), + iterfield=['in_file'], + name='highpass') preproc.connect(intnorm, 'out_file', highpass, 'in_file') - """ Generate a mean functional image from the first run """ -meanfunc3 = pe.MapNode(interface=fsl.ImageMaths(op_string='-Tmean', - suffix='_mean'), - iterfield=['in_file'], - name='meanfunc3') +meanfunc3 = pe.MapNode( + interface=fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), + iterfield=['in_file'], + name='meanfunc3') preproc.connect(highpass, ('out_file', pickfirst), meanfunc3, 'in_file') - """ Strip the structural image and coregister the mean functional image to the structural image """ -nosestrip = pe.Node(interface=fsl.BET(frac=0.3), - name='nosestrip') -skullstrip = pe.Node(interface=fsl.BET(mask=True), - name='stripstruct') - -coregister = pe.Node(interface=fsl.FLIRT(dof=6), - name='coregister') +nosestrip = pe.Node(interface=fsl.BET(frac=0.3), name='nosestrip') +skullstrip = pe.Node(interface=fsl.BET(mask=True), name='stripstruct') +coregister = pe.Node(interface=fsl.FLIRT(dof=6), name='coregister') """ Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in intensity and/or movement. """ -art = pe.MapNode(interface=ra.ArtifactDetect(use_differences=[True, False], - use_norm=True, - norm_threshold=1, - zintensity_threshold=3, - parameter_source='FSL', - mask_type='file'), - iterfield=['realigned_files', 'realignment_parameters'], - name="art") - - -preproc.connect([(inputnode, nosestrip, [('struct', 'in_file')]), - (nosestrip, skullstrip, [('out_file', 'in_file')]), - (skullstrip, coregister, [('out_file', 'in_file')]), - (meanfunc2, coregister, [(('out_file', pickfirst), 'reference')]), - (motion_correct, art, [('par_file', 'realignment_parameters')]), - (maskfunc2, art, [('out_file', 'realigned_files')]), - (dilatemask, art, [('out_file', 'mask_file')]), - ]) - +art = pe.MapNode( + interface=ra.ArtifactDetect( + use_differences=[True, False], + use_norm=True, + norm_threshold=1, + zintensity_threshold=3, + parameter_source='FSL', + mask_type='file'), + iterfield=['realigned_files', 'realignment_parameters'], + name="art") + +preproc.connect([ + (inputnode, nosestrip, [('struct', 'in_file')]), + (nosestrip, skullstrip, [('out_file', 'in_file')]), + (skullstrip, coregister, [('out_file', 'in_file')]), + (meanfunc2, coregister, [(('out_file', pickfirst), 'reference')]), + (motion_correct, art, [('par_file', 'realignment_parameters')]), + (maskfunc2, art, [('out_file', 'realigned_files')]), + (dilatemask, art, [('out_file', 'mask_file')]), +]) """ Set up model fitting workflow ----------------------------- @@ -364,61 +342,58 @@ def getinormscale(medianvals): """ modelfit = pe.Workflow(name='modelfit') - """ Use :class:`nipype.algorithms.modelgen.SpecifyModel` to generate design information. """ modelspec = pe.Node(interface=model.SpecifyModel(), name="modelspec") - """ Use :class:`nipype.interfaces.fsl.Level1Design` to generate a run specific fsf file for analysis """ level1design = pe.Node(interface=fsl.Level1Design(), name="level1design") - """ Use :class:`nipype.interfaces.fsl.FEATModel` to generate a run specific mat file for use by FILMGLS """ -modelgen = pe.MapNode(interface=fsl.FEATModel(), name='modelgen', - iterfield=['fsf_file', 'ev_files']) - - +modelgen = pe.MapNode( + interface=fsl.FEATModel(), + name='modelgen', + iterfield=['fsf_file', 'ev_files']) """ Use :class:`nipype.interfaces.fsl.FILMGLS` to estimate a model specified by a mat file and a functional run """ -modelestimate = pe.MapNode(interface=fsl.FILMGLS(smooth_autocorr=True, - mask_size=5, - threshold=1000), - name='modelestimate', - iterfield=['design_file', 'in_file']) - +modelestimate = pe.MapNode( + interface=fsl.FILMGLS(smooth_autocorr=True, mask_size=5, threshold=1000), + name='modelestimate', + iterfield=['design_file', 'in_file']) """ Use :class:`nipype.interfaces.fsl.ContrastMgr` to generate contrast estimates """ -conestimate = pe.MapNode(interface=fsl.ContrastMgr(), name='conestimate', - iterfield=['tcon_file', 'param_estimates', - 'sigmasquareds', 'corrections', - 'dof_file']) +conestimate = pe.MapNode( + interface=fsl.ContrastMgr(), + name='conestimate', + iterfield=[ + 'tcon_file', 'param_estimates', 'sigmasquareds', 'corrections', + 'dof_file' + ]) modelfit.connect([ (modelspec, level1design, [('session_info', 'session_info')]), - (level1design, modelgen, [('fsf_files', 'fsf_file'), - ('ev_files', 'ev_files')]), + (level1design, modelgen, [('fsf_files', 'fsf_file'), ('ev_files', + 'ev_files')]), (modelgen, modelestimate, [('design_file', 'design_file')]), (modelgen, conestimate, [('con_file', 'tcon_file')]), - (modelestimate, conestimate, [('param_estimates', 'param_estimates'), - ('sigmasquareds', 'sigmasquareds'), - ('corrections', 'corrections'), - ('dof_file', 'dof_file')]), + (modelestimate, conestimate, + [('param_estimates', 'param_estimates'), ('sigmasquareds', + 'sigmasquareds'), + ('corrections', 'corrections'), ('dof_file', 'dof_file')]), ]) - """ Set up fixed-effects workflow ----------------------------- @@ -426,43 +401,42 @@ def getinormscale(medianvals): """ fixed_fx = pe.Workflow(name='fixedfx') - """ Use :class:`nipype.interfaces.fsl.Merge` to merge the copes and varcopes for each condition """ -copemerge = pe.MapNode(interface=fsl.Merge(dimension='t'), - iterfield=['in_files'], - name="copemerge") - -varcopemerge = pe.MapNode(interface=fsl.Merge(dimension='t'), - iterfield=['in_files'], - name="varcopemerge") +copemerge = pe.MapNode( + interface=fsl.Merge(dimension='t'), + iterfield=['in_files'], + name="copemerge") +varcopemerge = pe.MapNode( + interface=fsl.Merge(dimension='t'), + iterfield=['in_files'], + name="varcopemerge") """ Use :class:`nipype.interfaces.fsl.L2Model` to generate subject and condition specific level 2 model design files """ -level2model = pe.Node(interface=fsl.L2Model(), - name='l2model') - +level2model = pe.Node(interface=fsl.L2Model(), name='l2model') """ Use :class:`nipype.interfaces.fsl.FLAMEO` to estimate a second level model """ -flameo = pe.MapNode(interface=fsl.FLAMEO(run_mode='fe'), name="flameo", - iterfield=['cope_file', 'var_cope_file']) - -fixed_fx.connect([(copemerge, flameo, [('merged_file', 'cope_file')]), - (varcopemerge, flameo, [('merged_file', 'var_cope_file')]), - (level2model, flameo, [('design_mat', 'design_file'), - ('design_con', 't_con_file'), - ('design_grp', 'cov_split_file')]), - ]) - +flameo = pe.MapNode( + interface=fsl.FLAMEO(run_mode='fe'), + name="flameo", + iterfield=['cope_file', 'var_cope_file']) +fixed_fx.connect([ + (copemerge, flameo, [('merged_file', 'cope_file')]), + (varcopemerge, flameo, [('merged_file', 'var_cope_file')]), + (level2model, flameo, [('design_mat', 'design_file'), + ('design_con', 't_con_file'), ('design_grp', + 'cov_split_file')]), +]) """ Set up first-level workflow --------------------------- @@ -483,18 +457,18 @@ def sort_copes(files): def num_copes(files): return len(files) -firstlevel = pe.Workflow(name='firstlevel') -firstlevel.connect([(preproc, modelfit, [('highpass.out_file', 'modelspec.functional_runs'), - ('art.outlier_files', 'modelspec.outlier_files'), - ('highpass.out_file', 'modelestimate.in_file')]), - (preproc, fixed_fx, [('coregister.out_file', 'flameo.mask_file')]), - (modelfit, fixed_fx, [(('conestimate.copes', sort_copes), 'copemerge.in_files'), - (('conestimate.varcopes', sort_copes), 'varcopemerge.in_files'), - (('conestimate.copes', num_copes), 'l2model.num_copes'), - ]) - ]) - +firstlevel = pe.Workflow(name='firstlevel') +firstlevel.connect( + [(preproc, modelfit, [('highpass.out_file', 'modelspec.functional_runs'), + ('art.outlier_files', 'modelspec.outlier_files'), + ('highpass.out_file', 'modelestimate.in_file')]), + (preproc, fixed_fx, + [('coregister.out_file', 'flameo.mask_file')]), (modelfit, fixed_fx, [ + (('conestimate.copes', sort_copes), 'copemerge.in_files'), + (('conestimate.varcopes', sort_copes), 'varcopemerge.in_files'), + (('conestimate.copes', num_copes), 'l2model.num_copes'), + ])]) """ Experiment specific components ------------------------------ @@ -521,12 +495,12 @@ def num_copes(files): # Specify the subject directories subject_list = ['s1'] # , 's3'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -537,7 +511,6 @@ def num_copes(files): """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataSource` object and fill in the information from above about the layout of our data. The @@ -546,29 +519,27 @@ def num_copes(files): functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """ Use the get_node function to retrieve an internal node by name. Then set the iterables on this node to perform two different extents of smoothing. """ smoothnode = firstlevel.get_node('preproc.smooth') -assert(str(smoothnode) == 'preproc.smooth') +assert (str(smoothnode) == 'preproc.smooth') smoothnode.iterables = ('fwhm', [5., 10.]) hpcutoff = 120 TR = 3. # ensure float firstlevel.inputs.preproc.highpass.suffix = '_hpf' firstlevel.inputs.preproc.highpass.op_string = '-bptf %d -1' % (hpcutoff / TR) - - """ Setup a function that returns subject-specific information about the experimental paradigm. This is used by the @@ -588,16 +559,18 @@ def subjectinfo(subject_id): for r in range(4): onsets = [list(range(15, 240, 60)), list(range(45, 240, 60))] output.insert(r, - Bunch(conditions=names, - onsets=deepcopy(onsets), - durations=[[15] for s in names], - amplitudes=None, - tmod=None, - pmod=None, - regressor_names=None, - regressors=None)) + Bunch( + conditions=names, + onsets=deepcopy(onsets), + durations=[[15] for s in names], + amplitudes=None, + tmod=None, + pmod=None, + regressor_names=None, + regressors=None)) return output + """ Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - @@ -619,7 +592,6 @@ def subjectinfo(subject_id): firstlevel.inputs.modelfit.level1design.bases = {'dgamma': {'derivs': False}} firstlevel.inputs.modelfit.level1design.contrasts = contrasts firstlevel.inputs.modelfit.level1design.model_serial_correlations = True - """ Set up complete workflow ======================== @@ -627,15 +599,21 @@ def subjectinfo(subject_id): l1pipeline = pe.Workflow(name="level1") l1pipeline.base_dir = os.path.abspath('./fsl/workingdir') -l1pipeline.config = {"execution": {"crashdump_dir": os.path.abspath('./fsl/crashdumps')}} - -l1pipeline.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (infosource, firstlevel, [(('subject_id', subjectinfo), 'modelfit.modelspec.subject_info')]), - (datasource, firstlevel, [('struct', 'preproc.inputspec.struct'), - ('func', 'preproc.inputspec.func'), - ]), - ]) - +l1pipeline.config = { + "execution": { + "crashdump_dir": os.path.abspath('./fsl/crashdumps') + } +} + +l1pipeline.connect([ + (infosource, datasource, [('subject_id', 'subject_id')]), + (infosource, firstlevel, [(('subject_id', subjectinfo), + 'modelfit.modelspec.subject_info')]), + (datasource, firstlevel, [ + ('struct', 'preproc.inputspec.struct'), + ('func', 'preproc.inputspec.func'), + ]), +]) """ Execute the pipeline -------------------- diff --git a/examples/fmri_fsl_feeds.py b/examples/fmri_fsl_feeds.py index c0856f652c..f7b0aaf91d 100755 --- a/examples/fmri_fsl_feeds.py +++ b/examples/fmri_fsl_feeds.py @@ -16,18 +16,15 @@ from __future__ import division from builtins import range -import os # system functions -from nipype.interfaces import io as nio # Data i/o -from nipype.interfaces import utility as niu # Utilities -from nipype.interfaces import fsl # fsl -from nipype.pipeline import engine as pe # pypeline engine -from nipype.algorithms import modelgen as model # model generation -from nipype.workflows.fmri.fsl import (create_featreg_preproc, - create_modelfit_workflow, - create_reg_workflow) +import os # system functions +from nipype.interfaces import io as nio # Data i/o +from nipype.interfaces import utility as niu # Utilities +from nipype.interfaces import fsl # fsl +from nipype.pipeline import engine as pe # pypeline engine +from nipype.algorithms import modelgen as model # model generation +from nipype.workflows.fmri.fsl import ( + create_featreg_preproc, create_modelfit_workflow, create_reg_workflow) from nipype.interfaces.base import Bunch - - """ Preliminaries ------------- @@ -37,8 +34,6 @@ """ fsl.FSLCommand.set_default_output_type('NIFTI_GZ') - - """ Experiment specific components ------------------------------ @@ -49,13 +44,11 @@ # Specify the location of the FEEDS data. You can find it at http://www.fmrib.ox.ac.uk/fsl/feeds/doc/index.html - -inputnode = pe.Node(niu.IdentityInterface(fields=['in_data']), name='inputnode') +inputnode = pe.Node( + niu.IdentityInterface(fields=['in_data']), name='inputnode') # Specify the subject directories # Map field names to individual subject runs. -info = dict(func=[['fmri']], - struct=[['structural']]) - +info = dict(func=[['fmri']], struct=[['structural']]) """ Now we create a :class:`nipype.interfaces.io.DataSource` object and fill in the information from above about the layout of our data. The @@ -63,8 +56,8 @@ additional housekeeping and pipeline specific functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber(outfields=['func', 'struct']), name='datasource') datasource.inputs.template = 'feeds/data/%s.nii.gz' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True @@ -74,19 +67,24 @@ preproc.inputs.inputspec.fwhm = 5 preproc.inputs.inputspec.highpass = 100. / TR -modelspec = pe.Node(interface=model.SpecifyModel(), - name="modelspec") +modelspec = pe.Node(interface=model.SpecifyModel(), name="modelspec") modelspec.inputs.input_units = 'secs' modelspec.inputs.time_repetition = TR modelspec.inputs.high_pass_filter_cutoff = 100 -modelspec.inputs.subject_info = [Bunch(conditions=['Visual', 'Auditory'], - onsets=[list(range(0, int(180 * TR), 60)), list(range(0, int(180 * TR), 90))], - durations=[[30], [45]], - amplitudes=None, - tmod=None, - pmod=None, - regressor_names=None, - regressors=None)] +modelspec.inputs.subject_info = [ + Bunch( + conditions=['Visual', 'Auditory'], + onsets=[ + list(range(0, int(180 * TR), 60)), + list(range(0, int(180 * TR), 90)) + ], + durations=[[30], [45]], + amplitudes=None, + tmod=None, + pmod=None, + regressor_names=None, + regressors=None) +] modelfit = create_modelfit_workflow(f_contrasts=True) modelfit.inputs.inputspec.interscan_interval = TR @@ -98,10 +96,11 @@ modelfit.inputs.inputspec.contrasts = [cont1, cont2, cont3] registration = create_reg_workflow() -registration.inputs.inputspec.target_image = fsl.Info.standard_image('MNI152_T1_2mm.nii.gz') -registration.inputs.inputspec.target_image_brain = fsl.Info.standard_image('MNI152_T1_2mm_brain.nii.gz') +registration.inputs.inputspec.target_image = fsl.Info.standard_image( + 'MNI152_T1_2mm.nii.gz') +registration.inputs.inputspec.target_image_brain = fsl.Info.standard_image( + 'MNI152_T1_2mm_brain.nii.gz') registration.inputs.inputspec.config_file = 'T1_2_MNI152_2mm' - """ Set up complete workflow ======================== @@ -109,30 +108,43 @@ l1pipeline = pe.Workflow(name="level1") l1pipeline.base_dir = os.path.abspath('./fsl_feeds/workingdir') -l1pipeline.config = {"execution": {"crashdump_dir": os.path.abspath('./fsl_feeds/crashdumps')}} +l1pipeline.config = { + "execution": { + "crashdump_dir": os.path.abspath('./fsl_feeds/crashdumps') + } +} l1pipeline.connect(inputnode, 'in_data', datasource, 'base_directory') l1pipeline.connect(datasource, 'func', preproc, 'inputspec.func') -l1pipeline.connect(preproc, 'outputspec.highpassed_files', modelspec, 'functional_runs') -l1pipeline.connect(preproc, 'outputspec.motion_parameters', modelspec, 'realignment_parameters') -l1pipeline.connect(modelspec, 'session_info', modelfit, 'inputspec.session_info') -l1pipeline.connect(preproc, 'outputspec.highpassed_files', modelfit, 'inputspec.functional_data') -l1pipeline.connect(preproc, 'outputspec.mean', registration, 'inputspec.mean_image') -l1pipeline.connect(datasource, 'struct', registration, 'inputspec.anatomical_image') -l1pipeline.connect(modelfit, 'outputspec.zfiles', registration, 'inputspec.source_files') - - +l1pipeline.connect(preproc, 'outputspec.highpassed_files', modelspec, + 'functional_runs') +l1pipeline.connect(preproc, 'outputspec.motion_parameters', modelspec, + 'realignment_parameters') +l1pipeline.connect(modelspec, 'session_info', modelfit, + 'inputspec.session_info') +l1pipeline.connect(preproc, 'outputspec.highpassed_files', modelfit, + 'inputspec.functional_data') +l1pipeline.connect(preproc, 'outputspec.mean', registration, + 'inputspec.mean_image') +l1pipeline.connect(datasource, 'struct', registration, + 'inputspec.anatomical_image') +l1pipeline.connect(modelfit, 'outputspec.zfiles', registration, + 'inputspec.source_files') """ Setup the datasink """ -datasink = pe.Node(interface=nio.DataSink(parameterization=False), name="datasink") +datasink = pe.Node( + interface=nio.DataSink(parameterization=False), name="datasink") datasink.inputs.base_directory = os.path.abspath('./fsl_feeds/l1out') -datasink.inputs.substitutions = [('fmri_dtype_mcf_mask_smooth_mask_gms_mean_warp', 'meanfunc')] +datasink.inputs.substitutions = [ + ('fmri_dtype_mcf_mask_smooth_mask_gms_mean_warp', 'meanfunc') +] # store relevant outputs from various stages of the 1st level analysis -l1pipeline.connect(registration, 'outputspec.transformed_files', datasink, 'level1.@Z') -l1pipeline.connect(registration, 'outputspec.transformed_mean', datasink, 'meanfunc') - +l1pipeline.connect(registration, 'outputspec.transformed_files', datasink, + 'level1.@Z') +l1pipeline.connect(registration, 'outputspec.transformed_mean', datasink, + 'meanfunc') """ Execute the pipeline -------------------- diff --git a/examples/fmri_fsl_reuse.py b/examples/fmri_fsl_reuse.py index beb09f0345..7b24dc24b8 100755 --- a/examples/fmri_fsl_reuse.py +++ b/examples/fmri_fsl_reuse.py @@ -20,19 +20,17 @@ from builtins import str from builtins import range -import os # system functions -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.fsl as fsl # fsl -from nipype.interfaces import utility as niu # Utilities -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.modelgen as model # model generation -import nipype.algorithms.rapidart as ra # artifact detection +import os # system functions +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.fsl as fsl # fsl +from nipype.interfaces import utility as niu # Utilities +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.modelgen as model # model generation +import nipype.algorithms.rapidart as ra # artifact detection from nipype.workflows.fmri.fsl import (create_featreg_preproc, create_modelfit_workflow, create_fixed_effects_flow) - - """ Preliminaries ------------- @@ -50,38 +48,37 @@ modelfit = create_modelfit_workflow() fixed_fx = create_fixed_effects_flow() - """ Add artifact detection and model specification nodes between the preprocessing and modelfitting workflows. """ -art = pe.MapNode(ra.ArtifactDetect(use_differences=[True, False], - use_norm=True, - norm_threshold=1, - zintensity_threshold=3, - parameter_source='FSL', - mask_type='file'), - iterfield=['realigned_files', 'realignment_parameters', 'mask_file'], - name="art") +art = pe.MapNode( + ra.ArtifactDetect( + use_differences=[True, False], + use_norm=True, + norm_threshold=1, + zintensity_threshold=3, + parameter_source='FSL', + mask_type='file'), + iterfield=['realigned_files', 'realignment_parameters', 'mask_file'], + name="art") modelspec = pe.Node(model.SpecifyModel(), name="modelspec") -level1_workflow.connect([(preproc, art, [('outputspec.motion_parameters', - 'realignment_parameters'), - ('outputspec.realigned_files', - 'realigned_files'), - ('outputspec.mask', 'mask_file')]), - (preproc, modelspec, [('outputspec.highpassed_files', - 'functional_runs'), - ('outputspec.motion_parameters', - 'realignment_parameters')]), - (art, modelspec, [('outlier_files', 'outlier_files')]), - (modelspec, modelfit, [('session_info', 'inputspec.session_info')]), - (preproc, modelfit, [('outputspec.highpassed_files', 'inputspec.functional_data')]) - ]) - - +level1_workflow.connect( + [(preproc, art, + [('outputspec.motion_parameters', 'realignment_parameters'), + ('outputspec.realigned_files', 'realigned_files'), ('outputspec.mask', + 'mask_file')]), + (preproc, modelspec, [('outputspec.highpassed_files', 'functional_runs'), + ('outputspec.motion_parameters', + 'realignment_parameters')]), (art, modelspec, + [('outlier_files', + 'outlier_files')]), + (modelspec, modelfit, [('session_info', 'inputspec.session_info')]), + (preproc, modelfit, [('outputspec.highpassed_files', + 'inputspec.functional_data')])]) """ Set up first-level workflow --------------------------- @@ -102,22 +99,18 @@ def sort_copes(files): def num_copes(files): return len(files) -pickfirst = lambda x: x[0] -level1_workflow.connect([(preproc, fixed_fx, [(('outputspec.mask', pickfirst), - 'flameo.mask_file')]), - (modelfit, fixed_fx, [(('outputspec.copes', sort_copes), - 'inputspec.copes'), - ('outputspec.dof_file', - 'inputspec.dof_files'), - (('outputspec.varcopes', - sort_copes), - 'inputspec.varcopes'), - (('outputspec.copes', num_copes), - 'l2model.num_copes'), - ]) - ]) +pickfirst = lambda x: x[0] +level1_workflow.connect( + [(preproc, fixed_fx, [(('outputspec.mask', pickfirst), + 'flameo.mask_file')]), + (modelfit, fixed_fx, [ + (('outputspec.copes', sort_copes), 'inputspec.copes'), + ('outputspec.dof_file', 'inputspec.dof_files'), + (('outputspec.varcopes', sort_copes), 'inputspec.varcopes'), + (('outputspec.copes', num_copes), 'l2model.num_copes'), + ])]) """ Experiment specific components ------------------------------ @@ -139,17 +132,18 @@ def num_copes(files): """ -inputnode = pe.Node(niu.IdentityInterface(fields=['in_data']), name='inputnode') +inputnode = pe.Node( + niu.IdentityInterface(fields=['in_data']), name='inputnode') # Specify the subject directories subject_list = ['s1'] # , 's3'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(niu.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) +infosource = pe.Node( + niu.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -160,7 +154,6 @@ def num_copes(files): """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataSource` object and fill in the information from above about the layout of our data. The @@ -169,13 +162,12 @@ def num_copes(files): functionality. """ -datasource = pe.Node(nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + nio.DataGrabber(infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.template = 'nipype-tutorial/data/%s/%s.nii' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """ Use the get_node function to retrieve an internal node by name. Then set the iterables on this node to perform two different extents of smoothing. @@ -187,7 +179,6 @@ def num_copes(files): hpcutoff = 120. TR = 3. featinput.inputs.highpass = hpcutoff / (2. * TR) - """ Setup a function that returns subject-specific information about the experimental paradigm. This is used by the @@ -207,11 +198,13 @@ def subjectinfo(subject_id): for r in range(4): onsets = [list(range(15, 240, 60)), list(range(45, 240, 60))] output.insert(r, - Bunch(conditions=names, - onsets=deepcopy(onsets), - durations=[[15] for s in names])) + Bunch( + conditions=names, + onsets=deepcopy(onsets), + durations=[[15] for s in names])) return output + """ Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - @@ -236,15 +229,15 @@ def subjectinfo(subject_id): modelfit.inputs.inputspec.film_threshold = 1000 level1_workflow.base_dir = os.path.abspath('./fsl/workingdir') -level1_workflow.config['execution'] = dict(crashdump_dir=os.path.abspath('./fsl/crashdumps')) - -level1_workflow.connect([(inputnode, datasource, [('in_data', 'base_directory')]), - (infosource, datasource, [('subject_id', 'subject_id')]), - (infosource, modelspec, [(('subject_id', subjectinfo), - 'subject_info')]), - (datasource, preproc, [('func', 'inputspec.func')]), - ]) - +level1_workflow.config['execution'] = dict( + crashdump_dir=os.path.abspath('./fsl/crashdumps')) + +level1_workflow.connect([ + (inputnode, datasource, [('in_data', 'base_directory')]), + (infosource, datasource, [('subject_id', 'subject_id')]), + (infosource, modelspec, [(('subject_id', subjectinfo), 'subject_info')]), + (datasource, preproc, [('func', 'inputspec.func')]), +]) """ Execute the pipeline -------------------- diff --git a/examples/fmri_nipy_glm.py b/examples/fmri_nipy_glm.py index a7abd9e8b7..0439050c7a 100755 --- a/examples/fmri_nipy_glm.py +++ b/examples/fmri_nipy_glm.py @@ -22,19 +22,16 @@ from nipype.interfaces.nipy.model import FitGLM, EstimateContrast from nipype.interfaces.nipy.preprocess import ComputeMask - - """Import necessary modules from nipype.""" -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.spm as spm # spm -import nipype.interfaces.matlab as mlab # how to run matlab -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.rapidart as ra # artifact detection -import nipype.algorithms.modelgen as model # model specification -import os # system functions - +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.spm as spm # spm +import nipype.interfaces.matlab as mlab # how to run matlab +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.rapidart as ra # artifact detection +import nipype.algorithms.modelgen as model # model specification +import os # system functions """ Preliminaries @@ -48,7 +45,6 @@ # Set the way matlab should be called mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") - """The nipype tutorial contains data for two subjects. Subject data is in two subdirectories, ``s1`` and ``s2``. Each subject directory contains four functional volumes: f3.nii, f5.nii, f7.nii, f10.nii. And @@ -71,12 +67,12 @@ # Specify the subject directories subject_list = ['s1'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -87,7 +83,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Preprocessing pipeline nodes ---------------------------- @@ -99,14 +94,14 @@ functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """Use :class:`nipype.interfaces.spm.Realign` for motion correction and register all images to the mean image. """ @@ -115,7 +110,6 @@ realign.inputs.register_to_mean = True compute_mask = pe.Node(interface=ComputeMask(), name="compute_mask") - """Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in intensity or movement. @@ -128,23 +122,18 @@ art.inputs.zintensity_threshold = 3 art.inputs.mask_type = 'file' art.inputs.parameter_source = 'SPM' - - """Use :class:`nipype.interfaces.spm.Coregister` to perform a rigid body registration of the functional data to the structural data. """ coregister = pe.Node(interface=spm.Coregister(), name="coregister") coregister.inputs.jobtype = 'estimate' - - """Smooth the functional data using :class:`nipype.interfaces.spm.Smooth`. """ smooth = pe.Node(interface=spm.Smooth(), name="smooth") smooth.inputs.fwhm = 4 - """ Set up analysis components -------------------------- @@ -166,16 +155,18 @@ def subjectinfo(subject_id): for r in range(4): onsets = [list(range(15, 240, 60)), list(range(45, 240, 60))] output.insert(r, - Bunch(conditions=names, - onsets=deepcopy(onsets), - durations=[[15] for s in names], - amplitudes=None, - tmod=None, - pmod=None, - regressor_names=None, - regressors=None)) + Bunch( + conditions=names, + onsets=deepcopy(onsets), + durations=[[15] for s in names], + amplitudes=None, + tmod=None, + pmod=None, + regressor_names=None, + regressors=None)) return output + """Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - [Name,Stat,[list of condition names],[weights on @@ -186,7 +177,6 @@ def subjectinfo(subject_id): cont1 = ('Task>Baseline', 'T', ['Task-Odd', 'Task-Even'], [0.5, 0.5]) cont2 = ('Task-Odd>Task-Even', 'T', ['Task-Odd', 'Task-Even'], [1, -1]) contrasts = [cont1, cont2] - """Generate design information using :class:`nipype.interfaces.spm.SpecifyModel`. nipy accepts only design specified in seconds so "output_units" has always have to be set to "secs". @@ -198,7 +188,6 @@ def subjectinfo(subject_id): modelspec.inputs.output_units = 'secs' modelspec.inputs.time_repetition = 3. modelspec.inputs.high_pass_filter_cutoff = 120 - """Fit the GLM model using nipy and ordinary least square method """ @@ -206,16 +195,15 @@ def subjectinfo(subject_id): model_estimate.inputs.TR = 3. model_estimate.inputs.model = "spherical" model_estimate.inputs.method = "ols" - """Estimate the contrasts. The format of the contrasts definition is the same as for FSL and SPM """ -contrast_estimate = pe.Node(interface=EstimateContrast(), name="contrast_estimate") +contrast_estimate = pe.Node( + interface=EstimateContrast(), name="contrast_estimate") cont1 = ('Task>Baseline', 'T', ['Task-Odd', 'Task-Even'], [0.5, 0.5]) cont2 = ('Task-Odd>Task-Even', 'T', ['Task-Odd', 'Task-Even'], [1, -1]) contrast_estimate.inputs.contrasts = [cont1, cont2] - """ Setup the pipeline ------------------ @@ -242,30 +230,32 @@ def subjectinfo(subject_id): l1pipeline = pe.Workflow(name="level1") l1pipeline.base_dir = os.path.abspath('nipy_tutorial/workingdir') -l1pipeline.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, realign, [('func', 'in_files')]), - (realign, compute_mask, [('mean_image', 'mean_volume')]), - (realign, coregister, [('mean_image', 'source'), - ('realigned_files', 'apply_to_files')]), - (datasource, coregister, [('struct', 'target')]), - (coregister, smooth, [('coregistered_files', 'in_files')]), - (realign, modelspec, [('realignment_parameters', 'realignment_parameters')]), - (smooth, modelspec, [('smoothed_files', 'functional_runs')]), - (realign, art, [('realignment_parameters', 'realignment_parameters')]), - (coregister, art, [('coregistered_files', 'realigned_files')]), - (compute_mask, art, [('brain_mask', 'mask_file')]), - (art, modelspec, [('outlier_files', 'outlier_files')]), - (infosource, modelspec, [(("subject_id", subjectinfo), "subject_info")]), - (modelspec, model_estimate, [('session_info', 'session_info')]), - (compute_mask, model_estimate, [('brain_mask', 'mask')]), - (model_estimate, contrast_estimate, [("beta", "beta"), - ("nvbeta", "nvbeta"), - ("s2", "s2"), - ("dof", "dof"), - ("axis", "axis"), - ("constants", "constants"), - ("reg_names", "reg_names")]) - ]) +l1pipeline.connect( + [(infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, realign, [('func', 'in_files')]), (realign, compute_mask, [ + ('mean_image', 'mean_volume') + ]), (realign, coregister, [('mean_image', 'source'), + ('realigned_files', + 'apply_to_files')]), (datasource, coregister, + [('struct', 'target')]), + (coregister, smooth, + [('coregistered_files', 'in_files')]), (realign, modelspec, [ + ('realignment_parameters', 'realignment_parameters') + ]), (smooth, modelspec, + [('smoothed_files', 'functional_runs')]), (realign, art, [ + ('realignment_parameters', 'realignment_parameters') + ]), (coregister, art, [('coregistered_files', 'realigned_files')]), + (compute_mask, art, [('brain_mask', 'mask_file')]), (art, modelspec, [ + ('outlier_files', 'outlier_files') + ]), (infosource, modelspec, [ + (("subject_id", subjectinfo), "subject_info") + ]), (modelspec, model_estimate, + [('session_info', 'session_info')]), (compute_mask, model_estimate, + [('brain_mask', 'mask')]), + (model_estimate, contrast_estimate, + [("beta", "beta"), ("nvbeta", "nvbeta"), ("s2", "s2"), ("dof", "dof"), + ("axis", "axis"), ("constants", "constants"), ("reg_names", + "reg_names")])]) if __name__ == '__main__': l1pipeline.run() diff --git a/examples/fmri_slicer_coregistration.py b/examples/fmri_slicer_coregistration.py index e0129651dd..461fedabdf 100755 --- a/examples/fmri_slicer_coregistration.py +++ b/examples/fmri_slicer_coregistration.py @@ -15,15 +15,12 @@ # raise RuntimeWarning, 'Slicer not fully implmented' from nipype.interfaces.slicer import BRAINSFit, BRAINSResample - - """Import necessary modules from nipype.""" -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import os # system functions - +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import os # system functions """ Preliminaries @@ -38,7 +35,6 @@ package_check('numpy', '1.3', 'tutorial1') package_check('scipy', '0.7', 'tutorial1') package_check('IPython', '0.10', 'tutorial1') - """The nipype tutorial contains data for two subjects. Subject data is in two subdirectories, ``s1`` and ``s2``. Each subject directory contains four functional volumes: f3.nii, f5.nii, f7.nii, f10.nii. And @@ -61,12 +57,10 @@ # Specify the subject directories subject_list = ['s1', 's3'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', 'f3']], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict(func=[['subject_id', 'f3']], struct=[['subject_id', 'struct']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -77,7 +71,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Preprocessing pipeline nodes ---------------------------- @@ -89,9 +82,10 @@ functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = info @@ -110,11 +104,11 @@ pipeline.connect([(infosource, datasource, [('subject_id', 'subject_id')]), (datasource, coregister, [('func', 'movingVolume')]), - (datasource, coregister, [('struct', 'fixedVolume')]), - (coregister, reslice, [('outputTransform', 'warpTransform')]), - (datasource, reslice, [('func', 'inputVolume')]), - (datasource, reslice, [('struct', 'referenceVolume')]) - ]) + (datasource, coregister, + [('struct', 'fixedVolume')]), (coregister, reslice, [ + ('outputTransform', 'warpTransform') + ]), (datasource, reslice, [('func', 'inputVolume')]), + (datasource, reslice, [('struct', 'referenceVolume')])]) if __name__ == '__main__': pipeline.run() diff --git a/examples/fmri_spm.py b/examples/fmri_spm.py index 4fb2ec5be0..23a16a36fe 100755 --- a/examples/fmri_spm.py +++ b/examples/fmri_spm.py @@ -19,7 +19,7 @@ from builtins import str from builtins import range -import os # system functions +import os # system functions from nipype import config # config.enable_provenance() @@ -31,13 +31,12 @@ # '/Applications/MATLAB/MATLAB_Compiler_Runtime/v713/ script') # spm.SPMCommand.set_mlab_paths(matlab_cmd=matlab_cmd, use_mcr=True) -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.rapidart as ra # artifact detection -import nipype.algorithms.modelgen as model # model specification +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.rapidart as ra # artifact detection +import nipype.algorithms.modelgen as model # model specification import nipype.interfaces.matlab as mlab - """ Preliminaries @@ -58,7 +57,6 @@ # In case a different path is required # mlab.MatlabCommand.set_default_paths('/software/matlab/spm12b/spm12b_r5918') - """The nipype tutorial contains data for two subjects. Subject data is in two subdirectories, ``s1`` and ``s2``. Each subject directory contains four functional volumes: f3.nii, f5.nii, f7.nii, f10.nii. And @@ -81,12 +79,12 @@ # Specify the subject directories subject_list = ['s1', 's3'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -97,7 +95,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Preprocessing pipeline nodes ---------------------------- @@ -109,21 +106,20 @@ functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """Use :class:`nipype.interfaces.spm.Realign` for motion correction and register all images to the mean image. """ realign = pe.Node(interface=spm.Realign(), name="realign") realign.inputs.register_to_mean = True - """Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in intensity or movement. @@ -136,22 +132,18 @@ art.inputs.zintensity_threshold = 3 art.inputs.mask_type = 'file' art.inputs.parameter_source = 'SPM' - """Skull strip structural images using :class:`nipype.interfaces.fsl.BET`. """ skullstrip = pe.Node(interface=fsl.BET(), name="skullstrip") skullstrip.inputs.mask = True - """Use :class:`nipype.interfaces.spm.Coregister` to perform a rigid body registration of the functional data to the structural data. """ coregister = pe.Node(interface=spm.Coregister(), name="coregister") coregister.inputs.jobtype = 'estimate' - - """Warp functional and structural data to SPM's T1 template using :class:`nipype.interfaces.spm.Normalize`. The tutorial data set includes the template image, T1.nii. @@ -159,8 +151,6 @@ normalize = pe.Node(interface=spm.Normalize(), name="normalize") normalize.inputs.template = os.path.abspath('data/T1.nii') - - """Smooth the functional data using :class:`nipype.interfaces.spm.Smooth`. """ @@ -168,7 +158,6 @@ smooth = pe.Node(interface=spm.Smooth(), name="smooth") fwhmlist = [4] smooth.iterables = ('fwhm', fwhmlist) - """ Set up analysis components -------------------------- @@ -190,11 +179,13 @@ def subjectinfo(subject_id): for r in range(4): onsets = [list(range(15, 240, 60)), list(range(45, 240, 60))] output.insert(r, - Bunch(conditions=names, - onsets=deepcopy(onsets), - durations=[[15] for s in names])) + Bunch( + conditions=names, + onsets=deepcopy(onsets), + durations=[[15] for s in names])) return output + """Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - [Name,Stat,[list of condition names],[weights on @@ -205,7 +196,6 @@ def subjectinfo(subject_id): cont1 = ('Task>Baseline', 'T', ['Task-Odd', 'Task-Even'], [0.5, 0.5]) cont2 = ('Task-Odd>Task-Even', 'T', ['Task-Odd', 'Task-Even'], [1, -1]) contrasts = [cont1, cont2] - """Generate SPM-specific design information using :class:`nipype.interfaces.spm.SpecifyModel`. """ @@ -216,7 +206,6 @@ def subjectinfo(subject_id): modelspec.inputs.output_units = 'secs' modelspec.inputs.time_repetition = 3. modelspec.inputs.high_pass_filter_cutoff = 120 - """Generate a first level SPM.mat file for analysis :class:`nipype.interfaces.spm.Level1Design`. """ @@ -225,24 +214,21 @@ def subjectinfo(subject_id): level1design.inputs.timing_units = modelspec.inputs.output_units level1design.inputs.interscan_interval = modelspec.inputs.time_repetition level1design.inputs.bases = {'hrf': {'derivs': [0, 0]}} - - """Use :class:`nipype.interfaces.spm.EstimateModel` to determine the parameters of the model. """ level1estimate = pe.Node(interface=spm.EstimateModel(), name="level1estimate") level1estimate.inputs.estimation_method = {'Classical': 1} - """Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the first level contrasts specified in a few steps above. """ -contrastestimate = pe.Node(interface=spm.EstimateContrast(), name="contrastestimate") +contrastestimate = pe.Node( + interface=spm.EstimateContrast(), name="contrastestimate") contrastestimate.inputs.contrasts = contrasts contrastestimate.overwrite = True contrastestimate.config = {'execution': {'remove_unnecessary_outputs': False}} - """ Setup the pipeline ------------------ @@ -269,32 +255,31 @@ def subjectinfo(subject_id): l1pipeline = pe.Workflow(name="level1") l1pipeline.base_dir = os.path.abspath('spm_tutorial/workingdir') -l1pipeline.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, realign, [('func', 'in_files')]), - (realign, coregister, [('mean_image', 'source'), - ('realigned_files', 'apply_to_files')]), - (datasource, coregister, [('struct', 'target')]), - (datasource, normalize, [('struct', 'source')]), - (coregister, normalize, [('coregistered_files', 'apply_to_files')]), - (normalize, smooth, [('normalized_files', 'in_files')]), - (infosource, modelspec, [(('subject_id', subjectinfo), - 'subject_info')]), - (realign, modelspec, [('realignment_parameters', 'realignment_parameters')]), - (smooth, modelspec, [('smoothed_files', 'functional_runs')]), - (normalize, skullstrip, [('normalized_source', 'in_file')]), - (realign, art, [('realignment_parameters', 'realignment_parameters')]), - (normalize, art, [('normalized_files', 'realigned_files')]), - (skullstrip, art, [('mask_file', 'mask_file')]), - (art, modelspec, [('outlier_files', 'outlier_files')]), - (modelspec, level1design, [('session_info', 'session_info')]), - (skullstrip, level1design, [('mask_file', 'mask_image')]), - (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), - (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - ]) - - +l1pipeline.connect([ + (infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, realign, [('func', 'in_files')]), + (realign, coregister, [('mean_image', 'source'), ('realigned_files', + 'apply_to_files')]), + (datasource, coregister, [('struct', 'target')]), + (datasource, normalize, [('struct', 'source')]), + (coregister, normalize, [('coregistered_files', 'apply_to_files')]), + (normalize, smooth, [('normalized_files', 'in_files')]), + (infosource, modelspec, [(('subject_id', subjectinfo), 'subject_info')]), + (realign, modelspec, [('realignment_parameters', + 'realignment_parameters')]), + (smooth, modelspec, [('smoothed_files', 'functional_runs')]), + (normalize, skullstrip, [('normalized_source', 'in_file')]), + (realign, art, [('realignment_parameters', 'realignment_parameters')]), + (normalize, art, [('normalized_files', 'realigned_files')]), + (skullstrip, art, [('mask_file', 'mask_file')]), + (art, modelspec, [('outlier_files', 'outlier_files')]), + (modelspec, level1design, [('session_info', 'session_info')]), + (skullstrip, level1design, [('mask_file', 'mask_image')]), + (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), + (level1estimate, contrastestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', 'beta_images'), + ('residual_image', 'residual_image')]), +]) """ Setup storage results @@ -321,26 +306,27 @@ def subjectinfo(subject_id): def getstripdir(subject_id): import os - return os.path.join(os.path.abspath('spm_tutorial/workingdir'), '_subject_id_%s' % subject_id) - -# store relevant outputs from various stages of the 1st level analysis -l1pipeline.connect([(infosource, datasink, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (realign, datasink, [('mean_image', 'realign.@mean'), - ('realignment_parameters', 'realign.@param')]), - (art, datasink, [('outlier_files', 'art.@outliers'), - ('statistic_files', 'art.@stats')]), - (level1design, datasink, [('spm_mat_file', 'model.pre-estimate')]), - (level1estimate, datasink, [('spm_mat_file', 'model.@spm'), - ('beta_images', 'model.@beta'), - ('mask_image', 'model.@mask'), - ('residual_image', 'model.@res'), - ('RPVimage', 'model.@rpv')]), - (contrastestimate, datasink, [('con_images', 'contrasts.@con'), - ('spmT_images', 'contrasts.@T')]), - ]) + return os.path.join( + os.path.abspath('spm_tutorial/workingdir'), + '_subject_id_%s' % subject_id) +# store relevant outputs from various stages of the 1st level analysis +l1pipeline.connect([ + (infosource, datasink, [('subject_id', 'container'), + (('subject_id', getstripdir), 'strip_dir')]), + (realign, datasink, [('mean_image', 'realign.@mean'), + ('realignment_parameters', 'realign.@param')]), + (art, datasink, [('outlier_files', 'art.@outliers'), ('statistic_files', + 'art.@stats')]), + (level1design, datasink, [('spm_mat_file', 'model.pre-estimate')]), + (level1estimate, datasink, + [('spm_mat_file', 'model.@spm'), ('beta_images', 'model.@beta'), + ('mask_image', 'model.@mask'), ('residual_image', 'model.@res'), + ('RPVimage', 'model.@rpv')]), + (contrastestimate, datasink, [('con_images', 'contrasts.@con'), + ('spmT_images', 'contrasts.@T')]), +]) """ Setup level 2 pipeline ---------------------- @@ -355,41 +341,39 @@ def getstripdir(subject_id): contrast_ids = list(range(1, len(contrasts) + 1)) l2source = pe.Node(nio.DataGrabber(infields=['fwhm', 'con']), name="l2source") # we use .*i* to capture both .img (SPM8) and .nii (SPM12) -l2source.inputs.template = os.path.abspath('spm_tutorial/l1output/*/con*/*/_fwhm_%d/con_%04d.*i*') +l2source.inputs.template = os.path.abspath( + 'spm_tutorial/l1output/*/con*/*/_fwhm_%d/con_%04d.*i*') # iterate over all contrast images -l2source.iterables = [('fwhm', fwhmlist), - ('con', contrast_ids)] +l2source.iterables = [('fwhm', fwhmlist), ('con', contrast_ids)] l2source.inputs.sort_filelist = True - - """Use :class:`nipype.interfaces.spm.OneSampleTTestDesign` to perform a simple statistical analysis of the contrasts from the group of subjects (n=2 in this example). """ # setup a 1-sample t-test node -onesamplettestdes = pe.Node(interface=spm.OneSampleTTestDesign(), name="onesampttestdes") +onesamplettestdes = pe.Node( + interface=spm.OneSampleTTestDesign(), name="onesampttestdes") l2estimate = pe.Node(interface=spm.EstimateModel(), name="level2estimate") l2estimate.inputs.estimation_method = {'Classical': 1} -l2conestimate = pe.Node(interface=spm.EstimateContrast(), name="level2conestimate") +l2conestimate = pe.Node( + interface=spm.EstimateContrast(), name="level2conestimate") cont1 = ('Group', 'T', ['mean'], [1]) l2conestimate.inputs.contrasts = [cont1] l2conestimate.inputs.group_contrast = True - - """As before, we setup a pipeline to connect these two nodes (l2source -> onesamplettest). """ l2pipeline = pe.Workflow(name="level2") l2pipeline.base_dir = os.path.abspath('spm_tutorial/l2output') -l2pipeline.connect([(l2source, onesamplettestdes, [('outfiles', 'in_files')]), - (onesamplettestdes, l2estimate, [('spm_mat_file', 'spm_mat_file')]), - (l2estimate, l2conestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - ]) - +l2pipeline.connect([ + (l2source, onesamplettestdes, [('outfiles', 'in_files')]), + (onesamplettestdes, l2estimate, [('spm_mat_file', 'spm_mat_file')]), + (l2estimate, l2conestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', 'beta_images'), + ('residual_image', 'residual_image')]), +]) """ Execute the pipeline -------------------- diff --git a/examples/fmri_spm_auditory.py b/examples/fmri_spm_auditory.py index 33c03f8bf0..e4c690421a 100755 --- a/examples/fmri_spm_auditory.py +++ b/examples/fmri_spm_auditory.py @@ -19,17 +19,14 @@ from builtins import range -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.spm as spm # spm -import nipype.interfaces.fsl as fsl # fsl -import nipype.interfaces.matlab as mlab # how to run matlab -import nipype.interfaces.fsl as fsl # fsl -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.modelgen as model # model specification -import os # system functions - - +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.spm as spm # spm +import nipype.interfaces.fsl as fsl # fsl +import nipype.interfaces.matlab as mlab # how to run matlab +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.modelgen as model # model specification +import os # system functions """ Preliminaries @@ -39,7 +36,6 @@ # Set the way matlab should be called mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") - """ Setting up workflows -------------------- @@ -57,7 +53,6 @@ """ preproc = pe.Workflow(name='preproc') - """We strongly encourage to use 4D files insteead of series of 3D for fMRI analyses for many reasons (cleanness and saving and filesystem inodes are among them). However, the the workflow presented in the SPM8 manual which this tutorial is based on @@ -72,14 +67,11 @@ if merge_to_4d: merge = pe.Node(interface=fsl.Merge(), name="merge") merge.inputs.dimension = "t" - """Use :class:`nipype.interfaces.spm.Realign` for motion correction and register all images to the mean image. """ realign = pe.Node(interface=spm.Realign(), name="realign") - - """Use :class:`nipype.interfaces.spm.Coregister` to perform a rigid body registration of the functional data to the structural data. """ @@ -87,14 +79,11 @@ coregister = pe.Node(interface=spm.Coregister(), name="coregister") coregister.inputs.jobtype = 'estimate' - segment = pe.Node(interface=spm.Segment(), name="segment") - """Uncomment the following line for faster execution """ # segment.inputs.gaussians_per_class = [1, 1, 1, 4] - """Warp functional and structural data to SPM's T1 template using :class:`nipype.interfaces.spm.Normalize`. The tutorial data set includes the template image, T1.nii. @@ -105,14 +94,11 @@ normalize_struc = pe.Node(interface=spm.Normalize(), name="normalize_struc") normalize_struc.inputs.jobtype = "write" - - """Smooth the functional data using :class:`nipype.interfaces.spm.Smooth`. """ smooth = pe.Node(interface=spm.Smooth(), name="smooth") - """`write_voxel_sizes` is the input of the normalize interface that is recommended to be set to the voxel sizes of the target volume. There is no need to set it manually since we van infer it from data using the following function: @@ -129,6 +115,7 @@ def get_vox_dims(volume): voxdims = hdr.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] + """Here we are connecting all the nodes together. Notice that we add the merge node only if you choose to use 4D. Also `get_vox_dims` function is passed along the input volume of normalise to set the optimal voxel sizes. @@ -137,18 +124,19 @@ def get_vox_dims(volume): if merge_to_4d: preproc.connect([(merge, realign, [('merged_file', 'in_files')])]) -preproc.connect([(realign, coregister, [('mean_image', 'target')]), - (coregister, segment, [('coregistered_source', 'data')]), - (segment, normalize_func, [('transformation_mat', 'parameter_file')]), - (segment, normalize_struc, [('transformation_mat', 'parameter_file'), - ('modulated_input_image', 'apply_to_files'), - (('modulated_input_image', get_vox_dims), 'write_voxel_sizes')]), - (realign, normalize_func, [('realigned_files', 'apply_to_files'), - (('realigned_files', get_vox_dims), 'write_voxel_sizes')]), - (normalize_func, smooth, [('normalized_files', 'in_files')]), - ]) - - +preproc.connect([ + (realign, coregister, [('mean_image', 'target')]), + (coregister, segment, [('coregistered_source', 'data')]), + (segment, normalize_func, [('transformation_mat', 'parameter_file')]), + (segment, normalize_struc, + [('transformation_mat', 'parameter_file'), ('modulated_input_image', + 'apply_to_files'), + (('modulated_input_image', get_vox_dims), 'write_voxel_sizes')]), + (realign, normalize_func, [('realigned_files', 'apply_to_files'), + (('realigned_files', get_vox_dims), + 'write_voxel_sizes')]), + (normalize_func, smooth, [('normalized_files', 'in_files')]), +]) """ Set up analysis workflow ------------------------ @@ -156,20 +144,17 @@ def get_vox_dims(volume): """ l1analysis = pe.Workflow(name='analysis') - """Generate SPM-specific design information using :class:`nipype.interfaces.spm.SpecifyModel`. """ modelspec = pe.Node(interface=model.SpecifySPMModel(), name="modelspec") - """Generate a first level SPM.mat file for analysis :class:`nipype.interfaces.spm.Level1Design`. """ level1design = pe.Node(interface=spm.Level1Design(), name="level1design") level1design.inputs.bases = {'hrf': {'derivs': [0, 0]}} - """Use :class:`nipype.interfaces.spm.EstimateModel` to determine the parameters of the model. """ @@ -178,49 +163,49 @@ def get_vox_dims(volume): level1estimate.inputs.estimation_method = {'Classical': 1} threshold = pe.Node(interface=spm.Threshold(), name="threshold") - - """Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the first level contrasts specified in a few steps above. """ -contrastestimate = pe.Node(interface=spm.EstimateContrast(), name="contrastestimate") - -l1analysis.connect([(modelspec, level1design, [('session_info', 'session_info')]), - (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), - (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - (contrastestimate, threshold, [('spm_mat_file', 'spm_mat_file'), - ('spmT_images', 'stat_image')]), - ]) +contrastestimate = pe.Node( + interface=spm.EstimateContrast(), name="contrastestimate") +l1analysis.connect([ + (modelspec, level1design, [('session_info', 'session_info')]), + (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), + (level1estimate, contrastestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', 'beta_images'), + ('residual_image', 'residual_image')]), + (contrastestimate, threshold, [('spm_mat_file', 'spm_mat_file'), + ('spmT_images', 'stat_image')]), +]) """ Preproc + Analysis pipeline --------------------------- """ - l1pipeline = pe.Workflow(name='firstlevel') -l1pipeline.connect([(preproc, l1analysis, [('realign.realignment_parameters', - 'modelspec.realignment_parameters')])]) - +l1pipeline.connect([(preproc, l1analysis, + [('realign.realignment_parameters', + 'modelspec.realignment_parameters')])]) """Pluging in `functional_runs` is a bit more complicated, because model spec expects a list of `runs`. Every run can be a 4D file or a list of 3D files. Therefore for 3D analysis we need a list of lists and to make one we need a helper function. """ if merge_to_4d: - l1pipeline.connect([(preproc, l1analysis, [('smooth.smoothed_files', - 'modelspec.functional_runs')])]) + l1pipeline.connect([(preproc, l1analysis, + [('smooth.smoothed_files', + 'modelspec.functional_runs')])]) else: + def makelist(item): return [item] - l1pipeline.connect([(preproc, l1analysis, [(('smooth.smoothed_files', makelist), - 'modelspec.functional_runs')])]) - + l1pipeline.connect([(preproc, l1analysis, + [(('smooth.smoothed_files', makelist), + 'modelspec.functional_runs')])]) """ Data specific components ------------------------ @@ -239,11 +224,13 @@ def makelist(item): # Specify the subject directories subject_list = ['M00223'] # Map field names to individual subject runs. -info = dict(func=[['f', 'subject_id', 'f', 'subject_id', list(range(16, 100))]], - struct=[['s', 'subject_id', 's', 'subject_id', 2]]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), name="infosource") +info = dict( + func=[['f', 'subject_id', 'f', 'subject_id', + list(range(16, 100))]], + struct=[['s', 'subject_id', 's', 'subject_id', 2]]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -254,7 +241,6 @@ def makelist(item): """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -263,15 +249,14 @@ def makelist(item): functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s%s/%s%s_%03d.img' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - - """ Experimental paradigm specific components ----------------------------------------- @@ -283,10 +268,10 @@ def makelist(item): """ from nipype.interfaces.base import Bunch -subjectinfo = [Bunch(conditions=['Task'], - onsets=[list(range(6, 84, 12))], - durations=[[6]])] - +subjectinfo = [ + Bunch( + conditions=['Task'], onsets=[list(range(6, 84, 12))], durations=[[6]]) +] """Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - [Name,Stat,[list of condition names],[weights on @@ -312,7 +297,6 @@ def makelist(item): l1pipeline.inputs.analysis.modelspec.subject_info = subjectinfo l1pipeline.inputs.analysis.contrastestimate.contrasts = contrasts l1pipeline.inputs.analysis.threshold.contrast_index = 1 - """ Setup the pipeline ------------------ @@ -340,14 +324,14 @@ def makelist(item): level1.base_dir = os.path.abspath('spm_auditory_tutorial/workingdir') level1.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, l1pipeline, [('struct', 'preproc.coregister.source')]) - ]) + (datasource, l1pipeline, [('struct', + 'preproc.coregister.source')])]) if merge_to_4d: - level1.connect([(datasource, l1pipeline, [('func', 'preproc.merge.in_files')])]) + level1.connect([(datasource, l1pipeline, [('func', + 'preproc.merge.in_files')])]) else: - level1.connect([(datasource, l1pipeline, [('func', 'preproc.realign.in_files')])]) - - + level1.connect([(datasource, l1pipeline, [('func', + 'preproc.realign.in_files')])]) """ Setup storage results @@ -369,21 +353,25 @@ def makelist(item): """ datasink = pe.Node(interface=nio.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.abspath('spm_auditory_tutorial/l1output') +datasink.inputs.base_directory = os.path.abspath( + 'spm_auditory_tutorial/l1output') def getstripdir(subject_id): import os - return os.path.join(os.path.abspath('spm_auditory_tutorial/workingdir'), '_subject_id_%s' % subject_id) - -# store relevant outputs from various stages of the 1st level analysis -level1.connect([(infosource, datasink, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (l1pipeline, datasink, [('analysis.contrastestimate.con_images', 'contrasts.@con'), - ('analysis.contrastestimate.spmT_images', 'contrasts.@T')]), - ]) + return os.path.join( + os.path.abspath('spm_auditory_tutorial/workingdir'), + '_subject_id_%s' % subject_id) +# store relevant outputs from various stages of the 1st level analysis +level1.connect([ + (infosource, datasink, [('subject_id', 'container'), + (('subject_id', getstripdir), 'strip_dir')]), + (l1pipeline, datasink, + [('analysis.contrastestimate.con_images', 'contrasts.@con'), + ('analysis.contrastestimate.spmT_images', 'contrasts.@T')]), +]) """ Execute the pipeline -------------------- diff --git a/examples/fmri_spm_dartel.py b/examples/fmri_spm_dartel.py index 746da9f810..587ff9b291 100755 --- a/examples/fmri_spm_dartel.py +++ b/examples/fmri_spm_dartel.py @@ -19,16 +19,15 @@ from builtins import str from builtins import range -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.spm as spm # spm -import nipype.workflows.fmri.spm as spm_wf # spm -import nipype.interfaces.fsl as fsl # fsl -from nipype.interfaces import utility as niu # Utilities -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.rapidart as ra # artifact detection -import nipype.algorithms.modelgen as model # model specification -import os # system functions - +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.spm as spm # spm +import nipype.workflows.fmri.spm as spm_wf # spm +import nipype.interfaces.fsl as fsl # fsl +from nipype.interfaces import utility as niu # Utilities +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.rapidart as ra # artifact detection +import nipype.algorithms.modelgen as model # model specification +import os # system functions """ Preliminaries @@ -46,7 +45,6 @@ # Set the way matlab should be called # mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") # mlab.MatlabCommand.set_default_paths('/software/spm8') - """ Setting up workflows -------------------- @@ -64,14 +62,12 @@ """ preproc = pe.Workflow(name='preproc') - """Use :class:`nipype.interfaces.spm.Realign` for motion correction and register all images to the mean image. """ realign = pe.Node(spm.Realign(), name="realign") realign.inputs.register_to_mean = True - """Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in intensity or movement. @@ -84,45 +80,43 @@ art.inputs.zintensity_threshold = 3 art.inputs.mask_type = 'file' art.inputs.parameter_source = 'SPM' - """Skull strip structural images using :class:`nipype.interfaces.fsl.BET`. """ skullstrip = pe.Node(fsl.BET(), name="skullstrip") skullstrip.inputs.mask = True - """Use :class:`nipype.interfaces.spm.Coregister` to perform a rigid body registration of the functional data to the structural data. """ coregister = pe.Node(spm.Coregister(), name="coregister") coregister.inputs.jobtype = 'estimate' - - """Normalize and smooth functional data using DARTEL template """ -normalize_and_smooth_func = pe.Node(spm.DARTELNorm2MNI(modulate=True), name='normalize_and_smooth_func') +normalize_and_smooth_func = pe.Node( + spm.DARTELNorm2MNI(modulate=True), name='normalize_and_smooth_func') fwhmlist = [4] normalize_and_smooth_func.iterables = ('fwhm', fwhmlist) - """Normalize structural data using DARTEL template """ -normalize_struct = pe.Node(spm.DARTELNorm2MNI(modulate=True), name='normalize_struct') +normalize_struct = pe.Node( + spm.DARTELNorm2MNI(modulate=True), name='normalize_struct') normalize_struct.inputs.fwhm = 2 -preproc.connect([(realign, coregister, [('mean_image', 'source'), - ('realigned_files', 'apply_to_files')]), - (coregister, normalize_and_smooth_func, [('coregistered_files', 'apply_to_files')]), - (normalize_struct, skullstrip, [('normalized_files', 'in_file')]), - (realign, art, [('realignment_parameters', 'realignment_parameters')]), - (normalize_and_smooth_func, art, [('normalized_files', 'realigned_files')]), - (skullstrip, art, [('mask_file', 'mask_file')]), - ]) - - +preproc.connect([ + (realign, coregister, [('mean_image', 'source'), ('realigned_files', + 'apply_to_files')]), + (coregister, normalize_and_smooth_func, [('coregistered_files', + 'apply_to_files')]), + (normalize_struct, skullstrip, [('normalized_files', 'in_file')]), + (realign, art, [('realignment_parameters', 'realignment_parameters')]), + (normalize_and_smooth_func, art, [('normalized_files', + 'realigned_files')]), + (skullstrip, art, [('mask_file', 'mask_file')]), +]) """ Set up analysis workflow ------------------------ @@ -130,40 +124,34 @@ """ l1analysis = pe.Workflow(name='analysis') - """Generate SPM-specific design information using :class:`nipype.interfaces.spm.SpecifyModel`. """ modelspec = pe.Node(model.SpecifySPMModel(), name="modelspec") modelspec.inputs.concatenate_runs = True - """Generate a first level SPM.mat file for analysis :class:`nipype.interfaces.spm.Level1Design`. """ level1design = pe.Node(spm.Level1Design(), name="level1design") level1design.inputs.bases = {'hrf': {'derivs': [0, 0]}} - """Use :class:`nipype.interfaces.spm.EstimateModel` to determine the parameters of the model. """ level1estimate = pe.Node(spm.EstimateModel(), name="level1estimate") level1estimate.inputs.estimation_method = {'Classical': 1} - """Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the first level contrasts specified in a few steps above. """ contrastestimate = pe.Node(spm.EstimateContrast(), name="contrastestimate") - """Use :class: `nipype.interfaces.utility.Select` to select each contrast for reporting. """ selectcontrast = pe.Node(niu.Select(), name="selectcontrast") - """Use :class:`nipype.interfaces.fsl.Overlay` to combine the statistical output of the contrast estimate and a background image into one volume. """ @@ -172,7 +160,6 @@ overlaystats.inputs.stat_thresh = (3, 10) overlaystats.inputs.show_negative_stats = True overlaystats.inputs.auto_thresh_bg = True - """Use :class:`nipype.interfaces.fsl.Slicer` to create images of the overlaid statistical volumes for a report of the first-level results. """ @@ -181,16 +168,19 @@ slicestats.inputs.all_axial = True slicestats.inputs.image_width = 750 -l1analysis.connect([(modelspec, level1design, [('session_info', 'session_info')]), - (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), - (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - (contrastestimate, selectcontrast, [('spmT_images', 'inlist')]), - (selectcontrast, overlaystats, [('out', 'stat_image')]), - (overlaystats, slicestats, [('out_file', 'in_file')]) - ]) - +l1analysis.connect([(modelspec, level1design, + [('session_info', + 'session_info')]), (level1design, level1estimate, + [('spm_mat_file', 'spm_mat_file')]), + (level1estimate, contrastestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', + 'beta_images'), + ('residual_image', + 'residual_image')]), (contrastestimate, selectcontrast, + [('spmT_images', 'inlist')]), + (selectcontrast, overlaystats, + [('out', 'stat_image')]), (overlaystats, slicestats, + [('out_file', 'in_file')])]) """ Preproc + Analysis pipeline --------------------------- @@ -198,19 +188,16 @@ """ l1pipeline = pe.Workflow(name='firstlevel') -l1pipeline.connect([(preproc, l1analysis, [('realign.realignment_parameters', - 'modelspec.realignment_parameters'), - ('normalize_and_smooth_func.normalized_files', - 'modelspec.functional_runs'), - ('art.outlier_files', - 'modelspec.outlier_files'), - ('skullstrip.mask_file', - 'level1design.mask_image'), - ('normalize_struct.normalized_files', - 'overlaystats.background_image')]), - ]) - - +l1pipeline.connect([ + (preproc, l1analysis, + [('realign.realignment_parameters', 'modelspec.realignment_parameters'), + ('normalize_and_smooth_func.normalized_files', + 'modelspec.functional_runs'), ('art.outlier_files', + 'modelspec.outlier_files'), + ('skullstrip.mask_file', + 'level1design.mask_image'), ('normalize_struct.normalized_files', + 'overlaystats.background_image')]), +]) """ Data specific components ------------------------ @@ -237,11 +224,12 @@ # Specify the subject directories subject_list = ['s1', 's3'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(niu.IdentityInterface(fields=['subject_id']), name="infosource") +info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) +infosource = pe.Node( + niu.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -252,7 +240,6 @@ """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -261,39 +248,39 @@ functionality. """ -inputnode = pe.Node(niu.IdentityInterface(fields=['in_data']), name='inputnode') -datasource = pe.Node(nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +inputnode = pe.Node( + niu.IdentityInterface(fields=['in_data']), name='inputnode') +datasource = pe.Node( + nio.DataGrabber(infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.template = 'nipype-tutorial/data/%s/%s.nii' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - """We need to create a separate workflow to make the DARTEL template """ -datasource_dartel = pe.MapNode(nio.DataGrabber(infields=['subject_id'], - outfields=['struct']), - name='datasource_dartel', - iterfield=['subject_id']) +datasource_dartel = pe.MapNode( + nio.DataGrabber(infields=['subject_id'], outfields=['struct']), + name='datasource_dartel', + iterfield=['subject_id']) datasource_dartel.inputs.template = 'nipype-tutorial/data/%s/%s.nii' -datasource_dartel.inputs.template_args = dict(struct=[['subject_id', 'struct']]) +datasource_dartel.inputs.template_args = dict( + struct=[['subject_id', 'struct']]) datasource_dartel.inputs.sort_filelist = True datasource_dartel.inputs.subject_id = subject_list - """Here we make sure that struct files have names corresponding to the subject ids. This way we will be able to pick the right field flows later. """ -rename_dartel = pe.MapNode(niu.Rename(format_string="subject_id_%(subject_id)s_struct"), - iterfield=['in_file', 'subject_id'], - name='rename_dartel') +rename_dartel = pe.MapNode( + niu.Rename(format_string="subject_id_%(subject_id)s_struct"), + iterfield=['in_file', 'subject_id'], + name='rename_dartel') rename_dartel.inputs.subject_id = subject_list rename_dartel.inputs.keep_ext = True dartel_workflow = spm_wf.create_DARTEL_template(name='dartel_workflow') dartel_workflow.inputs.inputspec.template_prefix = "template" - """This function will allow to pick the right field flow for each subject """ @@ -307,12 +294,13 @@ def pickFieldFlow(dartel_flow_fields, subject_id): raise Exception -pick_flow = pe.Node(niu.Function(input_names=['dartel_flow_fields', - 'subject_id'], - output_names=['dartel_flow_field'], - function=pickFieldFlow), - name="pick_flow") +pick_flow = pe.Node( + niu.Function( + input_names=['dartel_flow_fields', 'subject_id'], + output_names=['dartel_flow_field'], + function=pickFieldFlow), + name="pick_flow") """ Experimental paradigm specific components ----------------------------------------- @@ -334,16 +322,18 @@ def subjectinfo(subject_id): for r in range(4): onsets = [list(range(15, 240, 60)), list(range(45, 240, 60))] output.insert(r, - Bunch(conditions=names, - onsets=deepcopy(onsets), - durations=[[15] for s in names], - amplitudes=None, - tmod=None, - pmod=None, - regressor_names=None, - regressors=None)) + Bunch( + conditions=names, + onsets=deepcopy(onsets), + durations=[[15] for s in names], + amplitudes=None, + tmod=None, + pmod=None, + regressor_names=None, + regressors=None)) return output + """Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - [Name,Stat,[list of condition names],[weights on @@ -366,13 +356,10 @@ def subjectinfo(subject_id): l1designref.timing_units = modelspecref.output_units l1designref.interscan_interval = modelspecref.time_repetition - l1pipeline.inputs.analysis.contrastestimate.contrasts = contrasts - # Iterate over each contrast and create report images. selectcontrast.iterables = ('index', [[i] for i in range(len(contrasts))]) - """ Setup the pipeline ------------------ @@ -399,26 +386,31 @@ def subjectinfo(subject_id): level1 = pe.Workflow(name="level1") level1.base_dir = os.path.abspath('spm_dartel_tutorial/workingdir') -level1.connect([(inputnode, datasource, [('in_data', 'base_directory')]), - (inputnode, datasource_dartel, [('in_data', 'base_directory')]), - (datasource_dartel, rename_dartel, [('struct', 'in_file')]), - (rename_dartel, dartel_workflow, [('out_file', 'inputspec.structural_files')]), - - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, l1pipeline, [('func', 'preproc.realign.in_files'), - ('struct', 'preproc.coregister.target'), - ('struct', 'preproc.normalize_struct.apply_to_files')]), - (dartel_workflow, l1pipeline, [('outputspec.template_file', 'preproc.normalize_struct.template_file'), - ('outputspec.template_file', 'preproc.normalize_and_smooth_func.template_file')]), - (infosource, pick_flow, [('subject_id', 'subject_id')]), - (dartel_workflow, pick_flow, [('outputspec.flow_fields', 'dartel_flow_fields')]), - (pick_flow, l1pipeline, [('dartel_flow_field', 'preproc.normalize_struct.flowfield_files'), - ('dartel_flow_field', 'preproc.normalize_and_smooth_func.flowfield_files')]), - (infosource, l1pipeline, [(('subject_id', subjectinfo), - 'analysis.modelspec.subject_info')]), - ]) - - +level1.connect([ + (inputnode, datasource, [('in_data', 'base_directory')]), + (inputnode, datasource_dartel, [('in_data', 'base_directory')]), + (datasource_dartel, rename_dartel, [('struct', 'in_file')]), + (rename_dartel, dartel_workflow, [('out_file', + 'inputspec.structural_files')]), + (infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, l1pipeline, + [('func', 'preproc.realign.in_files'), ('struct', + 'preproc.coregister.target'), + ('struct', 'preproc.normalize_struct.apply_to_files')]), + (dartel_workflow, l1pipeline, + [('outputspec.template_file', 'preproc.normalize_struct.template_file'), + ('outputspec.template_file', + 'preproc.normalize_and_smooth_func.template_file')]), + (infosource, pick_flow, [('subject_id', 'subject_id')]), + (dartel_workflow, pick_flow, [('outputspec.flow_fields', + 'dartel_flow_fields')]), + (pick_flow, l1pipeline, + [('dartel_flow_field', 'preproc.normalize_struct.flowfield_files'), + ('dartel_flow_field', + 'preproc.normalize_and_smooth_func.flowfield_files')]), + (infosource, l1pipeline, [(('subject_id', subjectinfo), + 'analysis.modelspec.subject_info')]), +]) """ Setup storage results @@ -440,7 +432,8 @@ def subjectinfo(subject_id): """ datasink = pe.Node(nio.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.abspath('spm_dartel_tutorial/l1output') +datasink.inputs.base_directory = os.path.abspath( + 'spm_dartel_tutorial/l1output') report = pe.Node(nio.DataSink(), name='report') report.inputs.base_directory = os.path.abspath('spm_dartel_tutorial/report') report.inputs.parameterization = False @@ -448,19 +441,22 @@ def subjectinfo(subject_id): def getstripdir(subject_id): import os - return os.path.join(os.path.abspath('spm_dartel_tutorial/workingdir'), '_subject_id_%s' % subject_id) - -# store relevant outputs from various stages of the 1st level analysis -level1.connect([(infosource, datasink, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (l1pipeline, datasink, [('analysis.contrastestimate.con_images', 'contrasts.@con'), - ('analysis.contrastestimate.spmT_images', 'contrasts.@T')]), - (infosource, report, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (l1pipeline, report, [('analysis.slicestats.out_file', '@report')]), - ]) + return os.path.join( + os.path.abspath('spm_dartel_tutorial/workingdir'), + '_subject_id_%s' % subject_id) +# store relevant outputs from various stages of the 1st level analysis +level1.connect([ + (infosource, datasink, [('subject_id', 'container'), + (('subject_id', getstripdir), 'strip_dir')]), + (l1pipeline, datasink, + [('analysis.contrastestimate.con_images', 'contrasts.@con'), + ('analysis.contrastestimate.spmT_images', 'contrasts.@T')]), + (infosource, report, [('subject_id', 'container'), + (('subject_id', getstripdir), 'strip_dir')]), + (l1pipeline, report, [('analysis.slicestats.out_file', '@report')]), +]) """ Execute the pipeline -------------------- @@ -475,7 +471,6 @@ def getstripdir(subject_id): if __name__ == '__main__': level1.run(plugin_args={'n_procs': 4}) level1.write_graph() - """ Setup level 2 pipeline ---------------------- @@ -490,13 +485,11 @@ def getstripdir(subject_id): contrast_ids = list(range(1, len(contrasts) + 1)) l2source = pe.Node(nio.DataGrabber(infields=['fwhm', 'con']), name="l2source") # we use .*i* to capture both .img (SPM8) and .nii (SPM12) -l2source.inputs.template = os.path.abspath('spm_dartel_tutorial/l1output/*/con*/*/_fwhm_%d/con_%04d.*i*') +l2source.inputs.template = os.path.abspath( + 'spm_dartel_tutorial/l1output/*/con*/*/_fwhm_%d/con_%04d.*i*') # iterate over all contrast images -l2source.iterables = [('fwhm', fwhmlist), - ('con', contrast_ids)] +l2source.iterables = [('fwhm', fwhmlist), ('con', contrast_ids)] l2source.inputs.sort_filelist = True - - """Use :class:`nipype.interfaces.spm.OneSampleTTestDesign` to perform a simple statistical analysis of the contrasts from the group of subjects (n=2 in this example). @@ -510,21 +503,19 @@ def getstripdir(subject_id): cont1 = ('Group', 'T', ['mean'], [1]) l2conestimate.inputs.contrasts = [cont1] l2conestimate.inputs.group_contrast = True - - """As before, we setup a pipeline to connect these two nodes (l2source -> onesamplettest). """ l2pipeline = pe.Workflow(name="level2") l2pipeline.base_dir = os.path.abspath('spm_dartel_tutorial/l2output') -l2pipeline.connect([(l2source, onesamplettestdes, [('outfiles', 'in_files')]), - (onesamplettestdes, l2estimate, [('spm_mat_file', 'spm_mat_file')]), - (l2estimate, l2conestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - ]) - +l2pipeline.connect([ + (l2source, onesamplettestdes, [('outfiles', 'in_files')]), + (onesamplettestdes, l2estimate, [('spm_mat_file', 'spm_mat_file')]), + (l2estimate, l2conestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', 'beta_images'), + ('residual_image', 'residual_image')]), +]) """ Execute the second level pipeline --------------------------------- diff --git a/examples/fmri_spm_face.py b/examples/fmri_spm_face.py index c716e4793f..5644398d54 100755 --- a/examples/fmri_spm_face.py +++ b/examples/fmri_spm_face.py @@ -20,14 +20,13 @@ from __future__ import division from builtins import range -import os # system functions -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.spm as spm # spm -import nipype.interfaces.matlab as mlab # how to run matlab -import nipype.interfaces.utility as util # utility -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.modelgen as model # model specification - +import os # system functions +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.spm as spm # spm +import nipype.interfaces.matlab as mlab # how to run matlab +import nipype.interfaces.utility as util # utility +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.modelgen as model # model specification """ Preliminaries @@ -43,8 +42,6 @@ mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") # If SPM is not in your MATLAB path you should add it here # mlab.MatlabCommand.set_default_paths('/path/to/your/spm8') - - """ Setting up workflows -------------------- @@ -61,8 +58,6 @@ """ preproc = pe.Workflow(name='preproc') - - """Use :class:`nipype.interfaces.spm.Realign` for motion correction and register all images to the mean image. """ @@ -70,8 +65,6 @@ realign = pe.Node(interface=spm.Realign(), name="realign") slice_timing = pe.Node(interface=spm.SliceTiming(), name="slice_timing") - - """Use :class:`nipype.interfaces.spm.Coregister` to perform a rigid body registration of the functional data to the structural data. """ @@ -79,15 +72,12 @@ coregister = pe.Node(interface=spm.Coregister(), name="coregister") coregister.inputs.jobtype = 'estimate' - segment = pe.Node(interface=spm.Segment(), name="segment") segment.inputs.save_bias_corrected = True - """Uncomment the following line for faster execution """ # segment.inputs.gaussians_per_class = [1, 1, 1, 4] - """Warp functional and structural data to SPM's T1 template using :class:`nipype.interfaces.spm.Normalize`. The tutorial data set includes the template image, T1.nii. @@ -98,14 +88,11 @@ normalize_struc = pe.Node(interface=spm.Normalize(), name="normalize_struc") normalize_struc.inputs.jobtype = "write" - - """Smooth the functional data using :class:`nipype.interfaces.spm.Smooth`. """ smooth = pe.Node(interface=spm.Smooth(), name="smooth") - """`write_voxel_sizes` is the input of the normalize interface that is recommended to be set to the voxel sizes of the target volume. There is no need to set it manually since we van infer it from data using the following function: @@ -122,24 +109,26 @@ def get_vox_dims(volume): voxdims = hdr.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] + """Here we are connecting all the nodes together. Notice that we add the merge node only if you choose to use 4D. Also `get_vox_dims` function is passed along the input volume of normalise to set the optimal voxel sizes. """ -preproc.connect([(realign, coregister, [('mean_image', 'target')]), - (coregister, segment, [('coregistered_source', 'data')]), - (segment, normalize_func, [('transformation_mat', 'parameter_file')]), - (segment, normalize_struc, [('transformation_mat', 'parameter_file'), - ('bias_corrected_image', 'apply_to_files'), - (('bias_corrected_image', get_vox_dims), 'write_voxel_sizes')]), - (realign, slice_timing, [('realigned_files', 'in_files')]), - (slice_timing, normalize_func, [('timecorrected_files', 'apply_to_files'), - (('timecorrected_files', get_vox_dims), 'write_voxel_sizes')]), - (normalize_func, smooth, [('normalized_files', 'in_files')]), - ]) - - +preproc.connect([ + (realign, coregister, [('mean_image', 'target')]), + (coregister, segment, [('coregistered_source', 'data')]), + (segment, normalize_func, [('transformation_mat', 'parameter_file')]), + (segment, normalize_struc, + [('transformation_mat', 'parameter_file'), ('bias_corrected_image', + 'apply_to_files'), + (('bias_corrected_image', get_vox_dims), 'write_voxel_sizes')]), + (realign, slice_timing, [('realigned_files', 'in_files')]), + (slice_timing, normalize_func, [('timecorrected_files', 'apply_to_files'), + (('timecorrected_files', get_vox_dims), + 'write_voxel_sizes')]), + (normalize_func, smooth, [('normalized_files', 'in_files')]), +]) """ Set up analysis workflow ------------------------ @@ -147,19 +136,16 @@ def get_vox_dims(volume): """ l1analysis = pe.Workflow(name='analysis') - """Generate SPM-specific design information using :class:`nipype.interfaces.spm.SpecifyModel`. """ modelspec = pe.Node(interface=model.SpecifySPMModel(), name="modelspec") - """Generate a first level SPM.mat file for analysis :class:`nipype.interfaces.spm.Level1Design`. """ level1design = pe.Node(interface=spm.Level1Design(), name="level1design") - """Use :class:`nipype.interfaces.spm.EstimateModel` to determine the parameters of the model. """ @@ -168,27 +154,28 @@ def get_vox_dims(volume): level1estimate.inputs.estimation_method = {'Classical': 1} threshold = pe.Node(interface=spm.Threshold(), name="threshold") - - """Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the first level contrasts specified in a few steps above. """ -contrastestimate = pe.Node(interface=spm.EstimateContrast(), name="contrastestimate") +contrastestimate = pe.Node( + interface=spm.EstimateContrast(), name="contrastestimate") def pickfirst(l): return l[0] -l1analysis.connect([(modelspec, level1design, [('session_info', 'session_info')]), - (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), - (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - (contrastestimate, threshold, [('spm_mat_file', 'spm_mat_file'), - (('spmT_images', pickfirst), 'stat_image')]), - ]) +l1analysis.connect([ + (modelspec, level1design, [('session_info', 'session_info')]), + (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), + (level1estimate, contrastestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', 'beta_images'), + ('residual_image', 'residual_image')]), + (contrastestimate, threshold, [('spm_mat_file', 'spm_mat_file'), + (('spmT_images', pickfirst), + 'stat_image')]), +]) """ Preproc + Analysis pipeline --------------------------- @@ -196,9 +183,9 @@ def pickfirst(l): """ l1pipeline = pe.Workflow(name='firstlevel') -l1pipeline.connect([(preproc, l1analysis, [('realign.realignment_parameters', - 'modelspec.realignment_parameters')])]) - +l1pipeline.connect([(preproc, l1analysis, + [('realign.realignment_parameters', + 'modelspec.realignment_parameters')])]) """Pluging in `functional_runs` is a bit more complicated, because model spec expects a list of `runs`. Every run can be a 4D file or a list of 3D files. Therefore for 3D analysis we need a list of lists and to make one we need a helper function. @@ -207,10 +194,11 @@ def pickfirst(l): def makelist(item): return [item] -l1pipeline.connect([(preproc, l1analysis, [(('smooth.smoothed_files', makelist), - 'modelspec.functional_runs')])]) +l1pipeline.connect([(preproc, l1analysis, [(('smooth.smoothed_files', + makelist), + 'modelspec.functional_runs')])]) """ Data specific components ------------------------ @@ -229,12 +217,12 @@ def makelist(item): # Specify the subject directories subject_list = ['M03953'] # Map field names to individual subject runs. -info = dict(func=[['RawEPI', 'subject_id', 5, ["_%04d" % i for i in range(6, 357)]]], - struct=[['Structural', 'subject_id', 7, '']]) - -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +info = dict( + func=[['RawEPI', 'subject_id', 5, ["_%04d" % i for i in range(6, 357)]]], + struct=[['Structural', 'subject_id', 7, '']]) +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -245,7 +233,6 @@ def makelist(item): """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -254,15 +241,14 @@ def makelist(item): functionality. """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/s%s_%04d%s.img' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - - """ Experimental paradigm specific components ----------------------------------------- @@ -274,7 +260,6 @@ def makelist(item): """ from nipype.interfaces.base import Bunch - """We're importing the onset times from a mat file (found on http://www.fil.ion.ucl.ac.uk/spm/data/face_rep/) """ @@ -284,15 +269,17 @@ def makelist(item): sot = mat['sot'][0] itemlag = mat['itemlag'][0] -subjectinfo = [Bunch(conditions=['N1', 'N2', 'F1', 'F2'], - onsets=[sot[0], sot[1], sot[2], sot[3]], - durations=[[0], [0], [0], [0]], - amplitudes=None, - tmod=None, - pmod=None, - regressor_names=None, - regressors=None)] - +subjectinfo = [ + Bunch( + conditions=['N1', 'N2', 'F1', 'F2'], + onsets=[sot[0], sot[1], sot[2], sot[3]], + durations=[[0], [0], [0], [0]], + amplitudes=None, + tmod=None, + pmod=None, + regressor_names=None, + regressors=None) +] """Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - [Name,Stat,[list of condition names],[weights on @@ -300,27 +287,41 @@ def makelist(item): in the `subjectinfo` function described above. """ -cond1 = ('positive effect of condition', 'T', ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [1, 1, 1, 1]) -cond2 = ('positive effect of condition_dtemo', 'T', ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, 1, 1, 1]) -cond3 = ('positive effect of condition_ddisp', 'T', ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, 1, 1, 1]) +cond1 = ('positive effect of condition', 'T', + ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [1, 1, 1, 1]) +cond2 = ('positive effect of condition_dtemo', 'T', + ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, 1, 1, 1]) +cond3 = ('positive effect of condition_ddisp', 'T', + ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, 1, 1, 1]) # non-famous > famous -fam1 = ('positive effect of Fame', 'T', ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [1, 1, -1, -1]) -fam2 = ('positive effect of Fame_dtemp', 'T', ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, 1, -1, -1]) -fam3 = ('positive effect of Fame_ddisp', 'T', ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, 1, -1, -1]) +fam1 = ('positive effect of Fame', 'T', + ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [1, 1, -1, -1]) +fam2 = ('positive effect of Fame_dtemp', 'T', + ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, 1, -1, -1]) +fam3 = ('positive effect of Fame_ddisp', 'T', + ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, 1, -1, -1]) # rep1 > rep2 -rep1 = ('positive effect of Rep', 'T', ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [1, -1, 1, -1]) -rep2 = ('positive effect of Rep_dtemp', 'T', ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, -1, 1, -1]) -rep3 = ('positive effect of Rep_ddisp', 'T', ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, -1, 1, -1]) -int1 = ('positive interaction of Fame x Rep', 'T', ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [-1, -1, -1, 1]) -int2 = ('positive interaction of Fame x Rep_dtemp', 'T', ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, -1, -1, 1]) -int3 = ('positive interaction of Fame x Rep_ddisp', 'T', ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, -1, -1, 1]) +rep1 = ('positive effect of Rep', 'T', + ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [1, -1, 1, -1]) +rep2 = ('positive effect of Rep_dtemp', 'T', + ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, -1, 1, -1]) +rep3 = ('positive effect of Rep_ddisp', 'T', + ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, -1, 1, -1]) +int1 = ('positive interaction of Fame x Rep', 'T', + ['N1*bf(1)', 'N2*bf(1)', 'F1*bf(1)', 'F2*bf(1)'], [-1, -1, -1, 1]) +int2 = ('positive interaction of Fame x Rep_dtemp', 'T', + ['N1*bf(2)', 'N2*bf(2)', 'F1*bf(2)', 'F2*bf(2)'], [1, -1, -1, 1]) +int3 = ('positive interaction of Fame x Rep_ddisp', 'T', + ['N1*bf(3)', 'N2*bf(3)', 'F1*bf(3)', 'F2*bf(3)'], [1, -1, -1, 1]) contf1 = ['average effect condition', 'F', [cond1, cond2, cond3]] contf2 = ['main effect Fam', 'F', [fam1, fam2, fam3]] contf3 = ['main effect Rep', 'F', [rep1, rep2, rep3]] contf4 = ['interaction: Fam x Rep', 'F', [int1, int2, int3]] -contrasts = [cond1, cond2, cond3, fam1, fam2, fam3, rep1, rep2, rep3, int1, int2, int3, contf1, contf2, contf3, contf4] - +contrasts = [ + cond1, cond2, cond3, fam1, fam2, fam3, rep1, rep2, rep3, int1, int2, int3, + contf1, contf2, contf3, contf4 +] """Setting up nodes inputs """ @@ -349,7 +350,6 @@ def makelist(item): l1designref.microtime_resolution = slice_timingref.num_slices l1designref.microtime_onset = slice_timingref.ref_slice l1designref.bases = {'hrf': {'derivs': [1, 1]}} - """ The following lines automatically inform SPM to create a default set of contrats for a factorial design. @@ -361,32 +361,30 @@ def makelist(item): l1pipeline.inputs.analysis.modelspec.subject_info = subjectinfo l1pipeline.inputs.analysis.contrastestimate.contrasts = contrasts l1pipeline.inputs.analysis.threshold.contrast_index = 1 - """ Use derivative estimates in the non-parametric model """ l1pipeline.inputs.analysis.contrastestimate.use_derivs = True - """ Setting up parametricvariation of the model """ -subjectinfo_param = [Bunch(conditions=['N1', 'N2', 'F1', 'F2'], - onsets=[sot[0], sot[1], sot[2], sot[3]], - durations=[[0], [0], [0], [0]], - amplitudes=None, - tmod=None, - pmod=[None, - Bunch(name=['Lag'], - param=itemlag[1].tolist(), - poly=[2]), - None, - Bunch(name=['Lag'], - param=itemlag[3].tolist(), - poly=[2])], - regressor_names=None, - regressors=None)] +subjectinfo_param = [ + Bunch( + conditions=['N1', 'N2', 'F1', 'F2'], + onsets=[sot[0], sot[1], sot[2], sot[3]], + durations=[[0], [0], [0], [0]], + amplitudes=None, + tmod=None, + pmod=[ + None, + Bunch(name=['Lag'], param=itemlag[1].tolist(), poly=[2]), None, + Bunch(name=['Lag'], param=itemlag[3].tolist(), poly=[2]) + ], + regressor_names=None, + regressors=None) +] cont1 = ('Famous_lag1', 'T', ['F2xLag^1'], [1]) cont2 = ('Famous_lag2', 'T', ['F2xLag^2'], [1]) @@ -400,11 +398,10 @@ def makelist(item): paramanalysis.inputs.contrastestimate.contrasts = paramcontrasts paramanalysis.inputs.contrastestimate.use_derivs = False -l1pipeline.connect([(preproc, paramanalysis, [('realign.realignment_parameters', - 'modelspec.realignment_parameters'), - (('smooth.smoothed_files', makelist), - 'modelspec.functional_runs')])]) - +l1pipeline.connect( + [(preproc, paramanalysis, + [('realign.realignment_parameters', 'modelspec.realignment_parameters'), + (('smooth.smoothed_files', makelist), 'modelspec.functional_runs')])]) """ Setup the pipeline ------------------ @@ -432,11 +429,9 @@ def makelist(item): level1.base_dir = os.path.abspath('spm_face_tutorial/workingdir') level1.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, l1pipeline, [('struct', 'preproc.coregister.source'), - ('func', 'preproc.realign.in_files')]) - ]) - - + (datasource, l1pipeline, + [('struct', 'preproc.coregister.source'), + ('func', 'preproc.realign.in_files')])]) """ Setup storage results @@ -458,23 +453,28 @@ def makelist(item): """ datasink = pe.Node(interface=nio.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.abspath('spm_auditory_tutorial/l1output') +datasink.inputs.base_directory = os.path.abspath( + 'spm_auditory_tutorial/l1output') def getstripdir(subject_id): import os - return os.path.join(os.path.abspath('spm_auditory_tutorial/workingdir'), '_subject_id_%s' % subject_id) - -# store relevant outputs from various stages of the 1st level analysis -level1.connect([(infosource, datasink, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (l1pipeline, datasink, [('analysis.contrastestimate.con_images', 'contrasts.@con'), - ('analysis.contrastestimate.spmT_images', 'contrasts.@T'), - ('paramanalysis.contrastestimate.con_images', 'paramcontrasts.@con'), - ('paramanalysis.contrastestimate.spmT_images', 'paramcontrasts.@T')]), - ]) + return os.path.join( + os.path.abspath('spm_auditory_tutorial/workingdir'), + '_subject_id_%s' % subject_id) +# store relevant outputs from various stages of the 1st level analysis +level1.connect([ + (infosource, datasink, [('subject_id', 'container'), + (('subject_id', getstripdir), 'strip_dir')]), + (l1pipeline, datasink, + [('analysis.contrastestimate.con_images', 'contrasts.@con'), + ('analysis.contrastestimate.spmT_images', 'contrasts.@T'), + ('paramanalysis.contrastestimate.con_images', + 'paramcontrasts.@con'), ('paramanalysis.contrastestimate.spmT_images', + 'paramcontrasts.@T')]), +]) """ Execute the pipeline -------------------- diff --git a/examples/fmri_spm_nested.py b/examples/fmri_spm_nested.py index 9f1b51469d..534b8c960d 100755 --- a/examples/fmri_spm_nested.py +++ b/examples/fmri_spm_nested.py @@ -18,17 +18,16 @@ from __future__ import print_function from builtins import str from builtins import range -import os.path as op # system functions +import os.path as op # system functions -from nipype.interfaces import io as nio # Data i/o -from nipype.interfaces import spm as spm # spm +from nipype.interfaces import io as nio # Data i/o +from nipype.interfaces import spm as spm # spm # from nipype.interfaces import matlab as mlab # how to run matlab -from nipype.interfaces import fsl as fsl # fsl -from nipype.interfaces import utility as niu # utility -from nipype.pipeline import engine as pe # pypeline engine -from nipype.algorithms import rapidart as ra # artifact detection -from nipype.algorithms import modelgen as model # model specification - +from nipype.interfaces import fsl as fsl # fsl +from nipype.interfaces import utility as niu # utility +from nipype.pipeline import engine as pe # pypeline engine +from nipype.algorithms import rapidart as ra # artifact detection +from nipype.algorithms import modelgen as model # model specification """ Preliminaries @@ -46,8 +45,6 @@ # Set the way matlab should be called # mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") # mlab.MatlabCommand.set_default_paths('/software/spm8') - - """ Setting up workflows -------------------- @@ -61,6 +58,8 @@ ----------------------------------------------- """ + + def _template_path(in_data): import os.path as op return op.abspath(op.join(in_data, 'nipype-tutorial/data/T1.nii')) @@ -76,22 +75,19 @@ def _template_path(in_data): """ preproc = pe.Workflow(name='preproc') - """ A node called :code:`inputnode` is set to designate the path in which input data are located: """ -inputnode = pe.Node(niu.IdentityInterface(fields=['in_data']), name='inputnode') - - +inputnode = pe.Node( + niu.IdentityInterface(fields=['in_data']), name='inputnode') """Use :class:`nipype.interfaces.spm.Realign` for motion correction and register all images to the mean image. """ realign = pe.Node(spm.Realign(), name="realign") realign.inputs.register_to_mean = True - """Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in intensity or movement. @@ -104,30 +100,24 @@ def _template_path(in_data): art.inputs.zintensity_threshold = 3 art.inputs.mask_type = 'file' art.inputs.parameter_source = 'SPM' - """Skull strip structural images using :class:`nipype.interfaces.fsl.BET`. """ skullstrip = pe.Node(fsl.BET(), name="skullstrip") skullstrip.inputs.mask = True - """Use :class:`nipype.interfaces.spm.Coregister` to perform a rigid body registration of the functional data to the structural data. """ coregister = pe.Node(spm.Coregister(), name="coregister") coregister.inputs.jobtype = 'estimate' - - """Warp functional and structural data to SPM's T1 template using :class:`nipype.interfaces.spm.Normalize`. The tutorial data set includes the template image, T1.nii. """ normalize = pe.Node(spm.Normalize(), name="normalize") - - """Smooth the functional data using :class:`nipype.interfaces.spm.Smooth`. """ @@ -136,18 +126,17 @@ def _template_path(in_data): fwhmlist = [4] smooth.iterables = ('fwhm', fwhmlist) -preproc.connect([(inputnode, normalize, [(('in_data', _template_path), 'template')]), - (realign, coregister, [('mean_image', 'source'), - ('realigned_files', 'apply_to_files')]), - (coregister, normalize, [('coregistered_files', 'apply_to_files')]), - (normalize, smooth, [('normalized_files', 'in_files')]), - (normalize, skullstrip, [('normalized_source', 'in_file')]), - (realign, art, [('realignment_parameters', 'realignment_parameters')]), - (normalize, art, [('normalized_files', 'realigned_files')]), - (skullstrip, art, [('mask_file', 'mask_file')]), - ]) - - +preproc.connect([ + (inputnode, normalize, [(('in_data', _template_path), 'template')]), + (realign, coregister, [('mean_image', 'source'), ('realigned_files', + 'apply_to_files')]), + (coregister, normalize, [('coregistered_files', 'apply_to_files')]), + (normalize, smooth, [('normalized_files', 'in_files')]), + (normalize, skullstrip, [('normalized_source', 'in_file')]), + (realign, art, [('realignment_parameters', 'realignment_parameters')]), + (normalize, art, [('normalized_files', 'realigned_files')]), + (skullstrip, art, [('mask_file', 'mask_file')]), +]) """ Set up analysis workflow ------------------------ @@ -155,40 +144,34 @@ def _template_path(in_data): """ l1analysis = pe.Workflow(name='analysis') - """Generate SPM-specific design information using :class:`nipype.interfaces.spm.SpecifyModel`. """ modelspec = pe.Node(model.SpecifySPMModel(), name="modelspec") modelspec.inputs.concatenate_runs = True - """Generate a first level SPM.mat file for analysis :class:`nipype.interfaces.spm.Level1Design`. """ level1design = pe.Node(spm.Level1Design(), name="level1design") level1design.inputs.bases = {'hrf': {'derivs': [0, 0]}} - """Use :class:`nipype.interfaces.spm.EstimateModel` to determine the parameters of the model. """ level1estimate = pe.Node(spm.EstimateModel(), name="level1estimate") level1estimate.inputs.estimation_method = {'Classical': 1} - """Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the first level contrasts specified in a few steps above. """ contrastestimate = pe.Node(spm.EstimateContrast(), name="contrastestimate") - """Use :class: `nipype.interfaces.utility.Select` to select each contrast for reporting. """ selectcontrast = pe.Node(niu.Select(), name="selectcontrast") - """Use :class:`nipype.interfaces.fsl.Overlay` to combine the statistical output of the contrast estimate and a background image into one volume. """ @@ -197,7 +180,6 @@ def _template_path(in_data): overlaystats.inputs.stat_thresh = (3, 10) overlaystats.inputs.show_negative_stats = True overlaystats.inputs.auto_thresh_bg = True - """Use :class:`nipype.interfaces.fsl.Slicer` to create images of the overlaid statistical volumes for a report of the first-level results. """ @@ -206,16 +188,19 @@ def _template_path(in_data): slicestats.inputs.all_axial = True slicestats.inputs.image_width = 750 -l1analysis.connect([(modelspec, level1design, [('session_info', 'session_info')]), - (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]), - (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - (contrastestimate, selectcontrast, [('spmT_images', 'inlist')]), - (selectcontrast, overlaystats, [('out', 'stat_image')]), - (overlaystats, slicestats, [('out_file', 'in_file')]) - ]) - +l1analysis.connect([(modelspec, level1design, + [('session_info', + 'session_info')]), (level1design, level1estimate, + [('spm_mat_file', 'spm_mat_file')]), + (level1estimate, contrastestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', + 'beta_images'), + ('residual_image', + 'residual_image')]), (contrastestimate, selectcontrast, + [('spmT_images', 'inlist')]), + (selectcontrast, overlaystats, + [('out', 'stat_image')]), (overlaystats, slicestats, + [('out_file', 'in_file')])]) """ Preproc + Analysis pipeline --------------------------- @@ -223,19 +208,16 @@ def _template_path(in_data): """ l1pipeline = pe.Workflow(name='firstlevel') -l1pipeline.connect([(preproc, l1analysis, [('realign.realignment_parameters', - 'modelspec.realignment_parameters'), - ('smooth.smoothed_files', - 'modelspec.functional_runs'), - ('art.outlier_files', - 'modelspec.outlier_files'), - ('skullstrip.mask_file', - 'level1design.mask_image'), - ('normalize.normalized_source', - 'overlaystats.background_image')]), - ]) - - +l1pipeline.connect([ + (preproc, l1analysis, + [('realign.realignment_parameters', 'modelspec.realignment_parameters'), + ('smooth.smoothed_files', + 'modelspec.functional_runs'), ('art.outlier_files', + 'modelspec.outlier_files'), + ('skullstrip.mask_file', + 'level1design.mask_image'), ('normalize.normalized_source', + 'overlaystats.background_image')]), +]) """ Data specific components ------------------------ @@ -260,11 +242,12 @@ def _template_path(in_data): # Specify the subject directories subject_list = ['s1', 's3'] # Map field names to individual subject runs. -info = dict(func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) - -infosource = pe.Node(niu.IdentityInterface(fields=['subject_id']), name="infosource") +info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) +infosource = pe.Node( + niu.IdentityInterface(fields=['subject_id']), name="infosource") """Here we set up iteration over all the subjects. The following line is a particular example of the flexibility of the system. The ``datasource`` attribute ``iterables`` tells the pipeline engine that @@ -275,7 +258,6 @@ def _template_path(in_data): """ infosource.iterables = ('subject_id', subject_list) - """ Now we create a :class:`nipype.interfaces.io.DataGrabber` object and fill in the information from above about the layout of our data. The @@ -284,14 +266,12 @@ def _template_path(in_data): functionality. """ -datasource = pe.Node(nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +datasource = pe.Node( + nio.DataGrabber(infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.template = 'nipype-tutorial/data/%s/%s.nii' datasource.inputs.template_args = info datasource.inputs.sort_filelist = True - - """ Experimental paradigm specific components ----------------------------------------- @@ -313,16 +293,18 @@ def subjectinfo(subject_id): for r in range(4): onsets = [list(range(15, 240, 60)), list(range(45, 240, 60))] output.insert(r, - Bunch(conditions=names, - onsets=deepcopy(onsets), - durations=[[15] for s in names], - amplitudes=None, - tmod=None, - pmod=None, - regressor_names=None, - regressors=None)) + Bunch( + conditions=names, + onsets=deepcopy(onsets), + durations=[[15] for s in names], + amplitudes=None, + tmod=None, + pmod=None, + regressor_names=None, + regressors=None)) return output + """Setup the contrast structure that needs to be evaluated. This is a list of lists. The inner list specifies the contrasts and has the following format - [Name,Stat,[list of condition names],[weights on @@ -345,13 +327,10 @@ def subjectinfo(subject_id): l1designref.timing_units = modelspecref.output_units l1designref.interscan_interval = modelspecref.time_repetition - l1pipeline.inputs.analysis.contrastestimate.contrasts = contrasts - # Iterate over each contrast and create report images. selectcontrast.iterables = ('index', [[i] for i in range(len(contrasts))]) - """ Setup the pipeline ------------------ @@ -378,16 +357,15 @@ def subjectinfo(subject_id): level1 = pe.Workflow(name="level1") level1.base_dir = op.abspath('spm_tutorial2/workingdir') -level1.connect([(inputnode, datasource, [('in_data', 'base_directory')]), - (infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, l1pipeline, [('func', 'preproc.realign.in_files'), - ('struct', 'preproc.coregister.target'), - ('struct', 'preproc.normalize.source')]), - (infosource, l1pipeline, [(('subject_id', subjectinfo), - 'analysis.modelspec.subject_info')]), - ]) - - +level1.connect([ + (inputnode, datasource, [('in_data', 'base_directory')]), + (infosource, datasource, [('subject_id', 'subject_id')]), + (datasource, l1pipeline, [('func', 'preproc.realign.in_files'), + ('struct', 'preproc.coregister.target'), + ('struct', 'preproc.normalize.source')]), + (infosource, l1pipeline, [(('subject_id', subjectinfo), + 'analysis.modelspec.subject_info')]), +]) """ Setup storage results @@ -417,19 +395,21 @@ def subjectinfo(subject_id): def getstripdir(subject_id): import os.path as op - return op.join(op.abspath('spm_tutorial2/workingdir'), '_subject_id_%s' % subject_id) - -# store relevant outputs from various stages of the 1st level analysis -level1.connect([(infosource, datasink, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (l1pipeline, datasink, [('analysis.contrastestimate.con_images', 'contrasts.@con'), - ('analysis.contrastestimate.spmT_images', 'contrasts.@T')]), - (infosource, report, [('subject_id', 'container'), - (('subject_id', getstripdir), 'strip_dir')]), - (l1pipeline, report, [('analysis.slicestats.out_file', '@report')]), - ]) + return op.join( + op.abspath('spm_tutorial2/workingdir'), '_subject_id_%s' % subject_id) +# store relevant outputs from various stages of the 1st level analysis +level1.connect([ + (infosource, datasink, [('subject_id', 'container'), + (('subject_id', getstripdir), 'strip_dir')]), + (l1pipeline, datasink, + [('analysis.contrastestimate.con_images', 'contrasts.@con'), + ('analysis.contrastestimate.spmT_images', 'contrasts.@T')]), + (infosource, report, [('subject_id', 'container'), + (('subject_id', getstripdir), 'strip_dir')]), + (l1pipeline, report, [('analysis.slicestats.out_file', '@report')]), +]) """ Execute the pipeline -------------------- @@ -444,7 +424,6 @@ def getstripdir(subject_id): if __name__ == '__main__': level1.run('MultiProc') level1.write_graph() - """ Setup level 2 pipeline ---------------------- @@ -459,13 +438,11 @@ def getstripdir(subject_id): contrast_ids = list(range(1, len(contrasts) + 1)) l2source = pe.Node(nio.DataGrabber(infields=['fwhm', 'con']), name="l2source") # we use .*i* to capture both .img (SPM8) and .nii (SPM12) -l2source.inputs.template = op.abspath('spm_tutorial2/l1output/*/con*/*/_fwhm_%d/con_%04d.*i*') +l2source.inputs.template = op.abspath( + 'spm_tutorial2/l1output/*/con*/*/_fwhm_%d/con_%04d.*i*') # iterate over all contrast images -l2source.iterables = [('fwhm', fwhmlist), - ('con', contrast_ids)] +l2source.iterables = [('fwhm', fwhmlist), ('con', contrast_ids)] l2source.inputs.sort_filelist = True - - """Use :class:`nipype.interfaces.spm.OneSampleTTestDesign` to perform a simple statistical analysis of the contrasts from the group of subjects (n=2 in this example). @@ -479,22 +456,19 @@ def getstripdir(subject_id): cont1 = ('Group', 'T', ['mean'], [1]) l2conestimate.inputs.contrasts = [cont1] l2conestimate.inputs.group_contrast = True - - """As before, we setup a pipeline to connect these two nodes (l2source -> onesamplettest). """ l2pipeline = pe.Workflow(name="level2") l2pipeline.base_dir = op.abspath('spm_tutorial2/l2output') -l2pipeline.connect([(l2source, onesamplettestdes, [('outfiles', 'in_files')]), - (onesamplettestdes, l2estimate, [('spm_mat_file', 'spm_mat_file')]), - (l2estimate, l2conestimate, [('spm_mat_file', 'spm_mat_file'), - ('beta_images', 'beta_images'), - ('residual_image', 'residual_image')]), - ]) - - +l2pipeline.connect([ + (l2source, onesamplettestdes, [('outfiles', 'in_files')]), + (onesamplettestdes, l2estimate, [('spm_mat_file', 'spm_mat_file')]), + (l2estimate, l2conestimate, + [('spm_mat_file', 'spm_mat_file'), ('beta_images', 'beta_images'), + ('residual_image', 'residual_image')]), +]) """ Execute the second level pipeline --------------------------------- diff --git a/examples/frontiers_paper/smoothing_comparison.py b/examples/frontiers_paper/smoothing_comparison.py index 11698c0379..c4a31dad39 100644 --- a/examples/frontiers_paper/smoothing_comparison.py +++ b/examples/frontiers_paper/smoothing_comparison.py @@ -9,34 +9,35 @@ from builtins import range -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.spm as spm # spm -import nipype.interfaces.freesurfer as fs # freesurfer +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.spm as spm # spm +import nipype.interfaces.freesurfer as fs # freesurfer import nipype.interfaces.nipy as nipy import nipype.interfaces.utility as util -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.modelgen as model # model specification +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.modelgen as model # model specification import nipype.workflows.fmri.fsl as fsl_wf from nipype.interfaces.base import Bunch -import os # system functions +import os # system functions preprocessing = pe.Workflow(name="preprocessing") -iter_fwhm = pe.Node(interface=util.IdentityInterface(fields=["fwhm"]), - name="iter_fwhm") +iter_fwhm = pe.Node( + interface=util.IdentityInterface(fields=["fwhm"]), name="iter_fwhm") iter_fwhm.iterables = [('fwhm', [4, 8])] -iter_smoothing_method = pe.Node(interface=util.IdentityInterface(fields=["smoothing_method"]), - name="iter_smoothing_method") -iter_smoothing_method.iterables = [('smoothing_method', ['isotropic_voxel', - 'anisotropic_voxel', - 'isotropic_surface'])] +iter_smoothing_method = pe.Node( + interface=util.IdentityInterface(fields=["smoothing_method"]), + name="iter_smoothing_method") +iter_smoothing_method.iterables = [('smoothing_method', [ + 'isotropic_voxel', 'anisotropic_voxel', 'isotropic_surface' +])] realign = pe.Node(interface=spm.Realign(), name="realign") realign.inputs.register_to_mean = True -isotropic_voxel_smooth = pe.Node(interface=spm.Smooth(), - name="isotropic_voxel_smooth") +isotropic_voxel_smooth = pe.Node( + interface=spm.Smooth(), name="isotropic_voxel_smooth") preprocessing.connect(realign, "realigned_files", isotropic_voxel_smooth, "in_files") preprocessing.connect(iter_fwhm, "fwhm", isotropic_voxel_smooth, "fwhm") @@ -44,8 +45,8 @@ compute_mask = pe.Node(interface=nipy.ComputeMask(), name="compute_mask") preprocessing.connect(realign, "mean_image", compute_mask, "mean_volume") -anisotropic_voxel_smooth = fsl_wf.create_susan_smooth(name="anisotropic_voxel_smooth", - separate_masks=False) +anisotropic_voxel_smooth = fsl_wf.create_susan_smooth( + name="anisotropic_voxel_smooth", separate_masks=False) anisotropic_voxel_smooth.inputs.smooth.output_type = 'NIFTI' preprocessing.connect(realign, "realigned_files", anisotropic_voxel_smooth, "inputnode.in_files") @@ -54,7 +55,6 @@ preprocessing.connect(compute_mask, "brain_mask", anisotropic_voxel_smooth, 'inputnode.mask_file') - recon_all = pe.Node(interface=fs.ReconAll(), name="recon_all") surfregister = pe.Node(interface=fs.BBRegister(), name='surfregister') @@ -64,9 +64,10 @@ preprocessing.connect(recon_all, 'subject_id', surfregister, 'subject_id') preprocessing.connect(recon_all, 'subjects_dir', surfregister, 'subjects_dir') -isotropic_surface_smooth = pe.MapNode(interface=fs.Smooth(proj_frac_avg=(0, 1, 0.1)), - iterfield=['in_file'], - name="isotropic_surface_smooth") +isotropic_surface_smooth = pe.MapNode( + interface=fs.Smooth(proj_frac_avg=(0, 1, 0.1)), + iterfield=['in_file'], + name="isotropic_surface_smooth") preprocessing.connect(surfregister, 'out_reg_file', isotropic_surface_smooth, 'reg_file') preprocessing.connect(realign, "realigned_files", isotropic_surface_smooth, @@ -77,8 +78,8 @@ preprocessing.connect(recon_all, 'subjects_dir', isotropic_surface_smooth, 'subjects_dir') -merge_smoothed_files = pe.Node(interface=util.Merge(3), - name='merge_smoothed_files') +merge_smoothed_files = pe.Node( + interface=util.Merge(3), name='merge_smoothed_files') preprocessing.connect(isotropic_voxel_smooth, 'smoothed_files', merge_smoothed_files, 'in1') preprocessing.connect(anisotropic_voxel_smooth, 'outputnode.smoothed_files', @@ -86,21 +87,27 @@ preprocessing.connect(isotropic_surface_smooth, 'smoothed_file', merge_smoothed_files, 'in3') -select_smoothed_files = pe.Node(interface=util.Select(), - name="select_smoothed_files") +select_smoothed_files = pe.Node( + interface=util.Select(), name="select_smoothed_files") preprocessing.connect(merge_smoothed_files, 'out', select_smoothed_files, 'inlist') def chooseindex(roi): - return {'isotropic_voxel': list(range(0, 4)), 'anisotropic_voxel': list(range(4, 8)), - 'isotropic_surface': list(range(8, 12))}[roi] + return { + 'isotropic_voxel': list(range(0, 4)), + 'anisotropic_voxel': list(range(4, 8)), + 'isotropic_surface': list(range(8, 12)) + }[roi] + preprocessing.connect(iter_smoothing_method, ("smoothing_method", chooseindex), select_smoothed_files, 'index') -rename = pe.MapNode(util.Rename(format_string="%(orig)s"), name="rename", - iterfield=['in_file']) +rename = pe.MapNode( + util.Rename(format_string="%(orig)s"), + name="rename", + iterfield=['in_file']) rename.inputs.parse_string = "(?P.*)" preprocessing.connect(select_smoothed_files, 'out', rename, 'in_file') @@ -109,10 +116,13 @@ def chooseindex(roi): specify_model.inputs.input_units = 'secs' specify_model.inputs.time_repetition = 3. specify_model.inputs.high_pass_filter_cutoff = 120 -specify_model.inputs.subject_info = [Bunch(conditions=['Task-Odd', 'Task-Even'], - onsets=[list(range(15, 240, 60)), - list(range(45, 240, 60))], - durations=[[15], [15]])] * 4 +specify_model.inputs.subject_info = [ + Bunch( + conditions=['Task-Odd', 'Task-Even'], + onsets=[list(range(15, 240, 60)), + list(range(45, 240, 60))], + durations=[[15], [15]]) +] * 4 level1design = pe.Node(interface=spm.Level1Design(), name="level1design") level1design.inputs.bases = {'hrf': {'derivs': [0, 0]}} @@ -122,8 +132,8 @@ def chooseindex(roi): level1estimate = pe.Node(interface=spm.EstimateModel(), name="level1estimate") level1estimate.inputs.estimation_method = {'Classical': 1} -contrastestimate = pe.Node(interface=spm.EstimateContrast(), - name="contrastestimate") +contrastestimate = pe.Node( + interface=spm.EstimateContrast(), name="contrastestimate") contrastestimate.inputs.contrasts = [('Task>Baseline', 'T', ['Task-Odd', 'Task-Even'], [0.5, 0.5])] @@ -132,7 +142,8 @@ def chooseindex(roi): modelling.connect(level1design, 'spm_mat_file', level1estimate, 'spm_mat_file') modelling.connect(level1estimate, 'spm_mat_file', contrastestimate, 'spm_mat_file') -modelling.connect(level1estimate, 'beta_images', contrastestimate, 'beta_images') +modelling.connect(level1estimate, 'beta_images', contrastestimate, + 'beta_images') modelling.connect(level1estimate, 'residual_image', contrastestimate, 'residual_image') @@ -140,19 +151,20 @@ def chooseindex(roi): main_workflow.base_dir = "smoothing_comparison_workflow" main_workflow.connect(preprocessing, "realign.realignment_parameters", modelling, "specify_model.realignment_parameters") -main_workflow.connect(preprocessing, "select_smoothed_files.out", - modelling, "specify_model.functional_runs") -main_workflow.connect(preprocessing, "compute_mask.brain_mask", - modelling, "level1design.mask_image") - -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func', 'struct']), - name='datasource') +main_workflow.connect(preprocessing, "select_smoothed_files.out", modelling, + "specify_model.functional_runs") +main_workflow.connect(preprocessing, "compute_mask.brain_mask", modelling, + "level1design.mask_image") + +datasource = pe.Node( + interface=nio.DataGrabber( + infields=['subject_id'], outfields=['func', 'struct']), + name='datasource') datasource.inputs.base_directory = os.path.abspath('data') datasource.inputs.template = '%s/%s.nii' -datasource.inputs.template_args = info = dict(func=[['subject_id', - ['f3', 'f5', 'f7', 'f10']]], - struct=[['subject_id', 'struct']]) +datasource.inputs.template_args = info = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]], + struct=[['subject_id', 'struct']]) datasource.inputs.subject_id = 's1' datasource.inputs.sort_filelist = True @@ -161,7 +173,8 @@ def chooseindex(roi): 'recon_all.T1_files') datasink = pe.Node(interface=nio.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.abspath('smoothing_comparison_workflow/output') +datasink.inputs.base_directory = os.path.abspath( + 'smoothing_comparison_workflow/output') datasink.inputs.regexp_substitutions = [("_rename[0-9]", "")] main_workflow.connect(modelling, 'contrastestimate.spmT_images', datasink, diff --git a/examples/frontiers_paper/workflow_from_scratch.py b/examples/frontiers_paper/workflow_from_scratch.py index fd8ba8ffd3..9b1c939d29 100644 --- a/examples/frontiers_paper/workflow_from_scratch.py +++ b/examples/frontiers_paper/workflow_from_scratch.py @@ -10,14 +10,12 @@ from builtins import range -import nipype.interfaces.io as nio # Data i/o -import nipype.interfaces.spm as spm # spm -import nipype.pipeline.engine as pe # pypeline engine -import nipype.algorithms.modelgen as model # model specification +import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.spm as spm # spm +import nipype.pipeline.engine as pe # pypeline engine +import nipype.algorithms.modelgen as model # model specification from nipype.interfaces.base import Bunch -import os # system functions - - +import os # system functions """In the following section, to showcase NiPyPe, we will describe how to create and extend a typical fMRI processing pipeline. We will begin with a basic processing layout and follow with extending it by adding/exchanging different @@ -42,7 +40,6 @@ smooth = pe.Node(interface=spm.Smooth(), name="smooth") smooth.inputs.fwhm = 4 - """To connect two nodes a Workflow has to be created. connect() method of a Workflow allows to specify which outputs of which Nodes should be connected to which inputs of which Nodes (see Listing 2). By connecting realigned_files @@ -51,7 +48,6 @@ preprocessing = pe.Workflow(name="preprocessing") preprocessing.connect(realign, "realigned_files", smooth, "in_files") - """Creating a modelling workflow which will define the design, estimate model and contrasts follows the same suite. We will again use SPM implementations. NiPyPe, however, adds extra abstraction layer to model definition which allows @@ -67,10 +63,13 @@ specify_model.inputs.input_units = 'secs' specify_model.inputs.time_repetition = 3. specify_model.inputs.high_pass_filter_cutoff = 120 -specify_model.inputs.subject_info = [Bunch(conditions=['Task-Odd', 'Task-Even'], - onsets=[list(range(15, 240, 60)), - list(range(45, 240, 60))], - durations=[[15], [15]])] * 4 +specify_model.inputs.subject_info = [ + Bunch( + conditions=['Task-Odd', 'Task-Even'], + onsets=[list(range(15, 240, 60)), + list(range(45, 240, 60))], + durations=[[15], [15]]) +] * 4 level1design = pe.Node(interface=spm.Level1Design(), name="level1design") level1design.inputs.bases = {'hrf': {'derivs': [0, 0]}} @@ -80,8 +79,8 @@ level1estimate = pe.Node(interface=spm.EstimateModel(), name="level1estimate") level1estimate.inputs.estimation_method = {'Classical': 1} -contrastestimate = pe.Node(interface=spm.EstimateContrast(), - name="contrastestimate") +contrastestimate = pe.Node( + interface=spm.EstimateContrast(), name="contrastestimate") cont1 = ('Task>Baseline', 'T', ['Task-Odd', 'Task-Even'], [0.5, 0.5]) cont2 = ('Task-Odd>Task-Even', 'T', ['Task-Odd', 'Task-Even'], [1, -1]) contrastestimate.inputs.contrasts = [cont1, cont2] @@ -89,12 +88,12 @@ modelling = pe.Workflow(name="modelling") modelling.connect(specify_model, 'session_info', level1design, 'session_info') modelling.connect(level1design, 'spm_mat_file', level1estimate, 'spm_mat_file') -modelling.connect(level1estimate, 'spm_mat_file', - contrastestimate, 'spm_mat_file') -modelling.connect(level1estimate, 'beta_images', contrastestimate, 'beta_images') -modelling.connect(level1estimate, 'residual_image', - contrastestimate, 'residual_image') - +modelling.connect(level1estimate, 'spm_mat_file', contrastestimate, + 'spm_mat_file') +modelling.connect(level1estimate, 'beta_images', contrastestimate, + 'beta_images') +modelling.connect(level1estimate, 'residual_image', contrastestimate, + 'residual_image') """Having preprocessing and modelling workflows we need to connect them together, add data grabbing facility and save the results. For this we will create a master Workflow which will host preprocessing and model Workflows as @@ -106,39 +105,39 @@ main_workflow.base_dir = "workflow_from_scratch" main_workflow.connect(preprocessing, "realign.realignment_parameters", modelling, "specify_model.realignment_parameters") -main_workflow.connect(preprocessing, "smooth.smoothed_files", - modelling, "specify_model.functional_runs") - - +main_workflow.connect(preprocessing, "smooth.smoothed_files", modelling, + "specify_model.functional_runs") """DataGrabber allows to define flexible search patterns which can be parameterized by user defined inputs (such as subject ID, session etc.). This allows to adapt to a wide range of file layouts. In our case we will parameterize it with subject ID. In this way we will be able to run it for different subjects. We can automate this by iterating over a list of subject Ids, by setting an iterables property on the subject_id input of DataGrabber. -Its output will be connected to realignment node from preprocessing workflow.""" +Its output will be connected to realignment node from preprocessing workflow. +""" -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['func']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber(infields=['subject_id'], outfields=['func']), + name='datasource') datasource.inputs.base_directory = os.path.abspath('data') datasource.inputs.template = '%s/%s.nii' -datasource.inputs.template_args = dict(func=[['subject_id', - ['f3', 'f5', 'f7', 'f10']]]) +datasource.inputs.template_args = dict( + func=[['subject_id', ['f3', 'f5', 'f7', 'f10']]]) datasource.inputs.subject_id = 's1' datasource.inputs.sort_filelist = True main_workflow.connect(datasource, 'func', preprocessing, 'realign.in_files') - """DataSink on the other side provides means to storing selected results to a specified location. It supports automatic creation of folder stricter and -regular expression based substitutions. In this example we will store T maps.""" +regular expression based substitutions. In this example we will store T maps. +""" datasink = pe.Node(interface=nio.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.abspath('workflow_from_scratch/output') +datasink.inputs.base_directory = os.path.abspath( + 'workflow_from_scratch/output') -main_workflow.connect(modelling, 'contrastestimate.spmT_images', - datasink, 'contrasts.@T') +main_workflow.connect(modelling, 'contrastestimate.spmT_images', datasink, + 'contrasts.@T') main_workflow.run() main_workflow.write_graph() diff --git a/examples/howto_caching_example.py b/examples/howto_caching_example.py index b5c548fc76..debd826402 100644 --- a/examples/howto_caching_example.py +++ b/examples/howto_caching_example.py @@ -30,13 +30,16 @@ mem = Memory('.') # Apply an arbitrary (and pointless, here) threshold to the files) -threshold = [mem.cache(fsl.Threshold)(in_file=f, thresh=i) - for i, f in enumerate(in_files)] +threshold = [ + mem.cache(fsl.Threshold)(in_file=f, thresh=i) + for i, f in enumerate(in_files) +] # Merge all these files along the time dimension -out_merge = mem.cache(fsl.Merge)(dimension="t", - in_files=[t.outputs.out_file for t in threshold], - ) +out_merge = mem.cache(fsl.Merge)( + dimension="t", + in_files=[t.outputs.out_file for t in threshold], +) # And finally compute the mean out_mean = mem.cache(fsl.MeanImage)(in_file=out_merge.outputs.merged_file) diff --git a/examples/rsfmri_vol_surface_preprocessing.py b/examples/rsfmri_vol_surface_preprocessing.py index 8d86f73fd7..20b150b149 100644 --- a/examples/rsfmri_vol_surface_preprocessing.py +++ b/examples/rsfmri_vol_surface_preprocessing.py @@ -51,7 +51,6 @@ from nipype.interfaces.base import CommandLine CommandLine.set_default_terminal_output('allatonce') - from dicom import read_file from nipype.interfaces import (spm, fsl, Function, ants, freesurfer) @@ -76,14 +75,12 @@ import scipy as sp import nibabel as nb - -imports = ['import os', - 'import nibabel as nb', - 'import numpy as np', - 'import scipy as sp', - 'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename', - 'from scipy.special import legendre' - ] +imports = [ + 'import os', 'import nibabel as nb', 'import numpy as np', + 'import scipy as sp', + 'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename', + 'from scipy.special import legendre' +] def get_info(dicom_files): @@ -96,9 +93,11 @@ def get_info(dicom_files): Slice Acquisition Times Spacing between slices """ - meta = default_extractor(read_file(filename_to_list(dicom_files)[0], - stop_before_pixels=True, - force=True)) + meta = default_extractor( + read_file( + filename_to_list(dicom_files)[0], + stop_before_pixels=True, + force=True)) return (meta['RepetitionTime'] / 1000., meta['CsaImage.MosaicRefAcqTimes'], meta['SpacingBetweenSlices']) @@ -236,8 +235,8 @@ def build_filter1(motion_params, comp_norm, outliers, detrend_poly=None): timepoints = out_params.shape[0] X = np.empty((timepoints, 0)) for i in range(detrend_poly): - X = np.hstack((X, legendre( - i + 1)(np.linspace(-1, 1, timepoints))[:, None])) + X = np.hstack((X, legendre(i + 1)(np.linspace( + -1, 1, timepoints))[:, None])) out_params = np.hstack((out_params, X)) filename = os.path.join(os.getcwd(), "filter_regressor%02d.txt" % idx) np.savetxt(filename, out_params, fmt=b"%.10f") @@ -245,7 +244,9 @@ def build_filter1(motion_params, comp_norm, outliers, detrend_poly=None): return out_files -def extract_noise_components(realigned_file, mask_file, num_components=5, +def extract_noise_components(realigned_file, + mask_file, + num_components=5, extra_regressors=None): """Derive components most reflective of physiological noise @@ -346,9 +347,10 @@ def extract_subrois(timeseries_file, label_file, indices): ijk = np.nonzero(rois == fsindex) ts = data[ijk] for i0, row in enumerate(ts): - fp.write('%d,%d,%d,%d,' % (fsindex, ijk[0][i0], - ijk[1][i0], ijk[2][i0]) + - ','.join(['%.10f' % val for val in row]) + '\n') + fp.write('%d,%d,%d,%d,' % ( + fsindex, ijk[0][i0], ijk[1][i0], + ijk[2][i0]) + ','.join(['%.10f' % val + for val in row]) + '\n') return out_ts_file @@ -363,11 +365,13 @@ def combine_hemi(left, right): indices = np.vstack((1000000 + np.arange(0, lh_data.shape[0])[:, None], 2000000 + np.arange(0, rh_data.shape[0])[:, None])) - all_data = np.hstack((indices, np.vstack((lh_data.squeeze(), - rh_data.squeeze())))) + all_data = np.hstack((indices, + np.vstack((lh_data.squeeze(), rh_data.squeeze())))) filename = left.split('.')[1] + '_combined.txt' - np.savetxt(filename, all_data, - fmt=','.join(['%d'] + ['%.10f'] * (all_data.shape[1] - 1))) + np.savetxt( + filename, + all_data, + fmt=','.join(['%d'] + ['%.10f'] * (all_data.shape[1] - 1))) return os.path.abspath(filename) @@ -396,38 +400,32 @@ def create_reg_workflow(name='registration'): register = Workflow(name=name) - inputnode = Node(interface=IdentityInterface(fields=['source_files', - 'mean_image', - 'subject_id', - 'subjects_dir', - 'target_image']), - name='inputspec') - - outputnode = Node(interface=IdentityInterface(fields=['func2anat_transform', - 'out_reg_file', - 'anat2target_transform', - 'transforms', - 'transformed_mean', - 'segmentation_files', - 'anat2target', - 'aparc' - ]), - name='outputspec') + inputnode = Node( + interface=IdentityInterface(fields=[ + 'source_files', 'mean_image', 'subject_id', 'subjects_dir', + 'target_image' + ]), + name='inputspec') + + outputnode = Node( + interface=IdentityInterface(fields=[ + 'func2anat_transform', 'out_reg_file', 'anat2target_transform', + 'transforms', 'transformed_mean', 'segmentation_files', + 'anat2target', 'aparc' + ]), + name='outputspec') # Get the subject's freesurfer source directory - fssource = Node(FreeSurferSource(), - name='fssource') + fssource = Node(FreeSurferSource(), name='fssource') fssource.run_without_submitting = True register.connect(inputnode, 'subject_id', fssource, 'subject_id') register.connect(inputnode, 'subjects_dir', fssource, 'subjects_dir') - convert = Node(freesurfer.MRIConvert(out_type='nii'), - name="convert") + convert = Node(freesurfer.MRIConvert(out_type='nii'), name="convert") register.connect(fssource, 'T1', convert, 'in_file') # Coregister the median to the surface - bbregister = Node(freesurfer.BBRegister(), - name='bbregister') + bbregister = Node(freesurfer.BBRegister(), name='bbregister') bbregister.inputs.init = 'fsl' bbregister.inputs.contrast_type = 't2' bbregister.inputs.out_fsl_file = True @@ -435,7 +433,6 @@ def create_reg_workflow(name='registration'): register.connect(inputnode, 'subject_id', bbregister, 'subject_id') register.connect(inputnode, 'mean_image', bbregister, 'source_file') register.connect(inputnode, 'subjects_dir', bbregister, 'subjects_dir') - """ Estimate the tissue classes from the anatomical image. But use spm's segment as FSL appears to be breaking. @@ -445,42 +442,39 @@ def create_reg_workflow(name='registration'): register.connect(convert, 'out_file', stripper, 'in_file') fast = Node(fsl.FAST(), name='fast') register.connect(stripper, 'out_file', fast, 'in_files') - """ Binarize the segmentation """ - binarize = MapNode(fsl.ImageMaths(op_string='-nan -thr 0.9 -ero -bin'), - iterfield=['in_file'], - name='binarize') + binarize = MapNode( + fsl.ImageMaths(op_string='-nan -thr 0.9 -ero -bin'), + iterfield=['in_file'], + name='binarize') register.connect(fast, 'partial_volume_files', binarize, 'in_file') - """ Apply inverse transform to take segmentations to functional space """ - applyxfm = MapNode(freesurfer.ApplyVolTransform(inverse=True, - interp='nearest'), - iterfield=['target_file'], - name='inverse_transform') + applyxfm = MapNode( + freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), + iterfield=['target_file'], + name='inverse_transform') register.connect(inputnode, 'subjects_dir', applyxfm, 'subjects_dir') register.connect(bbregister, 'out_reg_file', applyxfm, 'reg_file') register.connect(binarize, 'out_file', applyxfm, 'target_file') register.connect(inputnode, 'mean_image', applyxfm, 'source_file') - """ Apply inverse transform to aparc file """ - aparcxfm = Node(freesurfer.ApplyVolTransform(inverse=True, - interp='nearest'), - name='aparc_inverse_transform') + aparcxfm = Node( + freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), + name='aparc_inverse_transform') register.connect(inputnode, 'subjects_dir', aparcxfm, 'subjects_dir') register.connect(bbregister, 'out_reg_file', aparcxfm, 'reg_file') - register.connect(fssource, ('aparc_aseg', get_aparc_aseg), - aparcxfm, 'target_file') + register.connect(fssource, ('aparc_aseg', get_aparc_aseg), aparcxfm, + 'target_file') register.connect(inputnode, 'mean_image', aparcxfm, 'source_file') - """ Convert the BBRegister transformation to ANTS ITK format """ @@ -491,7 +485,6 @@ def create_reg_workflow(name='registration'): register.connect(bbregister, 'out_fsl_file', convert2itk, 'transform_file') register.connect(inputnode, 'mean_image', convert2itk, 'source_file') register.connect(stripper, 'out_file', convert2itk, 'reference_file') - """ Compute registration between the subject's structural and MNI template This is currently set to perform a very quick registration. However, the @@ -504,8 +497,10 @@ def create_reg_workflow(name='registration'): reg = Node(ants.Registration(), name='antsRegister') reg.inputs.output_transform_prefix = "output_" reg.inputs.transforms = ['Rigid', 'Affine', 'SyN'] - reg.inputs.transform_parameters = [(0.1,), (0.1,), (0.2, 3.0, 0.0)] - reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[100, 30, 20]] + reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)] + reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[ + 100, 30, 20 + ]] reg.inputs.dimension = 3 reg.inputs.write_composite_transform = True reg.inputs.collapse_output_transforms = True @@ -530,7 +525,6 @@ def create_reg_workflow(name='registration'): reg.plugin_args = {'qsub_args': '-l nodes=1:ppn=4'} register.connect(stripper, 'out_file', reg, 'moving_image') register.connect(inputnode, 'target_image', reg, 'fixed_image') - """ Concatenate the affine and ants transforms into a list """ @@ -538,7 +532,6 @@ def create_reg_workflow(name='registration'): merge = Node(Merge(2), iterfield=['in2'], name='mergexfm') register.connect(convert2itk, 'itk_transform', merge, 'in2') register.connect(reg, 'composite_transform', merge, 'in1') - """ Transform the mean image. First to anatomical and then to target """ @@ -554,23 +547,20 @@ def create_reg_workflow(name='registration'): register.connect(inputnode, 'target_image', warpmean, 'reference_image') register.connect(inputnode, 'mean_image', warpmean, 'input_image') register.connect(merge, 'out', warpmean, 'transforms') - """ Assign all the output files """ register.connect(reg, 'warped_image', outputnode, 'anat2target') register.connect(warpmean, 'output_image', outputnode, 'transformed_mean') - register.connect(applyxfm, 'transformed_file', - outputnode, 'segmentation_files') - register.connect(aparcxfm, 'transformed_file', - outputnode, 'aparc') - register.connect(bbregister, 'out_fsl_file', - outputnode, 'func2anat_transform') - register.connect(bbregister, 'out_reg_file', - outputnode, 'out_reg_file') - register.connect(reg, 'composite_transform', - outputnode, 'anat2target_transform') + register.connect(applyxfm, 'transformed_file', outputnode, + 'segmentation_files') + register.connect(aparcxfm, 'transformed_file', outputnode, 'aparc') + register.connect(bbregister, 'out_fsl_file', outputnode, + 'func2anat_transform') + register.connect(bbregister, 'out_reg_file', outputnode, 'out_reg_file') + register.connect(reg, 'composite_transform', outputnode, + 'anat2target_transform') register.connect(merge, 'out', outputnode, 'transforms') return register @@ -600,9 +590,10 @@ def create_workflow(files, wf = Workflow(name=name) # Rename files in case they are named identically - name_unique = MapNode(Rename(format_string='rest_%(run)02d'), - iterfield=['in_file', 'run'], - name='rename') + name_unique = MapNode( + Rename(format_string='rest_%(run)02d'), + iterfield=['in_file', 'run'], + name='rename') name_unique.inputs.keep_ext = True name_unique.inputs.run = list(range(1, len(files) + 1)) name_unique.inputs.in_file = files @@ -625,16 +616,15 @@ def create_workflow(files, # Compute the median image across runs calc_median = Node(CalculateMedian(), name='median') wf.connect(tsnr, 'detrended_file', calc_median, 'in_files') - """Segment and Register """ registration = create_reg_workflow(name='registration') - wf.connect(calc_median, 'median_file', registration, 'inputspec.mean_image') + wf.connect(calc_median, 'median_file', registration, + 'inputspec.mean_image') registration.inputs.inputspec.subject_id = subject_id registration.inputs.inputspec.subjects_dir = subjects_dir registration.inputs.inputspec.target_image = target_file - """Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in intensity or movement. @@ -647,26 +637,28 @@ def create_workflow(files, art.inputs.zintensity_threshold = 9 art.inputs.mask_type = 'spm_global' art.inputs.parameter_source = 'SPM' - """Here we are connecting all the nodes together. Notice that we add the merge node only if you choose to use 4D. Also `get_vox_dims` function is passed along the input volume of normalise to set the optimal voxel sizes. """ - wf.connect([(name_unique, realign, [('out_file', 'in_files')]), - (realign, slice_timing, [('realigned_files', 'in_files')]), - (slice_timing, art, [('timecorrected_files', 'realigned_files')]), - (realign, art, [('realignment_parameters', 'realignment_parameters')]), - ]) + wf.connect([ + (name_unique, realign, [('out_file', 'in_files')]), + (realign, slice_timing, [('realigned_files', 'in_files')]), + (slice_timing, art, [('timecorrected_files', 'realigned_files')]), + (realign, art, [('realignment_parameters', 'realignment_parameters')]), + ]) def selectindex(files, idx): import numpy as np from nipype.utils.filemanip import filename_to_list, list_to_filename - return list_to_filename(np.array(filename_to_list(files))[idx].tolist()) + return list_to_filename( + np.array(filename_to_list(files))[idx].tolist()) mask = Node(fsl.BET(), name='getmask') mask.inputs.mask = True wf.connect(calc_median, 'median_file', mask, 'in_file') + # get segmentation in normalized functional space def merge_files(in1, in2): @@ -677,74 +669,81 @@ def merge_files(in1, in2): # filter some noise # Compute motion regressors - motreg = Node(Function(input_names=['motion_params', 'order', - 'derivatives'], - output_names=['out_files'], - function=motion_regressors, - imports=imports), - name='getmotionregress') + motreg = Node( + Function( + input_names=['motion_params', 'order', 'derivatives'], + output_names=['out_files'], + function=motion_regressors, + imports=imports), + name='getmotionregress') wf.connect(realign, 'realignment_parameters', motreg, 'motion_params') # Create a filter to remove motion and art confounds - createfilter1 = Node(Function(input_names=['motion_params', 'comp_norm', - 'outliers', 'detrend_poly'], - output_names=['out_files'], - function=build_filter1, - imports=imports), - name='makemotionbasedfilter') + createfilter1 = Node( + Function( + input_names=[ + 'motion_params', 'comp_norm', 'outliers', 'detrend_poly' + ], + output_names=['out_files'], + function=build_filter1, + imports=imports), + name='makemotionbasedfilter') createfilter1.inputs.detrend_poly = 2 wf.connect(motreg, 'out_files', createfilter1, 'motion_params') wf.connect(art, 'norm_files', createfilter1, 'comp_norm') wf.connect(art, 'outlier_files', createfilter1, 'outliers') - filter1 = MapNode(fsl.GLM(out_f_name='F_mcart.nii', - out_pf_name='pF_mcart.nii', - demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filtermotion') + filter1 = MapNode( + fsl.GLM( + out_f_name='F_mcart.nii', out_pf_name='pF_mcart.nii', demean=True), + iterfield=['in_file', 'design', 'out_res_name'], + name='filtermotion') wf.connect(slice_timing, 'timecorrected_files', filter1, 'in_file') wf.connect(slice_timing, ('timecorrected_files', rename, '_filtermotart'), filter1, 'out_res_name') wf.connect(createfilter1, 'out_files', filter1, 'design') - createfilter2 = MapNode(Function(input_names=['realigned_file', 'mask_file', - 'num_components', - 'extra_regressors'], - output_names=['out_files'], - function=extract_noise_components, - imports=imports), - iterfield=['realigned_file', 'extra_regressors'], - name='makecompcorrfilter') + createfilter2 = MapNode( + Function( + input_names=[ + 'realigned_file', 'mask_file', 'num_components', + 'extra_regressors' + ], + output_names=['out_files'], + function=extract_noise_components, + imports=imports), + iterfield=['realigned_file', 'extra_regressors'], + name='makecompcorrfilter') createfilter2.inputs.num_components = num_components wf.connect(createfilter1, 'out_files', createfilter2, 'extra_regressors') wf.connect(filter1, 'out_res', createfilter2, 'realigned_file') - wf.connect(registration, ('outputspec.segmentation_files', selectindex, [0, 2]), + wf.connect(registration, + ('outputspec.segmentation_files', selectindex, [0, 2]), createfilter2, 'mask_file') - filter2 = MapNode(fsl.GLM(out_f_name='F.nii', - out_pf_name='pF.nii', - demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filter_noise_nosmooth') + filter2 = MapNode( + fsl.GLM(out_f_name='F.nii', out_pf_name='pF.nii', demean=True), + iterfield=['in_file', 'design', 'out_res_name'], + name='filter_noise_nosmooth') wf.connect(filter1, 'out_res', filter2, 'in_file') - wf.connect(filter1, ('out_res', rename, '_cleaned'), - filter2, 'out_res_name') + wf.connect(filter1, ('out_res', rename, '_cleaned'), filter2, + 'out_res_name') wf.connect(createfilter2, 'out_files', filter2, 'design') wf.connect(mask, 'mask_file', filter2, 'mask') - bandpass = Node(Function(input_names=['files', 'lowpass_freq', - 'highpass_freq', 'fs'], - output_names=['out_files'], - function=bandpass_filter, - imports=imports), - name='bandpass_unsmooth') + bandpass = Node( + Function( + input_names=['files', 'lowpass_freq', 'highpass_freq', 'fs'], + output_names=['out_files'], + function=bandpass_filter, + imports=imports), + name='bandpass_unsmooth') bandpass.inputs.fs = 1. / TR bandpass.inputs.highpass_freq = highpass_freq bandpass.inputs.lowpass_freq = lowpass_freq wf.connect(filter2, 'out_res', bandpass, 'files') - """Smooth the functional data using :class:`nipype.interfaces.spm.Smooth`. """ @@ -757,13 +756,12 @@ def merge_files(in1, in2): collector = Node(Merge(2), name='collect_streams') wf.connect(smooth, 'smoothed_files', collector, 'in1') wf.connect(bandpass, 'out_files', collector, 'in2') - """ Transform the remaining images. First to anatomical and then to target """ - warpall = MapNode(ants.ApplyTransforms(), iterfield=['input_image'], - name='warpall') + warpall = MapNode( + ants.ApplyTransforms(), iterfield=['input_image'], name='warpall') warpall.inputs.input_image_type = 3 warpall.inputs.interpolation = 'Linear' warpall.inputs.invert_transform_flags = [False, False] @@ -794,16 +792,16 @@ def merge_files(in1, in2): # Convert aparc to subject functional space # Sample the average time series in aparc ROIs - sampleaparc = MapNode(freesurfer.SegStats(default_color_table=True), - iterfield=['in_file', 'summary_file', - 'avgwf_txt_file'], - name='aparc_ts') - sampleaparc.inputs.segment_id = ([8] + list(range(10, 14)) + [17, 18, 26, 47] + - list(range(49, 55)) + [58] + list(range(1001, 1036)) + - list(range(2001, 2036))) - - wf.connect(registration, 'outputspec.aparc', - sampleaparc, 'segmentation_file') + sampleaparc = MapNode( + freesurfer.SegStats(default_color_table=True), + iterfield=['in_file', 'summary_file', 'avgwf_txt_file'], + name='aparc_ts') + sampleaparc.inputs.segment_id = ( + [8] + list(range(10, 14)) + [17, 18, 26, 47] + list(range(49, 55)) + + [58] + list(range(1001, 1036)) + list(range(2001, 2036))) + + wf.connect(registration, 'outputspec.aparc', sampleaparc, + 'segmentation_file') wf.connect(collector, 'out', sampleaparc, 'in_file') def get_names(files, suffix): @@ -817,19 +815,20 @@ def get_names(files, suffix): out_names.append(name + suffix) return list_to_filename(out_names) - wf.connect(collector, ('out', get_names, '_avgwf.txt'), - sampleaparc, 'avgwf_txt_file') - wf.connect(collector, ('out', get_names, '_summary.stats'), - sampleaparc, 'summary_file') + wf.connect(collector, ('out', get_names, '_avgwf.txt'), sampleaparc, + 'avgwf_txt_file') + wf.connect(collector, ('out', get_names, '_summary.stats'), sampleaparc, + 'summary_file') # Sample the time series onto the surface of the target surface. Performs # sampling into left and right hemisphere target = Node(IdentityInterface(fields=['target_subject']), name='target') target.iterables = ('target_subject', filename_to_list(target_subject)) - samplerlh = MapNode(freesurfer.SampleToSurface(), - iterfield=['source_file'], - name='sampler_lh') + samplerlh = MapNode( + freesurfer.SampleToSurface(), + iterfield=['source_file'], + name='sampler_lh') samplerlh.inputs.sampling_method = "average" samplerlh.inputs.sampling_range = (0.1, 0.9, 0.1) samplerlh.inputs.sampling_units = "frac" @@ -852,23 +851,26 @@ def get_names(files, suffix): wf.connect(target, 'target_subject', samplerrh, 'target_subject') # Combine left and right hemisphere to text file - combiner = MapNode(Function(input_names=['left', 'right'], - output_names=['out_file'], - function=combine_hemi, - imports=imports), - iterfield=['left', 'right'], - name="combiner") + combiner = MapNode( + Function( + input_names=['left', 'right'], + output_names=['out_file'], + function=combine_hemi, + imports=imports), + iterfield=['left', 'right'], + name="combiner") wf.connect(samplerlh, 'out_file', combiner, 'left') wf.connect(samplerrh, 'out_file', combiner, 'right') # Sample the time series file for each subcortical roi - ts2txt = MapNode(Function(input_names=['timeseries_file', 'label_file', - 'indices'], - output_names=['out_file'], - function=extract_subrois, - imports=imports), - iterfield=['timeseries_file'], - name='getsubcortts') + ts2txt = MapNode( + Function( + input_names=['timeseries_file', 'label_file', 'indices'], + output_names=['out_file'], + function=extract_subrois, + imports=imports), + iterfield=['timeseries_file'], + name='getsubcortts') ts2txt.inputs.indices = [8] + list(range(10, 14)) + [17, 18, 26, 47] +\ list(range(49, 55)) + [58] ts2txt.inputs.label_file = \ @@ -878,61 +880,66 @@ def get_names(files, suffix): ###### - substitutions = [('_target_subject_', ''), - ('_filtermotart_cleaned_bp_trans_masked', ''), - ('_filtermotart_cleaned_bp', '') - ] - regex_subs = [('_ts_masker.*/sar', '/smooth/'), - ('_ts_masker.*/ar', '/unsmooth/'), - ('_combiner.*/sar', '/smooth/'), - ('_combiner.*/ar', '/unsmooth/'), - ('_aparc_ts.*/sar', '/smooth/'), - ('_aparc_ts.*/ar', '/unsmooth/'), - ('_getsubcortts.*/sar', '/smooth/'), - ('_getsubcortts.*/ar', '/unsmooth/'), - ('series/sar', 'series/smooth/'), - ('series/ar', 'series/unsmooth/'), - ('_inverse_transform./', ''), - ] + substitutions = [('_target_subject_', + ''), ('_filtermotart_cleaned_bp_trans_masked', ''), + ('_filtermotart_cleaned_bp', '')] + regex_subs = [ + ('_ts_masker.*/sar', '/smooth/'), + ('_ts_masker.*/ar', '/unsmooth/'), + ('_combiner.*/sar', '/smooth/'), + ('_combiner.*/ar', '/unsmooth/'), + ('_aparc_ts.*/sar', '/smooth/'), + ('_aparc_ts.*/ar', '/unsmooth/'), + ('_getsubcortts.*/sar', '/smooth/'), + ('_getsubcortts.*/ar', '/unsmooth/'), + ('series/sar', 'series/smooth/'), + ('series/ar', 'series/unsmooth/'), + ('_inverse_transform./', ''), + ] # Save the relevant data into an output directory datasink = Node(interface=DataSink(), name="datasink") datasink.inputs.base_directory = sink_directory datasink.inputs.container = subject_id datasink.inputs.substitutions = substitutions datasink.inputs.regexp_substitutions = regex_subs # (r'(/_.*(\d+/))', r'/run\2') - wf.connect(realign, 'realignment_parameters', datasink, 'resting.qa.motion') + wf.connect(realign, 'realignment_parameters', datasink, + 'resting.qa.motion') wf.connect(art, 'norm_files', datasink, 'resting.qa.art.@norm') wf.connect(art, 'intensity_files', datasink, 'resting.qa.art.@intensity') wf.connect(art, 'outlier_files', datasink, 'resting.qa.art.@outlier_files') - wf.connect(registration, 'outputspec.segmentation_files', datasink, 'resting.mask_files') - wf.connect(registration, 'outputspec.anat2target', datasink, 'resting.qa.ants') + wf.connect(registration, 'outputspec.segmentation_files', datasink, + 'resting.mask_files') + wf.connect(registration, 'outputspec.anat2target', datasink, + 'resting.qa.ants') wf.connect(mask, 'mask_file', datasink, 'resting.mask_files.@brainmask') wf.connect(mask_target, 'out_file', datasink, 'resting.mask_files.target') wf.connect(filter1, 'out_f', datasink, 'resting.qa.compmaps.@mc_F') wf.connect(filter1, 'out_pf', datasink, 'resting.qa.compmaps.@mc_pF') wf.connect(filter2, 'out_f', datasink, 'resting.qa.compmaps') wf.connect(filter2, 'out_pf', datasink, 'resting.qa.compmaps.@p') - wf.connect(bandpass, 'out_files', datasink, 'resting.timeseries.@bandpassed') - wf.connect(smooth, 'smoothed_files', datasink, 'resting.timeseries.@smoothed') - wf.connect(createfilter1, 'out_files', - datasink, 'resting.regress.@regressors') - wf.connect(createfilter2, 'out_files', - datasink, 'resting.regress.@compcorr') + wf.connect(bandpass, 'out_files', datasink, + 'resting.timeseries.@bandpassed') + wf.connect(smooth, 'smoothed_files', datasink, + 'resting.timeseries.@smoothed') + wf.connect(createfilter1, 'out_files', datasink, + 'resting.regress.@regressors') + wf.connect(createfilter2, 'out_files', datasink, + 'resting.regress.@compcorr') wf.connect(maskts, 'out_file', datasink, 'resting.timeseries.target') - wf.connect(sampleaparc, 'summary_file', - datasink, 'resting.parcellations.aparc') - wf.connect(sampleaparc, 'avgwf_txt_file', - datasink, 'resting.parcellations.aparc.@avgwf') - wf.connect(ts2txt, 'out_file', - datasink, 'resting.parcellations.grayo.@subcortical') + wf.connect(sampleaparc, 'summary_file', datasink, + 'resting.parcellations.aparc') + wf.connect(sampleaparc, 'avgwf_txt_file', datasink, + 'resting.parcellations.aparc.@avgwf') + wf.connect(ts2txt, 'out_file', datasink, + 'resting.parcellations.grayo.@subcortical') datasink2 = Node(interface=DataSink(), name="datasink2") datasink2.inputs.base_directory = sink_directory datasink2.inputs.container = subject_id datasink2.inputs.substitutions = substitutions datasink2.inputs.regexp_substitutions = regex_subs # (r'(/_.*(\d+/))', r'/run\2') - wf.connect(combiner, 'out_file', - datasink2, 'resting.parcellations.grayo.@surface') + wf.connect(combiner, 'out_file', datasink2, + 'resting.parcellations.grayo.@surface') return wf @@ -949,68 +956,121 @@ def create_resting_workflow(args, name=None): slice_times = (np.array(slice_times) / 1000.).tolist() if name is None: name = 'resting_' + args.subject_id - kwargs = dict(files=[os.path.abspath(filename) for filename in args.files], - target_file=os.path.abspath(args.target_file), - subject_id=args.subject_id, - TR=TR, - slice_times=slice_times, - vol_fwhm=args.vol_fwhm, - surf_fwhm=args.surf_fwhm, - norm_threshold=2., - subjects_dir=os.path.abspath(args.fsdir), - target_subject=args.target_surfs, - lowpass_freq=args.lowpass_freq, - highpass_freq=args.highpass_freq, - sink_directory=os.path.abspath(args.sink), - name=name) + kwargs = dict( + files=[os.path.abspath(filename) for filename in args.files], + target_file=os.path.abspath(args.target_file), + subject_id=args.subject_id, + TR=TR, + slice_times=slice_times, + vol_fwhm=args.vol_fwhm, + surf_fwhm=args.surf_fwhm, + norm_threshold=2., + subjects_dir=os.path.abspath(args.fsdir), + target_subject=args.target_surfs, + lowpass_freq=args.lowpass_freq, + highpass_freq=args.highpass_freq, + sink_directory=os.path.abspath(args.sink), + name=name) wf = create_workflow(**kwargs) return wf + if __name__ == "__main__": from argparse import ArgumentParser, RawTextHelpFormatter defstr = ' (default %(default)s)' - parser = ArgumentParser(description=__doc__, - formatter_class=RawTextHelpFormatter) - parser.add_argument("-d", "--dicom_file", dest="dicom_file", - help="an example dicom file from the resting series") - parser.add_argument("-f", "--files", dest="files", nargs="+", - help="4d nifti files for resting state", - required=True) - parser.add_argument("-t", "--target", dest="target_file", - help=("Target in MNI space. Best to use the MindBoggle " - "template - " - "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz"), - required=True) - parser.add_argument("-s", "--subject_id", dest="subject_id", - help="FreeSurfer subject id", required=True) - parser.add_argument("--subjects_dir", dest="fsdir", - help="FreeSurfer subject directory", required=True) - parser.add_argument("--target_surfaces", dest="target_surfs", nargs="+", - default=['fsaverage5'], - help="FreeSurfer target surfaces" + defstr) - parser.add_argument("--TR", dest="TR", default=None, type=float, - help="TR if dicom not provided in seconds") - parser.add_argument("--slice_times", dest="slice_times", nargs="+", - type=float, help="Slice onset times in seconds") - parser.add_argument('--vol_fwhm', default=6., dest='vol_fwhm', - type=float, help="Spatial FWHM" + defstr) - parser.add_argument('--surf_fwhm', default=15., dest='surf_fwhm', - type=float, help="Spatial FWHM" + defstr) - parser.add_argument("-l", "--lowpass_freq", dest="lowpass_freq", - default=0.1, type=float, - help="Low pass frequency (Hz)" + defstr) - parser.add_argument("-u", "--highpass_freq", dest="highpass_freq", - default=0.01, type=float, - help="High pass frequency (Hz)" + defstr) - parser.add_argument("-o", "--output_dir", dest="sink", - help="Output directory base", required=True) - parser.add_argument("-w", "--work_dir", dest="work_dir", - help="Output directory base") - parser.add_argument("-p", "--plugin", dest="plugin", - default='Linear', - help="Plugin to use") - parser.add_argument("--plugin_args", dest="plugin_args", - help="Plugin arguments") + parser = ArgumentParser( + description=__doc__, formatter_class=RawTextHelpFormatter) + parser.add_argument( + "-d", + "--dicom_file", + dest="dicom_file", + help="an example dicom file from the resting series") + parser.add_argument( + "-f", + "--files", + dest="files", + nargs="+", + help="4d nifti files for resting state", + required=True) + parser.add_argument( + "-t", + "--target", + dest="target_file", + help=("Target in MNI space. Best to use the MindBoggle " + "template - " + "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz"), + required=True) + parser.add_argument( + "-s", + "--subject_id", + dest="subject_id", + help="FreeSurfer subject id", + required=True) + parser.add_argument( + "--subjects_dir", + dest="fsdir", + help="FreeSurfer subject directory", + required=True) + parser.add_argument( + "--target_surfaces", + dest="target_surfs", + nargs="+", + default=['fsaverage5'], + help="FreeSurfer target surfaces" + defstr) + parser.add_argument( + "--TR", + dest="TR", + default=None, + type=float, + help="TR if dicom not provided in seconds") + parser.add_argument( + "--slice_times", + dest="slice_times", + nargs="+", + type=float, + help="Slice onset times in seconds") + parser.add_argument( + '--vol_fwhm', + default=6., + dest='vol_fwhm', + type=float, + help="Spatial FWHM" + defstr) + parser.add_argument( + '--surf_fwhm', + default=15., + dest='surf_fwhm', + type=float, + help="Spatial FWHM" + defstr) + parser.add_argument( + "-l", + "--lowpass_freq", + dest="lowpass_freq", + default=0.1, + type=float, + help="Low pass frequency (Hz)" + defstr) + parser.add_argument( + "-u", + "--highpass_freq", + dest="highpass_freq", + default=0.01, + type=float, + help="High pass frequency (Hz)" + defstr) + parser.add_argument( + "-o", + "--output_dir", + dest="sink", + help="Output directory base", + required=True) + parser.add_argument( + "-w", "--work_dir", dest="work_dir", help="Output directory base") + parser.add_argument( + "-p", + "--plugin", + dest="plugin", + default='Linear', + help="Plugin to use") + parser.add_argument( + "--plugin_args", dest="plugin_args", help="Plugin arguments") args = parser.parse_args() wf = create_resting_workflow(args) diff --git a/examples/rsfmri_vol_surface_preprocessing_nipy.py b/examples/rsfmri_vol_surface_preprocessing_nipy.py index 51a5742284..2545c38d17 100644 --- a/examples/rsfmri_vol_surface_preprocessing_nipy.py +++ b/examples/rsfmri_vol_surface_preprocessing_nipy.py @@ -77,13 +77,12 @@ import nibabel as nb from nipype.utils.config import NUMPY_MMAP -imports = ['import os', - 'import nibabel as nb', - 'import numpy as np', - 'import scipy as sp', - 'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename', - 'from scipy.special import legendre' - ] +imports = [ + 'import os', 'import nibabel as nb', 'import numpy as np', + 'import scipy as sp', + 'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename', + 'from scipy.special import legendre' +] def get_info(dicom_files): @@ -95,9 +94,11 @@ def get_info(dicom_files): Slice Acquisition Times Spacing between slices """ - meta = default_extractor(read_file(filename_to_list(dicom_files)[0], - stop_before_pixels=True, - force=True)) + meta = default_extractor( + read_file( + filename_to_list(dicom_files)[0], + stop_before_pixels=True, + force=True)) return (meta['RepetitionTime'] / 1000., meta['CsaImage.MosaicRefAcqTimes'], meta['SpacingBetweenSlices']) @@ -224,14 +225,15 @@ def build_filter1(motion_params, comp_norm, outliers, detrend_poly=None): timepoints = out_params.shape[0] X = np.empty((timepoints, 0)) for i in range(detrend_poly): - X = np.hstack((X, legendre( - i + 1)(np.linspace(-1, 1, timepoints))[:, None])) + X = np.hstack((X, legendre(i + 1)(np.linspace( + -1, 1, timepoints))[:, None])) out_params = np.hstack((out_params, X)) filename = os.path.join(os.getcwd(), "filter_regressor%02d.txt" % idx) np.savetxt(filename, out_params, fmt=b"%.10f") out_files.append(filename) return out_files + def rename(in_files, suffix=None): from nipype.utils.filemanip import (filename_to_list, split_filename, list_to_filename) @@ -280,9 +282,10 @@ def extract_subrois(timeseries_file, label_file, indices): ijk = np.nonzero(rois == fsindex) ts = data[ijk] for i0, row in enumerate(ts): - fp.write('%d,%d,%d,%d,' % (fsindex, ijk[0][i0], - ijk[1][i0], ijk[2][i0]) + - ','.join(['%.10f' % val for val in row]) + '\n') + fp.write('%d,%d,%d,%d,' % ( + fsindex, ijk[0][i0], ijk[1][i0], + ijk[2][i0]) + ','.join(['%.10f' % val + for val in row]) + '\n') return out_ts_file @@ -294,11 +297,13 @@ def combine_hemi(left, right): indices = np.vstack((1000000 + np.arange(0, lh_data.shape[0])[:, None], 2000000 + np.arange(0, rh_data.shape[0])[:, None])) - all_data = np.hstack((indices, np.vstack((lh_data.squeeze(), - rh_data.squeeze())))) + all_data = np.hstack((indices, + np.vstack((lh_data.squeeze(), rh_data.squeeze())))) filename = left.split('.')[1] + '_combined.txt' - np.savetxt(filename, all_data, - fmt=','.join(['%d'] + ['%.10f'] * (all_data.shape[1] - 1))) + np.savetxt( + filename, + all_data, + fmt=','.join(['%d'] + ['%.10f'] * (all_data.shape[1] - 1))) return os.path.abspath(filename) @@ -327,39 +332,32 @@ def create_reg_workflow(name='registration'): register = Workflow(name=name) - inputnode = Node(interface=IdentityInterface(fields=['source_files', - 'mean_image', - 'subject_id', - 'subjects_dir', - 'target_image']), - name='inputspec') - - outputnode = Node(interface=IdentityInterface(fields=['func2anat_transform', - 'out_reg_file', - 'anat2target_transform', - 'transforms', - 'transformed_mean', - 'segmentation_files', - 'anat2target', - 'aparc', - 'min_cost_file' - ]), - name='outputspec') + inputnode = Node( + interface=IdentityInterface(fields=[ + 'source_files', 'mean_image', 'subject_id', 'subjects_dir', + 'target_image' + ]), + name='inputspec') + + outputnode = Node( + interface=IdentityInterface(fields=[ + 'func2anat_transform', 'out_reg_file', 'anat2target_transform', + 'transforms', 'transformed_mean', 'segmentation_files', + 'anat2target', 'aparc', 'min_cost_file' + ]), + name='outputspec') # Get the subject's freesurfer source directory - fssource = Node(FreeSurferSource(), - name='fssource') + fssource = Node(FreeSurferSource(), name='fssource') fssource.run_without_submitting = True register.connect(inputnode, 'subject_id', fssource, 'subject_id') register.connect(inputnode, 'subjects_dir', fssource, 'subjects_dir') - convert = Node(freesurfer.MRIConvert(out_type='nii'), - name="convert") + convert = Node(freesurfer.MRIConvert(out_type='nii'), name="convert") register.connect(fssource, 'T1', convert, 'in_file') # Coregister the median to the surface - bbregister = Node(freesurfer.BBRegister(), - name='bbregister') + bbregister = Node(freesurfer.BBRegister(), name='bbregister') bbregister.inputs.init = 'fsl' bbregister.inputs.contrast_type = 't2' bbregister.inputs.out_fsl_file = True @@ -367,55 +365,54 @@ def create_reg_workflow(name='registration'): register.connect(inputnode, 'subject_id', bbregister, 'subject_id') register.connect(inputnode, 'mean_image', bbregister, 'source_file') register.connect(inputnode, 'subjects_dir', bbregister, 'subjects_dir') - """ Estimate the tissue classes from the anatomical image. But use aparc+aseg's brain mask """ - binarize = Node(fs.Binarize(min=0.5, out_type="nii.gz", dilate=1), name="binarize_aparc") - register.connect(fssource, ("aparc_aseg", get_aparc_aseg), binarize, "in_file") + binarize = Node( + fs.Binarize(min=0.5, out_type="nii.gz", dilate=1), + name="binarize_aparc") + register.connect(fssource, ("aparc_aseg", get_aparc_aseg), binarize, + "in_file") stripper = Node(fsl.ApplyMask(), name='stripper') register.connect(binarize, "binary_file", stripper, "mask_file") register.connect(convert, 'out_file', stripper, 'in_file') fast = Node(fsl.FAST(), name='fast') register.connect(stripper, 'out_file', fast, 'in_files') - """ Binarize the segmentation """ - binarize = MapNode(fsl.ImageMaths(op_string='-nan -thr 0.9 -ero -bin'), - iterfield=['in_file'], - name='binarize') + binarize = MapNode( + fsl.ImageMaths(op_string='-nan -thr 0.9 -ero -bin'), + iterfield=['in_file'], + name='binarize') register.connect(fast, 'partial_volume_files', binarize, 'in_file') - """ Apply inverse transform to take segmentations to functional space """ - applyxfm = MapNode(freesurfer.ApplyVolTransform(inverse=True, - interp='nearest'), - iterfield=['target_file'], - name='inverse_transform') + applyxfm = MapNode( + freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), + iterfield=['target_file'], + name='inverse_transform') register.connect(inputnode, 'subjects_dir', applyxfm, 'subjects_dir') register.connect(bbregister, 'out_reg_file', applyxfm, 'reg_file') register.connect(binarize, 'out_file', applyxfm, 'target_file') register.connect(inputnode, 'mean_image', applyxfm, 'source_file') - """ Apply inverse transform to aparc file """ - aparcxfm = Node(freesurfer.ApplyVolTransform(inverse=True, - interp='nearest'), - name='aparc_inverse_transform') + aparcxfm = Node( + freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), + name='aparc_inverse_transform') register.connect(inputnode, 'subjects_dir', aparcxfm, 'subjects_dir') register.connect(bbregister, 'out_reg_file', aparcxfm, 'reg_file') - register.connect(fssource, ('aparc_aseg', get_aparc_aseg), - aparcxfm, 'target_file') + register.connect(fssource, ('aparc_aseg', get_aparc_aseg), aparcxfm, + 'target_file') register.connect(inputnode, 'mean_image', aparcxfm, 'source_file') - """ Convert the BBRegister transformation to ANTS ITK format """ @@ -426,7 +423,6 @@ def create_reg_workflow(name='registration'): register.connect(bbregister, 'out_fsl_file', convert2itk, 'transform_file') register.connect(inputnode, 'mean_image', convert2itk, 'source_file') register.connect(stripper, 'out_file', convert2itk, 'reference_file') - """ Compute registration between the subject's structural and MNI template This is currently set to perform a very quick registration. However, the @@ -439,8 +435,10 @@ def create_reg_workflow(name='registration'): reg = Node(ants.Registration(), name='antsRegister') reg.inputs.output_transform_prefix = "output_" reg.inputs.transforms = ['Rigid', 'Affine', 'SyN'] - reg.inputs.transform_parameters = [(0.1,), (0.1,), (0.2, 3.0, 0.0)] - reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[100, 30, 20]] + reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)] + reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[ + 100, 30, 20 + ]] reg.inputs.dimension = 3 reg.inputs.write_composite_transform = True reg.inputs.collapse_output_transforms = True @@ -465,7 +463,6 @@ def create_reg_workflow(name='registration'): reg.plugin_args = {'sbatch_args': '-c%d' % 4} register.connect(stripper, 'out_file', reg, 'moving_image') register.connect(inputnode, 'target_image', reg, 'fixed_image') - """ Concatenate the affine and ants transforms into a list """ @@ -473,7 +470,6 @@ def create_reg_workflow(name='registration'): merge = Node(Merge(2), iterfield=['in2'], name='mergexfm') register.connect(convert2itk, 'itk_transform', merge, 'in2') register.connect(reg, 'composite_transform', merge, 'in1') - """ Transform the mean image. First to anatomical and then to target """ @@ -490,26 +486,22 @@ def create_reg_workflow(name='registration'): register.connect(inputnode, 'target_image', warpmean, 'reference_image') register.connect(inputnode, 'mean_image', warpmean, 'input_image') register.connect(merge, 'out', warpmean, 'transforms') - """ Assign all the output files """ register.connect(reg, 'warped_image', outputnode, 'anat2target') register.connect(warpmean, 'output_image', outputnode, 'transformed_mean') - register.connect(applyxfm, 'transformed_file', - outputnode, 'segmentation_files') - register.connect(aparcxfm, 'transformed_file', - outputnode, 'aparc') - register.connect(bbregister, 'out_fsl_file', - outputnode, 'func2anat_transform') - register.connect(bbregister, 'out_reg_file', - outputnode, 'out_reg_file') - register.connect(reg, 'composite_transform', - outputnode, 'anat2target_transform') + register.connect(applyxfm, 'transformed_file', outputnode, + 'segmentation_files') + register.connect(aparcxfm, 'transformed_file', outputnode, 'aparc') + register.connect(bbregister, 'out_fsl_file', outputnode, + 'func2anat_transform') + register.connect(bbregister, 'out_reg_file', outputnode, 'out_reg_file') + register.connect(reg, 'composite_transform', outputnode, + 'anat2target_transform') register.connect(merge, 'out', outputnode, 'transforms') - register.connect(bbregister, 'min_cost_file', - outputnode, 'min_cost_file') + register.connect(bbregister, 'min_cost_file', outputnode, 'min_cost_file') return register @@ -538,9 +530,10 @@ def create_workflow(files, wf = Workflow(name=name) # Rename files in case they are named identically - name_unique = MapNode(Rename(format_string='rest_%(run)02d'), - iterfield=['in_file', 'run'], - name='rename') + name_unique = MapNode( + Rename(format_string='rest_%(run)02d'), + iterfield=['in_file', 'run'], + name='rename') name_unique.inputs.keep_ext = True name_unique.inputs.run = list(range(1, len(files) + 1)) name_unique.inputs.in_file = files @@ -558,25 +551,26 @@ def create_workflow(files, # Compute the median image across runs calc_median = Node(CalculateMedian(), name='median') wf.connect(tsnr, 'detrended_file', calc_median, 'in_files') - """Segment and Register """ registration = create_reg_workflow(name='registration') - wf.connect(calc_median, 'median_file', registration, 'inputspec.mean_image') + wf.connect(calc_median, 'median_file', registration, + 'inputspec.mean_image') registration.inputs.inputspec.subject_id = subject_id registration.inputs.inputspec.subjects_dir = subjects_dir registration.inputs.inputspec.target_image = target_file - """Quantify TSNR in each freesurfer ROI """ - get_roi_tsnr = MapNode(fs.SegStats(default_color_table=True), - iterfield=['in_file'], name='get_aparc_tsnr') + get_roi_tsnr = MapNode( + fs.SegStats(default_color_table=True), + iterfield=['in_file'], + name='get_aparc_tsnr') get_roi_tsnr.inputs.avgwf_txt_file = True wf.connect(tsnr, 'tsnr_file', get_roi_tsnr, 'in_file') - wf.connect(registration, 'outputspec.aparc', get_roi_tsnr, 'segmentation_file') - + wf.connect(registration, 'outputspec.aparc', get_roi_tsnr, + 'segmentation_file') """Use :class:`nipype.algorithms.rapidart` to determine which of the images in the functional series are outliers based on deviations in intensity or movement. @@ -589,25 +583,27 @@ def create_workflow(files, art.inputs.zintensity_threshold = 9 art.inputs.mask_type = 'spm_global' art.inputs.parameter_source = 'NiPy' - """Here we are connecting all the nodes together. Notice that we add the merge node only if you choose to use 4D. Also `get_vox_dims` function is passed along the input volume of normalise to set the optimal voxel sizes. """ - wf.connect([(name_unique, realign, [('out_file', 'in_file')]), - (realign, art, [('out_file', 'realigned_files')]), - (realign, art, [('par_file', 'realignment_parameters')]), - ]) + wf.connect([ + (name_unique, realign, [('out_file', 'in_file')]), + (realign, art, [('out_file', 'realigned_files')]), + (realign, art, [('par_file', 'realignment_parameters')]), + ]) def selectindex(files, idx): import numpy as np from nipype.utils.filemanip import filename_to_list, list_to_filename - return list_to_filename(np.array(filename_to_list(files))[idx].tolist()) + return list_to_filename( + np.array(filename_to_list(files))[idx].tolist()) mask = Node(fsl.BET(), name='getmask') mask.inputs.mask = True wf.connect(calc_median, 'median_file', mask, 'in_file') + # get segmentation in normalized functional space def merge_files(in1, in2): @@ -618,75 +614,83 @@ def merge_files(in1, in2): # filter some noise # Compute motion regressors - motreg = Node(Function(input_names=['motion_params', 'order', - 'derivatives'], - output_names=['out_files'], - function=motion_regressors, - imports=imports), - name='getmotionregress') + motreg = Node( + Function( + input_names=['motion_params', 'order', 'derivatives'], + output_names=['out_files'], + function=motion_regressors, + imports=imports), + name='getmotionregress') wf.connect(realign, 'par_file', motreg, 'motion_params') # Create a filter to remove motion and art confounds - createfilter1 = Node(Function(input_names=['motion_params', 'comp_norm', - 'outliers', 'detrend_poly'], - output_names=['out_files'], - function=build_filter1, - imports=imports), - name='makemotionbasedfilter') + createfilter1 = Node( + Function( + input_names=[ + 'motion_params', 'comp_norm', 'outliers', 'detrend_poly' + ], + output_names=['out_files'], + function=build_filter1, + imports=imports), + name='makemotionbasedfilter') createfilter1.inputs.detrend_poly = 2 wf.connect(motreg, 'out_files', createfilter1, 'motion_params') wf.connect(art, 'norm_files', createfilter1, 'comp_norm') wf.connect(art, 'outlier_files', createfilter1, 'outliers') - filter1 = MapNode(fsl.GLM(out_f_name='F_mcart.nii.gz', - out_pf_name='pF_mcart.nii.gz', - demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filtermotion') + filter1 = MapNode( + fsl.GLM( + out_f_name='F_mcart.nii.gz', + out_pf_name='pF_mcart.nii.gz', + demean=True), + iterfield=['in_file', 'design', 'out_res_name'], + name='filtermotion') wf.connect(realign, 'out_file', filter1, 'in_file') - wf.connect(realign, ('out_file', rename, '_filtermotart'), - filter1, 'out_res_name') + wf.connect(realign, ('out_file', rename, '_filtermotart'), filter1, + 'out_res_name') wf.connect(createfilter1, 'out_files', filter1, 'design') - createfilter2 = MapNode(ACompCor(), - iterfield=['realigned_file', 'extra_regressors'], - name='makecompcorrfilter') + createfilter2 = MapNode( + ACompCor(), + iterfield=['realigned_file', 'extra_regressors'], + name='makecompcorrfilter') createfilter2.inputs.components_file = 'noise_components.txt' createfilter2.inputs.num_components = num_components wf.connect(createfilter1, 'out_files', createfilter2, 'extra_regressors') wf.connect(filter1, 'out_res', createfilter2, 'realigned_file') - wf.connect(registration, ('outputspec.segmentation_files', selectindex, [0, 2]), + wf.connect(registration, + ('outputspec.segmentation_files', selectindex, [0, 2]), createfilter2, 'mask_file') - filter2 = MapNode(fsl.GLM(out_f_name='F.nii.gz', - out_pf_name='pF.nii.gz', - demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filter_noise_nosmooth') + filter2 = MapNode( + fsl.GLM(out_f_name='F.nii.gz', out_pf_name='pF.nii.gz', demean=True), + iterfield=['in_file', 'design', 'out_res_name'], + name='filter_noise_nosmooth') wf.connect(filter1, 'out_res', filter2, 'in_file') - wf.connect(filter1, ('out_res', rename, '_cleaned'), - filter2, 'out_res_name') + wf.connect(filter1, ('out_res', rename, '_cleaned'), filter2, + 'out_res_name') wf.connect(createfilter2, 'components_file', filter2, 'design') wf.connect(mask, 'mask_file', filter2, 'mask') - bandpass = Node(Function(input_names=['files', 'lowpass_freq', - 'highpass_freq', 'fs'], - output_names=['out_files'], - function=bandpass_filter, - imports=imports), - name='bandpass_unsmooth') + bandpass = Node( + Function( + input_names=['files', 'lowpass_freq', 'highpass_freq', 'fs'], + output_names=['out_files'], + function=bandpass_filter, + imports=imports), + name='bandpass_unsmooth') bandpass.inputs.fs = 1. / TR bandpass.inputs.highpass_freq = highpass_freq bandpass.inputs.lowpass_freq = lowpass_freq wf.connect(filter2, 'out_res', bandpass, 'files') - """Smooth the functional data using :class:`nipype.interfaces.fsl.IsotropicSmooth`. """ - smooth = MapNode(interface=fsl.IsotropicSmooth(), name="smooth", iterfield=["in_file"]) + smooth = MapNode( + interface=fsl.IsotropicSmooth(), name="smooth", iterfield=["in_file"]) smooth.inputs.fwhm = vol_fwhm wf.connect(bandpass, 'out_files', smooth, 'in_file') @@ -694,13 +698,12 @@ def merge_files(in1, in2): collector = Node(Merge(2), name='collect_streams') wf.connect(smooth, 'out_file', collector, 'in1') wf.connect(bandpass, 'out_files', collector, 'in2') - """ Transform the remaining images. First to anatomical and then to target """ - warpall = MapNode(ants.ApplyTransforms(), iterfield=['input_image'], - name='warpall') + warpall = MapNode( + ants.ApplyTransforms(), iterfield=['input_image'], name='warpall') warpall.inputs.input_image_type = 3 warpall.inputs.interpolation = 'Linear' warpall.inputs.invert_transform_flags = [False, False] @@ -732,16 +735,16 @@ def merge_files(in1, in2): # Convert aparc to subject functional space # Sample the average time series in aparc ROIs - sampleaparc = MapNode(freesurfer.SegStats(default_color_table=True), - iterfield=['in_file', 'summary_file', - 'avgwf_txt_file'], - name='aparc_ts') - sampleaparc.inputs.segment_id = ([8] + list(range(10, 14)) + [17, 18, 26, 47] + - list(range(49, 55)) + [58] + list(range(1001, 1036)) + - list(range(2001, 2036))) - - wf.connect(registration, 'outputspec.aparc', - sampleaparc, 'segmentation_file') + sampleaparc = MapNode( + freesurfer.SegStats(default_color_table=True), + iterfield=['in_file', 'summary_file', 'avgwf_txt_file'], + name='aparc_ts') + sampleaparc.inputs.segment_id = ( + [8] + list(range(10, 14)) + [17, 18, 26, 47] + list(range(49, 55)) + + [58] + list(range(1001, 1036)) + list(range(2001, 2036))) + + wf.connect(registration, 'outputspec.aparc', sampleaparc, + 'segmentation_file') wf.connect(collector, 'out', sampleaparc, 'in_file') def get_names(files, suffix): @@ -756,19 +759,20 @@ def get_names(files, suffix): out_names.append(os.path.join(path, name + suffix)) return list_to_filename(out_names) - wf.connect(collector, ('out', get_names, '_avgwf.txt'), - sampleaparc, 'avgwf_txt_file') - wf.connect(collector, ('out', get_names, '_summary.stats'), - sampleaparc, 'summary_file') + wf.connect(collector, ('out', get_names, '_avgwf.txt'), sampleaparc, + 'avgwf_txt_file') + wf.connect(collector, ('out', get_names, '_summary.stats'), sampleaparc, + 'summary_file') # Sample the time series onto the surface of the target surface. Performs # sampling into left and right hemisphere target = Node(IdentityInterface(fields=['target_subject']), name='target') target.iterables = ('target_subject', filename_to_list(target_subject)) - samplerlh = MapNode(freesurfer.SampleToSurface(), - iterfield=['source_file'], - name='sampler_lh') + samplerlh = MapNode( + freesurfer.SampleToSurface(), + iterfield=['source_file'], + name='sampler_lh') samplerlh.inputs.sampling_method = "average" samplerlh.inputs.sampling_range = (0.1, 0.9, 0.1) samplerlh.inputs.sampling_units = "frac" @@ -791,23 +795,26 @@ def get_names(files, suffix): wf.connect(target, 'target_subject', samplerrh, 'target_subject') # Combine left and right hemisphere to text file - combiner = MapNode(Function(input_names=['left', 'right'], - output_names=['out_file'], - function=combine_hemi, - imports=imports), - iterfield=['left', 'right'], - name="combiner") + combiner = MapNode( + Function( + input_names=['left', 'right'], + output_names=['out_file'], + function=combine_hemi, + imports=imports), + iterfield=['left', 'right'], + name="combiner") wf.connect(samplerlh, 'out_file', combiner, 'left') wf.connect(samplerrh, 'out_file', combiner, 'right') # Sample the time series file for each subcortical roi - ts2txt = MapNode(Function(input_names=['timeseries_file', 'label_file', - 'indices'], - output_names=['out_file'], - function=extract_subrois, - imports=imports), - iterfield=['timeseries_file'], - name='getsubcortts') + ts2txt = MapNode( + Function( + input_names=['timeseries_file', 'label_file', 'indices'], + output_names=['out_file'], + function=extract_subrois, + imports=imports), + iterfield=['timeseries_file'], + name='getsubcortts') ts2txt.inputs.indices = [8] + list(range(10, 14)) + [17, 18, 26, 47] +\ list(range(49, 55)) + [58] ts2txt.inputs.label_file = \ @@ -817,36 +824,43 @@ def get_names(files, suffix): ###### - substitutions = [('_target_subject_', ''), - ('_filtermotart_cleaned_bp_trans_masked', ''), - ('_filtermotart_cleaned_bp', ''), - ] + substitutions = [ + ('_target_subject_', ''), + ('_filtermotart_cleaned_bp_trans_masked', ''), + ('_filtermotart_cleaned_bp', ''), + ] substitutions += [("_smooth%d" % i, "") for i in range(11)[::-1]] substitutions += [("_ts_masker%d" % i, "") for i in range(11)[::-1]] substitutions += [("_getsubcortts%d" % i, "") for i in range(11)[::-1]] substitutions += [("_combiner%d" % i, "") for i in range(11)[::-1]] substitutions += [("_filtermotion%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_filter_noise_nosmooth%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_makecompcorfilter%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_get_aparc_tsnr%d/" % i, "run%d_" % (i + 1)) for i in range(11)[::-1]] + substitutions += [("_filter_noise_nosmooth%d" % i, "") + for i in range(11)[::-1]] + substitutions += [("_makecompcorfilter%d" % i, "") + for i in range(11)[::-1]] + substitutions += [("_get_aparc_tsnr%d/" % i, "run%d_" % (i + 1)) + for i in range(11)[::-1]] substitutions += [("T1_out_brain_pve_0_maths_warped", "compcor_csf"), - ("T1_out_brain_pve_1_maths_warped", "compcor_gm"), - ("T1_out_brain_pve_2_maths_warped", "compcor_wm"), - ("output_warped_image_maths", "target_brain_mask"), - ("median_brain_mask", "native_brain_mask"), - ("corr_", "")] - - regex_subs = [('_combiner.*/sar', '/smooth/'), - ('_combiner.*/ar', '/unsmooth/'), - ('_aparc_ts.*/sar', '/smooth/'), - ('_aparc_ts.*/ar', '/unsmooth/'), - ('_getsubcortts.*/sar', '/smooth/'), - ('_getsubcortts.*/ar', '/unsmooth/'), - ('series/sar', 'series/smooth/'), - ('series/ar', 'series/unsmooth/'), - ('_inverse_transform./', ''), - ] + ("T1_out_brain_pve_1_maths_warped", + "compcor_gm"), ("T1_out_brain_pve_2_maths_warped", + "compcor_wm"), + ("output_warped_image_maths", + "target_brain_mask"), ("median_brain_mask", + "native_brain_mask"), ("corr_", + "")] + + regex_subs = [ + ('_combiner.*/sar', '/smooth/'), + ('_combiner.*/ar', '/unsmooth/'), + ('_aparc_ts.*/sar', '/smooth/'), + ('_aparc_ts.*/ar', '/unsmooth/'), + ('_getsubcortts.*/sar', '/smooth/'), + ('_getsubcortts.*/ar', '/unsmooth/'), + ('series/sar', 'series/smooth/'), + ('series/ar', 'series/unsmooth/'), + ('_inverse_transform./', ''), + ] # Save the relevant data into an output directory datasink = Node(interface=DataSink(), name="datasink") datasink.inputs.base_directory = sink_directory @@ -857,40 +871,45 @@ def get_names(files, suffix): wf.connect(art, 'norm_files', datasink, 'resting.qa.art.@norm') wf.connect(art, 'intensity_files', datasink, 'resting.qa.art.@intensity') wf.connect(art, 'outlier_files', datasink, 'resting.qa.art.@outlier_files') - wf.connect(registration, 'outputspec.segmentation_files', datasink, 'resting.mask_files') - wf.connect(registration, 'outputspec.anat2target', datasink, 'resting.qa.ants') + wf.connect(registration, 'outputspec.segmentation_files', datasink, + 'resting.mask_files') + wf.connect(registration, 'outputspec.anat2target', datasink, + 'resting.qa.ants') wf.connect(mask, 'mask_file', datasink, 'resting.mask_files.@brainmask') wf.connect(mask_target, 'out_file', datasink, 'resting.mask_files.target') wf.connect(filter1, 'out_f', datasink, 'resting.qa.compmaps.@mc_F') wf.connect(filter1, 'out_pf', datasink, 'resting.qa.compmaps.@mc_pF') wf.connect(filter2, 'out_f', datasink, 'resting.qa.compmaps') wf.connect(filter2, 'out_pf', datasink, 'resting.qa.compmaps.@p') - wf.connect(registration, 'outputspec.min_cost_file', datasink, 'resting.qa.mincost') + wf.connect(registration, 'outputspec.min_cost_file', datasink, + 'resting.qa.mincost') wf.connect(tsnr, 'tsnr_file', datasink, 'resting.qa.tsnr.@map') - wf.connect([(get_roi_tsnr, datasink, [('avgwf_txt_file', 'resting.qa.tsnr'), - ('summary_file', 'resting.qa.tsnr.@summary')])]) + wf.connect([(get_roi_tsnr, datasink, + [('avgwf_txt_file', 'resting.qa.tsnr'), + ('summary_file', 'resting.qa.tsnr.@summary')])]) - wf.connect(bandpass, 'out_files', datasink, 'resting.timeseries.@bandpassed') + wf.connect(bandpass, 'out_files', datasink, + 'resting.timeseries.@bandpassed') wf.connect(smooth, 'out_file', datasink, 'resting.timeseries.@smoothed') - wf.connect(createfilter1, 'out_files', - datasink, 'resting.regress.@regressors') - wf.connect(createfilter2, 'components_file', - datasink, 'resting.regress.@compcorr') + wf.connect(createfilter1, 'out_files', datasink, + 'resting.regress.@regressors') + wf.connect(createfilter2, 'components_file', datasink, + 'resting.regress.@compcorr') wf.connect(maskts, 'out_file', datasink, 'resting.timeseries.target') - wf.connect(sampleaparc, 'summary_file', - datasink, 'resting.parcellations.aparc') - wf.connect(sampleaparc, 'avgwf_txt_file', - datasink, 'resting.parcellations.aparc.@avgwf') - wf.connect(ts2txt, 'out_file', - datasink, 'resting.parcellations.grayo.@subcortical') + wf.connect(sampleaparc, 'summary_file', datasink, + 'resting.parcellations.aparc') + wf.connect(sampleaparc, 'avgwf_txt_file', datasink, + 'resting.parcellations.aparc.@avgwf') + wf.connect(ts2txt, 'out_file', datasink, + 'resting.parcellations.grayo.@subcortical') datasink2 = Node(interface=DataSink(), name="datasink2") datasink2.inputs.base_directory = sink_directory datasink2.inputs.container = subject_id datasink2.inputs.substitutions = substitutions datasink2.inputs.regexp_substitutions = regex_subs # (r'(/_.*(\d+/))', r'/run\2') - wf.connect(combiner, 'out_file', - datasink2, 'resting.parcellations.grayo.@surface') + wf.connect(combiner, 'out_file', datasink2, + 'resting.parcellations.grayo.@surface') return wf @@ -908,68 +927,121 @@ def create_resting_workflow(args, name=None): if name is None: name = 'resting_' + args.subject_id - kwargs = dict(files=[os.path.abspath(filename) for filename in args.files], - target_file=os.path.abspath(args.target_file), - subject_id=args.subject_id, - TR=TR, - slice_times=slice_times, - vol_fwhm=args.vol_fwhm, - surf_fwhm=args.surf_fwhm, - norm_threshold=2., - subjects_dir=os.path.abspath(args.fsdir), - target_subject=args.target_surfs, - lowpass_freq=args.lowpass_freq, - highpass_freq=args.highpass_freq, - sink_directory=os.path.abspath(args.sink), - name=name) + kwargs = dict( + files=[os.path.abspath(filename) for filename in args.files], + target_file=os.path.abspath(args.target_file), + subject_id=args.subject_id, + TR=TR, + slice_times=slice_times, + vol_fwhm=args.vol_fwhm, + surf_fwhm=args.surf_fwhm, + norm_threshold=2., + subjects_dir=os.path.abspath(args.fsdir), + target_subject=args.target_surfs, + lowpass_freq=args.lowpass_freq, + highpass_freq=args.highpass_freq, + sink_directory=os.path.abspath(args.sink), + name=name) wf = create_workflow(**kwargs) return wf + if __name__ == "__main__": from argparse import ArgumentParser, RawTextHelpFormatter defstr = ' (default %(default)s)' - parser = ArgumentParser(description=__doc__, - formatter_class=RawTextHelpFormatter) - parser.add_argument("-d", "--dicom_file", dest="dicom_file", - help="a SIEMENS example dicom file from the resting series") - parser.add_argument("-f", "--files", dest="files", nargs="+", - help="4d nifti files for resting state", - required=True) - parser.add_argument("-t", "--target", dest="target_file", - help=("Target in MNI space. Best to use the MindBoggle " - "template - " - "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz"), - required=True) - parser.add_argument("-s", "--subject_id", dest="subject_id", - help="FreeSurfer subject id", required=True) - parser.add_argument("--subjects_dir", dest="fsdir", - help="FreeSurfer subject directory", required=True) - parser.add_argument("--target_surfaces", dest="target_surfs", nargs="+", - default=['fsaverage5'], - help="FreeSurfer target surfaces" + defstr) - parser.add_argument("--TR", dest="TR", default=None, type=float, - help="TR if dicom not provided in seconds") - parser.add_argument("--slice_times", dest="slice_times", nargs="+", - type=float, help="Slice onset times in seconds") - parser.add_argument('--vol_fwhm', default=6., dest='vol_fwhm', - type=float, help="Spatial FWHM" + defstr) - parser.add_argument('--surf_fwhm', default=15., dest='surf_fwhm', - type=float, help="Spatial FWHM" + defstr) - parser.add_argument("-l", "--lowpass_freq", dest="lowpass_freq", - default=0.1, type=float, - help="Low pass frequency (Hz)" + defstr) - parser.add_argument("-u", "--highpass_freq", dest="highpass_freq", - default=0.01, type=float, - help="High pass frequency (Hz)" + defstr) - parser.add_argument("-o", "--output_dir", dest="sink", - help="Output directory base", required=True) - parser.add_argument("-w", "--work_dir", dest="work_dir", - help="Output directory base") - parser.add_argument("-p", "--plugin", dest="plugin", - default='Linear', - help="Plugin to use") - parser.add_argument("--plugin_args", dest="plugin_args", - help="Plugin arguments") + parser = ArgumentParser( + description=__doc__, formatter_class=RawTextHelpFormatter) + parser.add_argument( + "-d", + "--dicom_file", + dest="dicom_file", + help="a SIEMENS example dicom file from the resting series") + parser.add_argument( + "-f", + "--files", + dest="files", + nargs="+", + help="4d nifti files for resting state", + required=True) + parser.add_argument( + "-t", + "--target", + dest="target_file", + help=("Target in MNI space. Best to use the MindBoggle " + "template - " + "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz"), + required=True) + parser.add_argument( + "-s", + "--subject_id", + dest="subject_id", + help="FreeSurfer subject id", + required=True) + parser.add_argument( + "--subjects_dir", + dest="fsdir", + help="FreeSurfer subject directory", + required=True) + parser.add_argument( + "--target_surfaces", + dest="target_surfs", + nargs="+", + default=['fsaverage5'], + help="FreeSurfer target surfaces" + defstr) + parser.add_argument( + "--TR", + dest="TR", + default=None, + type=float, + help="TR if dicom not provided in seconds") + parser.add_argument( + "--slice_times", + dest="slice_times", + nargs="+", + type=float, + help="Slice onset times in seconds") + parser.add_argument( + '--vol_fwhm', + default=6., + dest='vol_fwhm', + type=float, + help="Spatial FWHM" + defstr) + parser.add_argument( + '--surf_fwhm', + default=15., + dest='surf_fwhm', + type=float, + help="Spatial FWHM" + defstr) + parser.add_argument( + "-l", + "--lowpass_freq", + dest="lowpass_freq", + default=0.1, + type=float, + help="Low pass frequency (Hz)" + defstr) + parser.add_argument( + "-u", + "--highpass_freq", + dest="highpass_freq", + default=0.01, + type=float, + help="High pass frequency (Hz)" + defstr) + parser.add_argument( + "-o", + "--output_dir", + dest="sink", + help="Output directory base", + required=True) + parser.add_argument( + "-w", "--work_dir", dest="work_dir", help="Output directory base") + parser.add_argument( + "-p", + "--plugin", + dest="plugin", + default='Linear', + help="Plugin to use") + parser.add_argument( + "--plugin_args", dest="plugin_args", help="Plugin arguments") args = parser.parse_args() wf = create_resting_workflow(args) diff --git a/examples/smri_ants_build_template.py b/examples/smri_ants_build_template.py index 07b133eac2..a75c0f6783 100644 --- a/examples/smri_ants_build_template.py +++ b/examples/smri_ants_build_template.py @@ -24,7 +24,6 @@ import nipype.pipeline.engine as pe # pypeline engine from nipype.workflows.smri.ants import ANTSTemplateBuildSingleIterationWF - """ 2. Download T1 volumes into home directory """ @@ -40,12 +39,18 @@ print(mydatadir) MyFileURLs = [ - ('http://slicer.kitware.com/midas3/download?bitstream=13121', '01_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13122', '02_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13124', '03_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13128', '01_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13123', '02_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13125', '03_T1_inv_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13121', + '01_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13122', + '02_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13124', + '03_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13128', + '01_T1_inv_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13123', + '02_T1_inv_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13125', + '03_T1_inv_half.nii.gz'), ] for tt in MyFileURLs: myURL = tt[0] @@ -65,31 +70,34 @@ os.path.join(mydatadir, '02_T1_half.nii.gz'), os.path.join(mydatadir, '03_T1_half.nii.gz') ] -input_passive_images = [ - {'INV_T1': os.path.join(mydatadir, '01_T1_inv_half.nii.gz')}, - {'INV_T1': os.path.join(mydatadir, '02_T1_inv_half.nii.gz')}, - {'INV_T1': os.path.join(mydatadir, '03_T1_inv_half.nii.gz')} -] - - +input_passive_images = [{ + 'INV_T1': + os.path.join(mydatadir, '01_T1_inv_half.nii.gz') +}, { + 'INV_T1': + os.path.join(mydatadir, '02_T1_inv_half.nii.gz') +}, { + 'INV_T1': + os.path.join(mydatadir, '03_T1_inv_half.nii.gz') +}] """ 3. Define the workflow and its working directory """ tbuilder = pe.Workflow(name="ANTSTemplateBuilder") tbuilder.base_dir = requestedPath - """ 4. Define data sources. In real life these would be replace by DataGrabbers """ -datasource = pe.Node(interface=util.IdentityInterface(fields=['imageList', 'passiveImagesDictionariesList']), - run_without_submitting=True, - name='InputImages') +datasource = pe.Node( + interface=util.IdentityInterface( + fields=['imageList', 'passiveImagesDictionariesList']), + run_without_submitting=True, + name='InputImages') datasource.inputs.imageList = input_images datasource.inputs.passiveImagesDictionariesList = input_passive_images datasource.inputs.sort_filelist = True - """ 5. Template is initialized by a simple average """ @@ -99,25 +107,30 @@ initAvg.inputs.normalize = True tbuilder.connect(datasource, "imageList", initAvg, "images") - """ 6. Define the first iteration of template building """ buildTemplateIteration1 = ANTSTemplateBuildSingleIterationWF('iteration01') -tbuilder.connect(initAvg, 'output_average_image', buildTemplateIteration1, 'inputspec.fixed_image') -tbuilder.connect(datasource, 'imageList', buildTemplateIteration1, 'inputspec.images') -tbuilder.connect(datasource, 'passiveImagesDictionariesList', buildTemplateIteration1, 'inputspec.ListOfPassiveImagesDictionaries') - +tbuilder.connect(initAvg, 'output_average_image', buildTemplateIteration1, + 'inputspec.fixed_image') +tbuilder.connect(datasource, 'imageList', buildTemplateIteration1, + 'inputspec.images') +tbuilder.connect(datasource, 'passiveImagesDictionariesList', + buildTemplateIteration1, + 'inputspec.ListOfPassiveImagesDictionaries') """ 7. Define the second iteration of template building """ buildTemplateIteration2 = ANTSTemplateBuildSingleIterationWF('iteration02') -tbuilder.connect(buildTemplateIteration1, 'outputspec.template', buildTemplateIteration2, 'inputspec.fixed_image') -tbuilder.connect(datasource, 'imageList', buildTemplateIteration2, 'inputspec.images') -tbuilder.connect(datasource, 'passiveImagesDictionariesList', buildTemplateIteration2, 'inputspec.ListOfPassiveImagesDictionaries') - +tbuilder.connect(buildTemplateIteration1, 'outputspec.template', + buildTemplateIteration2, 'inputspec.fixed_image') +tbuilder.connect(datasource, 'imageList', buildTemplateIteration2, + 'inputspec.images') +tbuilder.connect(datasource, 'passiveImagesDictionariesList', + buildTemplateIteration2, + 'inputspec.ListOfPassiveImagesDictionaries') """ 8. Move selected files to a designated results folder """ @@ -125,10 +138,13 @@ datasink = pe.Node(io.DataSink(), name="datasink") datasink.inputs.base_directory = os.path.join(requestedPath, "results") -tbuilder.connect(buildTemplateIteration2, 'outputspec.template', datasink, 'PrimaryTemplate') -tbuilder.connect(buildTemplateIteration2, 'outputspec.passive_deformed_templates', datasink, 'PassiveTemplate') -tbuilder.connect(initAvg, 'output_average_image', datasink, 'PreRegisterAverage') - +tbuilder.connect(buildTemplateIteration2, 'outputspec.template', datasink, + 'PrimaryTemplate') +tbuilder.connect(buildTemplateIteration2, + 'outputspec.passive_deformed_templates', datasink, + 'PassiveTemplate') +tbuilder.connect(initAvg, 'output_average_image', datasink, + 'PreRegisterAverage') """ 8. Run the workflow """ diff --git a/examples/smri_ants_registration.py b/examples/smri_ants_registration.py index cda3e49549..e7050b05b7 100644 --- a/examples/smri_ants_registration.py +++ b/examples/smri_ants_registration.py @@ -25,7 +25,6 @@ import urllib.parse from nipype.interfaces.ants import Registration from nipype.testing import example_data - """ 2. Download T1 volumes into home directory @@ -39,8 +38,10 @@ print(mydatadir) MyFileURLs = [ - ('http://slicer.kitware.com/midas3/download?bitstream=13121', '01_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13122', '02_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13121', + '01_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13122', + '02_T1_half.nii.gz'), ] for tt in MyFileURLs: myURL = tt[0] @@ -59,7 +60,6 @@ os.path.join(mydatadir, '01_T1_half.nii.gz'), os.path.join(mydatadir, '02_T1_half.nii.gz'), ] - """ 3. Define the parameters of the registration. Settings are found in the file ``smri_ants_registration_settings.json`` @@ -67,10 +67,10 @@ """ -reg = Registration(from_file=example_data('smri_ants_registration_settings.json')) +reg = Registration( + from_file=example_data('smri_ants_registration_settings.json')) reg.inputs.fixed_image = input_images[0] reg.inputs.moving_image = input_images[1] - """ Alternatively to the use of the ``from_file`` feature to load ANTs settings, the user can manually set all those inputs instead:: @@ -102,8 +102,6 @@ """ print(reg.cmdline) - - """ 3. Run the registration """ diff --git a/examples/smri_antsregistration_build_template.py b/examples/smri_antsregistration_build_template.py index ad4e0470ef..ecc214265c 100644 --- a/examples/smri_antsregistration_build_template.py +++ b/examples/smri_antsregistration_build_template.py @@ -23,7 +23,6 @@ import nipype.pipeline.engine as pe # pypeline engine from nipype.workflows.smri.ants import antsRegistrationTemplateBuildSingleIterationWF - """ 2. Download T1 volumes into home directory """ @@ -39,12 +38,18 @@ print(mydatadir) MyFileURLs = [ - ('http://slicer.kitware.com/midas3/download?bitstream=13121', '01_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13122', '02_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13124', '03_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13128', '01_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13123', '02_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13125', '03_T1_inv_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13121', + '01_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13122', + '02_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13124', + '03_T1_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13128', + '01_T1_inv_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13123', + '02_T1_inv_half.nii.gz'), + ('http://slicer.kitware.com/midas3/download?bitstream=13125', + '03_T1_inv_half.nii.gz'), ] for tt in MyFileURLs: myURL = tt[0] @@ -58,25 +63,44 @@ print("Downloaded file: {0}".format(localFilename)) else: print("File previously downloaded {0}".format(localFilename)) - - """ ListOfImagesDictionaries - a list of dictionaries where each dictionary is for one scan session, and the mappings in the dictionary are for all the co-aligned images for that one scan session """ -ListOfImagesDictionaries = [ - {'T1': os.path.join(mydatadir, '01_T1_half.nii.gz'), 'INV_T1': os.path.join(mydatadir, '01_T1_inv_half.nii.gz'), 'LABEL_MAP': os.path.join(mydatadir, '01_T1_inv_half.nii.gz')}, - {'T1': os.path.join(mydatadir, '02_T1_half.nii.gz'), 'INV_T1': os.path.join(mydatadir, '02_T1_inv_half.nii.gz'), 'LABEL_MAP': os.path.join(mydatadir, '02_T1_inv_half.nii.gz')}, - {'T1': os.path.join(mydatadir, '03_T1_half.nii.gz'), 'INV_T1': os.path.join(mydatadir, '03_T1_inv_half.nii.gz'), 'LABEL_MAP': os.path.join(mydatadir, '03_T1_inv_half.nii.gz')} -] -input_passive_images = [ - {'INV_T1': os.path.join(mydatadir, '01_T1_inv_half.nii.gz')}, - {'INV_T1': os.path.join(mydatadir, '02_T1_inv_half.nii.gz')}, - {'INV_T1': os.path.join(mydatadir, '03_T1_inv_half.nii.gz')} -] - +ListOfImagesDictionaries = [{ + 'T1': + os.path.join(mydatadir, '01_T1_half.nii.gz'), + 'INV_T1': + os.path.join(mydatadir, '01_T1_inv_half.nii.gz'), + 'LABEL_MAP': + os.path.join(mydatadir, '01_T1_inv_half.nii.gz') +}, { + 'T1': + os.path.join(mydatadir, '02_T1_half.nii.gz'), + 'INV_T1': + os.path.join(mydatadir, '02_T1_inv_half.nii.gz'), + 'LABEL_MAP': + os.path.join(mydatadir, '02_T1_inv_half.nii.gz') +}, { + 'T1': + os.path.join(mydatadir, '03_T1_half.nii.gz'), + 'INV_T1': + os.path.join(mydatadir, '03_T1_inv_half.nii.gz'), + 'LABEL_MAP': + os.path.join(mydatadir, '03_T1_inv_half.nii.gz') +}] +input_passive_images = [{ + 'INV_T1': + os.path.join(mydatadir, '01_T1_inv_half.nii.gz') +}, { + 'INV_T1': + os.path.join(mydatadir, '02_T1_inv_half.nii.gz') +}, { + 'INV_T1': + os.path.join(mydatadir, '03_T1_inv_half.nii.gz') +}] """ registrationImageTypes - A list of the image types to be used actively during the estimation process of registration, any image type not in this list @@ -85,38 +109,41 @@ """ registrationImageTypes = ['T1'] - """ interpolationMap - A map of image types to interpolation modes. If an image type is not listed, it will be linearly interpolated. { 'labelmap':'NearestNeighbor', 'FLAIR':'WindowedSinc' } """ -interpolationMapping = {'INV_T1': 'LanczosWindowedSinc', 'LABEL_MAP': 'NearestNeighbor', 'T1': 'Linear'} - +interpolationMapping = { + 'INV_T1': 'LanczosWindowedSinc', + 'LABEL_MAP': 'NearestNeighbor', + 'T1': 'Linear' +} """ 3. Define the workflow and its working directory """ tbuilder = pe.Workflow(name="antsRegistrationTemplateBuilder") tbuilder.base_dir = requestedPath - """ 4. Define data sources. In real life these would be replace by DataGrabbers """ InitialTemplateInputs = [mdict['T1'] for mdict in ListOfImagesDictionaries] -datasource = pe.Node(interface=util.IdentityInterface(fields=['InitialTemplateInputs', 'ListOfImagesDictionaries', - 'registrationImageTypes', 'interpolationMapping']), - run_without_submitting=True, - name='InputImages') +datasource = pe.Node( + interface=util.IdentityInterface(fields=[ + 'InitialTemplateInputs', 'ListOfImagesDictionaries', + 'registrationImageTypes', 'interpolationMapping' + ]), + run_without_submitting=True, + name='InputImages') datasource.inputs.InitialTemplateInputs = InitialTemplateInputs datasource.inputs.ListOfImagesDictionaries = ListOfImagesDictionaries datasource.inputs.registrationImageTypes = registrationImageTypes datasource.inputs.interpolationMapping = interpolationMapping datasource.inputs.sort_filelist = True - """ 5. Template is initialized by a simple average in this simple example, any reference image could be used (i.e. a previously created template) @@ -127,37 +154,53 @@ initAvg.inputs.normalize = True tbuilder.connect(datasource, "InitialTemplateInputs", initAvg, "images") - """ 6. Define the first iteration of template building """ -buildTemplateIteration1 = antsRegistrationTemplateBuildSingleIterationWF('iteration01') - +buildTemplateIteration1 = antsRegistrationTemplateBuildSingleIterationWF( + 'iteration01') """ Here we are fine tuning parameters of the SGE job (memory limit, numebr of cores etc.) """ BeginANTS = buildTemplateIteration1.get_node("BeginANTS") -BeginANTS.plugin_args = {'qsub_args': '-S /bin/bash -pe smp1 8-12 -l mem_free=6000M -o /dev/null -e /dev/null queue_name', 'overwrite': True} - -tbuilder.connect(initAvg, 'output_average_image', buildTemplateIteration1, 'inputspec.fixed_image') -tbuilder.connect(datasource, 'ListOfImagesDictionaries', buildTemplateIteration1, 'inputspec.ListOfImagesDictionaries') -tbuilder.connect(datasource, 'registrationImageTypes', buildTemplateIteration1, 'inputspec.registrationImageTypes') -tbuilder.connect(datasource, 'interpolationMapping', buildTemplateIteration1, 'inputspec.interpolationMapping') - +BeginANTS.plugin_args = { + 'qsub_args': + '-S /bin/bash -pe smp1 8-12 -l mem_free=6000M -o /dev/null -e /dev/null queue_name', + 'overwrite': + True +} + +tbuilder.connect(initAvg, 'output_average_image', buildTemplateIteration1, + 'inputspec.fixed_image') +tbuilder.connect(datasource, 'ListOfImagesDictionaries', + buildTemplateIteration1, 'inputspec.ListOfImagesDictionaries') +tbuilder.connect(datasource, 'registrationImageTypes', buildTemplateIteration1, + 'inputspec.registrationImageTypes') +tbuilder.connect(datasource, 'interpolationMapping', buildTemplateIteration1, + 'inputspec.interpolationMapping') """ 7. Define the second iteration of template building """ -buildTemplateIteration2 = antsRegistrationTemplateBuildSingleIterationWF('iteration02') +buildTemplateIteration2 = antsRegistrationTemplateBuildSingleIterationWF( + 'iteration02') BeginANTS = buildTemplateIteration2.get_node("BeginANTS") -BeginANTS.plugin_args = {'qsub_args': '-S /bin/bash -pe smp1 8-12 -l mem_free=6000M -o /dev/null -e /dev/null queue_name', 'overwrite': True} -tbuilder.connect(buildTemplateIteration1, 'outputspec.template', buildTemplateIteration2, 'inputspec.fixed_image') -tbuilder.connect(datasource, 'ListOfImagesDictionaries', buildTemplateIteration2, 'inputspec.ListOfImagesDictionaries') -tbuilder.connect(datasource, 'registrationImageTypes', buildTemplateIteration2, 'inputspec.registrationImageTypes') -tbuilder.connect(datasource, 'interpolationMapping', buildTemplateIteration2, 'inputspec.interpolationMapping') - +BeginANTS.plugin_args = { + 'qsub_args': + '-S /bin/bash -pe smp1 8-12 -l mem_free=6000M -o /dev/null -e /dev/null queue_name', + 'overwrite': + True +} +tbuilder.connect(buildTemplateIteration1, 'outputspec.template', + buildTemplateIteration2, 'inputspec.fixed_image') +tbuilder.connect(datasource, 'ListOfImagesDictionaries', + buildTemplateIteration2, 'inputspec.ListOfImagesDictionaries') +tbuilder.connect(datasource, 'registrationImageTypes', buildTemplateIteration2, + 'inputspec.registrationImageTypes') +tbuilder.connect(datasource, 'interpolationMapping', buildTemplateIteration2, + 'inputspec.interpolationMapping') """ 8. Move selected files to a designated results folder """ @@ -165,10 +208,13 @@ datasink = pe.Node(io.DataSink(), name="datasink") datasink.inputs.base_directory = os.path.join(requestedPath, "results") -tbuilder.connect(buildTemplateIteration2, 'outputspec.template', datasink, 'PrimaryTemplate') -tbuilder.connect(buildTemplateIteration2, 'outputspec.passive_deformed_templates', datasink, 'PassiveTemplate') -tbuilder.connect(initAvg, 'output_average_image', datasink, 'PreRegisterAverage') - +tbuilder.connect(buildTemplateIteration2, 'outputspec.template', datasink, + 'PrimaryTemplate') +tbuilder.connect(buildTemplateIteration2, + 'outputspec.passive_deformed_templates', datasink, + 'PassiveTemplate') +tbuilder.connect(initAvg, 'output_average_image', datasink, + 'PreRegisterAverage') """ 9. Run the workflow """ diff --git a/examples/smri_cbs_skullstripping.py b/examples/smri_cbs_skullstripping.py index 16fe3de000..1471496576 100644 --- a/examples/smri_cbs_skullstripping.py +++ b/examples/smri_cbs_skullstripping.py @@ -6,19 +6,21 @@ sMRI: USing CBS Tools for skullstripping ======================================== -This simple workflow uses SPECTRE2010 algorithm to skullstrip an MP2RAGE anatomical scan. +This simple workflow uses SPECTRE2010 algorithm to skullstrip an MP2RAGE +anatomical scan. """ - import nipype.pipeline.engine as pe -from nipype.interfaces.mipav.developer import JistIntensityMp2rageMasking, MedicAlgorithmSPECTRE2010 +from nipype.interfaces.mipav.developer import (JistIntensityMp2rageMasking, + MedicAlgorithmSPECTRE2010) wf = pe.Workflow("skullstripping") mask = pe.Node(JistIntensityMp2rageMasking(), name="masking") -mask.inputs.inSecond = "/Users/filo/7t_trt/niftis/sub001/session_1/MP2RAGE_INV2.nii.gz" -mask.inputs.inQuantitative = "/Users/filo/7t_trt/niftis/sub001/session_1/MP2RAGE_UNI.nii.gz" -mask.inputs.inT1weighted = "/Users/filo/7t_trt/niftis/sub001/session_1/MP2RAGE_T1.nii.gz" +folder_path = '/Users/filo/7t_trt/niftis/sub001/session_1/' +mask.inputs.inSecond = folder_path + "MP2RAGE_INV2.nii.gz" +mask.inputs.inQuantitative = folder_path + "MP2RAGE_UNI.nii.gz" +mask.inputs.inT1weighted = folder_path + "MP2RAGE_T1.nii.gz" mask.inputs.outMasked = True mask.inputs.outMasked2 = True mask.inputs.outSignal = True diff --git a/examples/smri_freesurfer.py b/examples/smri_freesurfer.py index 80959f0b0a..d365b44dd5 100644 --- a/examples/smri_freesurfer.py +++ b/examples/smri_freesurfer.py @@ -19,22 +19,20 @@ from nipype.interfaces.freesurfer.preprocess import ReconAll from nipype.interfaces.freesurfer.utils import MakeAverageSubject - subject_list = ['s1', 's3'] data_dir = os.path.abspath('data') subjects_dir = os.path.abspath('amri_freesurfer_tutorial/subjects_dir') wf = pe.Workflow(name="l1workflow") wf.base_dir = os.path.abspath('amri_freesurfer_tutorial/workdir') - """ Grab data """ -datasource = pe.MapNode(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['struct']), - name='datasource', - iterfield=['subject_id']) +datasource = pe.MapNode( + interface=nio.DataGrabber(infields=['subject_id'], outfields=['struct']), + name='datasource', + iterfield=['subject_id']) datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = dict(struct=[['subject_id', 'struct']]) @@ -44,15 +42,16 @@ Run recon-all """ -recon_all = pe.MapNode(interface=ReconAll(), name='recon_all', - iterfield=['subject_id', 'T1_files']) +recon_all = pe.MapNode( + interface=ReconAll(), + name='recon_all', + iterfield=['subject_id', 'T1_files']) recon_all.inputs.subject_id = subject_list if not os.path.exists(subjects_dir): os.mkdir(subjects_dir) recon_all.inputs.subjects_dir = subjects_dir wf.connect(datasource, 'struct', recon_all, 'T1_files') - """ Make average subject """ diff --git a/examples/smri_fsreconall.py b/examples/smri_fsreconall.py index 970d4a513a..6a9fc5446b 100644 --- a/examples/smri_fsreconall.py +++ b/examples/smri_fsreconall.py @@ -23,7 +23,6 @@ from nipype.workflows.smri.freesurfer import create_reconall_workflow from nipype.interfaces.freesurfer.utils import MakeAverageSubject from nipype.interfaces.utility import IdentityInterface - """ Assign the tutorial directory """ @@ -31,7 +30,6 @@ tutorial_dir = os.path.abspath('smri_fsreconall_tutorial') if not os.path.isdir(tutorial_dir): os.mkdir(tutorial_dir) - """ Define the workflow directories """ @@ -44,22 +42,20 @@ wf = pe.Workflow(name="l1workflow") wf.base_dir = os.path.join(tutorial_dir, 'workdir') - """ Create inputspec """ -inputspec = pe.Node(interface=IdentityInterface(['subject_id']), - name="inputspec") +inputspec = pe.Node( + interface=IdentityInterface(['subject_id']), name="inputspec") inputspec.iterables = ("subject_id", subject_list) - """ Grab data """ -datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'], - outfields=['struct']), - name='datasource') +datasource = pe.Node( + interface=nio.DataGrabber(infields=['subject_id'], outfields=['struct']), + name='datasource') datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = dict(struct=[['subject_id', 'struct']]) @@ -67,7 +63,6 @@ datasource.inputs.sort_filelist = True wf.connect(inputspec, 'subject_id', datasource, 'subject_id') - """ Run recon-all """ @@ -77,17 +72,18 @@ wf.connect(datasource, 'struct', recon_all, 'inputspec.T1_files') wf.connect(inputspec, 'subject_id', recon_all, 'inputspec.subject_id') - """ Make average subject """ -average = pe.JoinNode(interface=MakeAverageSubject(), - joinsource="inputspec", - joinfield="subjects_ids", - name="average") +average = pe.JoinNode( + interface=MakeAverageSubject(), + joinsource="inputspec", + joinfield="subjects_ids", + name="average") average.inputs.subjects_dir = subjects_dir -wf.connect(recon_all, 'postdatasink_outputspec.subject_id', average, 'subjects_ids') +wf.connect(recon_all, 'postdatasink_outputspec.subject_id', average, + 'subjects_ids') wf.run("MultiProc", plugin_args={'n_procs': 4}) diff --git a/examples/tessellation_tutorial.py b/examples/tessellation_tutorial.py index dcd0328120..832ad9cad2 100644 --- a/examples/tessellation_tutorial.py +++ b/examples/tessellation_tutorial.py @@ -34,13 +34,12 @@ Import the necessary modules and workflow from nipype. """ -import nipype.pipeline.engine as pe # pypeline engine +import nipype.pipeline.engine as pe # pypeline engine import nipype.interfaces.cmtk as cmtk -import nipype.interfaces.io as nio # Data i/o +import nipype.interfaces.io as nio # Data i/o import os import os.path as op from nipype.workflows.smri.freesurfer import create_tessellation_flow - """ Directories =========== @@ -52,7 +51,6 @@ lookup_file = op.join(fs_dir, 'FreeSurferColorLUT.txt') subjects_dir = op.join(fs_dir, 'subjects/') output_dir = './tessellate_tutorial' - """ Inputs ====== @@ -69,7 +67,6 @@ tessflow.inputs.inputspec.subject_id = 'fsaverage' tessflow.inputs.inputspec.subjects_dir = subjects_dir tessflow.inputs.inputspec.lookup_file = lookup_file - """ We also create a conditional node to package the surfaces for ConnectomeViewer. Simply set cff to "False" to ignore this step. @@ -90,7 +87,6 @@ datasink = pe.Node(interface=nio.DataSink(), name="datasink") datasink.inputs.base_directory = 'meshes' datasink.inputs.regexp_substitutions = [('_smoother[\d]*/', '')] - """ Execution ========= @@ -100,15 +96,16 @@ tesspipe = pe.Workflow(name='tessellate_tutorial') tesspipe.base_dir = output_dir -tesspipe.connect([(tessflow, datasink, [('outputspec.meshes', '@meshes.all')])]) - +tesspipe.connect([(tessflow, datasink, [('outputspec.meshes', + '@meshes.all')])]) """ If the surfaces are to be packaged, this will connect the CFFConverter node to the tessellation and smoothing workflow, as well as to the datasink. """ if cff: - tesspipe.connect([(tessflow, cff, [('outputspec.meshes', 'gifti_surfaces')])]) + tesspipe.connect([(tessflow, cff, [('outputspec.meshes', + 'gifti_surfaces')])]) tesspipe.connect([(cff, datasink, [('connectome_file', '@cff')])]) tesspipe.run() diff --git a/examples/test_spm.py b/examples/test_spm.py index 1242102f1b..4c31f144ed 100644 --- a/examples/test_spm.py +++ b/examples/test_spm.py @@ -13,6 +13,7 @@ def _get_first(inlist): return inlist[0] return inlist + def test_spm(name='test_spm_3d'): """ A simple workflow to test SPM's installation. By default will split the 4D volume in @@ -20,42 +21,57 @@ def test_spm(name='test_spm_3d'): """ workflow = pe.Workflow(name=name) - inputnode = pe.Node(niu.IdentityInterface(fields=['in_data']), name='inputnode') - dgr = pe.Node(nio.DataGrabber(template="feeds/data/fmri.nii.gz", outfields=['out_file'], - sort_filelist=False), name='datasource') + inputnode = pe.Node( + niu.IdentityInterface(fields=['in_data']), name='inputnode') + dgr = pe.Node( + nio.DataGrabber( + template="feeds/data/fmri.nii.gz", + outfields=['out_file'], + sort_filelist=False), + name='datasource') - stc = pe.Node(spm.SliceTiming( - num_slices=21, time_repetition=1.0, time_acquisition=2. - 2. / 32, - slice_order=list(range(21, 0, -1)), ref_slice=10), name='stc') - realign_estimate = pe.Node(spm.Realign(jobtype='estimate'), name='realign_estimate') + stc = pe.Node( + spm.SliceTiming( + num_slices=21, + time_repetition=1.0, + time_acquisition=2. - 2. / 32, + slice_order=list(range(21, 0, -1)), + ref_slice=10), + name='stc') + realign_estimate = pe.Node( + spm.Realign(jobtype='estimate'), name='realign_estimate') realign_write = pe.Node(spm.Realign(jobtype='write'), name='realign_write') - realign_estwrite = pe.Node(spm.Realign(jobtype='estwrite'), name='realign_estwrite') + realign_estwrite = pe.Node( + spm.Realign(jobtype='estwrite'), name='realign_estwrite') smooth = pe.Node(spm.Smooth(fwhm=[6, 6, 6]), name='smooth') - if name == 'test_spm_3d': - split = pe.Node(fsl.Split(dimension="t", output_type="NIFTI"), name="split") - workflow.connect([ - (dgr, split, [(('out_file', _get_first), 'in_file')]), - (split, stc, [("out_files", "in_files")])]) + split = pe.Node( + fsl.Split(dimension="t", output_type="NIFTI"), name="split") + workflow.connect([(dgr, split, [(('out_file', _get_first), + 'in_file')]), + (split, stc, [("out_files", "in_files")])]) elif name == 'test_spm_4d': gunzip = pe.Node(Gunzip(), name="gunzip") - workflow.connect([ - (dgr, gunzip, [(('out_file', _get_first), 'in_file')]), - (gunzip, stc, [("out_file", "in_files")]) - ]) + workflow.connect([(dgr, gunzip, [(('out_file', _get_first), + 'in_file')]), + (gunzip, stc, [("out_file", "in_files")])]) else: - raise NotImplementedError('No implementation of the test workflow \'{}\' was found'.format( - name)) - - workflow.connect([ - (inputnode, dgr, [('in_data', 'base_directory')]), - (stc, realign_estimate, [('timecorrected_files', 'in_files')]), - (realign_estimate, realign_write, [('modified_in_files', 'in_files')]), - (stc, realign_estwrite, [('timecorrected_files', 'in_files')]), - (realign_write, smooth, [('realigned_files', 'in_files')]) - ]) + raise NotImplementedError( + 'No implementation of the test workflow \'{}\' was found'.format( + name)) + + workflow.connect([(inputnode, dgr, [('in_data', 'base_directory')]), + (stc, realign_estimate, + [('timecorrected_files', + 'in_files')]), (realign_estimate, realign_write, + [('modified_in_files', 'in_files')]), + (stc, realign_estwrite, + [('timecorrected_files', + 'in_files')]), (realign_write, smooth, + [('realigned_files', 'in_files')])]) return workflow + workflow3d = test_spm() workflow4d = test_spm(name='test_spm_4d') diff --git a/examples/workshop_dartmouth_2010.py b/examples/workshop_dartmouth_2010.py index 055ae8d57d..931a633c52 100644 --- a/examples/workshop_dartmouth_2010.py +++ b/examples/workshop_dartmouth_2010.py @@ -102,7 +102,6 @@ import nipype.interfaces.fsl as fsl result = fsl.BET(in_file='data/s1/struct.nii').run() print(result) - """ Running a single program is not much of a breakthrough. Lets run motion correction followed by smoothing (isotropic - in other words not using SUSAN). Notice that in the first line we are setting the output data type @@ -112,7 +111,6 @@ fsl.FSLCommand.set_default_output_type('NIFTI_GZ') result1 = fsl.MCFLIRT(in_file='data/s1/f3.nii').run() result2 = fsl.Smooth(in_file='f3_mcf.nii.gz', fwhm=6).run() - """ Simple workflow --------------- @@ -127,18 +125,18 @@ import nipype.pipeline.engine as pe import os -motion_correct = pe.Node(interface=fsl.MCFLIRT(in_file=os.path.abspath('data/s1/f3.nii')), - name="motion_correct") +motion_correct = pe.Node( + interface=fsl.MCFLIRT(in_file=os.path.abspath('data/s1/f3.nii')), + name="motion_correct") smooth = pe.Node(interface=fsl.Smooth(fwhm=6), name="smooth") motion_correct_and_smooth = pe.Workflow(name="motion_correct_and_smooth") -motion_correct_and_smooth.base_dir = os.path.abspath('.') # define where will be the root folder for the workflow -motion_correct_and_smooth.connect([ - (motion_correct, smooth, [('out_file', 'in_file')]) -]) +motion_correct_and_smooth.base_dir = os.path.abspath( + '.') # define where will be the root folder for the workflow +motion_correct_and_smooth.connect([(motion_correct, smooth, [('out_file', + 'in_file')])]) # we are connecting 'out_file' output of motion_correct to 'in_file' input of smooth motion_correct_and_smooth.run() - """ Another workflow ---------------- @@ -154,14 +152,11 @@ demean = pe.Workflow(name="demean") demean.base_dir = os.path.abspath('.') -demean.connect([ - (calc_mean, subtract, [('out_file', 'in_file2')]) -]) +demean.connect([(calc_mean, subtract, [('out_file', 'in_file2')])]) demean.inputs.calc_mean.in_file = os.path.abspath('data/s1/f3.nii') demean.inputs.subtract.in_file = os.path.abspath('data/s1/f3.nii') demean.run() - """ Reusing workflows ----------------- @@ -175,16 +170,12 @@ preproc.inputs.inputspec.func = os.path.abspath('data/s1/f3.nii') preproc.inputs.inputspec.struct = os.path.abspath('data/s1/struct.nii') preproc.run() - - """ ... and we can run it again and it won't actually rerun anything because none of the parameters have changed. """ preproc.run() - - """ ... and we can change a parameter and run it again. Only the dependent nodes are rerun and that too only if the input state has changed. @@ -192,7 +183,6 @@ preproc.inputs.meanfuncmask.frac = 0.5 preproc.run() - """ Visualizing workflows 1 ----------------------- @@ -201,7 +191,6 @@ """ preproc.write_graph() - """ Datasink -------- @@ -216,12 +205,9 @@ datasink = pe.Node(interface=nio.DataSink(), name='sinker') preprocess = pe.Workflow(name='preprocout') preprocess.base_dir = os.path.abspath('.') -preprocess.connect([ - (preproc, datasink, [('meanfunc2.out_file', 'meanfunc'), - ('maskfunc3.out_file', 'funcruns')]) -]) +preprocess.connect([(preproc, datasink, [('meanfunc2.out_file', 'meanfunc'), + ('maskfunc3.out_file', 'funcruns')])]) preprocess.run() - """ Datagrabber ----------- @@ -256,7 +242,6 @@ datasource4.inputs.subject_id = ['s1', 's3'] results = datasource4.run() print(results.outputs) - """ Iterables --------- @@ -266,14 +251,17 @@ """ import nipype.interfaces.utility as util -infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']), - name="infosource") +infosource = pe.Node( + interface=util.IdentityInterface(fields=['subject_id']), name="infosource") infosource.iterables = ('subject_id', ['s1', 's3']) -datasource = pe.Node(nio.DataGrabber(infields=['subject_id'], outfields=['func', 'struct']), name="datasource") +datasource = pe.Node( + nio.DataGrabber(infields=['subject_id'], outfields=['func', 'struct']), + name="datasource") datasource.inputs.template = '%s/%s.nii' datasource.inputs.base_directory = os.path.abspath('data') -datasource.inputs.template_args = dict(func=[['subject_id', 'f3']], struct=[['subject_id', 'struct']]) +datasource.inputs.template_args = dict( + func=[['subject_id', 'f3']], struct=[['subject_id', 'struct']]) datasource.inputs.sort_filelist = True my_workflow = pe.Workflow(name="my_workflow") @@ -283,18 +271,15 @@ (datasource, preproc, [('func', 'inputspec.func'), ('struct', 'inputspec.struct')])]) my_workflow.run() - - """ and we can change a node attribute and run it again """ smoothnode = my_workflow.get_node('preproc.smooth') -assert(str(smoothnode) == 'preproc.smooth') +assert (str(smoothnode) == 'preproc.smooth') smoothnode.iterables = ('fwhm', [5., 10.]) my_workflow.run() - """ Visualizing workflows 2 ----------------------- diff --git a/nipype/__init__.py b/nipype/__init__.py index f761a8ef09..a15b2721bd 100644 --- a/nipype/__init__.py +++ b/nipype/__init__.py @@ -1,15 +1,14 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from distutils.version import LooseVersion -from .info import (LONG_DESCRIPTION as __doc__, - URL as __url__, - STATUS as __status__, - __version__) +from .info import (LONG_DESCRIPTION as __doc__, URL as __url__, STATUS as + __status__, __version__) from .utils.config import NipypeConfig from .utils.logger import Logging from .refs import due @@ -30,15 +29,17 @@ def __call__(self, doctests=True): try: import pytest except: - raise RuntimeError('py.test not installed, run: pip install pytest') + raise RuntimeError( + 'py.test not installed, run: pip install pytest') params = {'args': []} if doctests: params['args'].append('--doctest-modules') nipype_path = os.path.dirname(__file__) - params['args'].extend(['-x', '--ignore={}/external'.format(nipype_path), - nipype_path]) + params['args'].extend( + ['-x', '--ignore={}/external'.format(nipype_path), nipype_path]) pytest.main(**params) + test = NipypeTester() @@ -46,6 +47,7 @@ def get_info(): """Returns package information""" return _get_pkg_info(os.path.dirname(__file__)) + from .pipeline import Node, MapNode, JoinNode, Workflow -from .interfaces import (DataGrabber, DataSink, SelectFiles, - IdentityInterface, Rename, Function, Select, Merge) +from .interfaces import (DataGrabber, DataSink, SelectFiles, IdentityInterface, + Rename, Function, Select, Merge) diff --git a/nipype/algorithms/confounds.py b/nipype/algorithms/confounds.py index 4bb0ddeac6..10985edc6f 100644 --- a/nipype/algorithms/confounds.py +++ b/nipype/algorithms/confounds.py @@ -11,7 +11,8 @@ >>> os.chdir(datadir) ''' -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range import os @@ -34,36 +35,41 @@ class ComputeDVARSInputSpec(BaseInterfaceInputSpec): - in_file = File(exists=True, mandatory=True, desc='functional data, after HMC') + in_file = File( + exists=True, mandatory=True, desc='functional data, after HMC') in_mask = File(exists=True, mandatory=True, desc='a brain mask') - remove_zerovariance = traits.Bool(True, usedefault=True, - desc='remove voxels with zero variance') - save_std = traits.Bool(True, usedefault=True, - desc='save standardized DVARS') - save_nstd = traits.Bool(False, usedefault=True, - desc='save non-standardized DVARS') - save_vxstd = traits.Bool(False, usedefault=True, - desc='save voxel-wise standardized DVARS') + remove_zerovariance = traits.Bool( + True, usedefault=True, desc='remove voxels with zero variance') + save_std = traits.Bool( + True, usedefault=True, desc='save standardized DVARS') + save_nstd = traits.Bool( + False, usedefault=True, desc='save non-standardized DVARS') + save_vxstd = traits.Bool( + False, usedefault=True, desc='save voxel-wise standardized DVARS') save_all = traits.Bool(False, usedefault=True, desc='output all DVARS') series_tr = traits.Float(desc='repetition time in sec.') save_plot = traits.Bool(False, usedefault=True, desc='write DVARS plot') figdpi = traits.Int(100, usedefault=True, desc='output dpi for the plot') - figsize = traits.Tuple(traits.Float(11.7), traits.Float(2.3), usedefault=True, - desc='output figure size') - figformat = traits.Enum('png', 'pdf', 'svg', usedefault=True, - desc='output format for figures') - intensity_normalization = traits.Float(1000.0, usedefault=True, - desc='Divide value in each voxel at each timepoint ' - 'by the median calculated across all voxels' - 'and timepoints within the mask (if specified)' - 'and then multiply by the value specified by' - 'this parameter. By using the default (1000)' \ - 'output DVARS will be expressed in ' \ - 'x10 % BOLD units compatible with Power et al.' \ - '2012. Set this to 0 to disable intensity' \ - 'normalization altogether.') - + figsize = traits.Tuple( + traits.Float(11.7), + traits.Float(2.3), + usedefault=True, + desc='output figure size') + figformat = traits.Enum( + 'png', 'pdf', 'svg', usedefault=True, desc='output format for figures') + intensity_normalization = traits.Float( + 1000.0, + usedefault=True, + desc='Divide value in each voxel at each timepoint ' + 'by the median calculated across all voxels' + 'and timepoints within the mask (if specified)' + 'and then multiply by the value specified by' + 'this parameter. By using the default (1000)' + 'output DVARS will be expressed in ' + 'x10 % BOLD units compatible with Power et al.' + '2012. Set this to 0 to disable intensity' + 'normalization altogether.') class ComputeDVARSOutputSpec(TraitedSpec): @@ -86,7 +92,8 @@ class ComputeDVARS(BaseInterface): input_spec = ComputeDVARSInputSpec output_spec = ComputeDVARSOutputSpec references_ = [{ - 'entry': BibTeX("""\ + 'entry': + BibTeX("""\ @techreport{nichols_notes_2013, address = {Coventry, UK}, title = {Notes on {Creating} a {Standardized} {Version} of {DVARS}}, @@ -99,7 +106,8 @@ class ComputeDVARS(BaseInterface): }"""), 'tags': ['method'] }, { - 'entry': BibTeX("""\ + 'entry': + BibTeX("""\ @article{power_spurious_2012, title = {Spurious but systematic correlations in functional connectivity {MRI} networks \ arise from subject motion}, @@ -122,8 +130,7 @@ def __init__(self, **inputs): super(ComputeDVARS, self).__init__(**inputs) def _gen_fname(self, suffix, ext=None): - fname, in_ext = op.splitext(op.basename( - self.inputs.in_file)) + fname, in_ext = op.splitext(op.basename(self.inputs.in_file)) if in_ext == '.gz': fname, in_ext2 = op.splitext(fname) @@ -138,13 +145,15 @@ def _gen_fname(self, suffix, ext=None): return op.abspath('{}_{}.{}'.format(fname, suffix, ext)) def _run_interface(self, runtime): - dvars = compute_dvars(self.inputs.in_file, self.inputs.in_mask, - remove_zerovariance=self.inputs.remove_zerovariance, - intensity_normalization=self.inputs.intensity_normalization) + dvars = compute_dvars( + self.inputs.in_file, + self.inputs.in_mask, + remove_zerovariance=self.inputs.remove_zerovariance, + intensity_normalization=self.inputs.intensity_normalization) - (self._results['avg_std'], - self._results['avg_nstd'], - self._results['avg_vxstd']) = np.mean(dvars, axis=1).astype(float) + (self._results['avg_std'], self._results['avg_nstd'], + self._results['avg_vxstd']) = np.mean( + dvars, axis=1).astype(float) tr = None if isdefined(self.inputs.series_tr): @@ -158,11 +167,16 @@ def _run_interface(self, runtime): if self.inputs.save_plot: self._results['fig_std'] = self._gen_fname( 'dvars_std', ext=self.inputs.figformat) - fig = plot_confound(dvars[0], self.inputs.figsize, 'Standardized DVARS', - series_tr=tr) - fig.savefig(self._results['fig_std'], dpi=float(self.inputs.figdpi), - format=self.inputs.figformat, - bbox_inches='tight') + fig = plot_confound( + dvars[0], + self.inputs.figsize, + 'Standardized DVARS', + series_tr=tr) + fig.savefig( + self._results['fig_std'], + dpi=float(self.inputs.figdpi), + format=self.inputs.figformat, + bbox_inches='tight') fig.clf() if self.inputs.save_nstd: @@ -173,10 +187,13 @@ def _run_interface(self, runtime): if self.inputs.save_plot: self._results['fig_nstd'] = self._gen_fname( 'dvars_nstd', ext=self.inputs.figformat) - fig = plot_confound(dvars[1], self.inputs.figsize, 'DVARS', series_tr=tr) - fig.savefig(self._results['fig_nstd'], dpi=float(self.inputs.figdpi), - format=self.inputs.figformat, - bbox_inches='tight') + fig = plot_confound( + dvars[1], self.inputs.figsize, 'DVARS', series_tr=tr) + fig.savefig( + self._results['fig_nstd'], + dpi=float(self.inputs.figdpi), + format=self.inputs.figformat, + bbox_inches='tight') fig.clf() if self.inputs.save_vxstd: @@ -187,17 +204,27 @@ def _run_interface(self, runtime): if self.inputs.save_plot: self._results['fig_vxstd'] = self._gen_fname( 'dvars_vxstd', ext=self.inputs.figformat) - fig = plot_confound(dvars[2], self.inputs.figsize, 'Voxelwise std DVARS', - series_tr=tr) - fig.savefig(self._results['fig_vxstd'], dpi=float(self.inputs.figdpi), - format=self.inputs.figformat, - bbox_inches='tight') + fig = plot_confound( + dvars[2], + self.inputs.figsize, + 'Voxelwise std DVARS', + series_tr=tr) + fig.savefig( + self._results['fig_vxstd'], + dpi=float(self.inputs.figdpi), + format=self.inputs.figformat, + bbox_inches='tight') fig.clf() if self.inputs.save_all: out_file = self._gen_fname('dvars', ext='tsv') - np.savetxt(out_file, np.vstack(dvars).T, fmt=b'%0.8f', delimiter=b'\t', - header='std DVARS\tnon-std DVARS\tvx-wise std DVARS', comments='') + np.savetxt( + out_file, + np.vstack(dvars).T, + fmt=b'%0.8f', + delimiter=b'\t', + header='std DVARS\tnon-std DVARS\tvx-wise std DVARS', + comments='') self._results['out_all'] = out_file return runtime @@ -208,20 +235,34 @@ def _list_outputs(self): class FramewiseDisplacementInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True, desc='motion parameters') - parameter_source = traits.Enum("FSL", "AFNI", "SPM", "FSFAST", "NIPY", - desc="Source of movement parameters", - mandatory=True) - radius = traits.Float(50, usedefault=True, - desc='radius in mm to calculate angular FDs, 50mm is the ' - 'default since it is used in Power et al. 2012') - out_file = File('fd_power_2012.txt', usedefault=True, desc='output file name') - out_figure = File('fd_power_2012.pdf', usedefault=True, desc='output figure name') + parameter_source = traits.Enum( + "FSL", + "AFNI", + "SPM", + "FSFAST", + "NIPY", + desc="Source of movement parameters", + mandatory=True) + radius = traits.Float( + 50, + usedefault=True, + desc='radius in mm to calculate angular FDs, 50mm is the ' + 'default since it is used in Power et al. 2012') + out_file = File( + 'fd_power_2012.txt', usedefault=True, desc='output file name') + out_figure = File( + 'fd_power_2012.pdf', usedefault=True, desc='output figure name') series_tr = traits.Float(desc='repetition time in sec.') save_plot = traits.Bool(False, usedefault=True, desc='write FD plot') - normalize = traits.Bool(False, usedefault=True, desc='calculate FD in mm/s') - figdpi = traits.Int(100, usedefault=True, desc='output dpi for the FD plot') - figsize = traits.Tuple(traits.Float(11.7), traits.Float(2.3), usedefault=True, - desc='output figure size') + normalize = traits.Bool( + False, usedefault=True, desc='calculate FD in mm/s') + figdpi = traits.Int( + 100, usedefault=True, desc='output dpi for the FD plot') + figsize = traits.Tuple( + traits.Float(11.7), + traits.Float(2.3), + usedefault=True, + desc='output figure size') class FramewiseDisplacementOutputSpec(TraitedSpec): @@ -247,7 +288,8 @@ class FramewiseDisplacement(BaseInterface): output_spec = FramewiseDisplacementOutputSpec references_ = [{ - 'entry': BibTeX("""\ + 'entry': + BibTeX("""\ @article{power_spurious_2012, title = {Spurious but systematic correlations in functional connectivity {MRI} networks \ arise from subject motion}, @@ -267,9 +309,11 @@ class FramewiseDisplacement(BaseInterface): def _run_interface(self, runtime): mpars = np.loadtxt(self.inputs.in_file) # mpars is N_t x 6 - mpars = np.apply_along_axis(func1d=normalize_mc_params, - axis=1, arr=mpars, - source=self.inputs.parameter_source) + mpars = np.apply_along_axis( + func1d=normalize_mc_params, + axis=1, + arr=mpars, + source=self.inputs.parameter_source) diff = mpars[:-1, :6] - mpars[1:, :6] diff[:, 3:6] *= self.inputs.radius fd_res = np.abs(diff).sum(axis=1) @@ -278,7 +322,11 @@ def _run_interface(self, runtime): 'out_file': op.abspath(self.inputs.out_file), 'fd_average': float(fd_res.mean()) } - np.savetxt(self.inputs.out_file, fd_res, header='FramewiseDisplacement', comments='') + np.savetxt( + self.inputs.out_file, + fd_res, + header='FramewiseDisplacement', + comments='') if self.inputs.save_plot: tr = None @@ -289,11 +337,18 @@ def _run_interface(self, runtime): IFLOGGER.warn('FD plot cannot be normalized if TR is not set') self._results['out_figure'] = op.abspath(self.inputs.out_figure) - fig = plot_confound(fd_res, self.inputs.figsize, 'FD', units='mm', - series_tr=tr, normalize=self.inputs.normalize) - fig.savefig(self._results['out_figure'], dpi=float(self.inputs.figdpi), - format=self.inputs.out_figure[-3:], - bbox_inches='tight') + fig = plot_confound( + fd_res, + self.inputs.figsize, + 'FD', + units='mm', + series_tr=tr, + normalize=self.inputs.normalize) + fig.savefig( + self._results['out_figure'], + dpi=float(self.inputs.figdpi), + format=self.inputs.out_figure[-3:], + bbox_inches='tight') fig.clf() return runtime @@ -303,56 +358,74 @@ def _list_outputs(self): class CompCorInputSpec(BaseInterfaceInputSpec): - realigned_file = File(exists=True, mandatory=True, - desc='already realigned brain image (4D)') - mask_files = InputMultiPath(File(exists=True), - desc=('One or more mask files that determines ' - 'ROI (3D). When more that one file is ' - 'provided `merge_method` or ' - '`merge_index` must be provided')) - merge_method = traits.Enum('union', 'intersect', 'none', xor=['mask_index'], - requires=['mask_files'], - desc=('Merge method if multiple masks are ' - 'present - `union` uses voxels included in' - ' at least one input mask, `intersect` ' - 'uses only voxels present in all input ' - 'masks, `none` performs CompCor on ' - 'each mask individually')) - mask_index = traits.Range(low=0, xor=['merge_method'], - requires=['mask_files'], - desc=('Position of mask in `mask_files` to use - ' - 'first is the default.')) - components_file = traits.Str('components_file.txt', usedefault=True, - desc='Filename to store physiological components') - num_components = traits.Int(6, usedefault=True) # 6 for BOLD, 4 for ASL - pre_filter = traits.Enum('polynomial', 'cosine', False, usedefault=True, - desc='Detrend time series prior to component ' - 'extraction') - use_regress_poly = traits.Bool(True, - deprecated='0.15.0', new_name='pre_filter', - desc=('use polynomial regression ' - 'pre-component extraction')) - regress_poly_degree = traits.Range(low=1, default=1, usedefault=True, - desc='the degree polynomial to use') - header_prefix = traits.Str(desc=('the desired header for the output tsv ' - 'file (one column). If undefined, will ' - 'default to "CompCor"')) + realigned_file = File( + exists=True, mandatory=True, desc='already realigned brain image (4D)') + mask_files = InputMultiPath( + File(exists=True), + desc=('One or more mask files that determines ' + 'ROI (3D). When more that one file is ' + 'provided `merge_method` or ' + '`merge_index` must be provided')) + merge_method = traits.Enum( + 'union', + 'intersect', + 'none', + xor=['mask_index'], + requires=['mask_files'], + desc=('Merge method if multiple masks are ' + 'present - `union` uses voxels included in' + ' at least one input mask, `intersect` ' + 'uses only voxels present in all input ' + 'masks, `none` performs CompCor on ' + 'each mask individually')) + mask_index = traits.Range( + low=0, + xor=['merge_method'], + requires=['mask_files'], + desc=('Position of mask in `mask_files` to use - ' + 'first is the default.')) + components_file = traits.Str( + 'components_file.txt', + usedefault=True, + desc='Filename to store physiological components') + num_components = traits.Int(6, usedefault=True) # 6 for BOLD, 4 for ASL + pre_filter = traits.Enum( + 'polynomial', + 'cosine', + False, + usedefault=True, + desc='Detrend time series prior to component ' + 'extraction') + use_regress_poly = traits.Bool( + True, + deprecated='0.15.0', + new_name='pre_filter', + desc=('use polynomial regression ' + 'pre-component extraction')) + regress_poly_degree = traits.Range( + low=1, default=1, usedefault=True, desc='the degree polynomial to use') + header_prefix = traits.Str( + desc=('the desired header for the output tsv ' + 'file (one column). If undefined, will ' + 'default to "CompCor"')) high_pass_cutoff = traits.Float( - 128, usedefault=True, + 128, + usedefault=True, desc='Cutoff (in seconds) for "cosine" pre-filter') repetition_time = traits.Float( desc='Repetition time (TR) of series - derived from image header if ' - 'unspecified') + 'unspecified') save_pre_filter = traits.Either( traits.Bool, File, desc='Save pre-filter basis as text file') ignore_initial_volumes = traits.Range( - low=0, usedefault=True, + low=0, + usedefault=True, desc='Number of volumes at start of series to ignore') class CompCorOutputSpec(TraitedSpec): - components_file = File(exists=True, - desc='text file containing the noise components') + components_file = File( + exists=True, desc='text file containing the noise components') pre_filter_file = File(desc='text file containing high-pass filter basis') @@ -393,19 +466,21 @@ class CompCor(BaseInterface): """ input_spec = CompCorInputSpec output_spec = CompCorOutputSpec - references_ = [{'entry': BibTeX("@article{compcor_2007," - "title = {A component based noise correction method (CompCor) for BOLD and perfusion based}," - "volume = {37}," - "number = {1}," - "doi = {10.1016/j.neuroimage.2007.04.042}," - "urldate = {2016-08-13}," - "journal = {NeuroImage}," - "author = {Behzadi, Yashar and Restom, Khaled and Liau, Joy and Liu, Thomas T.}," - "year = {2007}," - "pages = {90-101},}" - ), - 'tags': ['method', 'implementation'] - }] + references_ = [{ + 'entry': + BibTeX( + "@article{compcor_2007," + "title = {A component based noise correction method (CompCor) for BOLD and perfusion based}," + "volume = {37}," + "number = {1}," + "doi = {10.1016/j.neuroimage.2007.04.042}," + "urldate = {2016-08-13}," + "journal = {NeuroImage}," + "author = {Behzadi, Yashar and Restom, Khaled and Liau, Joy and Liu, Thomas T.}," + "year = {2007}," + "pages = {90-101},}"), + 'tags': ['method', 'implementation'] + }] def __init__(self, *args, **kwargs): ''' exactly the same as compcor except the header ''' @@ -423,21 +498,22 @@ def _run_interface(self, runtime): self.inputs.pre_filter = 'polynomial' # Degree 0 == remove mean; see compute_noise_components - degree = (self.inputs.regress_poly_degree if - self.inputs.pre_filter == 'polynomial' else 0) + degree = (self.inputs.regress_poly_degree + if self.inputs.pre_filter == 'polynomial' else 0) imgseries = nb.load(self.inputs.realigned_file, mmap=NUMPY_MMAP) if len(imgseries.shape) != 4: raise ValueError('{} expected a 4-D nifti file. Input {} has ' '{} dimensions (shape {})'.format( - self._header, self.inputs.realigned_file, - len(imgseries.shape), imgseries.shape)) + self._header, self.inputs.realigned_file, + len(imgseries.shape), imgseries.shape)) if len(mask_images) == 0: - img = nb.Nifti1Image(np.ones(imgseries.shape[:3], dtype=np.bool), - affine=imgseries.affine, - header=imgseries.header) + img = nb.Nifti1Image( + np.ones(imgseries.shape[:3], dtype=np.bool), + affine=imgseries.affine, + header=imgseries.header) mask_images = [img] skip_vols = self.inputs.ignore_initial_volumes @@ -473,32 +549,47 @@ def _run_interface(self, runtime): if skip_vols: old_comp = components nrows = skip_vols + components.shape[0] - components = np.zeros((nrows, components.shape[1]), - dtype=components.dtype) + components = np.zeros( + (nrows, components.shape[1]), dtype=components.dtype) components[skip_vols:] = old_comp - components_file = os.path.join(os.getcwd(), self.inputs.components_file) - np.savetxt(components_file, components, fmt=b"%.10f", delimiter='\t', - header=self._make_headers(components.shape[1]), comments='') + components_file = os.path.join(os.getcwd(), + self.inputs.components_file) + np.savetxt( + components_file, + components, + fmt=b"%.10f", + delimiter='\t', + header=self._make_headers(components.shape[1]), + comments='') if self.inputs.pre_filter and self.inputs.save_pre_filter: pre_filter_file = self._list_outputs()['pre_filter_file'] - ftype = {'polynomial': 'Legendre', - 'cosine': 'Cosine'}[self.inputs.pre_filter] + ftype = { + 'polynomial': 'Legendre', + 'cosine': 'Cosine' + }[self.inputs.pre_filter] ncols = filter_basis.shape[1] if filter_basis.size > 0 else 0 header = ['{}{:02d}'.format(ftype, i) for i in range(ncols)] if skip_vols: old_basis = filter_basis # nrows defined above - filter_basis = np.zeros((nrows, ncols + skip_vols), - dtype=filter_basis.dtype) + filter_basis = np.zeros( + (nrows, ncols + skip_vols), dtype=filter_basis.dtype) if old_basis.size > 0: filter_basis[skip_vols:, :ncols] = old_basis filter_basis[:skip_vols, -skip_vols:] = np.eye(skip_vols) - header.extend(['NonSteadyStateOutlier{:02d}'.format(i) - for i in range(skip_vols)]) - np.savetxt(pre_filter_file, filter_basis, fmt=b'%.10f', - delimiter='\t', header='\t'.join(header), comments='') + header.extend([ + 'NonSteadyStateOutlier{:02d}'.format(i) + for i in range(skip_vols) + ]) + np.savetxt( + pre_filter_file, + filter_basis, + fmt=b'%.10f', + delimiter='\t', + header='\t'.join(header), + comments='') return runtime @@ -507,7 +598,8 @@ def _process_masks(self, mask_images, timeseries=None): def _list_outputs(self): outputs = self._outputs().get() - outputs['components_file'] = os.path.abspath(self.inputs.components_file) + outputs['components_file'] = os.path.abspath( + self.inputs.components_file) save_pre_filter = self.inputs.save_pre_filter if save_pre_filter: @@ -539,22 +631,28 @@ def __init__(self, *args, **kwargs): class TCompCorInputSpec(CompCorInputSpec): # and all the fields in CompCorInputSpec - percentile_threshold = traits.Range(low=0., high=1., value=.02, - exclude_low=True, exclude_high=True, - usedefault=True, desc='the percentile ' - 'used to select highest-variance ' - 'voxels, represented by a number ' - 'between 0 and 1, exclusive. By ' - 'default, this value is set to .02. ' - 'That is, the 2% of voxels ' - 'with the highest variance are used.') + percentile_threshold = traits.Range( + low=0., + high=1., + value=.02, + exclude_low=True, + exclude_high=True, + usedefault=True, + desc='the percentile ' + 'used to select highest-variance ' + 'voxels, represented by a number ' + 'between 0 and 1, exclusive. By ' + 'default, this value is set to .02. ' + 'That is, the 2% of voxels ' + 'with the highest variance are used.') class TCompCorOutputSpec(CompCorOutputSpec): # and all the fields in CompCorOutputSpec - high_variance_masks = OutputMultiPath(File(exists=True), - desc=(("voxels exceeding the variance" - " threshold"))) + high_variance_masks = OutputMultiPath( + File(exists=True), + desc=(("voxels exceeding the variance" + " threshold"))) class TCompCor(CompCor): @@ -591,12 +689,14 @@ def _process_masks(self, mask_images, timeseries=None): imgseries = timeseries[mask, :] imgseries = regress_poly(2, imgseries)[0] tSTD = _compute_tSTD(imgseries, 0, axis=-1) - threshold_std = np.percentile(tSTD, np.round(100. * - (1. - self.inputs.percentile_threshold)).astype(int)) + threshold_std = np.percentile( + tSTD, + np.round(100. * + (1. - self.inputs.percentile_threshold)).astype(int)) mask_data = np.zeros_like(mask) mask_data[mask != 0] = tSTD >= threshold_std - out_image = nb.Nifti1Image(mask_data, affine=img.affine, - header=img.header) + out_image = nb.Nifti1Image( + mask_data, affine=img.affine, header=img.header) # save mask mask_file = os.path.abspath('mask_{:03d}.nii.gz'.format(i)) @@ -614,17 +714,31 @@ def _list_outputs(self): class TSNRInputSpec(BaseInterfaceInputSpec): - in_file = InputMultiPath(File(exists=True), mandatory=True, - desc='realigned 4D file or a list of 3D files') + in_file = InputMultiPath( + File(exists=True), + mandatory=True, + desc='realigned 4D file or a list of 3D files') regress_poly = traits.Range(low=1, desc='Remove polynomials') - tsnr_file = File('tsnr.nii.gz', usedefault=True, hash_files=False, - desc='output tSNR file') - mean_file = File('mean.nii.gz', usedefault=True, hash_files=False, - desc='output mean file') - stddev_file = File('stdev.nii.gz', usedefault=True, hash_files=False, - desc='output tSNR file') - detrended_file = File('detrend.nii.gz', usedefault=True, hash_files=False, - desc='input file after detrending') + tsnr_file = File( + 'tsnr.nii.gz', + usedefault=True, + hash_files=False, + desc='output tSNR file') + mean_file = File( + 'mean.nii.gz', + usedefault=True, + hash_files=False, + desc='output mean file') + stddev_file = File( + 'stdev.nii.gz', + usedefault=True, + hash_files=False, + desc='output tSNR file') + detrended_file = File( + 'detrend.nii.gz', + usedefault=True, + hash_files=False, + desc='input file after detrending') class TSNROutputSpec(TraitedSpec): @@ -654,9 +768,16 @@ class TSNR(BaseInterface): def _run_interface(self, runtime): img = nb.load(self.inputs.in_file[0], mmap=NUMPY_MMAP) header = img.header.copy() - vollist = [nb.load(filename, mmap=NUMPY_MMAP) for filename in self.inputs.in_file] - data = np.concatenate([vol.get_data().reshape( - vol.shape[:3] + (-1,)) for vol in vollist], axis=3) + vollist = [ + nb.load(filename, mmap=NUMPY_MMAP) + for filename in self.inputs.in_file + ] + data = np.concatenate( + [ + vol.get_data().reshape(vol.shape[:3] + (-1, )) + for vol in vollist + ], + axis=3) data = np.nan_to_num(data) if data.dtype.kind == 'i': @@ -664,14 +785,16 @@ def _run_interface(self, runtime): data = data.astype(np.float32) if isdefined(self.inputs.regress_poly): - data = regress_poly(self.inputs.regress_poly, data, remove_mean=False)[0] + data = regress_poly( + self.inputs.regress_poly, data, remove_mean=False)[0] img = nb.Nifti1Image(data, img.affine, header) nb.save(img, op.abspath(self.inputs.detrended_file)) meanimg = np.mean(data, axis=3) stddevimg = np.std(data, axis=3) tsnr = np.zeros_like(meanimg) - tsnr[stddevimg > 1.e-3] = meanimg[stddevimg > 1.e-3] / stddevimg[stddevimg > 1.e-3] + tsnr[stddevimg > 1.e-3] = meanimg[stddevimg > 1.e-3] / stddevimg[ + stddevimg > 1.e-3] img = nb.Nifti1Image(tsnr, img.affine, header) nb.save(img, op.abspath(self.inputs.tsnr_file)) img = nb.Nifti1Image(meanimg, img.affine, header) @@ -696,7 +819,7 @@ class NonSteadyStateDetectorInputSpec(BaseInterfaceInputSpec): class NonSteadyStateDetectorOutputSpec(TraitedSpec): n_volumes_to_discard = traits.Int(desc='Number of non-steady state volumes' - 'detected in the beginning of the scan.') + 'detected in the beginning of the scan.') class NonSteadyStateDetector(BaseInterface): @@ -710,11 +833,10 @@ class NonSteadyStateDetector(BaseInterface): def _run_interface(self, runtime): in_nii = nb.load(self.inputs.in_file) - global_signal = in_nii.get_data()[:,:,:,:50].mean(axis=0).mean(axis=0).mean(axis=0) + global_signal = in_nii.get_data()[:, :, :, :50].mean(axis=0).mean( + axis=0).mean(axis=0) - self._results = { - 'n_volumes_to_discard': is_outlier(global_signal) - } + self._results = {'n_volumes_to_discard': is_outlier(global_signal)} return runtime @@ -722,7 +844,9 @@ def _list_outputs(self): return self._results -def compute_dvars(in_file, in_mask, remove_zerovariance=False, +def compute_dvars(in_file, + in_mask, + remove_zerovariance=False, intensity_normalization=1000): """ Compute the :abbr:`DVARS (D referring to temporal @@ -761,8 +885,7 @@ def compute_dvars(in_file, in_mask, remove_zerovariance=False, mask = nb.load(in_mask, mmap=NUMPY_MMAP).get_data().astype(np.uint8) if len(func.shape) != 4: - raise RuntimeError( - "Input fMRI dataset should be 4-dimensional") + raise RuntimeError("Input fMRI dataset should be 4-dimensional") idx = np.where(mask > 0) mfunc = func[idx[0], idx[1], idx[2], :] @@ -780,10 +903,10 @@ def compute_dvars(in_file, in_mask, remove_zerovariance=False, func_sd = func_sd[func_sd != 0] # Compute (non-robust) estimate of lag-1 autocorrelation - ar1 = np.apply_along_axis( - AR_est_YW, 1, - regress_poly(0, mfunc, remove_mean=True)[0].astype(np.float32), - 1)[:, 0] + ar1 = np.apply_along_axis(AR_est_YW, 1, + regress_poly(0, mfunc, + remove_mean=True)[0].astype( + np.float32), 1)[:, 0] # Compute (predicted) standard deviation of temporal difference time series diff_sdhat = np.squeeze(np.sqrt(((1 - ar1) * 2).tolist())) * func_sd @@ -809,8 +932,12 @@ def compute_dvars(in_file, in_mask, remove_zerovariance=False, return (dvars_stdz, dvars_nstd, dvars_vx_stdz) -def plot_confound(tseries, figsize, name, units=None, - series_tr=None, normalize=False): +def plot_confound(tseries, + figsize, + name, + units=None, + series_tr=None, + normalize=False): """ A helper function to plot :abbr:`fMRI (functional MRI)` confounds. @@ -874,7 +1001,7 @@ def is_outlier(points, thresh=3.5): if len(points.shape) == 1: points = points[:, None] median = np.median(points, axis=0) - diff = np.sum((points - median) ** 2, axis=-1) + diff = np.sum((points - median)**2, axis=-1) diff = np.sqrt(diff) med_abs_deviation = np.median(diff) @@ -929,7 +1056,7 @@ def regress_poly(degree, data, remove_mean=True, axis=-1): data = data.reshape((-1, timepoints)) # Generate design matrix - X = np.ones((timepoints, 1)) # quick way to calc degree 0 + X = np.ones((timepoints, 1)) # quick way to calc degree 0 for i in range(degree): polynomial_func = Legendre.basis(i + 1) value_array = np.linspace(-1, 1, timepoints) @@ -943,7 +1070,7 @@ def regress_poly(degree, data, remove_mean=True, axis=-1): # Estimation if remove_mean: datahat = X.dot(betas).T - else: # disregard the first layer of X, which is degree 0 + else: # disregard the first layer of X, which is degree 0 datahat = X[:, 1:].dot(betas[1:, ...]).T regressed_data = data - datahat @@ -1007,8 +1134,7 @@ def combine_mask_files(mask_files, mask_method=None, mask_index=None): def compute_noise_components(imgseries, mask_images, num_components, - filter_type, degree, period_cut, - repetition_time): + filter_type, degree, period_cut, repetition_time): """Compute the noise components from the imgseries for each mask imgseries: a nibabel img @@ -1072,8 +1198,7 @@ def compute_noise_components(imgseries, mask_images, num_components, if components is None: components = u[:, :num_components] else: - components = np.hstack((components, - u[:, :num_components])) + components = np.hstack((components, u[:, :num_components])) if components is None and num_components > 0: raise ValueError('No components found') return components, basis @@ -1092,6 +1217,7 @@ def _compute_tSTD(M, x, axis=0): # Nipy release: 0.4.1 # Modified for smooth integration in CompCor classes + def _cosine_drift(period_cut, frametimes): """Create a cosine drift matrix with periods greater or equals to period_cut @@ -1117,14 +1243,15 @@ def _cosine_drift(period_cut, frametimes): dt = frametimes[1] - frametimes[0] # hfcut = 1/(2*dt) yields len_time # If series is too short, return constant regressor - order = max(int(np.floor(2*len_tim*hfcut*dt)), 1) + order = max(int(np.floor(2 * len_tim * hfcut * dt)), 1) cdrift = np.zeros((len_tim, order)) - nfct = np.sqrt(2.0/len_tim) + nfct = np.sqrt(2.0 / len_tim) for k in range(1, order): - cdrift[:, k-1] = nfct * np.cos((np.pi / len_tim) * (n_times + .5) * k) + cdrift[:, k - 1] = nfct * np.cos( + (np.pi / len_tim) * (n_times + .5) * k) - cdrift[:, order-1] = 1. # or 1./sqrt(len_tim) to normalize + cdrift[:, order - 1] = 1. # or 1./sqrt(len_tim) to normalize return cdrift diff --git a/nipype/algorithms/icc.py b/nipype/algorithms/icc.py index 0b7e2987d7..133fa79745 100644 --- a/nipype/algorithms/icc.py +++ b/nipype/algorithms/icc.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range import os import numpy as np @@ -12,9 +13,10 @@ class ICCInputSpec(BaseInterfaceInputSpec): - subjects_sessions = traits.List(traits.List(File(exists=True)), - desc="n subjects m sessions 3D stat files", - mandatory=True) + subjects_sessions = traits.List( + traits.List(File(exists=True)), + desc="n subjects m sessions 3D stat files", + mandatory=True) mask = File(exists=True, mandatory=True) @@ -36,10 +38,16 @@ class ICC(BaseInterface): def _run_interface(self, runtime): maskdata = nb.load(self.inputs.mask).get_data() - maskdata = np.logical_not(np.logical_or(maskdata == 0, np.isnan(maskdata))) - - session_datas = [[nb.load(fname, mmap=NUMPY_MMAP).get_data()[maskdata].reshape(-1, 1) for fname in sessions] for sessions in self.inputs.subjects_sessions] - list_of_sessions = [np.dstack(session_data) for session_data in session_datas] + maskdata = np.logical_not( + np.logical_or(maskdata == 0, np.isnan(maskdata))) + + session_datas = [[ + nb.load(fname, mmap=NUMPY_MMAP).get_data()[maskdata].reshape( + -1, 1) for fname in sessions + ] for sessions in self.inputs.subjects_sessions] + list_of_sessions = [ + np.dstack(session_data) for session_data in session_datas + ] all_data = np.hstack(list_of_sessions) icc = np.zeros(session_datas[0][0].shape) session_F = np.zeros(session_datas[0][0].shape) @@ -48,21 +56,22 @@ def _run_interface(self, runtime): for x in range(icc.shape[0]): Y = all_data[x, :, :] - icc[x], subject_var[x], session_var[x], session_F[x], _, _ = ICC_rep_anova(Y) + icc[x], subject_var[x], session_var[x], session_F[ + x], _, _ = ICC_rep_anova(Y) nim = nb.load(self.inputs.subjects_sessions[0][0]) new_data = np.zeros(nim.shape) - new_data[maskdata] = icc.reshape(-1,) + new_data[maskdata] = icc.reshape(-1, ) new_img = nb.Nifti1Image(new_data, nim.affine, nim.header) nb.save(new_img, 'icc_map.nii') new_data = np.zeros(nim.shape) - new_data[maskdata] = session_var.reshape(-1,) + new_data[maskdata] = session_var.reshape(-1, ) new_img = nb.Nifti1Image(new_data, nim.affine, nim.header) nb.save(new_img, 'session_var_map.nii') new_data = np.zeros(nim.shape) - new_data[maskdata] = subject_var.reshape(-1,) + new_data[maskdata] = subject_var.reshape(-1, ) new_img = nb.Nifti1Image(new_data, nim.affine, nim.header) nb.save(new_img, 'subject_var_map.nii') @@ -97,7 +106,7 @@ def ICC_rep_anova(Y): # Sum Square Total mean_Y = mean(Y) - SST = ((Y - mean_Y) ** 2).sum() + SST = ((Y - mean_Y)**2).sum() # create the design matrix for the different levels x = kron(eye(nb_conditions), ones((nb_subjects, 1))) # sessions @@ -107,14 +116,14 @@ def ICC_rep_anova(Y): # Sum Square Error predicted_Y = dot(dot(dot(X, pinv(dot(X.T, X))), X.T), Y.flatten('F')) residuals = Y.flatten('F') - predicted_Y - SSE = (residuals ** 2).sum() + SSE = (residuals**2).sum() residuals.shape = Y.shape MSE = SSE / dfe # Sum square session effect - between colums/sessions - SSC = ((mean(Y, 0) - mean_Y) ** 2).sum() * nb_subjects + SSC = ((mean(Y, 0) - mean_Y)**2).sum() * nb_subjects MSC = SSC / dfc / nb_subjects session_effect_F = MSC / MSE @@ -123,7 +132,8 @@ def ICC_rep_anova(Y): SSR = SST - SSC - SSE MSR = SSR / dfr - # ICC(3,1) = (mean square subjeT - mean square error) / (mean square subjeT + (k-1)*-mean square error) + # ICC(3,1) = (mean square subjeT - mean square error) / + # (mean square subjeT + (k-1)*-mean square error) ICC = (MSR - MSE) / (MSR + dfc * MSE) e_var = MSE # variance of error diff --git a/nipype/algorithms/mesh.py b/nipype/algorithms/mesh.py index 18aa7bc864..b37826530d 100644 --- a/nipype/algorithms/mesh.py +++ b/nipype/algorithms/mesh.py @@ -12,7 +12,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import zip, str, bytes import os.path as op @@ -39,15 +40,25 @@ def __init__(self, **inputs): class WarpPointsInputSpec(BaseInterfaceInputSpec): - points = File(exists=True, mandatory=True, - desc='file containing the point set') - warp = File(exists=True, mandatory=True, - desc='dense deformation field to be applied') - interp = traits.Enum('cubic', 'nearest', 'linear', usedefault=True, - mandatory=True, desc='interpolation') - out_points = File(name_source='points', name_template='%s_warped', - output_name='out_points', keep_extension=True, - desc='the warped point set') + points = File( + exists=True, mandatory=True, desc='file containing the point set') + warp = File( + exists=True, + mandatory=True, + desc='dense deformation field to be applied') + interp = traits.Enum( + 'cubic', + 'nearest', + 'linear', + usedefault=True, + mandatory=True, + desc='interpolation') + out_points = File( + name_source='points', + name_template='%s_warped', + output_name='out_points', + keep_extension=True, + desc='the warped point set') class WarpPointsOutputSpec(TraitedSpec): @@ -110,10 +121,9 @@ def _run_interface(self, runtime): wdata = axis.get_data() if np.any(wdata != 0): - warp = ndimage.map_coordinates(wdata, - voxpoints.transpose()) + warp = ndimage.map_coordinates(wdata, voxpoints.transpose()) else: - warp = np.zeros((points.shape[0],)) + warp = np.zeros((points.shape[0], )) warps.append(warp) @@ -122,44 +132,59 @@ def _run_interface(self, runtime): mesh.points = newpoints w = tvtk.PolyDataWriter() VTKInfo.configure_input_data(w, mesh) - w.file_name = self._gen_fname(self.inputs.points, suffix='warped', ext='.vtk') + w.file_name = self._gen_fname( + self.inputs.points, suffix='warped', ext='.vtk') w.write() return runtime def _list_outputs(self): outputs = self._outputs().get() - outputs['out_points'] = self._gen_fname(self.inputs.points, suffix='warped', - ext='.vtk') + outputs['out_points'] = self._gen_fname( + self.inputs.points, suffix='warped', ext='.vtk') return outputs class ComputeMeshWarpInputSpec(BaseInterfaceInputSpec): - surface1 = File(exists=True, mandatory=True, - desc=('Reference surface (vtk format) to which compute ' - 'distance.')) - surface2 = File(exists=True, mandatory=True, - - desc=('Test surface (vtk format) from which compute ' - 'distance.')) - metric = traits.Enum('euclidean', 'sqeuclidean', usedefault=True, - desc='norm used to report distance') + surface1 = File( + exists=True, + mandatory=True, + desc=('Reference surface (vtk format) to which compute ' + 'distance.')) + surface2 = File( + exists=True, + mandatory=True, + desc=('Test surface (vtk format) from which compute ' + 'distance.')) + metric = traits.Enum( + 'euclidean', + 'sqeuclidean', + usedefault=True, + desc='norm used to report distance') weighting = traits.Enum( - 'none', 'area', usedefault=True, + 'none', + 'area', + usedefault=True, desc=('"none": no weighting is performed, surface": edge distance is ' 'weighted by the corresponding surface area')) - out_warp = File('surfwarp.vtk', usedefault=True, - desc='vtk file based on surface1 and warpings mapping it ' - 'to surface2') - out_file = File('distance.npy', usedefault=True, - desc='numpy file keeping computed distances and weights') + out_warp = File( + 'surfwarp.vtk', + usedefault=True, + desc='vtk file based on surface1 and warpings mapping it ' + 'to surface2') + out_file = File( + 'distance.npy', + usedefault=True, + desc='numpy file keeping computed distances and weights') class ComputeMeshWarpOutputSpec(TraitedSpec): distance = traits.Float(desc="computed distance") - out_warp = File(exists=True, desc=('vtk file with the vertex-wise ' - 'mapping of surface1 to surface2')) - out_file = File(exists=True, - desc='numpy file keeping computed distances and weights') + out_warp = File( + exists=True, + desc=('vtk file with the vertex-wise ' + 'mapping of surface1 to surface2')) + out_file = File( + exists=True, desc='numpy file keeping computed distances and weights') class ComputeMeshWarp(TVTKBaseInterface): @@ -203,7 +228,7 @@ def _run_interface(self, runtime): vtk2 = VTKInfo.vtk_output(r2) r1.update() r2.update() - assert(len(vtk1.points) == len(vtk2.points)) + assert (len(vtk1.points) == len(vtk2.points)) points1 = np.array(vtk1.points) points2 = np.array(vtk2.points) @@ -259,31 +284,45 @@ def _list_outputs(self): class MeshWarpMathsInputSpec(BaseInterfaceInputSpec): - in_surf = File(exists=True, mandatory=True, - desc=('Input surface in vtk format, with associated warp ' - 'field as point data (ie. from ComputeMeshWarp')) - float_trait = traits.Either(traits.Float(1.0), traits.Tuple( - traits.Float(1.0), traits.Float(1.0), traits.Float(1.0))) + in_surf = File( + exists=True, + mandatory=True, + desc=('Input surface in vtk format, with associated warp ' + 'field as point data (ie. from ComputeMeshWarp')) + float_trait = traits.Either( + traits.Float(1.0), + traits.Tuple(traits.Float(1.0), traits.Float(1.0), traits.Float(1.0))) operator = traits.Either( - float_trait, File(exists=True), default=1.0, mandatory=True, + float_trait, + File(exists=True), + default=1.0, + mandatory=True, desc='image, float or tuple of floats to act as operator') - operation = traits.Enum('sum', 'sub', 'mul', 'div', usedefault=True, - desc='operation to be performed') + operation = traits.Enum( + 'sum', + 'sub', + 'mul', + 'div', + usedefault=True, + desc='operation to be performed') - out_warp = File('warp_maths.vtk', usedefault=True, - desc='vtk file based on in_surf and warpings mapping it ' - 'to out_file') - out_file = File('warped_surf.vtk', usedefault=True, - desc='vtk with surface warped') + out_warp = File( + 'warp_maths.vtk', + usedefault=True, + desc='vtk file based on in_surf and warpings mapping it ' + 'to out_file') + out_file = File( + 'warped_surf.vtk', usedefault=True, desc='vtk with surface warped') class MeshWarpMathsOutputSpec(TraitedSpec): - out_warp = File(exists=True, desc=('vtk file with the vertex-wise ' - 'mapping of surface1 to surface2')) - out_file = File(exists=True, - desc='vtk with surface warped') + out_warp = File( + exists=True, + desc=('vtk file with the vertex-wise ' + 'mapping of surface1 to surface2')) + out_file = File(exists=True, desc='vtk with surface warped') class MeshWarpMaths(TVTKBaseInterface): @@ -327,7 +366,7 @@ def _run_interface(self, runtime): r2 = tvtk.PolyDataReader(file_name=self.inputs.surface2) vtk2 = VTKInfo.vtk_output(r2) r2.update() - assert(len(points1) == len(vtk2.points)) + assert (len(points1) == len(vtk2.points)) opfield = vtk2.point_data.vectors @@ -335,8 +374,7 @@ def _run_interface(self, runtime): opfield = vtk2.point_data.scalars if opfield is None: - raise RuntimeError( - 'No operator values found in operator file') + raise RuntimeError('No operator values found in operator file') opfield = np.array(opfield) @@ -358,13 +396,15 @@ def _run_interface(self, runtime): warping /= opfield vtk1.point_data.vectors = warping - writer = tvtk.PolyDataWriter(file_name=op.abspath(self.inputs.out_warp)) + writer = tvtk.PolyDataWriter( + file_name=op.abspath(self.inputs.out_warp)) VTKInfo.configure_input_data(writer, vtk1) writer.write() vtk1.point_data.vectors = None vtk1.points = points1 + warping - writer = tvtk.PolyDataWriter(file_name=op.abspath(self.inputs.out_file)) + writer = tvtk.PolyDataWriter( + file_name=op.abspath(self.inputs.out_file)) VTKInfo.configure_input_data(writer, vtk1) writer.write() return runtime @@ -389,5 +429,5 @@ class P2PDistance(ComputeMeshWarp): def __init__(self, **inputs): super(P2PDistance, self).__init__(**inputs) - IFLOGGER.warn('This interface has been deprecated since 1.0, please use ' - 'ComputeMeshWarp') + IFLOGGER.warn('This interface has been deprecated since 1.0, please ' + 'use ComputeMeshWarp') diff --git a/nipype/algorithms/metrics.py b/nipype/algorithms/metrics.py index 23963de679..002b2a8216 100644 --- a/nipype/algorithms/metrics.py +++ b/nipype/algorithms/metrics.py @@ -12,7 +12,8 @@ >>> os.chdir(datadir) ''' -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import zip, range import os @@ -28,22 +29,28 @@ from ..utils.misc import package_check from ..interfaces.base import (BaseInterface, traits, TraitedSpec, File, - InputMultiPath, - BaseInterfaceInputSpec, isdefined) + InputMultiPath, BaseInterfaceInputSpec, + isdefined) from ..utils import NUMPY_MMAP iflogger = logging.getLogger('interface') class DistanceInputSpec(BaseInterfaceInputSpec): - volume1 = File(exists=True, mandatory=True, - desc="Has to have the same dimensions as volume2.") + volume1 = File( + exists=True, + mandatory=True, + desc="Has to have the same dimensions as volume2.") volume2 = File( - exists=True, mandatory=True, - desc="Has to have the same dimensions as volume1." - ) + exists=True, + mandatory=True, + desc="Has to have the same dimensions as volume1.") method = traits.Enum( - "eucl_min", "eucl_cog", "eucl_mean", "eucl_wmean", "eucl_max", + "eucl_min", + "eucl_cog", + "eucl_mean", + "eucl_wmean", + "eucl_max", desc='""eucl_min": Euclidean distance between two closest points\ "eucl_cog": mean Euclidian distance between the Center of Gravity\ of volume1 and CoGs of volume2\ @@ -53,16 +60,15 @@ class DistanceInputSpec(BaseInterfaceInputSpec): to volume1 weighted by their values\ "eucl_max": maximum over minimum Euclidian distances of all volume2\ voxels to volume1 (also known as the Hausdorff distance)', - usedefault=True - ) + usedefault=True) mask_volume = File( exists=True, desc="calculate overlap only within this mask.") class DistanceOutputSpec(TraitedSpec): distance = traits.Float() - point1 = traits.Array(shape=(3,)) - point2 = traits.Array(shape=(3,)) + point1 = traits.Array(shape=(3, )) + point2 = traits.Array(shape=(3, )) histogram = File() @@ -103,23 +109,24 @@ def _eucl_min(self, nii1, nii2): np.argmin(dist_matrix), dist_matrix.shape) return (euclidean(set1_coordinates.T[point1, :], set2_coordinates.T[point2, :]), - set1_coordinates.T[point1, :], - set2_coordinates.T[point2, :]) + set1_coordinates.T[point1, :], set2_coordinates.T[point2, :]) def _eucl_cog(self, nii1, nii2): - origdata1 = np.logical_and(nii1.get_data() != 0, np.logical_not(np.isnan(nii1.get_data()))) + origdata1 = np.logical_and(nii1.get_data() != 0, + np.logical_not(np.isnan(nii1.get_data()))) cog_t = np.array(center_of_mass(origdata1.copy())).reshape(-1, 1) cog_t = np.vstack((cog_t, np.array([1]))) cog_t_coor = np.dot(nii1.affine, cog_t)[:3, :] - origdata2 = np.logical_and(nii2.get_data() != 0, np.logical_not(np.isnan(nii2.get_data()))) + origdata2 = np.logical_and(nii2.get_data() != 0, + np.logical_not(np.isnan(nii2.get_data()))) (labeled_data, n_labels) = label(origdata2) cogs = np.ones((4, n_labels)) for i in range(n_labels): - cogs[:3, i] = np.array(center_of_mass(origdata2, - labeled_data, i + 1)) + cogs[:3, i] = np.array( + center_of_mass(origdata2, labeled_data, i + 1)) cogs_coor = np.dot(nii2.affine, cogs)[:3, :] @@ -149,9 +156,7 @@ def _eucl_mean(self, nii1, nii2, weighted=False): if weighted: return np.average( - min_dist_matrix, - weights=nii2.get_data()[origdata2].flat - ) + min_dist_matrix, weights=nii2.get_data()[origdata2].flat) else: return np.mean(min_dist_matrix) @@ -179,8 +184,8 @@ def _eucl_max(self, nii1, nii2): set1_coordinates = self._get_coordinates(border1, nii1.affine) set2_coordinates = self._get_coordinates(border2, nii2.affine) distances = cdist(set1_coordinates.T, set2_coordinates.T) - mins = np.concatenate( - (np.amin(distances, axis=0), np.amin(distances, axis=1))) + mins = np.concatenate((np.amin(distances, axis=0), + np.amin(distances, axis=1))) return np.max(mins) @@ -218,39 +223,52 @@ def _list_outputs(self): class OverlapInputSpec(BaseInterfaceInputSpec): - volume1 = File(exists=True, mandatory=True, - desc='Has to have the same dimensions as volume2.') - volume2 = File(exists=True, mandatory=True, - desc='Has to have the same dimensions as volume1.') - mask_volume = File(exists=True, - desc='calculate overlap only within this mask.') - bg_overlap = traits.Bool(False, usedefault=True, mandatory=True, - desc='consider zeros as a label') + volume1 = File( + exists=True, + mandatory=True, + desc='Has to have the same dimensions as volume2.') + volume2 = File( + exists=True, + mandatory=True, + desc='Has to have the same dimensions as volume1.') + mask_volume = File( + exists=True, desc='calculate overlap only within this mask.') + bg_overlap = traits.Bool( + False, + usedefault=True, + mandatory=True, + desc='consider zeros as a label') out_file = File('diff.nii', usedefault=True) - weighting = traits.Enum('none', 'volume', 'squared_vol', usedefault=True, - desc=('\'none\': no class-overlap weighting is ' - 'performed. \'volume\': computed class-' - 'overlaps are weighted by class volume ' - '\'squared_vol\': computed class-overlaps ' - 'are weighted by the squared volume of ' - 'the class')) - vol_units = traits.Enum('voxel', 'mm', mandatory=True, usedefault=True, - desc='units for volumes') + weighting = traits.Enum( + 'none', + 'volume', + 'squared_vol', + usedefault=True, + desc=('\'none\': no class-overlap weighting is ' + 'performed. \'volume\': computed class-' + 'overlaps are weighted by class volume ' + '\'squared_vol\': computed class-overlaps ' + 'are weighted by the squared volume of ' + 'the class')) + vol_units = traits.Enum( + 'voxel', + 'mm', + mandatory=True, + usedefault=True, + desc='units for volumes') class OverlapOutputSpec(TraitedSpec): jaccard = traits.Float(desc='averaged jaccard index') dice = traits.Float(desc='averaged dice index') - roi_ji = traits.List(traits.Float(), - desc=('the Jaccard index (JI) per ROI')) + roi_ji = traits.List( + traits.Float(), desc=('the Jaccard index (JI) per ROI')) roi_di = traits.List(traits.Float(), desc=('the Dice index (DI) per ROI')) volume_difference = traits.Float(desc=('averaged volume difference')) - roi_voldiff = traits.List(traits.Float(), - desc=('volume differences of ROIs')) - labels = traits.List(traits.Int(), - desc=('detected labels')) - diff_file = File(exists=True, - desc='error map of differences') + roi_voldiff = traits.List( + traits.Float(), desc=('volume differences of ROIs')) + labels = traits.List(traits.Int(), desc=('detected labels')) + diff_file = File(exists=True, desc='error map of differences') class Overlap(BaseInterface): @@ -298,8 +316,6 @@ def _run_interface(self, runtime): data1 = data1.astype(np.min_scalar_type(max1)) data2 = nii2.get_data().astype(np.min_scalar_type(max1)) data2[np.logical_or(data1 < 0, np.isnan(data1))] = 0 - max2 = data2.max() - maxlabel = max(max1, max2) if isdefined(self.inputs.mask_volume): maskdata = nb.load(self.inputs.mask_volume).get_data() @@ -316,8 +332,9 @@ def _run_interface(self, runtime): labels.insert(0, 0) for l in labels: - res.append(self._bool_vec_dissimilarity(data1 == l, - data2 == l, method='jaccard')) + res.append( + self._bool_vec_dissimilarity( + data1 == l, data2 == l, method='jaccard')) volumes1.append(scale * len(data1[data1 == l])) volumes2.append(scale * len(data2[data2 == l])) @@ -325,7 +342,7 @@ def _run_interface(self, runtime): results['jaccard'] = np.array(res) results['dice'] = 2.0 * results['jaccard'] / (results['jaccard'] + 1.0) - weights = np.ones((len(volumes1),), dtype=np.float32) + weights = np.ones((len(volumes1), ), dtype=np.float32) if self.inputs.weighting != 'none': weights = weights / np.array(volumes1) if self.inputs.weighting == 'squared_vol': @@ -335,13 +352,14 @@ def _run_interface(self, runtime): both_data = np.zeros(data1.shape) both_data[(data1 - data2) != 0] = 1 - nb.save(nb.Nifti1Image(both_data, nii1.affine, nii1.header), - self.inputs.out_file) + nb.save( + nb.Nifti1Image(both_data, nii1.affine, nii1.header), + self.inputs.out_file) self._labels = labels self._ove_rois = results - self._vol_rois = (np.array(volumes1) - - np.array(volumes2)) / np.array(volumes1) + self._vol_rois = ( + np.array(volumes1) - np.array(volumes2)) / np.array(volumes1) self._dice = round(np.sum(weights * results['dice']), 5) self._jaccard = round(np.sum(weights * results['jaccard']), 5) @@ -364,26 +382,44 @@ def _list_outputs(self): class FuzzyOverlapInputSpec(BaseInterfaceInputSpec): - in_ref = InputMultiPath(File(exists=True), mandatory=True, - desc='Reference image. Requires the same dimensions as in_tst.') - in_tst = InputMultiPath(File(exists=True), mandatory=True, - desc='Test image. Requires the same dimensions as in_ref.') - weighting = traits.Enum('none', 'volume', 'squared_vol', usedefault=True, - desc=('\'none\': no class-overlap weighting is ' - 'performed. \'volume\': computed class-' - 'overlaps are weighted by class volume ' - '\'squared_vol\': computed class-overlaps ' - 'are weighted by the squared volume of ' - 'the class')) - out_file = File('diff.nii', desc='alternative name for resulting difference-map', usedefault=True) + in_ref = InputMultiPath( + File(exists=True), + mandatory=True, + desc='Reference image. Requires the same dimensions as in_tst.') + in_tst = InputMultiPath( + File(exists=True), + mandatory=True, + desc='Test image. Requires the same dimensions as in_ref.') + weighting = traits.Enum( + 'none', + 'volume', + 'squared_vol', + usedefault=True, + desc=('\'none\': no class-overlap weighting is ' + 'performed. \'volume\': computed class-' + 'overlaps are weighted by class volume ' + '\'squared_vol\': computed class-overlaps ' + 'are weighted by the squared volume of ' + 'the class')) + out_file = File( + 'diff.nii', + desc='alternative name for resulting difference-map', + usedefault=True) class FuzzyOverlapOutputSpec(TraitedSpec): jaccard = traits.Float(desc='Fuzzy Jaccard Index (fJI), all the classes') dice = traits.Float(desc='Fuzzy Dice Index (fDI), all the classes') - diff_file = File(exists=True, desc='resulting difference-map of all classes, using the chosen weighting') - class_fji = traits.List(traits.Float(), desc='Array containing the fJIs of each computed class') - class_fdi = traits.List(traits.Float(), desc='Array containing the fDIs of each computed class') + diff_file = File( + exists=True, + desc= + 'resulting difference-map of all classes, using the chosen weighting') + class_fji = traits.List( + traits.Float(), + desc='Array containing the fJIs of each computed class') + class_fdi = traits.List( + traits.Float(), + desc='Array containing the fDIs of each computed class') class FuzzyOverlap(BaseInterface): @@ -411,11 +447,17 @@ class FuzzyOverlap(BaseInterface): def _run_interface(self, runtime): ncomp = len(self.inputs.in_ref) - assert(ncomp == len(self.inputs.in_tst)) + assert (ncomp == len(self.inputs.in_tst)) weights = np.ones(shape=ncomp) - img_ref = np.array([nb.load(fname, mmap=NUMPY_MMAP).get_data() for fname in self.inputs.in_ref]) - img_tst = np.array([nb.load(fname, mmap=NUMPY_MMAP).get_data() for fname in self.inputs.in_tst]) + img_ref = np.array([ + nb.load(fname, mmap=NUMPY_MMAP).get_data() + for fname in self.inputs.in_ref + ]) + img_tst = np.array([ + nb.load(fname, mmap=NUMPY_MMAP).get_data() + for fname in self.inputs.in_tst + ]) msk = np.sum(img_ref, axis=0) msk[msk > 0] = 1.0 @@ -444,7 +486,7 @@ def _run_interface(self, runtime): if self.inputs.weighting != "none": weights = 1.0 / np.array(volumes) if self.inputs.weighting == "squared_vol": - weights = weights ** 2 + weights = weights**2 weights = weights / np.sum(weights) @@ -457,9 +499,11 @@ def _run_interface(self, runtime): ch[msk == 0] = 0 diff += w * ch - nb.save(nb.Nifti1Image(diff, nb.load(self.inputs.in_ref[0]).affine, - nb.load(self.inputs.in_ref[0]).header), - self.inputs.out_file) + nb.save( + nb.Nifti1Image(diff, + nb.load(self.inputs.in_ref[0]).affine, + nb.load(self.inputs.in_ref[0]).header), + self.inputs.out_file) return runtime @@ -475,14 +519,21 @@ def _list_outputs(self): class ErrorMapInputSpec(BaseInterfaceInputSpec): - in_ref = File(exists=True, mandatory=True, - desc="Reference image. Requires the same dimensions as in_tst.") - in_tst = File(exists=True, mandatory=True, - desc="Test image. Requires the same dimensions as in_ref.") + in_ref = File( + exists=True, + mandatory=True, + desc="Reference image. Requires the same dimensions as in_tst.") + in_tst = File( + exists=True, + mandatory=True, + desc="Test image. Requires the same dimensions as in_ref.") mask = File(exists=True, desc="calculate overlap only within this mask.") - metric = traits.Enum("sqeuclidean", "euclidean", - desc='error map metric (as implemented in scipy cdist)', - usedefault=True, mandatory=True) + metric = traits.Enum( + "sqeuclidean", + "euclidean", + desc='error map metric (as implemented in scipy cdist)', + usedefault=True, + mandatory=True) out_map = File(desc="Name for the output file") @@ -511,7 +562,7 @@ def _run_interface(self, runtime): nii_ref = nb.load(self.inputs.in_ref) ref_data = np.squeeze(nii_ref.get_data()) tst_data = np.squeeze(nb.load(self.inputs.in_tst).get_data()) - assert(ref_data.ndim == tst_data.ndim) + assert (ref_data.ndim == tst_data.ndim) # Load mask comps = 1 @@ -547,11 +598,13 @@ def _run_interface(self, runtime): elif self.inputs.metric == 'euclidean': errvector = np.linalg.norm(diffvector, axis=1) - errvectorexp = np.zeros_like(mskvector, dtype=np.float32) # The default type is uint8 + errvectorexp = np.zeros_like( + mskvector, dtype=np.float32) # The default type is uint8 errvectorexp[msk_idxs] = errvector # Get averaged error - self._distance = np.average(errvector) # Only average the masked voxels + self._distance = np.average( + errvector) # Only average the masked voxels errmap = errvectorexp.reshape(mapshape) @@ -586,20 +639,23 @@ class SimilarityInputSpec(BaseInterfaceInputSpec): volume2 = File(exists=True, desc="3D/4D volume", mandatory=True) mask1 = File(exists=True, desc="3D volume") mask2 = File(exists=True, desc="3D volume") - metric = traits.Either(traits.Enum('cc', 'cr', 'crl1', 'mi', 'nmi', 'slr'), - traits.Callable(), - desc="""str or callable + metric = traits.Either( + traits.Enum('cc', 'cr', 'crl1', 'mi', 'nmi', 'slr'), + traits.Callable(), + desc="""str or callable Cost-function for assessing image similarity. If a string, one of 'cc': correlation coefficient, 'cr': correlation ratio, 'crl1': L1-norm based correlation ratio, 'mi': mutual information, 'nmi': normalized mutual information, 'slr': supervised log-likelihood ratio. If a callable, it should take a two-dimensional array representing the image joint -histogram as an input and return a float.""", usedefault=True) +histogram as an input and return a float.""", + usedefault=True) class SimilarityOutputSpec(TraitedSpec): - similarity = traits.List(traits.Float(desc="Similarity between volume 1 and 2, frame by frame")) + similarity = traits.List( + traits.Float(desc="Similarity between volume 1 and 2, frame by frame")) class Similarity(BaseInterface): @@ -630,7 +686,7 @@ class Similarity(BaseInterface): def __init__(self, **inputs): try: package_check('nipy') - except Exception as e: + except Exception: self._have_nipy = False super(Similarity, self).__init__(**inputs) @@ -654,7 +710,8 @@ def _run_interface(self, runtime): vols2 = nb.four_to_three(vol2_nii) if dims < 2 or dims > 4: - raise RuntimeError('Image dimensions not supported (detected %dD file)' % dims) + raise RuntimeError( + 'Image dimensions not supported (detected %dD file)' % dims) if isdefined(self.inputs.mask1): mask1 = nb.load(self.inputs.mask1).get_data() == 1 @@ -669,11 +726,12 @@ def _run_interface(self, runtime): self._similarity = [] for ts1, ts2 in zip(vols1, vols2): - histreg = HistogramRegistration(from_img=ts1, - to_img=ts2, - similarity=self.inputs.metric, - from_mask=mask1, - to_mask=mask2) + histreg = HistogramRegistration( + from_img=ts1, + to_img=ts2, + similarity=self.inputs.metric, + from_mask=mask1, + to_mask=mask2) self._similarity.append(histreg.eval(Affine())) return runtime diff --git a/nipype/algorithms/misc.py b/nipype/algorithms/misc.py index a16507bf36..87b1fae400 100644 --- a/nipype/algorithms/misc.py +++ b/nipype/algorithms/misc.py @@ -11,7 +11,8 @@ >>> os.chdir(datadir) ''' -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, zip, range, open from future.utils import raise_from @@ -29,10 +30,9 @@ from .. import logging from . import metrics as nam -from ..interfaces.base import (BaseInterface, traits, TraitedSpec, File, - InputMultiPath, OutputMultiPath, - BaseInterfaceInputSpec, isdefined, - DynamicTraitedSpec, Undefined) +from ..interfaces.base import ( + BaseInterface, traits, TraitedSpec, File, InputMultiPath, OutputMultiPath, + BaseInterfaceInputSpec, isdefined, DynamicTraitedSpec, Undefined) from ..utils.filemanip import fname_presuffix, split_filename, filename_to_list from ..utils import NUMPY_MMAP @@ -42,23 +42,25 @@ class PickAtlasInputSpec(BaseInterfaceInputSpec): - atlas = File(exists=True, desc="Location of the atlas that will be used.", - mandatory=True) + atlas = File( + exists=True, + desc="Location of the atlas that will be used.", + mandatory=True) labels = traits.Either( - traits.Int, traits.List(traits.Int), + traits.Int, + traits.List(traits.Int), desc=("Labels of regions that will be included in the mask. Must be\ compatible with the atlas used."), - mandatory=True - ) + mandatory=True) hemi = traits.Enum( - 'both', 'left', 'right', + 'both', + 'left', + 'right', desc="Restrict the mask to only one hemisphere: left or right", - usedefault=True - ) + usedefault=True) dilation_size = traits.Int( usedefault=True, - desc="Defines how much the mask will be dilated (expanded in 3D)." - ) + desc="Defines how much the mask will be dilated (expanded in 3D).") output_file = File(desc="Where to store the output mask.") @@ -82,8 +84,11 @@ def _run_interface(self, runtime): def _gen_output_filename(self): if not isdefined(self.inputs.output_file): - output = fname_presuffix(fname=self.inputs.atlas, suffix="_mask", - newpath=os.getcwd(), use_ext=True) + output = fname_presuffix( + fname=self.inputs.atlas, + suffix="_mask", + newpath=os.getcwd(), + use_ext=True) else: output = os.path.realpath(self.inputs.output_file) return output @@ -105,11 +110,10 @@ def _get_brodmann_area(self): newdata[:int(ceil(float(origdata.shape[0]) / 2)), :, :] = 0 if self.inputs.dilation_size != 0: - newdata = grey_dilation( - newdata, (2 * self.inputs.dilation_size + 1, - 2 * self.inputs.dilation_size + - 1, - 2 * self.inputs.dilation_size + 1)) + newdata = grey_dilation(newdata, + (2 * self.inputs.dilation_size + 1, + 2 * self.inputs.dilation_size + 1, + 2 * self.inputs.dilation_size + 1)) return nb.Nifti1Image(newdata, nii.affine, nii.header) @@ -125,8 +129,7 @@ class SimpleThresholdInputSpec(BaseInterfaceInputSpec): threshold = traits.Float( desc='volumes to be thresholdedeverything below this value will be set\ to zero', - mandatory=True - ) + mandatory=True) class SimpleThresholdOutputSpec(TraitedSpec): @@ -170,15 +173,13 @@ class ModifyAffineInputSpec(BaseInterfaceInputSpec): volumes = InputMultiPath( File(exists=True), desc='volumes which affine matrices will be modified', - mandatory=True - ) + mandatory=True) transformation_matrix = traits.Array( value=np.eye(4), shape=(4, 4), desc="transformation matrix that will be left multiplied by the\ affine matrix", - usedefault=True - ) + usedefault=True) class ModifyAffineOutputSpec(TraitedSpec): @@ -203,8 +204,9 @@ def _run_interface(self, runtime): affine = img.affine affine = np.dot(self.inputs.transformation_matrix, affine) - nb.save(nb.Nifti1Image(img.get_data(), affine, img.header), - self._gen_output_filename(fname)) + nb.save( + nb.Nifti1Image(img.get_data(), affine, img.header), + self._gen_output_filename(fname)) return runtime @@ -260,6 +262,7 @@ def _list_outputs(self): outputs['nifti_file'] = self._gen_output_file_name() return outputs + class GunzipInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True) @@ -306,8 +309,9 @@ def matlab2csv(in_array, name, reshape): output_array = np.asarray(in_array) if reshape: if len(np.shape(output_array)) > 1: - output_array = np.reshape(output_array, ( - np.shape(output_array)[0] * np.shape(output_array)[1], 1)) + output_array = np.reshape( + output_array, + (np.shape(output_array)[0] * np.shape(output_array)[1], 1)) iflogger.info(np.shape(output_array)) output_name = op.abspath(name + '.csv') np.savetxt(output_name, output_array, delimiter=',') @@ -317,17 +321,16 @@ def matlab2csv(in_array, name, reshape): class Matlab2CSVInputSpec(TraitedSpec): in_file = File(exists=True, mandatory=True, desc='Input MATLAB .mat file') reshape_matrix = traits.Bool( - True, usedefault=True, + True, + usedefault=True, desc='The output of this interface is meant for R, so matrices will be\ - reshaped to vectors by default.' - ) + reshaped to vectors by default.') class Matlab2CSVOutputSpec(TraitedSpec): csv_files = OutputMultiPath( File(desc='Output CSV files for each variable saved in the input .mat\ - file') - ) + file')) class Matlab2CSV(BaseInterface): @@ -369,9 +372,10 @@ def _run_interface(self, runtime): iflogger.info('%i variables found:', len(saved_variables)) iflogger.info(saved_variables) for variable in saved_variables: - iflogger.info('...Converting %s - type %s - to CSV', - variable, type(in_dict[variable])) - matlab2csv(in_dict[variable], variable, self.inputs.reshape_matrix) + iflogger.info('...Converting %s - type %s - to CSV', variable, + type(in_dict[variable])) + matlab2csv(in_dict[variable], variable, + self.inputs.reshape_matrix) elif len(saved_variables) == 1: _, name, _ = split_filename(self.inputs.in_file) variable = saved_variables[0] @@ -410,10 +414,10 @@ def merge_csvs(in_list): for idx, in_file in enumerate(in_list): try: in_array = np.loadtxt(in_file, delimiter=',') - except ValueError as ex: + except ValueError: try: in_array = np.loadtxt(in_file, delimiter=',', skiprows=1) - except ValueError as ex: + except ValueError: with open(in_file, 'r') as first: header_line = first.readline() @@ -421,12 +425,16 @@ def merge_csvs(in_list): n_cols = len(header_list) try: in_array = np.loadtxt( - in_file, delimiter=',', skiprows=1, - usecols=list(range(1, n_cols)) - ) - except ValueError as ex: + in_file, + delimiter=',', + skiprows=1, + usecols=list(range(1, n_cols))) + except ValueError: in_array = np.loadtxt( - in_file, delimiter=',', skiprows=1, usecols=list(range(1, n_cols - 1))) + in_file, + delimiter=',', + skiprows=1, + usecols=list(range(1, n_cols - 1))) if idx == 0: out_array = in_array else: @@ -473,8 +481,8 @@ def maketypelist(rowheadings, shape, extraheadingBool, extraheading): return typelist -def makefmtlist(output_array, typelist, rowheadingsBool, - shape, extraheadingBool): +def makefmtlist(output_array, typelist, rowheadingsBool, shape, + extraheadingBool): fmtlist = [] if rowheadingsBool: fmtlist.append('%s') @@ -495,19 +503,27 @@ def makefmtlist(output_array, typelist, rowheadingsBool, class MergeCSVFilesInputSpec(TraitedSpec): - in_files = InputMultiPath(File(exists=True), mandatory=True, - desc='Input comma-separated value (CSV) files') - out_file = File('merged.csv', usedefault=True, - desc='Output filename for merged CSV file') + in_files = InputMultiPath( + File(exists=True), + mandatory=True, + desc='Input comma-separated value (CSV) files') + out_file = File( + 'merged.csv', + usedefault=True, + desc='Output filename for merged CSV file') column_headings = traits.List( - traits.Str, desc='List of column headings to save in merged CSV file\ + traits.Str, + desc='List of column headings to save in merged CSV file\ (must be equal to number of input files). If left undefined, these\ will be pulled from the input filenames.') row_headings = traits.List( - traits.Str, desc='List of row headings to save in merged CSV file\ + traits.Str, + desc='List of row headings to save in merged CSV file\ (must be equal to number of rows in the input files).') row_heading_title = traits.Str( - 'label', usedefault=True, desc='Column heading for the row headings\ + 'label', + usedefault=True, + desc='Column heading for the row headings\ added') extra_column_heading = traits.Str( desc='New heading to add for the added field.') @@ -552,16 +568,19 @@ def _run_interface(self, runtime): iflogger.info('Column headings have been provided:') headings = self.inputs.column_headings else: - iflogger.info('Column headings not provided! Pulled from input filenames:') + iflogger.info( + 'Column headings not provided! Pulled from input filenames:') headings = remove_identical_paths(self.inputs.in_files) if isdefined(self.inputs.extra_field): if isdefined(self.inputs.extra_column_heading): extraheading = self.inputs.extra_column_heading - iflogger.info('Extra column heading provided: %s', extraheading) + iflogger.info('Extra column heading provided: %s', + extraheading) else: extraheading = 'type' - iflogger.info('Extra column heading was not defined. Using "type"') + iflogger.info( + 'Extra column heading was not defined. Using "type"') headings.append(extraheading) extraheadingBool = True @@ -572,8 +591,8 @@ def _run_interface(self, runtime): iflogger.info('Row headings have been provided. Adding "labels"' 'column header.') prefix = '"{p}","'.format(p=self.inputs.row_heading_title) - csv_headings = prefix + '","'.join(itertools.chain( - headings)) + '"\n' + csv_headings = prefix + '","'.join( + itertools.chain(headings)) + '"\n' rowheadingsBool = True else: iflogger.info('Row headings have not been provided.') @@ -581,7 +600,6 @@ def _run_interface(self, runtime): iflogger.info('Final Headings:') iflogger.info(csv_headings) - """ Next we merge the arrays and define the output text file """ @@ -596,10 +614,10 @@ def _run_interface(self, runtime): file_handle.write(csv_headings) shape = np.shape(output_array) - typelist = maketypelist( - rowheadingsBool, shape, extraheadingBool, extraheading) - fmt, output = makefmtlist( - output_array, typelist, rowheadingsBool, shape, extraheadingBool) + typelist = maketypelist(rowheadingsBool, shape, extraheadingBool, + extraheading) + fmt, output = makefmtlist(output_array, typelist, rowheadingsBool, + shape, extraheadingBool) if rowheadingsBool: row_heading_list = self.inputs.row_headings @@ -638,10 +656,14 @@ def _list_outputs(self): class AddCSVColumnInputSpec(TraitedSpec): - in_file = File(exists=True, mandatory=True, - desc='Input comma-separated value (CSV) files') - out_file = File('extra_heading.csv', usedefault=True, - desc='Output filename for merged CSV file') + in_file = File( + exists=True, + mandatory=True, + desc='Input comma-separated value (CSV) files') + out_file = File( + 'extra_heading.csv', + usedefault=True, + desc='Output filename for merged CSV file') extra_column_heading = traits.Str( desc='New heading to add for the added field.') extra_field = traits.Str( @@ -701,8 +723,8 @@ def _list_outputs(self): class AddCSVRowInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - in_file = traits.File(mandatory=True, - desc='Input comma-separated value (CSV) files') + in_file = traits.File( + mandatory=True, desc='Input comma-separated value (CSV) files') _outputs = traits.Dict(traits.Any, value={}, usedefault=True) def __setattr__(self, key, value): @@ -721,7 +743,6 @@ class AddCSVRowOutputSpec(TraitedSpec): class AddCSVRow(BaseInterface): - """Simple interface to add an extra row to a csv file .. note:: Requires `pandas `_ @@ -769,8 +790,9 @@ def _run_interface(self, runtime): try: import pandas as pd except ImportError as e: - raise_from(ImportError('This interface requires pandas ' - '(http://pandas.pydata.org/) to run.'), e) + raise_from( + ImportError('This interface requires pandas ' + '(http://pandas.pydata.org/) to run.'), e) try: import lockfile as pl @@ -783,7 +805,8 @@ def _run_interface(self, runtime): input_dict = {} for key, val in list(self.inputs._outputs.items()): # expand lists to several columns - if key == 'trait_added' and val in self.inputs.copyable_trait_names(): + if key == 'trait_added' and val in self.inputs.copyable_trait_names( + ): continue if isinstance(val, list): @@ -833,7 +856,8 @@ def _add_output_traits(self, base): class CalculateNormalizedMomentsInputSpec(TraitedSpec): timeseries_file = File( - exists=True, mandatory=True, + exists=True, + mandatory=True, desc='Text file with timeseries in columns and timepoints in rows,\ whitespace separated') moment = traits.Int( @@ -863,8 +887,8 @@ class CalculateNormalizedMoments(BaseInterface): def _run_interface(self, runtime): - self._moments = calc_moments( - self.inputs.timeseries_file, self.inputs.moment) + self._moments = calc_moments(self.inputs.timeseries_file, + self.inputs.moment) return runtime def _list_outputs(self): @@ -886,20 +910,32 @@ def calc_moments(timeseries_file, moment): m2 = stats.moment(timeseries, 2, axis=0) m3 = stats.moment(timeseries, moment, axis=0) zero = (m2 == 0) - return np.where(zero, 0, m3 / m2 ** (moment / 2.0)) + return np.where(zero, 0, m3 / m2**(moment / 2.0)) class AddNoiseInputSpec(TraitedSpec): - in_file = File(exists=True, mandatory=True, - desc='input image that will be corrupted with noise') - in_mask = File(exists=True, desc=('input mask, voxels outside this mask ' - 'will be considered background')) + in_file = File( + exists=True, + mandatory=True, + desc='input image that will be corrupted with noise') + in_mask = File( + exists=True, + desc=('input mask, voxels outside this mask ' + 'will be considered background')) snr = traits.Float(10.0, desc='desired output SNR in dB', usedefault=True) - dist = traits.Enum('normal', 'rician', usedefault=True, mandatory=True, - desc=('desired noise distribution')) - bg_dist = traits.Enum('normal', 'rayleigh', usedefault=True, mandatory=True, - desc=('desired noise distribution, currently ' - 'only normal is implemented')) + dist = traits.Enum( + 'normal', + 'rician', + usedefault=True, + mandatory=True, + desc=('desired noise distribution')) + bg_dist = traits.Enum( + 'normal', + 'rayleigh', + usedefault=True, + mandatory=True, + desc=('desired noise distribution, currently ' + 'only normal is implemented')) out_file = File(desc='desired output filename') @@ -935,8 +971,12 @@ def _run_interface(self, runtime): else: in_mask = np.ones_like(in_data) - result = self.gen_noise(in_data, mask=in_mask, snr_db=snr, - dist=self.inputs.dist, bg_dist=self.inputs.bg_dist) + result = self.gen_noise( + in_data, + mask=in_mask, + snr_db=snr, + dist=self.inputs.dist, + bg_dist=self.inputs.bg_dist) res_im = nb.Nifti1Image(result, in_image.affine, in_image.header) res_im.to_filename(self._gen_output_filename()) return runtime @@ -944,7 +984,8 @@ def _run_interface(self, runtime): def _gen_output_filename(self): if not isdefined(self.inputs.out_file): _, base, ext = split_filename(self.inputs.in_file) - out_file = os.path.abspath('%s_SNR%03.2f%s' % (base, self.inputs.snr, ext)) + out_file = os.path.abspath('%s_SNR%03.2f%s' % + (base, self.inputs.snr, ext)) else: out_file = self.inputs.out_file @@ -955,7 +996,12 @@ def _list_outputs(self): outputs['out_file'] = self._gen_output_filename() return outputs - def gen_noise(self, image, mask=None, snr_db=10.0, dist='normal', bg_dist='normal'): + def gen_noise(self, + image, + mask=None, + snr_db=10.0, + dist='normal', + bg_dist='normal'): """ Generates a copy of an image with a certain amount of added gaussian noise (rayleigh for background in mask) @@ -1000,15 +1046,14 @@ def gen_noise(self, image, mask=None, snr_db=10.0, dist='normal', bg_dist='norma class NormalizeProbabilityMapSetInputSpec(TraitedSpec): - in_files = InputMultiPath(File(exists=True, mandatory=True, - desc='The tpms to be normalized')) - in_mask = File(exists=True, - desc='Masked voxels must sum up 1.0, 0.0 otherwise.') + in_files = InputMultiPath( + File(exists=True, mandatory=True, desc='The tpms to be normalized')) + in_mask = File( + exists=True, desc='Masked voxels must sum up 1.0, 0.0 otherwise.') class NormalizeProbabilityMapSetOutputSpec(TraitedSpec): - out_files = OutputMultiPath(File(exists=True), - desc="normalized maps") + out_files = OutputMultiPath(File(exists=True), desc="normalized maps") class NormalizeProbabilityMapSet(BaseInterface): @@ -1047,20 +1092,18 @@ def _list_outputs(self): class SplitROIsInputSpec(TraitedSpec): - in_file = File(exists=True, mandatory=True, - desc='file to be splitted') + in_file = File(exists=True, mandatory=True, desc='file to be splitted') in_mask = File(exists=True, desc='only process files inside mask') - roi_size = traits.Tuple(traits.Int, traits.Int, traits.Int, - desc='desired ROI size') + roi_size = traits.Tuple( + traits.Int, traits.Int, traits.Int, desc='desired ROI size') class SplitROIsOutputSpec(TraitedSpec): - out_files = OutputMultiPath(File(exists=True), - desc='the resulting ROIs') - out_masks = OutputMultiPath(File(exists=True), - desc='a mask indicating valid values') - out_index = OutputMultiPath(File(exists=True), - desc='arrays keeping original locations') + out_files = OutputMultiPath(File(exists=True), desc='the resulting ROIs') + out_masks = OutputMultiPath( + File(exists=True), desc='a mask indicating valid values') + out_index = OutputMultiPath( + File(exists=True), desc='arrays keeping original locations') class SplitROIs(BaseInterface): @@ -1091,8 +1134,7 @@ def _run_interface(self, runtime): if isdefined(self.inputs.roi_size): roisize = self.inputs.roi_size - res = split_rois(self.inputs.in_file, - mask, roisize) + res = split_rois(self.inputs.in_file, mask, roisize) self._outnames['out_files'] = res[0] self._outnames['out_masks'] = res[1] self._outnames['out_index'] = res[2] @@ -1106,10 +1148,11 @@ def _list_outputs(self): class MergeROIsInputSpec(TraitedSpec): - in_files = InputMultiPath(File(exists=True, mandatory=True, - desc='files to be re-merged')) - in_index = InputMultiPath(File(exists=True, mandatory=True), - desc='array keeping original locations') + in_files = InputMultiPath( + File(exists=True, mandatory=True, desc='files to be re-merged')) + in_index = InputMultiPath( + File(exists=True, mandatory=True), + desc='array keeping original locations') in_reference = File(exists=True, desc='reference file') @@ -1137,8 +1180,7 @@ class MergeROIs(BaseInterface): output_spec = MergeROIsOutputSpec def _run_interface(self, runtime): - res = merge_rois(self.inputs.in_files, - self.inputs.in_index, + res = merge_rois(self.inputs.in_files, self.inputs.in_index, self.inputs.in_reference) self._merged = res return runtime @@ -1178,8 +1220,9 @@ def normalize_tpms(in_files, in_mask=None, out_files=[]): hdr = imgs[0].header.copy() hdr['data_type'] = 16 hdr.set_data_dtype(np.float32) - nb.save(nb.Nifti1Image(img_data.astype(np.float32), imgs[0].affine, - hdr), out_files[0]) + nb.save( + nb.Nifti1Image(img_data.astype(np.float32), imgs[0].affine, hdr), + out_files[0]) return out_files[0] img_data = np.array([im.get_data() for im in imgs]).astype(np.float32) @@ -1203,8 +1246,9 @@ def normalize_tpms(in_files, in_mask=None, out_files=[]): hdr = imgs[i].header.copy() hdr['data_type'] = 16 hdr.set_data_dtype('float32') - nb.save(nb.Nifti1Image(probmap.astype(np.float32), imgs[i].affine, - hdr), out_file) + nb.save( + nb.Nifti1Image(probmap.astype(np.float32), imgs[i].affine, hdr), + out_file) return out_files @@ -1264,11 +1308,13 @@ def split_rois(in_file, mask=None, roishape=None): droi = data[first:last, ...] iname = op.abspath('roi%010d_idx' % i) out_idxs.append(iname + '.npz') - np.savez(iname, (nzels[0][first:last],)) + np.savez(iname, (nzels[0][first:last], )) if fill > 0: - droi = np.vstack((droi, np.zeros((int(fill), int(nvols)), dtype=np.float32))) - partialmsk = np.ones((roisize,), dtype=np.uint8) + droi = np.vstack((droi, + np.zeros( + (int(fill), int(nvols)), dtype=np.float32))) + partialmsk = np.ones((roisize, ), dtype=np.uint8) partialmsk[-int(fill):] = 0 partname = op.abspath('partialmask.nii.gz') nb.Nifti1Image(partialmsk.reshape(roishape), None, @@ -1278,14 +1324,12 @@ def split_rois(in_file, mask=None, roishape=None): out_mask.append(roidefname) fname = op.abspath('roi%010d.nii.gz' % i) - nb.Nifti1Image(droi.reshape(droishape), - None, None).to_filename(fname) + nb.Nifti1Image(droi.reshape(droishape), None, None).to_filename(fname) out_files.append(fname) return out_files, out_mask, out_idxs -def merge_rois(in_files, in_idxs, in_ref, - dtype=None, out_file=None): +def merge_rois(in_files, in_idxs, in_ref, dtype=None, out_file=None): """ Re-builds an image resulting from a parallelized processing """ @@ -1331,7 +1375,8 @@ def merge_rois(in_files, in_idxs, in_ref, for cname, iname in zip(in_files, in_idxs): f = np.load(iname) idxs = np.squeeze(f['arr_0']) - cdata = nb.load(cname, mmap=NUMPY_MMAP).get_data().reshape(-1, ndirs) + cdata = nb.load( + cname, mmap=NUMPY_MMAP).get_data().reshape(-1, ndirs) nels = len(idxs) idata = (idxs, ) try: @@ -1343,8 +1388,8 @@ def merge_rois(in_files, in_idxs, in_ref, raise hdr.set_data_shape(newshape) - nb.Nifti1Image(data.reshape(newshape).astype(dtype), - aff, hdr).to_filename(out_file) + nb.Nifti1Image(data.reshape(newshape).astype(dtype), aff, + hdr).to_filename(out_file) else: hdr.set_data_shape(rsh[:3]) @@ -1360,12 +1405,13 @@ def merge_rois(in_files, in_idxs, in_ref, for d, fname in enumerate(nii): data = nb.load(fname, mmap=NUMPY_MMAP).get_data().reshape(-1) - cdata = nb.load(cname, mmap=NUMPY_MMAP).get_data().reshape(-1, ndirs)[:, d] + cdata = nb.load( + cname, mmap=NUMPY_MMAP).get_data().reshape(-1, ndirs)[:, d] nels = len(idxs) idata = (idxs, ) data[idata] = cdata[0:nels] - nb.Nifti1Image(data.reshape(rsh[:3]), - aff, hdr).to_filename(fname) + nb.Nifti1Image(data.reshape(rsh[:3]), aff, + hdr).to_filename(fname) imgs = [nb.load(im, mmap=NUMPY_MMAP) for im in nii] allim = nb.concat_images(imgs) @@ -1375,15 +1421,20 @@ def merge_rois(in_files, in_idxs, in_ref, class CalculateMedianInputSpec(BaseInterfaceInputSpec): - in_files = InputMultiPath(File(exists=True, mandatory=True, - desc="One or more realigned Nifti 4D timeseries")) + in_files = InputMultiPath( + File( + exists=True, + mandatory=True, + desc="One or more realigned Nifti 4D timeseries")) median_file = traits.Str(desc="Filename prefix to store median images") - median_per_file = traits.Bool(False, usedefault=True, - desc="Calculate a median file for each Nifti") + median_per_file = traits.Bool( + False, usedefault=True, desc="Calculate a median file for each Nifti") + class CalculateMedianOutputSpec(TraitedSpec): - median_files = OutputMultiPath(File(exists=True), - desc="One or more median images") + median_files = OutputMultiPath( + File(exists=True), desc="One or more median images") + class CalculateMedian(BaseInterface): """ @@ -1456,7 +1507,8 @@ def _write_nifti(self, img, data, idx, suffix='median'): median_img = nb.Nifti1Image(data, img.affine, img.header) filename = self._gen_fname(suffix, idx=idx) else: - median_img = nb.Nifti1Image(data/(idx+1), img.affine, img.header) + median_img = nb.Nifti1Image(data / (idx + 1), img.affine, + img.header) filename = self._gen_fname(suffix) median_img.to_filename(filename) return filename @@ -1464,12 +1516,14 @@ def _write_nifti(self, img, data, idx, suffix='median'): # Deprecated interfaces ------------------------------------------------------ + class Distance(nam.Distance): """Calculates distance between two volumes. .. deprecated:: 0.10.0 Use :py:class:`nipype.algorithms.metrics.Distance` instead. """ + def __init__(self, **inputs): super(nam.Distance, self).__init__(**inputs) warnings.warn(("This interface has been deprecated since 0.10.0," @@ -1483,6 +1537,7 @@ class Overlap(nam.Overlap): .. deprecated:: 0.10.0 Use :py:class:`nipype.algorithms.metrics.Overlap` instead. """ + def __init__(self, **inputs): super(nam.Overlap, self).__init__(**inputs) warnings.warn(("This interface has been deprecated since 0.10.0," @@ -1497,17 +1552,20 @@ class FuzzyOverlap(nam.FuzzyOverlap): .. deprecated:: 0.10.0 Use :py:class:`nipype.algorithms.metrics.FuzzyOverlap` instead. """ + def __init__(self, **inputs): super(nam.FuzzyOverlap, self).__init__(**inputs) warnings.warn(("This interface has been deprecated since 0.10.0," " please use nipype.algorithms.metrics.FuzzyOverlap"), DeprecationWarning) + class TSNR(confounds.TSNR): """ .. deprecated:: 0.12.1 Use :py:class:`nipype.algorithms.confounds.TSNR` instead """ + def __init__(self, **inputs): super(confounds.TSNR, self).__init__(**inputs) warnings.warn(("This interface has been moved since 0.12.0," diff --git a/nipype/algorithms/modelgen.py b/nipype/algorithms/modelgen.py index 2c994bf20d..289ebc8388 100644 --- a/nipype/algorithms/modelgen.py +++ b/nipype/algorithms/modelgen.py @@ -18,7 +18,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, str, bytes, int from copy import deepcopy @@ -99,8 +100,8 @@ def spm_hrf(RT, P=None, fMRI_T=16): dt = RT / float(fMRI_T) u = np.arange(0, int(p[6] / dt + 1)) - p[5] / dt with np.errstate(divide='ignore'): # Known division-by-zero - hrf = _spm_Gpdf(u, p[0] / p[2], dt / p[2]) - _spm_Gpdf(u, p[1] / p[3], - dt / p[3]) / p[4] + hrf = _spm_Gpdf(u, p[0] / p[2], dt / p[2]) - _spm_Gpdf( + u, p[1] / p[3], dt / p[3]) / p[4] idx = np.arange(0, int((p[6] / RT) + 1)) * fMRI_T hrf = hrf[idx] hrf = hrf / np.sum(hrf) @@ -181,43 +182,58 @@ def gen_info(run_event_files): class SpecifyModelInputSpec(BaseInterfaceInputSpec): - subject_info = InputMultiPath(Bunch, mandatory=True, - xor=['subject_info', 'event_files'], - desc='Bunch or List(Bunch) subject-specific ' - 'condition information. see ' - ':ref:`SpecifyModel` or ' - 'SpecifyModel.__doc__ for details') - event_files = InputMultiPath(traits.List(File(exists=True)), mandatory=True, - xor=['subject_info', 'event_files'], - desc='List of event description files 1, 2 or 3 ' - 'column format corresponding to onsets, ' - 'durations and amplitudes') - realignment_parameters = InputMultiPath(File(exists=True), - desc='Realignment parameters returned ' - 'by motion correction algorithm', - copyfile=False) - parameter_source = traits.Enum("SPM", "FSL", "AFNI", "FSFAST", "NIPY", - usedefault=True, - desc="Source of motion parameters") - outlier_files = InputMultiPath(File(exists=True), - desc='Files containing scan outlier indices ' - 'that should be tossed', - copyfile=False) - functional_runs = InputMultiPath(traits.Either(traits.List(File(exists=True)), - File(exists=True)), - mandatory=True, - desc='Data files for model. List of 4D ' - 'files or list of list of 3D ' - 'files per session', - copyfile=False) - input_units = traits.Enum('secs', 'scans', mandatory=True, - desc='Units of event onsets and durations (secs ' - 'or scans). Output units are always in secs') - high_pass_filter_cutoff = traits.Float(mandatory=True, - desc='High-pass filter cutoff in secs') - time_repetition = traits.Float(mandatory=True, - desc='Time between the start of one volume ' - 'to the start of the next image volume.') + subject_info = InputMultiPath( + Bunch, + mandatory=True, + xor=['subject_info', 'event_files'], + desc='Bunch or List(Bunch) subject-specific ' + 'condition information. see ' + ':ref:`SpecifyModel` or ' + 'SpecifyModel.__doc__ for details') + event_files = InputMultiPath( + traits.List(File(exists=True)), + mandatory=True, + xor=['subject_info', 'event_files'], + desc='List of event description files 1, 2 or 3 ' + 'column format corresponding to onsets, ' + 'durations and amplitudes') + realignment_parameters = InputMultiPath( + File(exists=True), + desc='Realignment parameters returned ' + 'by motion correction algorithm', + copyfile=False) + parameter_source = traits.Enum( + "SPM", + "FSL", + "AFNI", + "FSFAST", + "NIPY", + usedefault=True, + desc="Source of motion parameters") + outlier_files = InputMultiPath( + File(exists=True), + desc='Files containing scan outlier indices ' + 'that should be tossed', + copyfile=False) + functional_runs = InputMultiPath( + traits.Either(traits.List(File(exists=True)), File(exists=True)), + mandatory=True, + desc='Data files for model. List of 4D ' + 'files or list of list of 3D ' + 'files per session', + copyfile=False) + input_units = traits.Enum( + 'secs', + 'scans', + mandatory=True, + desc='Units of event onsets and durations (secs ' + 'or scans). Output units are always in secs') + high_pass_filter_cutoff = traits.Float( + mandatory=True, desc='High-pass filter cutoff in secs') + time_repetition = traits.Float( + mandatory=True, + desc='Time between the start of one volume ' + 'to the start of the next image volume.') # Not implemented yet # polynomial_order = traits.Range(0, low=0, # desc ='Number of polynomial functions to model high pass filter.') @@ -295,8 +311,11 @@ class SpecifyModel(BaseInterface): input_spec = SpecifyModelInputSpec output_spec = SpecifyModelOutputSpec - def _generate_standard_design(self, infolist, functional_runs=None, - realignment_parameters=None, outliers=None): + def _generate_standard_design(self, + infolist, + functional_runs=None, + realignment_parameters=None, + outliers=None): """ Generates a standard design matrix paradigm given information about each run """ @@ -315,15 +334,13 @@ def _generate_standard_design(self, infolist, functional_runs=None, for cid, cond in enumerate(info.conditions): sessinfo[i]['cond'].insert(cid, dict()) sessinfo[i]['cond'][cid]['name'] = info.conditions[cid] - scaled_onset = scale_timings(info.onsets[cid], - self.inputs.input_units, - output_units, - self.inputs.time_repetition) + scaled_onset = scale_timings( + info.onsets[cid], self.inputs.input_units, + output_units, self.inputs.time_repetition) sessinfo[i]['cond'][cid]['onset'] = scaled_onset - scaled_duration = scale_timings(info.durations[cid], - self.inputs.input_units, - output_units, - self.inputs.time_repetition) + scaled_duration = scale_timings( + info.durations[cid], self.inputs.input_units, + output_units, self.inputs.time_repetition) sessinfo[i]['cond'][cid]['duration'] = scaled_duration if hasattr(info, 'amplitudes') and info.amplitudes: sessinfo[i]['cond'][cid]['amplitudes'] = \ @@ -364,8 +381,10 @@ def _generate_standard_design(self, infolist, functional_runs=None, mc = realignment_parameters[i] for col in range(mc.shape[1]): colidx = len(sessinfo[i]['regress']) - sessinfo[i]['regress'].insert(colidx, dict(name='', val=[])) - sessinfo[i]['regress'][colidx]['name'] = 'Realign%d' % (col + 1) + sessinfo[i]['regress'].insert(colidx, dict( + name='', val=[])) + sessinfo[i]['regress'][colidx]['name'] = 'Realign%d' % ( + col + 1) sessinfo[i]['regress'][colidx]['val'] = mc[:, col].tolist() if outliers is not None: @@ -383,8 +402,10 @@ def _generate_standard_design(self, infolist, functional_runs=None, for j, scanno in enumerate(out): colidx = len(sessinfo[i]['regress']) - sessinfo[i]['regress'].insert(colidx, dict(name='', val=[])) - sessinfo[i]['regress'][colidx]['name'] = 'Outlier%d' % (j + 1) + sessinfo[i]['regress'].insert(colidx, dict( + name='', val=[])) + sessinfo[i]['regress'][colidx]['name'] = 'Outlier%d' % ( + j + 1) sessinfo[i]['regress'][colidx]['val'] = \ np.zeros((1, numscans))[0].tolist() sessinfo[i]['regress'][colidx]['val'][int(scanno)] = 1 @@ -397,9 +418,11 @@ def _generate_design(self, infolist=None): if isdefined(self.inputs.realignment_parameters): for parfile in self.inputs.realignment_parameters: realignment_parameters.append( - np.apply_along_axis(func1d=normalize_mc_params, - axis=1, arr=np.loadtxt(parfile), - source=self.inputs.parameter_source)) + np.apply_along_axis( + func1d=normalize_mc_params, + axis=1, + arr=np.loadtxt(parfile), + source=self.inputs.parameter_source)) outliers = [] if isdefined(self.inputs.outlier_files): for filename in self.inputs.outlier_files: @@ -418,10 +441,11 @@ def _generate_design(self, infolist=None): infolist = self.inputs.subject_info else: infolist = gen_info(self.inputs.event_files) - self._sessinfo = self._generate_standard_design(infolist, - functional_runs=self.inputs.functional_runs, - realignment_parameters=realignment_parameters, - outliers=outliers) + self._sessinfo = self._generate_standard_design( + infolist, + functional_runs=self.inputs.functional_runs, + realignment_parameters=realignment_parameters, + outliers=outliers) def _run_interface(self, runtime): """ @@ -440,12 +464,17 @@ def _list_outputs(self): class SpecifySPMModelInputSpec(SpecifyModelInputSpec): - concatenate_runs = traits.Bool(False, usedefault=True, - desc='Concatenate all runs to look like a ' - 'single session.') - output_units = traits.Enum('secs', 'scans', usedefault=True, - desc='Units of design event onsets and durations ' - '(secs or scans)') + concatenate_runs = traits.Bool( + False, + usedefault=True, + desc='Concatenate all runs to look like a ' + 'single session.') + output_units = traits.Enum( + 'secs', + 'scans', + usedefault=True, + desc='Units of design event onsets and durations ' + '(secs or scans)') class SpecifySPMModel(SpecifyModel): @@ -493,8 +522,8 @@ def _concatenate_info(self, infolist): infoout = infolist[0] for j, val in enumerate(infolist[0].durations): if len(infolist[0].onsets[j]) > 1 and len(val) == 1: - infoout.durations[j] = (infolist[0].durations[j] * - len(infolist[0].onsets[j])) + infoout.durations[j] = ( + infolist[0].durations[j] * len(infolist[0].onsets[j])) for i, info in enumerate(infolist[1:]): # info.[conditions, tmod] remain the same @@ -512,8 +541,8 @@ def _concatenate_info(self, infolist): for j, val in enumerate(info.durations): if len(info.onsets[j]) > 1 and len(val) == 1: - infoout.durations[j].extend(info.durations[j] * - len(info.onsets[j])) + infoout.durations[j].extend( + info.durations[j] * len(info.onsets[j])) elif len(info.onsets[j]) == len(val): infoout.durations[j].extend(info.durations[j]) else: @@ -542,8 +571,9 @@ def _concatenate_info(self, infolist): infoout.regressors = [] onelist = np.zeros((1, sum(nscans))) onelist[0, sum(nscans[0:i]):sum(nscans[0:(i + 1)])] = 1 - infoout.regressors.insert(len(infoout.regressors), - onelist.tolist()[0]) + infoout.regressors.insert( + len(infoout.regressors), + onelist.tolist()[0]) return [infoout], nscans def _generate_design(self, infolist=None): @@ -562,9 +592,11 @@ def _generate_design(self, infolist=None): if isdefined(self.inputs.realignment_parameters): realignment_parameters = [] for parfile in self.inputs.realignment_parameters: - mc = np.apply_along_axis(func1d=normalize_mc_params, - axis=1, arr=np.loadtxt(parfile), - source=self.inputs.parameter_source) + mc = np.apply_along_axis( + func1d=normalize_mc_params, + axis=1, + arr=np.loadtxt(parfile), + source=self.inputs.parameter_source) if not realignment_parameters: realignment_parameters.insert(0, mc) else: @@ -581,41 +613,46 @@ def _generate_design(self, infolist=None): out = np.array([]) if out.size > 0: - iflogger.debug('fname=%s, out=%s, nscans=%d', - filename, out, sum(nscans[0:i])) + iflogger.debug('fname=%s, out=%s, nscans=%d', filename, + out, sum(nscans[0:i])) sumscans = out.astype(int) + sum(nscans[0:i]) if out.size == 1: - outliers[0]+= [np.array(sumscans, dtype=int).tolist()] + outliers[0] += [np.array(sumscans, dtype=int).tolist()] else: - outliers[0]+= np.array(sumscans, dtype=int).tolist() + outliers[0] += np.array(sumscans, dtype=int).tolist() - self._sessinfo = self._generate_standard_design(concatlist, - functional_runs=functional_runs, - realignment_parameters=realignment_parameters, - outliers=outliers) + self._sessinfo = self._generate_standard_design( + concatlist, + functional_runs=functional_runs, + realignment_parameters=realignment_parameters, + outliers=outliers) class SpecifySparseModelInputSpec(SpecifyModelInputSpec): - time_acquisition = traits.Float(0, mandatory=True, - desc='Time in seconds to acquire a single ' - 'image volume') - volumes_in_cluster = traits.Range(1, usedefault=True, - desc='Number of scan volumes in a cluster') + time_acquisition = traits.Float( + 0, + mandatory=True, + desc='Time in seconds to acquire a single ' + 'image volume') + volumes_in_cluster = traits.Range( + 1, usedefault=True, desc='Number of scan volumes in a cluster') model_hrf = traits.Bool(desc='Model sparse events with hrf') - stimuli_as_impulses = traits.Bool(True, - desc='Treat each stimulus to be impulse-like', - usedefault=True) - use_temporal_deriv = traits.Bool(requires=['model_hrf'], - desc='Create a temporal derivative in ' - 'addition to regular regressor') - scale_regressors = traits.Bool(True, desc='Scale regressors by the peak', - usedefault=True) - scan_onset = traits.Float(0.0, - desc='Start of scanning relative to onset of run in secs', - usedefault=True) - save_plot = traits.Bool(desc=('Save plot of sparse design calculation ' - '(requires matplotlib)')) + stimuli_as_impulses = traits.Bool( + True, desc='Treat each stimulus to be impulse-like', usedefault=True) + use_temporal_deriv = traits.Bool( + requires=['model_hrf'], + desc='Create a temporal derivative in ' + 'addition to regular regressor') + scale_regressors = traits.Bool( + True, desc='Scale regressors by the peak', usedefault=True) + scan_onset = traits.Float( + 0.0, + desc='Start of scanning relative to onset of run in secs', + usedefault=True) + save_plot = traits.Bool( + desc=('Save plot of sparse design calculation ' + '(requires matplotlib)')) class SpecifySparseModelOutputSpec(SpecifyModelOutputSpec): @@ -791,17 +828,13 @@ def _cond_to_regress(self, info, nscans): amplitudes = None regnames.insert(len(regnames), cond) scaled_onsets = scale_timings(info.onsets[i], - self.inputs.input_units, - 'secs', + self.inputs.input_units, 'secs', self.inputs.time_repetition) scaled_durations = scale_timings(info.durations[i], - self.inputs.input_units, - 'secs', + self.inputs.input_units, 'secs', self.inputs.time_repetition) - regressor = self._gen_regress(scaled_onsets, - scaled_durations, - amplitudes, - nscans) + regressor = self._gen_regress(scaled_onsets, scaled_durations, + amplitudes, nscans) if isdefined(self.inputs.use_temporal_deriv) and \ self.inputs.use_temporal_deriv: reg.insert(len(reg), regressor[0]) @@ -863,6 +896,8 @@ def _list_outputs(self): outputs['session_info'] = self._sessinfo if isdefined(self.inputs.save_plot) and self.inputs.save_plot: - outputs['sparse_png_file'] = os.path.join(os.getcwd(), 'sparse.png') - outputs['sparse_svg_file'] = os.path.join(os.getcwd(), 'sparse.svg') + outputs['sparse_png_file'] = os.path.join(os.getcwd(), + 'sparse.png') + outputs['sparse_svg_file'] = os.path.join(os.getcwd(), + 'sparse.svg') return outputs diff --git a/nipype/algorithms/rapidart.py b/nipype/algorithms/rapidart.py index 0ab74b7404..ddf8de8992 100644 --- a/nipype/algorithms/rapidart.py +++ b/nipype/algorithms/rapidart.py @@ -18,8 +18,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) >>> os.chdir(datadir) """ -from __future__ import (print_function, division, - unicode_literals, absolute_import) +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open, range, str, bytes import os @@ -59,7 +59,7 @@ def _get_affine_matrix(params, source): q = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0]) if len(params) < 12: params = np.hstack((params, q[len(params):])) - params.shape = (len(params),) + params.shape = (len(params), ) # Translation T = np.eye(4) T[0:3, -1] = params[0:3] @@ -100,8 +100,9 @@ def _calc_norm(mc, use_differences, source, brain_pts=None): """ - affines = [_get_affine_matrix(mc[i, :], source) - for i in range(mc.shape[0])] + affines = [ + _get_affine_matrix(mc[i, :], source) for i in range(mc.shape[0]) + ] return _calc_norm_affine(affines, use_differences, brain_pts) @@ -137,16 +138,18 @@ def _calc_norm_affine(affines, use_differences, brain_pts=None): for i, affine in enumerate(affines): newpos[i, :] = np.dot(affine, all_pts)[0:3, :].ravel() if brain_pts is not None: - displacement[i, :] = np.sqrt(np.sum( - np.power(np.reshape(newpos[i, :], - (3, all_pts.shape[1])) - all_pts[0:3, :], - 2), - axis=0)) + displacement[i, :] = np.sqrt( + np.sum( + np.power( + np.reshape(newpos[i, :], + (3, all_pts.shape[1])) - all_pts[0:3, :], + 2), + axis=0)) # np.savez('displacement.npz', newpos=newpos, pts=all_pts) normdata = np.zeros(len(affines)) if use_differences: - newpos = np.concatenate((np.zeros((1, n_pts)), - np.diff(newpos, n=1, axis=0)), axis=0) + newpos = np.concatenate( + (np.zeros((1, n_pts)), np.diff(newpos, n=1, axis=0)), axis=0) for i in range(newpos.shape[0]): normdata[i] = \ np.max(np.sqrt(np.sum( @@ -160,117 +163,148 @@ def _calc_norm_affine(affines, use_differences, brain_pts=None): class ArtifactDetectInputSpec(BaseInterfaceInputSpec): - realigned_files = InputMultiPath(File(exists=True), - desc=("Names of realigned functional data " - "files"), - mandatory=True) - realignment_parameters = InputMultiPath(File(exists=True), - mandatory=True, - desc=("Names of realignment " - "parameters corresponding to " - "the functional data files")) - parameter_source = traits.Enum("SPM", "FSL", "AFNI", "NiPy", "FSFAST", - desc="Source of movement parameters", - mandatory=True) - use_differences = traits.ListBool([True, False], - minlen=2, - maxlen=2, - usedefault=True, - desc=("Use differences between successive" - " motion (first element) and " - "intensity parameter (second " - "element) estimates in order to " - "determine outliers. " - "(default is [True, False])")) - use_norm = traits.Bool(True, - usedefault=True, - requires=['norm_threshold'], - desc=("Uses a composite of the motion parameters in " - "order to determine outliers.")) - norm_threshold = traits.Float(xor=['rotation_threshold', - 'translation_threshold'], - mandatory=True, - desc=("Threshold to use to detect motion-rela" - "ted outliers when composite motion is " - "being used")) - rotation_threshold = traits.Float(mandatory=True, - xor=['norm_threshold'], - desc=("Threshold (in radians) to use to " - "detect rotation-related outliers")) - translation_threshold = traits.Float(mandatory=True, - xor=['norm_threshold'], - desc=("Threshold (in mm) to use to " - "detect translation-related " - "outliers")) - zintensity_threshold = traits.Float(mandatory=True, - desc=("Intensity Z-threshold use to " - "detection images that deviate " - "from the mean")) - mask_type = traits.Enum('spm_global', 'file', 'thresh', - mandatory=True, - desc=("Type of mask that should be used to mask the" - " functional data. *spm_global* uses an " - "spm_global like calculation to determine the" - " brain mask. *file* specifies a brain mask " - "file (should be an image file consisting of " - "0s and 1s). *thresh* specifies a threshold " - "to use. By default all voxels are used," - "unless one of these mask types are defined")) - mask_file = File(exists=True, - desc="Mask file to be used if mask_type is 'file'.") - mask_threshold = traits.Float(desc=("Mask threshold to be used if mask_type" - " is 'thresh'.")) - intersect_mask = traits.Bool(True, - desc=("Intersect the masks when computed from " - "spm_global.")) - save_plot = traits.Bool(True, desc="save plots containing outliers", - usedefault=True) - plot_type = traits.Enum('png', 'svg', 'eps', 'pdf', - desc="file type of the outlier plot", - usedefault=True) - bound_by_brainmask = traits.Bool(False, desc=("use the brain mask to " - "determine bounding box" - "for composite norm (works" - "for SPM and Nipy - currently" - "inaccurate for FSL, AFNI"), - usedefault=True) - global_threshold = traits.Float(8.0, desc=("use this threshold when mask " - "type equal's spm_global"), - usedefault=True) + realigned_files = InputMultiPath( + File(exists=True), + desc=("Names of realigned functional data " + "files"), + mandatory=True) + realignment_parameters = InputMultiPath( + File(exists=True), + mandatory=True, + desc=("Names of realignment " + "parameters corresponding to " + "the functional data files")) + parameter_source = traits.Enum( + "SPM", + "FSL", + "AFNI", + "NiPy", + "FSFAST", + desc="Source of movement parameters", + mandatory=True) + use_differences = traits.ListBool( + [True, False], + minlen=2, + maxlen=2, + usedefault=True, + desc=("Use differences between successive" + " motion (first element) and " + "intensity parameter (second " + "element) estimates in order to " + "determine outliers. " + "(default is [True, False])")) + use_norm = traits.Bool( + True, + usedefault=True, + requires=['norm_threshold'], + desc=("Uses a composite of the motion parameters in " + "order to determine outliers.")) + norm_threshold = traits.Float( + xor=['rotation_threshold', 'translation_threshold'], + mandatory=True, + desc=("Threshold to use to detect motion-rela" + "ted outliers when composite motion is " + "being used")) + rotation_threshold = traits.Float( + mandatory=True, + xor=['norm_threshold'], + desc=("Threshold (in radians) to use to " + "detect rotation-related outliers")) + translation_threshold = traits.Float( + mandatory=True, + xor=['norm_threshold'], + desc=("Threshold (in mm) to use to " + "detect translation-related " + "outliers")) + zintensity_threshold = traits.Float( + mandatory=True, + desc=("Intensity Z-threshold use to " + "detection images that deviate " + "from the mean")) + mask_type = traits.Enum( + 'spm_global', + 'file', + 'thresh', + mandatory=True, + desc=("Type of mask that should be used to mask the" + " functional data. *spm_global* uses an " + "spm_global like calculation to determine the" + " brain mask. *file* specifies a brain mask " + "file (should be an image file consisting of " + "0s and 1s). *thresh* specifies a threshold " + "to use. By default all voxels are used," + "unless one of these mask types are defined")) + mask_file = File( + exists=True, desc="Mask file to be used if mask_type is 'file'.") + mask_threshold = traits.Float( + desc=("Mask threshold to be used if mask_type" + " is 'thresh'.")) + intersect_mask = traits.Bool( + True, desc=("Intersect the masks when computed from " + "spm_global.")) + save_plot = traits.Bool( + True, desc="save plots containing outliers", usedefault=True) + plot_type = traits.Enum( + 'png', + 'svg', + 'eps', + 'pdf', + desc="file type of the outlier plot", + usedefault=True) + bound_by_brainmask = traits.Bool( + False, + desc=("use the brain mask to " + "determine bounding box" + "for composite norm (works" + "for SPM and Nipy - currently" + "inaccurate for FSL, AFNI"), + usedefault=True) + global_threshold = traits.Float( + 8.0, + desc=("use this threshold when mask " + "type equal's spm_global"), + usedefault=True) class ArtifactDetectOutputSpec(TraitedSpec): - outlier_files = OutputMultiPath(File(exists=True), - desc=("One file for each functional run " - "containing a list of 0-based indices" - " corresponding to outlier volumes")) - intensity_files = OutputMultiPath(File(exists=True), - desc=("One file for each functional run " - "containing the global intensity " - "values determined from the " - "brainmask")) - norm_files = OutputMultiPath(File, - desc=("One file for each functional run " - "containing the composite norm")) - statistic_files = OutputMultiPath(File(exists=True), - desc=("One file for each functional run " - "containing information about the " - "different types of artifacts and " - "if design info is provided then " - "details of stimulus correlated " - "motion and a listing or artifacts " - "by event type.")) - plot_files = OutputMultiPath(File, - desc=("One image file for each functional run " - "containing the detected outliers")) - mask_files = OutputMultiPath(File, - desc=("One image file for each functional run " - "containing the mask used for global " - "signal calculation")) - displacement_files = OutputMultiPath(File, - desc=("One image file for each " - "functional run containing the " - "voxel displacement timeseries")) + outlier_files = OutputMultiPath( + File(exists=True), + desc=("One file for each functional run " + "containing a list of 0-based indices" + " corresponding to outlier volumes")) + intensity_files = OutputMultiPath( + File(exists=True), + desc=("One file for each functional run " + "containing the global intensity " + "values determined from the " + "brainmask")) + norm_files = OutputMultiPath( + File, + desc=("One file for each functional run " + "containing the composite norm")) + statistic_files = OutputMultiPath( + File(exists=True), + desc=("One file for each functional run " + "containing information about the " + "different types of artifacts and " + "if design info is provided then " + "details of stimulus correlated " + "motion and a listing or artifacts " + "by event type.")) + plot_files = OutputMultiPath( + File, + desc=("One image file for each functional run " + "containing the detected outliers")) + mask_files = OutputMultiPath( + File, + desc=("One image file for each functional run " + "containing the mask used for global " + "signal calculation")) + displacement_files = OutputMultiPath( + File, + desc=("One image file for each " + "functional run containing the " + "voxel displacement timeseries")) class ArtifactDetect(BaseInterface): @@ -330,8 +364,8 @@ def _get_output_filenames(self, motionfile, output_dir): '.txt'))) plotfile = os.path.join(output_dir, ''.join(('plot.', filename, '.', self.inputs.plot_type))) - displacementfile = os.path.join(output_dir, ''.join(('disp.', - filename, ext))) + displacementfile = os.path.join(output_dir, ''.join(('disp.', filename, + ext))) maskfile = os.path.join(output_dir, ''.join(('mask.', filename, ext))) return (artifactfile, intensityfile, statsfile, normfile, plotfile, displacementfile, maskfile) @@ -372,9 +406,9 @@ def _plot_outliers_with_wave(self, wave, outliers, name): plt.ylim([wave.min(), wave.max()]) plt.xlim([0, len(wave) - 1]) if len(outliers): - plt.plot(np.tile(outliers[:, None], (1, 2)).T, - np.tile([wave.min(), wave.max()], (len(outliers), 1)).T, - 'r') + plt.plot( + np.tile(outliers[:, None], (1, 2)).T, + np.tile([wave.min(), wave.max()], (len(outliers), 1)).T, 'r') plt.xlabel('Scans - 0-based') plt.ylabel(name) @@ -448,8 +482,8 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): # compute normalized intensity values gz = signal.detrend(g, axis=0) # detrend the signal if self.inputs.use_differences[1]: - gz = np.concatenate((np.zeros((1, 1)), np.diff(gz, n=1, axis=0)), - axis=0) + gz = np.concatenate( + (np.zeros((1, 1)), np.diff(gz, n=1, axis=0)), axis=0) gz = (gz - np.mean(gz)) / np.std(gz) # normalize the detrended signal iidx = find_indices(abs(gz) > self.inputs.zintensity_threshold) @@ -458,7 +492,8 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): mc = deepcopy(mc_in) (artifactfile, intensityfile, statsfile, normfile, plotfile, - displacementfile, maskfile) = self._get_output_filenames(imgfile, cwd) + displacementfile, maskfile) = self._get_output_filenames( + imgfile, cwd) mask_img = Nifti1Image(mask.astype(np.uint8), affine) mask_img.to_filename(maskfile) @@ -471,34 +506,33 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): voxel_coords[2])))).T brain_pts = np.dot(affine, np.hstack((coords, - np.ones((coords.shape[0], 1)))).T) + np.ones((coords.shape[0], + 1)))).T) # calculate the norm of the motion parameters - normval, displacement = _calc_norm(mc, - self.inputs.use_differences[0], - self.inputs.parameter_source, - brain_pts=brain_pts) + normval, displacement = _calc_norm( + mc, + self.inputs.use_differences[0], + self.inputs.parameter_source, + brain_pts=brain_pts) tidx = find_indices(normval > self.inputs.norm_threshold) ridx = find_indices(normval < 0) if displacement is not None: dmap = np.zeros((x, y, z, timepoints), dtype=np.float) for i in range(timepoints): - dmap[voxel_coords[0], - voxel_coords[1], - voxel_coords[2], i] = displacement[i, :] + dmap[voxel_coords[0], voxel_coords[1], voxel_coords[2], + i] = displacement[i, :] dimg = Nifti1Image(dmap, affine) dimg.to_filename(displacementfile) else: if self.inputs.use_differences[0]: - mc = np.concatenate((np.zeros((1, 6)), - np.diff(mc_in, n=1, axis=0)), - axis=0) + mc = np.concatenate( + (np.zeros((1, 6)), np.diff(mc_in, n=1, axis=0)), axis=0) traval = mc[:, 0:3] # translation parameters (mm) rotval = mc[:, 3:6] # rotation parameters (rad) - tidx = find_indices(np.sum(abs(traval) > - self.inputs.translation_threshold, 1) > - 0) - ridx = find_indices(np.sum(abs(rotval) > - self.inputs.rotation_threshold, 1) > 0) + tidx = find_indices( + np.sum(abs(traval) > self.inputs.translation_threshold, 1) > 0) + ridx = find_indices( + np.sum(abs(rotval) > self.inputs.rotation_threshold, 1) > 0) outliers = np.unique(np.union1d(iidx, np.union1d(tidx, ridx))) @@ -536,35 +570,53 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): plt.close(fig) motion_outliers = np.union1d(tidx, ridx) - stats = [{'motion_file': motionfile, - 'functional_file': imgfile}, - {'common_outliers': len(np.intersect1d(iidx, motion_outliers)), - 'intensity_outliers': len(np.setdiff1d(iidx, - motion_outliers)), - 'motion_outliers': len(np.setdiff1d(motion_outliers, iidx)), - }, - {'motion': [ - {'using differences': self.inputs.use_differences[0]}, - {'mean': np.mean(mc_in, axis=0).tolist(), - 'min': np.min(mc_in, axis=0).tolist(), - 'max': np.max(mc_in, axis=0).tolist(), - 'std': np.std(mc_in, axis=0).tolist()}, - ]}, - {'intensity': [ - {'using differences': self.inputs.use_differences[1]}, - {'mean': np.mean(gz, axis=0).tolist(), - 'min': np.min(gz, axis=0).tolist(), - 'max': np.max(gz, axis=0).tolist(), - 'std': np.std(gz, axis=0).tolist()}, - ]}, - ] + stats = [ + { + 'motion_file': motionfile, + 'functional_file': imgfile + }, + { + 'common_outliers': len(np.intersect1d(iidx, motion_outliers)), + 'intensity_outliers': len(np.setdiff1d(iidx, motion_outliers)), + 'motion_outliers': len(np.setdiff1d(motion_outliers, iidx)), + }, + { + 'motion': [ + { + 'using differences': self.inputs.use_differences[0] + }, + { + 'mean': np.mean(mc_in, axis=0).tolist(), + 'min': np.min(mc_in, axis=0).tolist(), + 'max': np.max(mc_in, axis=0).tolist(), + 'std': np.std(mc_in, axis=0).tolist() + }, + ] + }, + { + 'intensity': [ + { + 'using differences': self.inputs.use_differences[1] + }, + { + 'mean': np.mean(gz, axis=0).tolist(), + 'min': np.min(gz, axis=0).tolist(), + 'max': np.max(gz, axis=0).tolist(), + 'std': np.std(gz, axis=0).tolist() + }, + ] + }, + ] if self.inputs.use_norm: - stats.insert(3, {'motion_norm': - {'mean': np.mean(normval, axis=0).tolist(), - 'min': np.min(normval, axis=0).tolist(), - 'max': np.max(normval, axis=0).tolist(), - 'std': np.std(normval, axis=0).tolist(), - }}) + stats.insert( + 3, { + 'motion_norm': { + 'mean': np.mean(normval, axis=0).tolist(), + 'min': np.min(normval, axis=0).tolist(), + 'max': np.max(normval, axis=0).tolist(), + 'std': np.std(normval, axis=0).tolist(), + } + }) save_json(statsfile, stats) def _run_interface(self, runtime): @@ -573,33 +625,38 @@ def _run_interface(self, runtime): funcfilelist = filename_to_list(self.inputs.realigned_files) motparamlist = filename_to_list(self.inputs.realignment_parameters) for i, imgf in enumerate(funcfilelist): - self._detect_outliers_core(imgf, motparamlist[i], i, - cwd=os.getcwd()) + self._detect_outliers_core( + imgf, motparamlist[i], i, cwd=os.getcwd()) return runtime class StimCorrInputSpec(BaseInterfaceInputSpec): - realignment_parameters = InputMultiPath(File(exists=True), - mandatory=True, - desc=("Names of realignment " - "parameters corresponding to " - "the functional data files")) - intensity_values = InputMultiPath(File(exists=True), - mandatory=True, - desc=("Name of file containing intensity " - "values")) - spm_mat_file = File(exists=True, - mandatory=True, - desc="SPM mat file (use pre-estimate SPM.mat file)") - concatenated_design = traits.Bool(mandatory=True, - desc=("state if the design matrix " - "contains concatenated sessions")) + realignment_parameters = InputMultiPath( + File(exists=True), + mandatory=True, + desc=("Names of realignment " + "parameters corresponding to " + "the functional data files")) + intensity_values = InputMultiPath( + File(exists=True), + mandatory=True, + desc=("Name of file containing intensity " + "values")) + spm_mat_file = File( + exists=True, + mandatory=True, + desc="SPM mat file (use pre-estimate SPM.mat file)") + concatenated_design = traits.Bool( + mandatory=True, + desc=("state if the design matrix " + "contains concatenated sessions")) class StimCorrOutputSpec(TraitedSpec): - stimcorr_files = OutputMultiPath(File(exists=True), - desc=("List of files containing " - "correlation values")) + stimcorr_files = OutputMultiPath( + File(exists=True), + desc=("List of files containing " + "correlation values")) class StimulusCorrelation(BaseInterface): @@ -644,7 +701,8 @@ def _get_output_filenames(self, motionfile, output_dir): '_stimcorr.txt'))) return corrfile - def _stimcorr_core(self, motionfile, intensityfile, designmatrix, cwd=None): + def _stimcorr_core(self, motionfile, intensityfile, designmatrix, + cwd=None): """ Core routine for determining stimulus correlation @@ -687,10 +745,11 @@ def _get_spm_submatrix(self, spmmat, sessidx, rows=None): U = spmmat['SPM'][0][0].Sess[0][sessidx].U[0] if rows is None: rows = spmmat['SPM'][0][0].Sess[0][sessidx].row[0] - 1 - cols = ( - spmmat['SPM'][0][0].Sess[0][sessidx].col[0][list(range(len(U)))]-1) - outmatrix = designmatrix.take(rows.tolist(), axis=0).take(cols.tolist(), - axis=1) + cols = (spmmat['SPM'][0][0].Sess[0][sessidx].col[0][list( + range(len(U)))] - 1) + outmatrix = designmatrix.take( + rows.tolist(), axis=0).take( + cols.tolist(), axis=1) return outmatrix def _run_interface(self, runtime): @@ -709,8 +768,8 @@ def _run_interface(self, runtime): rows = np.sum(nrows) + np.arange(mc_in.shape[0]) nrows.append(mc_in.shape[0]) matrix = self._get_spm_submatrix(spmmat, sessidx, rows) - self._stimcorr_core(motparamlist[i], intensityfiles[i], - matrix, os.getcwd()) + self._stimcorr_core(motparamlist[i], intensityfiles[i], matrix, + os.getcwd()) return runtime def _list_outputs(self): diff --git a/nipype/algorithms/tests/test_CompCor.py b/nipype/algorithms/tests/test_CompCor.py index 9407e6ef0d..488ad3c960 100644 --- a/nipype/algorithms/tests/test_CompCor.py +++ b/nipype/algorithms/tests/test_CompCor.py @@ -13,18 +13,20 @@ class TestCompCor(): ''' Note: Tests currently do a poor job of testing functionality ''' - filenames = {'functionalnii': 'compcorfunc.nii', - 'masknii': 'compcormask.nii', - 'masknii2': 'compcormask2.nii', - 'components_file': None} + filenames = { + 'functionalnii': 'compcorfunc.nii', + 'masknii': 'compcormask.nii', + 'masknii2': 'compcormask2.nii', + 'components_file': None + } @pytest.fixture(autouse=True) def setup_class(self, tmpdir): # setup tmpdir.chdir() noise = np.fromfunction(self.fake_noise_fun, self.fake_data.shape) - self.realigned_file = utils.save_toy_nii(self.fake_data + noise, - self.filenames['functionalnii']) + self.realigned_file = utils.save_toy_nii( + self.fake_data + noise, self.filenames['functionalnii']) mask = np.ones(self.fake_data.shape[:3]) mask[0, 0, 0] = 0 mask[0, 0, 1] = 0 @@ -37,35 +39,35 @@ def setup_class(self, tmpdir): self.mask_files = [mask1, mask2] - def test_compcor(self): - expected_components = [['-0.1989607212', '-0.5753813646'], - ['0.5692369697', '0.5674945949'], - ['-0.6662573243', '0.4675843432'], - ['0.4206466244', '-0.3361270124'], + expected_components = [['-0.1989607212', '-0.5753813646'], [ + '0.5692369697', '0.5674945949' + ], ['-0.6662573243', + '0.4675843432'], ['0.4206466244', '-0.3361270124'], ['-0.1246655485', '-0.1235705610']] - self.run_cc(CompCor(realigned_file=self.realigned_file, - mask_files=self.mask_files, - mask_index=0), - expected_components) - - self.run_cc(ACompCor(realigned_file=self.realigned_file, - mask_files=self.mask_files, - mask_index=0, - components_file='acc_components_file'), - expected_components, 'aCompCor') + self.run_cc( + CompCor( + realigned_file=self.realigned_file, + mask_files=self.mask_files, + mask_index=0), expected_components) + self.run_cc( + ACompCor( + realigned_file=self.realigned_file, + mask_files=self.mask_files, + mask_index=0, + components_file='acc_components_file'), expected_components, + 'aCompCor') def test_tcompcor(self): - ccinterface = TCompCor(realigned_file=self.realigned_file, - percentile_threshold=0.75) - self.run_cc(ccinterface, [['-0.1114536190', '-0.4632908609'], - ['0.4566907310', '0.6983205193'], - ['-0.7132557407', '0.1340170559'], - ['0.5022537643', '-0.5098322262'], - ['-0.1342351356', '0.1407855119']], - 'tCompCor') + ccinterface = TCompCor( + realigned_file=self.realigned_file, percentile_threshold=0.75) + self.run_cc(ccinterface, [['-0.1114536190', '-0.4632908609'], [ + '0.4566907310', '0.6983205193' + ], ['-0.7132557407', '0.1340170559'], [ + '0.5022537643', '-0.5098322262' + ], ['-0.1342351356', '0.1407855119']], 'tCompCor') def test_tcompcor_no_percentile(self): ccinterface = TCompCor(realigned_file=self.realigned_file) @@ -76,66 +78,80 @@ def test_tcompcor_no_percentile(self): assert num_nonmasked_voxels == 1 def test_compcor_no_regress_poly(self): - self.run_cc(CompCor(realigned_file=self.realigned_file, - mask_files=self.mask_files, - mask_index=0, - pre_filter=False), - [['0.4451946442', '-0.7683311482'], - ['-0.4285129505', '-0.0926034137'], - ['0.5721540256', '0.5608764842'], - ['-0.5367548139', '0.0059943226'], - ['-0.0520809054', '0.2940637551']]) + self.run_cc( + CompCor( + realigned_file=self.realigned_file, + mask_files=self.mask_files, + mask_index=0, + pre_filter=False), [['0.4451946442', '-0.7683311482'], [ + '-0.4285129505', '-0.0926034137' + ], ['0.5721540256', '0.5608764842'], [ + '-0.5367548139', '0.0059943226' + ], ['-0.0520809054', '0.2940637551']]) def test_tcompcor_asymmetric_dim(self): asymmetric_shape = (2, 3, 4, 5) - asymmetric_data = utils.save_toy_nii(np.zeros(asymmetric_shape), - 'asymmetric.nii') + asymmetric_data = utils.save_toy_nii( + np.zeros(asymmetric_shape), 'asymmetric.nii') TCompCor(realigned_file=asymmetric_data).run() - assert nb.load('mask_000.nii.gz').get_data().shape == asymmetric_shape[:3] + assert nb.load( + 'mask_000.nii.gz').get_data().shape == asymmetric_shape[:3] def test_compcor_bad_input_shapes(self): - shape_less_than = (1, 2, 2, 5) # dim 0 is < dim 0 of self.mask_files (2) - shape_more_than = (3, 3, 3, 5) # dim 0 is > dim 0 of self.mask_files (2) + # dim 0 is < dim 0 of self.mask_files (2) + shape_less_than = (1, 2, 2, 5) + # dim 0 is > dim 0 of self.mask_files (2) + shape_more_than = (3, 3, 3, 5) for data_shape in (shape_less_than, shape_more_than): data_file = utils.save_toy_nii(np.zeros(data_shape), 'temp.nii') - interface = CompCor(realigned_file=data_file, - mask_files=self.mask_files[0]) - with pytest.raises(ValueError, message="Dimension mismatch"): interface.run() + interface = CompCor( + realigned_file=data_file, mask_files=self.mask_files[0]) + with pytest.raises(ValueError, message="Dimension mismatch"): + interface.run() def test_tcompcor_bad_input_dim(self): bad_dims = (2, 2, 2) data_file = utils.save_toy_nii(np.zeros(bad_dims), 'temp.nii') interface = TCompCor(realigned_file=data_file) - with pytest.raises(ValueError, message='Not a 4D file'): interface.run() + with pytest.raises(ValueError, message='Not a 4D file'): + interface.run() def test_tcompcor_merge_intersect_masks(self): for method in ['union', 'intersect']: - TCompCor(realigned_file=self.realigned_file, - mask_files=self.mask_files, - merge_method=method).run() + TCompCor( + realigned_file=self.realigned_file, + mask_files=self.mask_files, + merge_method=method).run() if method == 'union': - assert np.array_equal(nb.load('mask_000.nii.gz').get_data(), - ([[[0,0],[0,0]],[[0,0],[1,0]]])) + assert np.array_equal( + nb.load('mask_000.nii.gz').get_data(), + ([[[0, 0], [0, 0]], [[0, 0], [1, 0]]])) if method == 'intersect': - assert np.array_equal(nb.load('mask_000.nii.gz').get_data(), - ([[[0,0],[0,0]],[[0,1],[0,0]]])) + assert np.array_equal( + nb.load('mask_000.nii.gz').get_data(), + ([[[0, 0], [0, 0]], [[0, 1], [0, 0]]])) def test_tcompcor_index_mask(self): - TCompCor(realigned_file=self.realigned_file, - mask_files=self.mask_files, - mask_index=1).run() - assert np.array_equal(nb.load('mask_000.nii.gz').get_data(), - ([[[0,0],[0,0]],[[0,1],[0,0]]])) + TCompCor( + realigned_file=self.realigned_file, + mask_files=self.mask_files, + mask_index=1).run() + assert np.array_equal( + nb.load('mask_000.nii.gz').get_data(), + ([[[0, 0], [0, 0]], [[0, 1], [0, 0]]])) def test_tcompcor_multi_mask_no_index(self): - interface = TCompCor(realigned_file=self.realigned_file, - mask_files=self.mask_files) + interface = TCompCor( + realigned_file=self.realigned_file, mask_files=self.mask_files) with pytest.raises(ValueError, message='more than one mask file'): interface.run() - def run_cc(self, ccinterface, expected_components, expected_header='CompCor'): + def run_cc(self, + ccinterface, + expected_components, + expected_header='CompCor'): # run ccresult = ccinterface.run() @@ -154,8 +170,10 @@ def run_cc(self, ccinterface, expected_components, expected_header='CompCor'): # the first item will be '#', we can throw it out header = components_data.pop(0) - expected_header = [expected_header + '{:02d}'.format(i) for i in - range(expected_n_components)] + expected_header = [ + expected_header + '{:02d}'.format(i) + for i in range(expected_n_components) + ] for i, heading in enumerate(header): assert expected_header[i] in heading @@ -167,19 +185,11 @@ def run_cc(self, ccinterface, expected_components, expected_header='CompCor'): assert timepoint[:2] == expected_components[index] return ccresult - @staticmethod def fake_noise_fun(i, j, l, m): - return m*i + l - j - - fake_data = np.array([[[[8, 5, 3, 8, 0], - [6, 7, 4, 7, 1]], - - [[7, 9, 1, 6, 5], - [0, 7, 4, 7, 7]]], - - [[[2, 4, 5, 7, 0], - [1, 7, 0, 5, 4]], + return m * i + l - j - [[7, 3, 9, 0, 4], - [9, 4, 1, 5, 0]]]]) + fake_data = np.array([[[[8, 5, 3, 8, 0], [6, 7, 4, 7, 1]], + [[7, 9, 1, 6, 5], [0, 7, 4, 7, 7]]], + [[[2, 4, 5, 7, 0], [1, 7, 0, 5, 4]], + [[7, 3, 9, 0, 4], [9, 4, 1, 5, 0]]]]) diff --git a/nipype/algorithms/tests/test_ErrorMap.py b/nipype/algorithms/tests/test_ErrorMap.py index 4b40d14907..cfd30b0b74 100644 --- a/nipype/algorithms/tests/test_ErrorMap.py +++ b/nipype/algorithms/tests/test_ErrorMap.py @@ -13,8 +13,10 @@ def test_errormap(tmpdir): # Single-Spectual # Make two fake 2*2*2 voxel volumes - volume1 = np.array([[[2.0, 8.0], [1.0, 2.0]], [[1.0, 9.0], [0.0, 3.0]]]) # John von Neumann's birthday - volume2 = np.array([[[0.0, 7.0], [2.0, 3.0]], [[1.0, 9.0], [1.0, 2.0]]]) # Alan Turing's birthday + # John von Neumann's birthday + volume1 = np.array([[[2.0, 8.0], [1.0, 2.0]], [[1.0, 9.0], [0.0, 3.0]]]) + # Alan Turing's birthday + volume2 = np.array([[[0.0, 7.0], [2.0, 3.0]], [[1.0, 9.0], [1.0, 2.0]]]) mask = np.array([[[1, 0], [0, 1]], [[1, 0], [0, 1]]]) img1 = nb.Nifti1Image(volume1, np.eye(4)) @@ -49,7 +51,8 @@ def test_errormap(tmpdir): assert result.outputs.distance == 1.0 # Multi-Spectual - volume3 = np.array([[[1.0, 6.0], [0.0, 3.0]], [[1.0, 9.0], [3.0, 6.0]]]) # Raymond Vahan Damadian's birthday + # Raymond Vahan Damadian's birthday + volume3 = np.array([[[1.0, 6.0], [0.0, 3.0]], [[1.0, 9.0], [3.0, 6.0]]]) msvolume1 = np.zeros(shape=(2, 2, 2, 2)) msvolume1[:, :, :, 0] = volume1 diff --git a/nipype/algorithms/tests/test_Overlap.py b/nipype/algorithms/tests/test_Overlap.py index e0ec5bcfcb..786a7328b8 100644 --- a/nipype/algorithms/tests/test_Overlap.py +++ b/nipype/algorithms/tests/test_Overlap.py @@ -39,6 +39,5 @@ def check_close(val1, val2): overlap.inputs.vol_units = 'mm' res = overlap.run() check_close(res.outputs.jaccard, 0.99705) - check_close(res.outputs.roi_voldiff, - np.array([0.0063086, -0.0025506, 0.0])) - + check_close(res.outputs.roi_voldiff, np.array([0.0063086, -0.0025506, + 0.0])) diff --git a/nipype/algorithms/tests/test_TSNR.py b/nipype/algorithms/tests/test_TSNR.py index f4bac9a17d..1d192ec056 100644 --- a/nipype/algorithms/tests/test_TSNR.py +++ b/nipype/algorithms/tests/test_TSNR.py @@ -20,9 +20,9 @@ class TestTSNR(): 'in_file': 'tsnrinfile.nii', } - out_filenames = {# default output file names + out_filenames = { # default output file names 'detrended_file': 'detrend.nii.gz', - 'mean_file': 'mean.nii.gz', + 'mean_file': 'mean.nii.gz', 'stddev_file': 'stdev.nii.gz', 'tsnr_file': 'tsnr.nii.gz' } @@ -39,59 +39,67 @@ def test_tsnr(self): tsnrresult = TSNR(in_file=self.in_filenames['in_file']).run() # assert - self.assert_expected_outputs(tsnrresult, { - 'mean_file': (2.8, 7.4), - 'stddev_file': (0.8, 2.9), - 'tsnr_file': (1.3, 9.25) - }) + self.assert_expected_outputs( + tsnrresult, { + 'mean_file': (2.8, 7.4), + 'stddev_file': (0.8, 2.9), + 'tsnr_file': (1.3, 9.25) + }) def test_tsnr_withpoly1(self): # run - tsnrresult = TSNR(in_file=self.in_filenames['in_file'], - regress_poly=1).run() + tsnrresult = TSNR( + in_file=self.in_filenames['in_file'], regress_poly=1).run() # assert - self.assert_expected_outputs_poly(tsnrresult, { - 'detrended_file': (-0.1, 8.7), - 'mean_file': (2.8, 7.4), - 'stddev_file': (0.75, 2.75), - 'tsnr_file': (1.4, 9.9) - }) + self.assert_expected_outputs_poly( + tsnrresult, { + 'detrended_file': (-0.1, 8.7), + 'mean_file': (2.8, 7.4), + 'stddev_file': (0.75, 2.75), + 'tsnr_file': (1.4, 9.9) + }) def test_tsnr_withpoly2(self): # run - tsnrresult = TSNR(in_file=self.in_filenames['in_file'], - regress_poly=2).run() + tsnrresult = TSNR( + in_file=self.in_filenames['in_file'], regress_poly=2).run() # assert - self.assert_expected_outputs_poly(tsnrresult, { - 'detrended_file': (-0.22, 8.55), - 'mean_file': (2.8, 7.7), - 'stddev_file': (0.21, 2.4), - 'tsnr_file': (1.7, 35.9) - }) + self.assert_expected_outputs_poly( + tsnrresult, { + 'detrended_file': (-0.22, 8.55), + 'mean_file': (2.8, 7.7), + 'stddev_file': (0.21, 2.4), + 'tsnr_file': (1.7, 35.9) + }) def test_tsnr_withpoly3(self): # run - tsnrresult = TSNR(in_file=self.in_filenames['in_file'], - regress_poly=3).run() + tsnrresult = TSNR( + in_file=self.in_filenames['in_file'], regress_poly=3).run() # assert - self.assert_expected_outputs_poly(tsnrresult, { - 'detrended_file': (1.8, 7.95), - 'mean_file': (2.8, 7.7), - 'stddev_file': (0.1, 1.7), - 'tsnr_file': (2.6, 57.3) - }) + self.assert_expected_outputs_poly( + tsnrresult, { + 'detrended_file': (1.8, 7.95), + 'mean_file': (2.8, 7.7), + 'stddev_file': (0.1, 1.7), + 'tsnr_file': (2.6, 57.3) + }) @mock.patch('warnings.warn') def test_warning(self, mock_warn): - ''' test that usage of misc.TSNR trips a warning to use confounds.TSNR instead ''' + ''' test that usage of misc.TSNR trips a warning to use + confounds.TSNR instead ''' # run misc.TSNR(in_file=self.in_filenames['in_file']) # assert - assert True in [args[0].count('confounds') > 0 for _, args, _ in mock_warn.mock_calls] + assert True in [ + args[0].count('confounds') > 0 + for _, args, _ in mock_warn.mock_calls + ] def assert_expected_outputs_poly(self, tsnrresult, expected_ranges): assert os.path.basename(tsnrresult.outputs.detrended_file) == \ @@ -116,15 +124,7 @@ def assert_unchanged(self, expected_ranges): npt.assert_almost_equal(np.amin(data), min_, decimal=1) npt.assert_almost_equal(np.amax(data), max_, decimal=1) - - fake_data = np.array([[[[2, 4, 3, 9, 1], - [3, 6, 4, 7, 4]], - - [[8, 3, 4, 6, 2], - [4, 0, 4, 4, 2]]], - - [[[9, 7, 5, 5, 7], - [7, 8, 4, 8, 4]], - - [[0, 4, 7, 1, 7], - [6, 8, 8, 8, 7]]]]) + fake_data = np.array([[[[2, 4, 3, 9, 1], [3, 6, 4, 7, 4]], + [[8, 3, 4, 6, 2], [4, 0, 4, 4, 2]]], + [[[9, 7, 5, 5, 7], [7, 8, 4, 8, 4]], + [[0, 4, 7, 1, 7], [6, 8, 8, 8, 7]]]]) diff --git a/nipype/algorithms/tests/test_auto_ACompCor.py b/nipype/algorithms/tests/test_auto_ACompCor.py index a266d57ddb..f819f51f8b 100644 --- a/nipype/algorithms/tests/test_auto_ACompCor.py +++ b/nipype/algorithms/tests/test_auto_ACompCor.py @@ -4,48 +4,45 @@ def test_ACompCor_inputs(): - input_map = dict(components_file=dict(usedefault=True, - ), - header_prefix=dict(), - high_pass_cutoff=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_initial_volumes=dict(usedefault=True, - ), - mask_files=dict(), - mask_index=dict(requires=['mask_files'], - xor=['merge_method'], - ), - merge_method=dict(requires=['mask_files'], - xor=['mask_index'], - ), - num_components=dict(usedefault=True, - ), - pre_filter=dict(usedefault=True, - ), - realigned_file=dict(mandatory=True, - ), - regress_poly_degree=dict(usedefault=True, - ), - repetition_time=dict(), - save_pre_filter=dict(), - use_regress_poly=dict(deprecated='0.15.0', - new_name='pre_filter', - ), + input_map = dict( + components_file=dict(usedefault=True, ), + header_prefix=dict(), + high_pass_cutoff=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_initial_volumes=dict(usedefault=True, ), + mask_files=dict(), + mask_index=dict( + requires=['mask_files'], + xor=['merge_method'], + ), + merge_method=dict( + requires=['mask_files'], + xor=['mask_index'], + ), + num_components=dict(usedefault=True, ), + pre_filter=dict(usedefault=True, ), + realigned_file=dict(mandatory=True, ), + regress_poly_degree=dict(usedefault=True, ), + repetition_time=dict(), + save_pre_filter=dict(), + use_regress_poly=dict( + deprecated='0.15.0', + new_name='pre_filter', + ), ) inputs = ACompCor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ACompCor_outputs(): - output_map = dict(components_file=dict(), - pre_filter_file=dict(), + output_map = dict( + components_file=dict(), + pre_filter_file=dict(), ) outputs = ACompCor.output_spec() diff --git a/nipype/algorithms/tests/test_auto_AddCSVColumn.py b/nipype/algorithms/tests/test_auto_AddCSVColumn.py index 0b17e12661..feedcf46e8 100644 --- a/nipype/algorithms/tests/test_auto_AddCSVColumn.py +++ b/nipype/algorithms/tests/test_auto_AddCSVColumn.py @@ -4,23 +4,19 @@ def test_AddCSVColumn_inputs(): - input_map = dict(extra_column_heading=dict(), - extra_field=dict(), - in_file=dict(mandatory=True, - ), - out_file=dict(usedefault=True, - ), + input_map = dict( + extra_column_heading=dict(), + extra_field=dict(), + in_file=dict(mandatory=True, ), + out_file=dict(usedefault=True, ), ) inputs = AddCSVColumn.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AddCSVColumn_outputs(): - output_map = dict(csv_file=dict(), - ) + output_map = dict(csv_file=dict(), ) outputs = AddCSVColumn.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_AddCSVRow.py b/nipype/algorithms/tests/test_auto_AddCSVRow.py index 31cc6f7a09..0af4639d41 100644 --- a/nipype/algorithms/tests/test_auto_AddCSVRow.py +++ b/nipype/algorithms/tests/test_auto_AddCSVRow.py @@ -4,25 +4,22 @@ def test_AddCSVRow_inputs(): - input_map = dict(_outputs=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), + input_map = dict( + _outputs=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), ) inputs = AddCSVRow.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AddCSVRow_outputs(): - output_map = dict(csv_file=dict(), - ) + output_map = dict(csv_file=dict(), ) outputs = AddCSVRow.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_AddNoise.py b/nipype/algorithms/tests/test_auto_AddNoise.py index c69e707c52..6e0655a93e 100644 --- a/nipype/algorithms/tests/test_auto_AddNoise.py +++ b/nipype/algorithms/tests/test_auto_AddNoise.py @@ -4,29 +4,27 @@ def test_AddNoise_inputs(): - input_map = dict(bg_dist=dict(mandatory=True, - usedefault=True, - ), - dist=dict(mandatory=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - in_mask=dict(), - out_file=dict(), - snr=dict(usedefault=True, - ), + input_map = dict( + bg_dist=dict( + mandatory=True, + usedefault=True, + ), + dist=dict( + mandatory=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + in_mask=dict(), + out_file=dict(), + snr=dict(usedefault=True, ), ) inputs = AddNoise.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AddNoise_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = AddNoise.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_ArtifactDetect.py b/nipype/algorithms/tests/test_auto_ArtifactDetect.py index 196d297847..1de952cf78 100644 --- a/nipype/algorithms/tests/test_auto_ArtifactDetect.py +++ b/nipype/algorithms/tests/test_auto_ArtifactDetect.py @@ -4,63 +4,60 @@ def test_ArtifactDetect_inputs(): - input_map = dict(bound_by_brainmask=dict(usedefault=True, - ), - global_threshold=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - intersect_mask=dict(), - mask_file=dict(), - mask_threshold=dict(), - mask_type=dict(mandatory=True, - ), - norm_threshold=dict(mandatory=True, - xor=['rotation_threshold', 'translation_threshold'], - ), - parameter_source=dict(mandatory=True, - ), - plot_type=dict(usedefault=True, - ), - realigned_files=dict(mandatory=True, - ), - realignment_parameters=dict(mandatory=True, - ), - rotation_threshold=dict(mandatory=True, - xor=['norm_threshold'], - ), - save_plot=dict(usedefault=True, - ), - translation_threshold=dict(mandatory=True, - xor=['norm_threshold'], - ), - use_differences=dict(maxlen=2, - minlen=2, - usedefault=True, - ), - use_norm=dict(requires=['norm_threshold'], - usedefault=True, - ), - zintensity_threshold=dict(mandatory=True, - ), + input_map = dict( + bound_by_brainmask=dict(usedefault=True, ), + global_threshold=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + intersect_mask=dict(), + mask_file=dict(), + mask_threshold=dict(), + mask_type=dict(mandatory=True, ), + norm_threshold=dict( + mandatory=True, + xor=['rotation_threshold', 'translation_threshold'], + ), + parameter_source=dict(mandatory=True, ), + plot_type=dict(usedefault=True, ), + realigned_files=dict(mandatory=True, ), + realignment_parameters=dict(mandatory=True, ), + rotation_threshold=dict( + mandatory=True, + xor=['norm_threshold'], + ), + save_plot=dict(usedefault=True, ), + translation_threshold=dict( + mandatory=True, + xor=['norm_threshold'], + ), + use_differences=dict( + maxlen=2, + minlen=2, + usedefault=True, + ), + use_norm=dict( + requires=['norm_threshold'], + usedefault=True, + ), + zintensity_threshold=dict(mandatory=True, ), ) inputs = ArtifactDetect.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ArtifactDetect_outputs(): - output_map = dict(displacement_files=dict(), - intensity_files=dict(), - mask_files=dict(), - norm_files=dict(), - outlier_files=dict(), - plot_files=dict(), - statistic_files=dict(), + output_map = dict( + displacement_files=dict(), + intensity_files=dict(), + mask_files=dict(), + norm_files=dict(), + outlier_files=dict(), + plot_files=dict(), + statistic_files=dict(), ) outputs = ArtifactDetect.output_spec() diff --git a/nipype/algorithms/tests/test_auto_CalculateMedian.py b/nipype/algorithms/tests/test_auto_CalculateMedian.py index 77784f1bc9..84cafca391 100644 --- a/nipype/algorithms/tests/test_auto_CalculateMedian.py +++ b/nipype/algorithms/tests/test_auto_CalculateMedian.py @@ -4,25 +4,23 @@ def test_CalculateMedian_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(), - median_file=dict(), - median_per_file=dict(usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict(), + median_file=dict(), + median_per_file=dict(usedefault=True, ), ) inputs = CalculateMedian.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CalculateMedian_outputs(): - output_map = dict(median_files=dict(), - ) + output_map = dict(median_files=dict(), ) outputs = CalculateMedian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py b/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py index 05443b08b6..3dbbd772c8 100644 --- a/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py +++ b/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py @@ -4,21 +4,17 @@ def test_CalculateNormalizedMoments_inputs(): - input_map = dict(moment=dict(mandatory=True, - ), - timeseries_file=dict(mandatory=True, - ), + input_map = dict( + moment=dict(mandatory=True, ), + timeseries_file=dict(mandatory=True, ), ) inputs = CalculateNormalizedMoments.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CalculateNormalizedMoments_outputs(): - output_map = dict(moments=dict(), - ) + output_map = dict(moments=dict(), ) outputs = CalculateNormalizedMoments.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_ComputeDVARS.py b/nipype/algorithms/tests/test_auto_ComputeDVARS.py index 81aa16dde4..a35e785c99 100644 --- a/nipype/algorithms/tests/test_auto_ComputeDVARS.py +++ b/nipype/algorithms/tests/test_auto_ComputeDVARS.py @@ -4,54 +4,43 @@ def test_ComputeDVARS_inputs(): - input_map = dict(figdpi=dict(usedefault=True, - ), - figformat=dict(usedefault=True, - ), - figsize=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - in_mask=dict(mandatory=True, - ), - intensity_normalization=dict(usedefault=True, - ), - remove_zerovariance=dict(usedefault=True, - ), - save_all=dict(usedefault=True, - ), - save_nstd=dict(usedefault=True, - ), - save_plot=dict(usedefault=True, - ), - save_std=dict(usedefault=True, - ), - save_vxstd=dict(usedefault=True, - ), - series_tr=dict(), + input_map = dict( + figdpi=dict(usedefault=True, ), + figformat=dict(usedefault=True, ), + figsize=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + in_mask=dict(mandatory=True, ), + intensity_normalization=dict(usedefault=True, ), + remove_zerovariance=dict(usedefault=True, ), + save_all=dict(usedefault=True, ), + save_nstd=dict(usedefault=True, ), + save_plot=dict(usedefault=True, ), + save_std=dict(usedefault=True, ), + save_vxstd=dict(usedefault=True, ), + series_tr=dict(), ) inputs = ComputeDVARS.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeDVARS_outputs(): - output_map = dict(avg_nstd=dict(), - avg_std=dict(), - avg_vxstd=dict(), - fig_nstd=dict(), - fig_std=dict(), - fig_vxstd=dict(), - out_all=dict(), - out_nstd=dict(), - out_std=dict(), - out_vxstd=dict(), + output_map = dict( + avg_nstd=dict(), + avg_std=dict(), + avg_vxstd=dict(), + fig_nstd=dict(), + fig_std=dict(), + fig_vxstd=dict(), + out_all=dict(), + out_nstd=dict(), + out_std=dict(), + out_vxstd=dict(), ) outputs = ComputeDVARS.output_spec() diff --git a/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py b/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py index e6cda0e7d7..be9b85e728 100644 --- a/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py +++ b/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py @@ -4,34 +4,29 @@ def test_ComputeMeshWarp_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - metric=dict(usedefault=True, - ), - out_file=dict(usedefault=True, - ), - out_warp=dict(usedefault=True, - ), - surface1=dict(mandatory=True, - ), - surface2=dict(mandatory=True, - ), - weighting=dict(usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + metric=dict(usedefault=True, ), + out_file=dict(usedefault=True, ), + out_warp=dict(usedefault=True, ), + surface1=dict(mandatory=True, ), + surface2=dict(mandatory=True, ), + weighting=dict(usedefault=True, ), ) inputs = ComputeMeshWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeMeshWarp_outputs(): - output_map = dict(distance=dict(), - out_file=dict(), - out_warp=dict(), + output_map = dict( + distance=dict(), + out_file=dict(), + out_warp=dict(), ) outputs = ComputeMeshWarp.output_spec() diff --git a/nipype/algorithms/tests/test_auto_CreateNifti.py b/nipype/algorithms/tests/test_auto_CreateNifti.py index 0d74e283fe..c4ff4a8a59 100644 --- a/nipype/algorithms/tests/test_auto_CreateNifti.py +++ b/nipype/algorithms/tests/test_auto_CreateNifti.py @@ -4,26 +4,23 @@ def test_CreateNifti_inputs(): - input_map = dict(affine=dict(), - data_file=dict(mandatory=True, - ), - header_file=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), + input_map = dict( + affine=dict(), + data_file=dict(mandatory=True, ), + header_file=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = CreateNifti.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CreateNifti_outputs(): - output_map = dict(nifti_file=dict(), - ) + output_map = dict(nifti_file=dict(), ) outputs = CreateNifti.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_Distance.py b/nipype/algorithms/tests/test_auto_Distance.py index 713221c14a..6d7c9368c0 100644 --- a/nipype/algorithms/tests/test_auto_Distance.py +++ b/nipype/algorithms/tests/test_auto_Distance.py @@ -4,30 +4,28 @@ def test_Distance_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask_volume=dict(), - method=dict(usedefault=True, - ), - volume1=dict(mandatory=True, - ), - volume2=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask_volume=dict(), + method=dict(usedefault=True, ), + volume1=dict(mandatory=True, ), + volume2=dict(mandatory=True, ), ) inputs = Distance.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Distance_outputs(): - output_map = dict(distance=dict(), - histogram=dict(), - point1=dict(), - point2=dict(), + output_map = dict( + distance=dict(), + histogram=dict(), + point1=dict(), + point2=dict(), ) outputs = Distance.output_spec() diff --git a/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py b/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py index cb56b470a4..9cda94f617 100644 --- a/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py +++ b/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py @@ -4,41 +4,33 @@ def test_FramewiseDisplacement_inputs(): - input_map = dict(figdpi=dict(usedefault=True, - ), - figsize=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - normalize=dict(usedefault=True, - ), - out_figure=dict(usedefault=True, - ), - out_file=dict(usedefault=True, - ), - parameter_source=dict(mandatory=True, - ), - radius=dict(usedefault=True, - ), - save_plot=dict(usedefault=True, - ), - series_tr=dict(), + input_map = dict( + figdpi=dict(usedefault=True, ), + figsize=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + normalize=dict(usedefault=True, ), + out_figure=dict(usedefault=True, ), + out_file=dict(usedefault=True, ), + parameter_source=dict(mandatory=True, ), + radius=dict(usedefault=True, ), + save_plot=dict(usedefault=True, ), + series_tr=dict(), ) inputs = FramewiseDisplacement.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FramewiseDisplacement_outputs(): - output_map = dict(fd_average=dict(), - out_figure=dict(), - out_file=dict(), + output_map = dict( + fd_average=dict(), + out_figure=dict(), + out_file=dict(), ) outputs = FramewiseDisplacement.output_spec() diff --git a/nipype/algorithms/tests/test_auto_FuzzyOverlap.py b/nipype/algorithms/tests/test_auto_FuzzyOverlap.py index 726b3bec5b..b59ba2a5a5 100644 --- a/nipype/algorithms/tests/test_auto_FuzzyOverlap.py +++ b/nipype/algorithms/tests/test_auto_FuzzyOverlap.py @@ -4,32 +4,29 @@ def test_FuzzyOverlap_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_ref=dict(mandatory=True, - ), - in_tst=dict(mandatory=True, - ), - out_file=dict(usedefault=True, - ), - weighting=dict(usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_ref=dict(mandatory=True, ), + in_tst=dict(mandatory=True, ), + out_file=dict(usedefault=True, ), + weighting=dict(usedefault=True, ), ) inputs = FuzzyOverlap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FuzzyOverlap_outputs(): - output_map = dict(class_fdi=dict(), - class_fji=dict(), - dice=dict(), - diff_file=dict(), - jaccard=dict(), + output_map = dict( + class_fdi=dict(), + class_fji=dict(), + dice=dict(), + diff_file=dict(), + jaccard=dict(), ) outputs = FuzzyOverlap.output_spec() diff --git a/nipype/algorithms/tests/test_auto_Gunzip.py b/nipype/algorithms/tests/test_auto_Gunzip.py index 43f74364c5..7be9fd2507 100644 --- a/nipype/algorithms/tests/test_auto_Gunzip.py +++ b/nipype/algorithms/tests/test_auto_Gunzip.py @@ -4,23 +4,21 @@ def test_Gunzip_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), ) inputs = Gunzip.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Gunzip_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Gunzip.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_ICC.py b/nipype/algorithms/tests/test_auto_ICC.py index ec2a37baa6..7312fcc85e 100644 --- a/nipype/algorithms/tests/test_auto_ICC.py +++ b/nipype/algorithms/tests/test_auto_ICC.py @@ -4,26 +4,25 @@ def test_ICC_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask=dict(mandatory=True, - ), - subjects_sessions=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask=dict(mandatory=True, ), + subjects_sessions=dict(mandatory=True, ), ) inputs = ICC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ICC_outputs(): - output_map = dict(icc_map=dict(), - session_var_map=dict(), - subject_var_map=dict(), + output_map = dict( + icc_map=dict(), + session_var_map=dict(), + subject_var_map=dict(), ) outputs = ICC.output_spec() diff --git a/nipype/algorithms/tests/test_auto_Matlab2CSV.py b/nipype/algorithms/tests/test_auto_Matlab2CSV.py index e53ce09b56..fcc1648bf9 100644 --- a/nipype/algorithms/tests/test_auto_Matlab2CSV.py +++ b/nipype/algorithms/tests/test_auto_Matlab2CSV.py @@ -4,21 +4,17 @@ def test_Matlab2CSV_inputs(): - input_map = dict(in_file=dict(mandatory=True, - ), - reshape_matrix=dict(usedefault=True, - ), + input_map = dict( + in_file=dict(mandatory=True, ), + reshape_matrix=dict(usedefault=True, ), ) inputs = Matlab2CSV.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Matlab2CSV_outputs(): - output_map = dict(csv_files=dict(), - ) + output_map = dict(csv_files=dict(), ) outputs = Matlab2CSV.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_MergeCSVFiles.py b/nipype/algorithms/tests/test_auto_MergeCSVFiles.py index 42be5b85ab..fd882e850a 100644 --- a/nipype/algorithms/tests/test_auto_MergeCSVFiles.py +++ b/nipype/algorithms/tests/test_auto_MergeCSVFiles.py @@ -4,27 +4,22 @@ def test_MergeCSVFiles_inputs(): - input_map = dict(column_headings=dict(), - extra_column_heading=dict(), - extra_field=dict(), - in_files=dict(mandatory=True, - ), - out_file=dict(usedefault=True, - ), - row_heading_title=dict(usedefault=True, - ), - row_headings=dict(), + input_map = dict( + column_headings=dict(), + extra_column_heading=dict(), + extra_field=dict(), + in_files=dict(mandatory=True, ), + out_file=dict(usedefault=True, ), + row_heading_title=dict(usedefault=True, ), + row_headings=dict(), ) inputs = MergeCSVFiles.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MergeCSVFiles_outputs(): - output_map = dict(csv_file=dict(), - ) + output_map = dict(csv_file=dict(), ) outputs = MergeCSVFiles.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_MergeROIs.py b/nipype/algorithms/tests/test_auto_MergeROIs.py index c349934e4d..01b2b097a8 100644 --- a/nipype/algorithms/tests/test_auto_MergeROIs.py +++ b/nipype/algorithms/tests/test_auto_MergeROIs.py @@ -4,20 +4,18 @@ def test_MergeROIs_inputs(): - input_map = dict(in_files=dict(), - in_index=dict(), - in_reference=dict(), + input_map = dict( + in_files=dict(), + in_index=dict(), + in_reference=dict(), ) inputs = MergeROIs.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MergeROIs_outputs(): - output_map = dict(merged_file=dict(), - ) + output_map = dict(merged_file=dict(), ) outputs = MergeROIs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_MeshWarpMaths.py b/nipype/algorithms/tests/test_auto_MeshWarpMaths.py index c19a4a7506..99b6bb7391 100644 --- a/nipype/algorithms/tests/test_auto_MeshWarpMaths.py +++ b/nipype/algorithms/tests/test_auto_MeshWarpMaths.py @@ -4,32 +4,28 @@ def test_MeshWarpMaths_inputs(): - input_map = dict(float_trait=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_surf=dict(mandatory=True, - ), - operation=dict(usedefault=True, - ), - operator=dict(mandatory=True, - ), - out_file=dict(usedefault=True, - ), - out_warp=dict(usedefault=True, - ), + input_map = dict( + float_trait=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_surf=dict(mandatory=True, ), + operation=dict(usedefault=True, ), + operator=dict(mandatory=True, ), + out_file=dict(usedefault=True, ), + out_warp=dict(usedefault=True, ), ) inputs = MeshWarpMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MeshWarpMaths_outputs(): - output_map = dict(out_file=dict(), - out_warp=dict(), + output_map = dict( + out_file=dict(), + out_warp=dict(), ) outputs = MeshWarpMaths.output_spec() diff --git a/nipype/algorithms/tests/test_auto_ModifyAffine.py b/nipype/algorithms/tests/test_auto_ModifyAffine.py index a9c7fe1b49..3b07511e0b 100644 --- a/nipype/algorithms/tests/test_auto_ModifyAffine.py +++ b/nipype/algorithms/tests/test_auto_ModifyAffine.py @@ -4,25 +4,22 @@ def test_ModifyAffine_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - transformation_matrix=dict(usedefault=True, - ), - volumes=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + transformation_matrix=dict(usedefault=True, ), + volumes=dict(mandatory=True, ), ) inputs = ModifyAffine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ModifyAffine_outputs(): - output_map = dict(transformed_volumes=dict(), - ) + output_map = dict(transformed_volumes=dict(), ) outputs = ModifyAffine.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py b/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py index 6d3fe0c879..436af1fa14 100644 --- a/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py +++ b/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py @@ -4,23 +4,21 @@ def test_NonSteadyStateDetector_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), ) inputs = NonSteadyStateDetector.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NonSteadyStateDetector_outputs(): - output_map = dict(n_volumes_to_discard=dict(), - ) + output_map = dict(n_volumes_to_discard=dict(), ) outputs = NonSteadyStateDetector.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py b/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py index 3b8375efe7..4c9a5584d0 100644 --- a/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py +++ b/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py @@ -4,19 +4,17 @@ def test_NormalizeProbabilityMapSet_inputs(): - input_map = dict(in_files=dict(), - in_mask=dict(), + input_map = dict( + in_files=dict(), + in_mask=dict(), ) inputs = NormalizeProbabilityMapSet.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NormalizeProbabilityMapSet_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = NormalizeProbabilityMapSet.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_P2PDistance.py b/nipype/algorithms/tests/test_auto_P2PDistance.py index a1ddcd56c0..8175d73be5 100644 --- a/nipype/algorithms/tests/test_auto_P2PDistance.py +++ b/nipype/algorithms/tests/test_auto_P2PDistance.py @@ -4,34 +4,29 @@ def test_P2PDistance_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - metric=dict(usedefault=True, - ), - out_file=dict(usedefault=True, - ), - out_warp=dict(usedefault=True, - ), - surface1=dict(mandatory=True, - ), - surface2=dict(mandatory=True, - ), - weighting=dict(usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + metric=dict(usedefault=True, ), + out_file=dict(usedefault=True, ), + out_warp=dict(usedefault=True, ), + surface1=dict(mandatory=True, ), + surface2=dict(mandatory=True, ), + weighting=dict(usedefault=True, ), ) inputs = P2PDistance.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_P2PDistance_outputs(): - output_map = dict(distance=dict(), - out_file=dict(), - out_warp=dict(), + output_map = dict( + distance=dict(), + out_file=dict(), + out_warp=dict(), ) outputs = P2PDistance.output_spec() diff --git a/nipype/algorithms/tests/test_auto_PickAtlas.py b/nipype/algorithms/tests/test_auto_PickAtlas.py index 11b84f8e8a..1f2d9f6429 100644 --- a/nipype/algorithms/tests/test_auto_PickAtlas.py +++ b/nipype/algorithms/tests/test_auto_PickAtlas.py @@ -4,30 +4,25 @@ def test_PickAtlas_inputs(): - input_map = dict(atlas=dict(mandatory=True, - ), - dilation_size=dict(usedefault=True, - ), - hemi=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - labels=dict(mandatory=True, - ), - output_file=dict(), + input_map = dict( + atlas=dict(mandatory=True, ), + dilation_size=dict(usedefault=True, ), + hemi=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + labels=dict(mandatory=True, ), + output_file=dict(), ) inputs = PickAtlas.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PickAtlas_outputs(): - output_map = dict(mask_file=dict(), - ) + output_map = dict(mask_file=dict(), ) outputs = PickAtlas.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_Similarity.py b/nipype/algorithms/tests/test_auto_Similarity.py index 6b90321975..9c82533c13 100644 --- a/nipype/algorithms/tests/test_auto_Similarity.py +++ b/nipype/algorithms/tests/test_auto_Similarity.py @@ -4,29 +4,25 @@ def test_Similarity_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask1=dict(), - mask2=dict(), - metric=dict(usedefault=True, - ), - volume1=dict(mandatory=True, - ), - volume2=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask1=dict(), + mask2=dict(), + metric=dict(usedefault=True, ), + volume1=dict(mandatory=True, ), + volume2=dict(mandatory=True, ), ) inputs = Similarity.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Similarity_outputs(): - output_map = dict(similarity=dict(), - ) + output_map = dict(similarity=dict(), ) outputs = Similarity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SimpleThreshold.py b/nipype/algorithms/tests/test_auto_SimpleThreshold.py index 8d4993425e..1e7c48c506 100644 --- a/nipype/algorithms/tests/test_auto_SimpleThreshold.py +++ b/nipype/algorithms/tests/test_auto_SimpleThreshold.py @@ -4,25 +4,22 @@ def test_SimpleThreshold_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - threshold=dict(mandatory=True, - ), - volumes=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + threshold=dict(mandatory=True, ), + volumes=dict(mandatory=True, ), ) inputs = SimpleThreshold.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SimpleThreshold_outputs(): - output_map = dict(thresholded_volumes=dict(), - ) + output_map = dict(thresholded_volumes=dict(), ) outputs = SimpleThreshold.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SpecifyModel.py b/nipype/algorithms/tests/test_auto_SpecifyModel.py index 11af243c11..232e6cd740 100644 --- a/nipype/algorithms/tests/test_auto_SpecifyModel.py +++ b/nipype/algorithms/tests/test_auto_SpecifyModel.py @@ -4,42 +4,38 @@ def test_SpecifyModel_inputs(): - input_map = dict(event_files=dict(mandatory=True, - xor=['subject_info', 'event_files'], - ), - functional_runs=dict(copyfile=False, - mandatory=True, - ), - high_pass_filter_cutoff=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_units=dict(mandatory=True, - ), - outlier_files=dict(copyfile=False, - ), - parameter_source=dict(usedefault=True, - ), - realignment_parameters=dict(copyfile=False, - ), - subject_info=dict(mandatory=True, - xor=['subject_info', 'event_files'], - ), - time_repetition=dict(mandatory=True, - ), + input_map = dict( + event_files=dict( + mandatory=True, + xor=['subject_info', 'event_files'], + ), + functional_runs=dict( + copyfile=False, + mandatory=True, + ), + high_pass_filter_cutoff=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_units=dict(mandatory=True, ), + outlier_files=dict(copyfile=False, ), + parameter_source=dict(usedefault=True, ), + realignment_parameters=dict(copyfile=False, ), + subject_info=dict( + mandatory=True, + xor=['subject_info', 'event_files'], + ), + time_repetition=dict(mandatory=True, ), ) inputs = SpecifyModel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SpecifyModel_outputs(): - output_map = dict(session_info=dict(), - ) + output_map = dict(session_info=dict(), ) outputs = SpecifyModel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SpecifySPMModel.py b/nipype/algorithms/tests/test_auto_SpecifySPMModel.py index bea8ee473e..2fda43e8fe 100644 --- a/nipype/algorithms/tests/test_auto_SpecifySPMModel.py +++ b/nipype/algorithms/tests/test_auto_SpecifySPMModel.py @@ -4,46 +4,40 @@ def test_SpecifySPMModel_inputs(): - input_map = dict(concatenate_runs=dict(usedefault=True, - ), - event_files=dict(mandatory=True, - xor=['subject_info', 'event_files'], - ), - functional_runs=dict(copyfile=False, - mandatory=True, - ), - high_pass_filter_cutoff=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_units=dict(mandatory=True, - ), - outlier_files=dict(copyfile=False, - ), - output_units=dict(usedefault=True, - ), - parameter_source=dict(usedefault=True, - ), - realignment_parameters=dict(copyfile=False, - ), - subject_info=dict(mandatory=True, - xor=['subject_info', 'event_files'], - ), - time_repetition=dict(mandatory=True, - ), + input_map = dict( + concatenate_runs=dict(usedefault=True, ), + event_files=dict( + mandatory=True, + xor=['subject_info', 'event_files'], + ), + functional_runs=dict( + copyfile=False, + mandatory=True, + ), + high_pass_filter_cutoff=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_units=dict(mandatory=True, ), + outlier_files=dict(copyfile=False, ), + output_units=dict(usedefault=True, ), + parameter_source=dict(usedefault=True, ), + realignment_parameters=dict(copyfile=False, ), + subject_info=dict( + mandatory=True, + xor=['subject_info', 'event_files'], + ), + time_repetition=dict(mandatory=True, ), ) inputs = SpecifySPMModel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SpecifySPMModel_outputs(): - output_map = dict(session_info=dict(), - ) + output_map = dict(session_info=dict(), ) outputs = SpecifySPMModel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SpecifySparseModel.py b/nipype/algorithms/tests/test_auto_SpecifySparseModel.py index c8e07a292b..6e5ca35b9e 100644 --- a/nipype/algorithms/tests/test_auto_SpecifySparseModel.py +++ b/nipype/algorithms/tests/test_auto_SpecifySparseModel.py @@ -4,57 +4,49 @@ def test_SpecifySparseModel_inputs(): - input_map = dict(event_files=dict(mandatory=True, - xor=['subject_info', 'event_files'], - ), - functional_runs=dict(copyfile=False, - mandatory=True, - ), - high_pass_filter_cutoff=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_units=dict(mandatory=True, - ), - model_hrf=dict(), - outlier_files=dict(copyfile=False, - ), - parameter_source=dict(usedefault=True, - ), - realignment_parameters=dict(copyfile=False, - ), - save_plot=dict(), - scale_regressors=dict(usedefault=True, - ), - scan_onset=dict(usedefault=True, - ), - stimuli_as_impulses=dict(usedefault=True, - ), - subject_info=dict(mandatory=True, - xor=['subject_info', 'event_files'], - ), - time_acquisition=dict(mandatory=True, - ), - time_repetition=dict(mandatory=True, - ), - use_temporal_deriv=dict(requires=['model_hrf'], - ), - volumes_in_cluster=dict(usedefault=True, - ), + input_map = dict( + event_files=dict( + mandatory=True, + xor=['subject_info', 'event_files'], + ), + functional_runs=dict( + copyfile=False, + mandatory=True, + ), + high_pass_filter_cutoff=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_units=dict(mandatory=True, ), + model_hrf=dict(), + outlier_files=dict(copyfile=False, ), + parameter_source=dict(usedefault=True, ), + realignment_parameters=dict(copyfile=False, ), + save_plot=dict(), + scale_regressors=dict(usedefault=True, ), + scan_onset=dict(usedefault=True, ), + stimuli_as_impulses=dict(usedefault=True, ), + subject_info=dict( + mandatory=True, + xor=['subject_info', 'event_files'], + ), + time_acquisition=dict(mandatory=True, ), + time_repetition=dict(mandatory=True, ), + use_temporal_deriv=dict(requires=['model_hrf'], ), + volumes_in_cluster=dict(usedefault=True, ), ) inputs = SpecifySparseModel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SpecifySparseModel_outputs(): - output_map = dict(session_info=dict(), - sparse_png_file=dict(), - sparse_svg_file=dict(), + output_map = dict( + session_info=dict(), + sparse_png_file=dict(), + sparse_svg_file=dict(), ) outputs = SpecifySparseModel.output_spec() diff --git a/nipype/algorithms/tests/test_auto_SplitROIs.py b/nipype/algorithms/tests/test_auto_SplitROIs.py index 60c28f810b..963926666d 100644 --- a/nipype/algorithms/tests/test_auto_SplitROIs.py +++ b/nipype/algorithms/tests/test_auto_SplitROIs.py @@ -4,22 +4,21 @@ def test_SplitROIs_inputs(): - input_map = dict(in_file=dict(mandatory=True, - ), - in_mask=dict(), - roi_size=dict(), + input_map = dict( + in_file=dict(mandatory=True, ), + in_mask=dict(), + roi_size=dict(), ) inputs = SplitROIs.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SplitROIs_outputs(): - output_map = dict(out_files=dict(), - out_index=dict(), - out_masks=dict(), + output_map = dict( + out_files=dict(), + out_index=dict(), + out_masks=dict(), ) outputs = SplitROIs.output_spec() diff --git a/nipype/algorithms/tests/test_auto_StimulusCorrelation.py b/nipype/algorithms/tests/test_auto_StimulusCorrelation.py index 169dcf6d80..4360525990 100644 --- a/nipype/algorithms/tests/test_auto_StimulusCorrelation.py +++ b/nipype/algorithms/tests/test_auto_StimulusCorrelation.py @@ -4,29 +4,24 @@ def test_StimulusCorrelation_inputs(): - input_map = dict(concatenated_design=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - intensity_values=dict(mandatory=True, - ), - realignment_parameters=dict(mandatory=True, - ), - spm_mat_file=dict(mandatory=True, - ), + input_map = dict( + concatenated_design=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + intensity_values=dict(mandatory=True, ), + realignment_parameters=dict(mandatory=True, ), + spm_mat_file=dict(mandatory=True, ), ) inputs = StimulusCorrelation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_StimulusCorrelation_outputs(): - output_map = dict(stimcorr_files=dict(), - ) + output_map = dict(stimcorr_files=dict(), ) outputs = StimulusCorrelation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_TCompCor.py b/nipype/algorithms/tests/test_auto_TCompCor.py index 8f9585f26b..b7a94415a3 100644 --- a/nipype/algorithms/tests/test_auto_TCompCor.py +++ b/nipype/algorithms/tests/test_auto_TCompCor.py @@ -4,51 +4,47 @@ def test_TCompCor_inputs(): - input_map = dict(components_file=dict(usedefault=True, - ), - header_prefix=dict(), - high_pass_cutoff=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_initial_volumes=dict(usedefault=True, - ), - mask_files=dict(), - mask_index=dict(requires=['mask_files'], - xor=['merge_method'], - ), - merge_method=dict(requires=['mask_files'], - xor=['mask_index'], - ), - num_components=dict(usedefault=True, - ), - percentile_threshold=dict(usedefault=True, - ), - pre_filter=dict(usedefault=True, - ), - realigned_file=dict(mandatory=True, - ), - regress_poly_degree=dict(usedefault=True, - ), - repetition_time=dict(), - save_pre_filter=dict(), - use_regress_poly=dict(deprecated='0.15.0', - new_name='pre_filter', - ), + input_map = dict( + components_file=dict(usedefault=True, ), + header_prefix=dict(), + high_pass_cutoff=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_initial_volumes=dict(usedefault=True, ), + mask_files=dict(), + mask_index=dict( + requires=['mask_files'], + xor=['merge_method'], + ), + merge_method=dict( + requires=['mask_files'], + xor=['mask_index'], + ), + num_components=dict(usedefault=True, ), + percentile_threshold=dict(usedefault=True, ), + pre_filter=dict(usedefault=True, ), + realigned_file=dict(mandatory=True, ), + regress_poly_degree=dict(usedefault=True, ), + repetition_time=dict(), + save_pre_filter=dict(), + use_regress_poly=dict( + deprecated='0.15.0', + new_name='pre_filter', + ), ) inputs = TCompCor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TCompCor_outputs(): - output_map = dict(components_file=dict(), - high_variance_masks=dict(), - pre_filter_file=dict(), + output_map = dict( + components_file=dict(), + high_variance_masks=dict(), + pre_filter_file=dict(), ) outputs = TCompCor.output_spec() diff --git a/nipype/algorithms/tests/test_auto_TVTKBaseInterface.py b/nipype/algorithms/tests/test_auto_TVTKBaseInterface.py index 14e20fd36a..83980b45b1 100644 --- a/nipype/algorithms/tests/test_auto_TVTKBaseInterface.py +++ b/nipype/algorithms/tests/test_auto_TVTKBaseInterface.py @@ -4,14 +4,14 @@ def test_TVTKBaseInterface_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ) + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = TVTKBaseInterface.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/algorithms/tests/test_auto_WarpPoints.py b/nipype/algorithms/tests/test_auto_WarpPoints.py index d866214fec..7339eef7ba 100644 --- a/nipype/algorithms/tests/test_auto_WarpPoints.py +++ b/nipype/algorithms/tests/test_auto_WarpPoints.py @@ -4,33 +4,32 @@ def test_WarpPoints_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interp=dict(mandatory=True, - usedefault=True, - ), - out_points=dict(keep_extension=True, - name_source='points', - name_template='%s_warped', - output_name='out_points', - ), - points=dict(mandatory=True, - ), - warp=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interp=dict( + mandatory=True, + usedefault=True, + ), + out_points=dict( + keep_extension=True, + name_source='points', + name_template='%s_warped', + output_name='out_points', + ), + points=dict(mandatory=True, ), + warp=dict(mandatory=True, ), ) inputs = WarpPoints.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WarpPoints_outputs(): - output_map = dict(out_points=dict(), - ) + output_map = dict(out_points=dict(), ) outputs = WarpPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_confounds.py b/nipype/algorithms/tests/test_confounds.py index 8c2626457e..2c601374ab 100644 --- a/nipype/algorithms/tests/test_confounds.py +++ b/nipype/algorithms/tests/test_confounds.py @@ -10,7 +10,6 @@ is_outlier import numpy as np - nonitime = True try: import nitime @@ -22,9 +21,10 @@ def test_fd(tmpdir): tempdir = tmpdir.strpath ground_truth = np.loadtxt(example_data('fsl_motion_outliers_fd.txt')) - fdisplacement = FramewiseDisplacement(in_file=example_data('fsl_mcflirt_movpar.txt'), - out_file=tempdir + '/fd.txt', - parameter_source="FSL") + fdisplacement = FramewiseDisplacement( + in_file=example_data('fsl_mcflirt_movpar.txt'), + out_file=tempdir + '/fd.txt', + parameter_source="FSL") res = fdisplacement.run() with open(res.outputs.out_file) as all_lines: @@ -32,31 +32,33 @@ def test_fd(tmpdir): assert 'FramewiseDisplacement' in line break - assert np.allclose(ground_truth, np.loadtxt(res.outputs.out_file, skiprows=1), atol=.16) + assert np.allclose( + ground_truth, np.loadtxt(res.outputs.out_file, skiprows=1), atol=.16) assert np.abs(ground_truth.mean() - res.outputs.fd_average) < 1e-2 @pytest.mark.skipif(nonitime, reason="nitime is not installed") def test_dvars(tmpdir): ground_truth = np.loadtxt(example_data('ds003_sub-01_mc.DVARS')) - dvars = ComputeDVARS(in_file=example_data('ds003_sub-01_mc.nii.gz'), - in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'), - save_all=True, - intensity_normalization=0) + dvars = ComputeDVARS( + in_file=example_data('ds003_sub-01_mc.nii.gz'), + in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'), + save_all=True, + intensity_normalization=0) tmpdir.chdir() res = dvars.run() dv1 = np.loadtxt(res.outputs.out_all, skiprows=1) - assert (np.abs(dv1[:, 0] - ground_truth[:, 0]).sum()/ len(dv1)) < 0.05 + assert (np.abs(dv1[:, 0] - ground_truth[:, 0]).sum() / len(dv1)) < 0.05 assert (np.abs(dv1[:, 1] - ground_truth[:, 1]).sum() / len(dv1)) < 0.05 assert (np.abs(dv1[:, 2] - ground_truth[:, 2]).sum() / len(dv1)) < 0.05 - dvars = ComputeDVARS(in_file=example_data('ds003_sub-01_mc.nii.gz'), - in_mask=example_data( - 'ds003_sub-01_mc_brainmask.nii.gz'), - save_all=True) + dvars = ComputeDVARS( + in_file=example_data('ds003_sub-01_mc.nii.gz'), + in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'), + save_all=True) res = dvars.run() dv1 = np.loadtxt(res.outputs.out_all, skiprows=1) @@ -73,4 +75,3 @@ def test_outliers(): in_data[0] += 10 assert is_outlier(in_data) == 1 - diff --git a/nipype/algorithms/tests/test_icc_anova.py b/nipype/algorithms/tests/test_icc_anova.py index 65b1e9c6ed..ef19b7f410 100644 --- a/nipype/algorithms/tests/test_icc_anova.py +++ b/nipype/algorithms/tests/test_icc_anova.py @@ -5,14 +5,11 @@ def test_ICC_rep_anova(): - # see table 2 in P. E. Shrout & Joseph L. Fleiss (1979). "Intraclass Correlations: Uses in - # Assessing Rater Reliability". Psychological Bulletin 86 (2): 420-428 - Y = np.array([[9, 2, 5, 8], - [6, 1, 3, 2], - [8, 4, 6, 8], - [7, 1, 2, 6], - [10, 5, 6, 9], - [6, 2, 4, 7]]) + # see table 2 in P. E. Shrout & Joseph L. Fleiss (1979). "Intraclass + # Correlations: Uses in Assessing Rater Reliability". Psychological + # Bulletin 86 (2): 420-428 + Y = np.array([[9, 2, 5, 8], [6, 1, 3, 2], [8, 4, 6, 8], [7, 1, 2, 6], + [10, 5, 6, 9], [6, 2, 4, 7]]) icc, r_var, e_var, _, dfc, dfe = ICC_rep_anova(Y) # see table 4 diff --git a/nipype/algorithms/tests/test_mesh_ops.py b/nipype/algorithms/tests/test_mesh_ops.py index d5fbc56825..53eec75b69 100644 --- a/nipype/algorithms/tests/test_mesh_ops.py +++ b/nipype/algorithms/tests/test_mesh_ops.py @@ -32,7 +32,6 @@ def test_ident_distances(tmpdir): @pytest.mark.skipif(VTKInfo.no_tvtk(), reason="tvtk is not installed") def test_trans_distances(tmpdir): - tempdir = tmpdir.strpath from ...interfaces.vtkbase import tvtk in_surf = example_data('surf01.vtk') diff --git a/nipype/algorithms/tests/test_misc.py b/nipype/algorithms/tests/test_misc.py index d148ee8ca1..e9d5cbdb3c 100644 --- a/nipype/algorithms/tests/test_misc.py +++ b/nipype/algorithms/tests/test_misc.py @@ -25,21 +25,21 @@ def test_CreateNifti(create_analyze_pair_file_in_directory): # .inputs based parameters setting create_nifti.inputs.header_file = filelist[0] - create_nifti.inputs.data_file = fname_presuffix(filelist[0], - '', - '.img', - use_ext=False) + create_nifti.inputs.data_file = fname_presuffix( + filelist[0], '', '.img', use_ext=False) result = create_nifti.run() assert os.path.exists(result.outputs.nifti_file) assert nb.load(result.outputs.nifti_file, mmap=NUMPY_MMAP) + def test_CalculateMedian(create_analyze_pair_file_in_directory): mean = misc.CalculateMedian() - with pytest.raises(TypeError): mean.run() + with pytest.raises(TypeError): + mean.run() mean.inputs.in_files = example_data('ds003_sub-01_mc.nii.gz') eg = mean.run() diff --git a/nipype/algorithms/tests/test_modelgen.py b/nipype/algorithms/tests/test_modelgen.py index 3c9ec4096b..824a634354 100644 --- a/nipype/algorithms/tests/test_modelgen.py +++ b/nipype/algorithms/tests/test_modelgen.py @@ -19,46 +19,91 @@ def test_modelgen1(tmpdir): filename1 = tmpdir.join('test1.nii').strpath filename2 = tmpdir.join('test2.nii').strpath - Nifti1Image(np.random.rand(10, 10, 10, 200), np.eye(4)).to_filename(filename1) - Nifti1Image(np.random.rand(10, 10, 10, 200), np.eye(4)).to_filename(filename2) + Nifti1Image(np.random.rand(10, 10, 10, 200), + np.eye(4)).to_filename(filename1) + Nifti1Image(np.random.rand(10, 10, 10, 200), + np.eye(4)).to_filename(filename2) s = SpecifyModel() s.inputs.input_units = 'scans' set_output_units = lambda: setattr(s.inputs, 'output_units', 'scans') - with pytest.raises(TraitError): set_output_units() + with pytest.raises(TraitError): + set_output_units() s.inputs.functional_runs = [filename1, filename2] s.inputs.time_repetition = 6 s.inputs.high_pass_filter_cutoff = 128. - info = [Bunch(conditions=['cond1'], onsets=[[2, 50, 100, 180]], durations=[[1]], amplitudes=None, - pmod=None, regressors=None, regressor_names=None, tmod=None), - Bunch(conditions=['cond1'], onsets=[[30, 40, 100, 150]], durations=[[1]], amplitudes=None, - pmod=None, regressors=None, regressor_names=None, tmod=None)] + info = [ + Bunch( + conditions=['cond1'], + onsets=[[2, 50, 100, 180]], + durations=[[1]], + amplitudes=None, + pmod=None, + regressors=None, + regressor_names=None, + tmod=None), + Bunch( + conditions=['cond1'], + onsets=[[30, 40, 100, 150]], + durations=[[1]], + amplitudes=None, + pmod=None, + regressors=None, + regressor_names=None, + tmod=None) + ] s.inputs.subject_info = info res = s.run() assert len(res.outputs.session_info) == 2 assert len(res.outputs.session_info[0]['regress']) == 0 assert len(res.outputs.session_info[0]['cond']) == 1 - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['onset']), np.array([12, 300, 600, 1080])) - info = [Bunch(conditions=['cond1'], onsets=[[2]], durations=[[1]]), - Bunch(conditions=['cond1'], onsets=[[3]], durations=[[1]])] + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['onset']), + np.array([12, 300, 600, 1080])) + info = [ + Bunch(conditions=['cond1'], onsets=[[2]], durations=[[1]]), + Bunch(conditions=['cond1'], onsets=[[3]], durations=[[1]]) + ] s.inputs.subject_info = deepcopy(info) res = s.run() - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['duration']), np.array([6.])) - npt.assert_almost_equal(np.array(res.outputs.session_info[1]['cond'][0]['duration']), np.array([6.])) - info = [Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2]], durations=[[1, 1], [1]]), - Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2, 4]], durations=[[1, 1], [1, 1]])] + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['duration']), + np.array([6.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[1]['cond'][0]['duration']), + np.array([6.])) + info = [ + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2]], + durations=[[1, 1], [1]]), + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2, 4]], + durations=[[1, 1], [1, 1]]) + ] s.inputs.subject_info = deepcopy(info) s.inputs.input_units = 'scans' res = s.run() - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['duration']), np.array([6., 6.])) - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][1]['duration']), np.array([6., ])) - npt.assert_almost_equal(np.array(res.outputs.session_info[1]['cond'][1]['duration']), np.array([6., 6.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['duration']), + np.array([6., 6.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][1]['duration']), + np.array([ + 6., + ])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[1]['cond'][1]['duration']), + np.array([6., 6.])) def test_modelgen_spm_concat(tmpdir): filename1 = tmpdir.join('test1.nii').strpath filename2 = tmpdir.join('test2.nii').strpath - Nifti1Image(np.random.rand(10, 10, 10, 30), np.eye(4)).to_filename(filename1) - Nifti1Image(np.random.rand(10, 10, 10, 30), np.eye(4)).to_filename(filename2) + Nifti1Image(np.random.rand(10, 10, 10, 30), + np.eye(4)).to_filename(filename1) + Nifti1Image(np.random.rand(10, 10, 10, 30), + np.eye(4)).to_filename(filename2) # Test case when only one duration is passed, as being the same for all onsets. s = SpecifySPMModel() @@ -69,67 +114,124 @@ def test_modelgen_spm_concat(tmpdir): s.inputs.functional_runs = [filename1, filename2] s.inputs.time_repetition = 6 s.inputs.high_pass_filter_cutoff = 128. - info = [Bunch(conditions=['cond1'], onsets=[[2, 50, 100, 170]], durations=[[1]]), - Bunch(conditions=['cond1'], onsets=[[30, 40, 100, 150]], durations=[[1]])] + info = [ + Bunch( + conditions=['cond1'], onsets=[[2, 50, 100, 170]], durations=[[1]]), + Bunch( + conditions=['cond1'], onsets=[[30, 40, 100, 150]], durations=[[1]]) + ] s.inputs.subject_info = deepcopy(info) res = s.run() assert len(res.outputs.session_info) == 1 assert len(res.outputs.session_info[0]['regress']) == 1 assert np.sum(res.outputs.session_info[0]['regress'][0]['val']) == 30 assert len(res.outputs.session_info[0]['cond']) == 1 - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['onset']), np.array([2.0, 50.0, 100.0, 170.0, 210.0, 220.0, 280.0, 330.0])) - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['duration']), np.array([1., 1., 1., 1., 1., 1., 1., 1.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['onset']), + np.array([2.0, 50.0, 100.0, 170.0, 210.0, 220.0, 280.0, 330.0])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['duration']), + np.array([1., 1., 1., 1., 1., 1., 1., 1.])) # Test case of scans as output units instead of seconds setattr(s.inputs, 'output_units', 'scans') assert s.inputs.output_units == 'scans' s.inputs.subject_info = deepcopy(info) res = s.run() - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['onset']), np.array([2.0, 50.0, 100.0, 170.0, 210.0, 220.0, 280.0, 330.0]) / 6) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['onset']), + np.array([2.0, 50.0, 100.0, 170.0, 210.0, 220.0, 280.0, 330.0]) / 6) # Test case for no concatenation with seconds as output units s.inputs.concatenate_runs = False s.inputs.subject_info = deepcopy(info) s.inputs.output_units = 'secs' res = s.run() - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['onset']), np.array([2.0, 50.0, 100.0, 170.0])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['onset']), + np.array([2.0, 50.0, 100.0, 170.0])) # Test case for variable number of events in separate runs, sometimes unique. filename3 = tmpdir.join('test3.nii').strpath - Nifti1Image(np.random.rand(10, 10, 10, 30), np.eye(4)).to_filename(filename3) + Nifti1Image(np.random.rand(10, 10, 10, 30), + np.eye(4)).to_filename(filename3) s.inputs.functional_runs = [filename1, filename2, filename3] - info = [Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2]], durations=[[1, 1], [1]]), - Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2, 4]], durations=[[1, 1], [1, 1]]), - Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2]], durations=[[1, 1], [1]])] + info = [ + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2]], + durations=[[1, 1], [1]]), + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2, 4]], + durations=[[1, 1], [1, 1]]), + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2]], + durations=[[1, 1], [1]]) + ] s.inputs.subject_info = deepcopy(info) res = s.run() - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['duration']), np.array([1., 1.])) - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][1]['duration']), np.array([1., ])) - npt.assert_almost_equal(np.array(res.outputs.session_info[1]['cond'][1]['duration']), np.array([1., 1.])) - npt.assert_almost_equal(np.array(res.outputs.session_info[2]['cond'][1]['duration']), np.array([1., ])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['duration']), + np.array([1., 1.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][1]['duration']), + np.array([ + 1., + ])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[1]['cond'][1]['duration']), + np.array([1., 1.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[2]['cond'][1]['duration']), + np.array([ + 1., + ])) # Test case for variable number of events in concatenated runs, sometimes unique. s.inputs.concatenate_runs = True - info = [Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2]], durations=[[1, 1], [1]]), - Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2, 4]], durations=[[1, 1], [1, 1]]), - Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2]], durations=[[1, 1], [1]])] + info = [ + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2]], + durations=[[1, 1], [1]]), + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2, 4]], + durations=[[1, 1], [1, 1]]), + Bunch( + conditions=['cond1', 'cond2'], + onsets=[[2, 3], [2]], + durations=[[1, 1], [1]]) + ] s.inputs.subject_info = deepcopy(info) res = s.run() - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['duration']), np.array([1., 1., 1., 1., 1., 1.])) - npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][1]['duration']), np.array([1., 1., 1., 1.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][0]['duration']), + np.array([1., 1., 1., 1., 1., 1.])) + npt.assert_almost_equal( + np.array(res.outputs.session_info[0]['cond'][1]['duration']), + np.array([1., 1., 1., 1.])) def test_modelgen_sparse(tmpdir): filename1 = tmpdir.join('test1.nii').strpath filename2 = tmpdir.join('test2.nii').strpath - Nifti1Image(np.random.rand(10, 10, 10, 50), np.eye(4)).to_filename(filename1) - Nifti1Image(np.random.rand(10, 10, 10, 50), np.eye(4)).to_filename(filename2) + Nifti1Image(np.random.rand(10, 10, 10, 50), + np.eye(4)).to_filename(filename1) + Nifti1Image(np.random.rand(10, 10, 10, 50), + np.eye(4)).to_filename(filename2) s = SpecifySparseModel() s.inputs.input_units = 'secs' s.inputs.functional_runs = [filename1, filename2] s.inputs.time_repetition = 6 - info = [Bunch(conditions=['cond1'], onsets=[[0, 50, 100, 180]], durations=[[2]]), - Bunch(conditions=['cond1'], onsets=[[30, 40, 100, 150]], durations=[[1]])] + info = [ + Bunch( + conditions=['cond1'], onsets=[[0, 50, 100, 180]], durations=[[2]]), + Bunch( + conditions=['cond1'], onsets=[[30, 40, 100, 150]], durations=[[1]]) + ] s.inputs.subject_info = info s.inputs.volumes_in_cluster = 1 s.inputs.time_acquisition = 2 @@ -145,12 +247,17 @@ def test_modelgen_sparse(tmpdir): s.inputs.model_hrf = True res = s.run() - npt.assert_almost_equal(res.outputs.session_info[0]['regress'][0]['val'][0], 0.016675298129743384) + npt.assert_almost_equal( + res.outputs.session_info[0]['regress'][0]['val'][0], + 0.016675298129743384) assert len(res.outputs.session_info[0]['regress']) == 1 s.inputs.use_temporal_deriv = True res = s.run() assert len(res.outputs.session_info[0]['regress']) == 2 - npt.assert_almost_equal(res.outputs.session_info[0]['regress'][0]['val'][0], 0.016675298129743384) - npt.assert_almost_equal(res.outputs.session_info[1]['regress'][1]['val'][5], 0.007671459162258378) - + npt.assert_almost_equal( + res.outputs.session_info[0]['regress'][0]['val'][0], + 0.016675298129743384) + npt.assert_almost_equal( + res.outputs.session_info[1]['regress'][1]['val'][5], + 0.007671459162258378) diff --git a/nipype/algorithms/tests/test_moments.py b/nipype/algorithms/tests/test_moments.py index 17c8e922b2..fa174a79e4 100644 --- a/nipype/algorithms/tests/test_moments.py +++ b/nipype/algorithms/tests/test_moments.py @@ -128,9 +128,10 @@ def test_skew(tmpdir): f = tmpdir.join("filetest") f.write(data) skewness = calc_moments(f.strpath, 3) - assert np.allclose(skewness, np.array( - [-0.23418937314622, 0.2946365564954823, -0.05781002053540932, - -0.3512508282578762, - - 0.07035664150233077, - - 0.01935867699166935, - 0.00483863369427428, 0.21879460029850167])) + assert np.allclose( + skewness, + np.array([ + -0.23418937314622, 0.2946365564954823, -0.05781002053540932, + -0.3512508282578762, -0.07035664150233077, -0.01935867699166935, + 0.00483863369427428, 0.21879460029850167 + ])) diff --git a/nipype/algorithms/tests/test_normalize_tpms.py b/nipype/algorithms/tests/test_normalize_tpms.py index 5d0fc5c47b..a65cc66770 100644 --- a/nipype/algorithms/tests/test_normalize_tpms.py +++ b/nipype/algorithms/tests/test_normalize_tpms.py @@ -51,4 +51,3 @@ def test_normalize_tpms(tmpdir): assert np.allclose(normdata, mapdata[i]) assert np.allclose(sumdata[sumdata > 0.0], 1.0) - diff --git a/nipype/algorithms/tests/test_rapidart.py b/nipype/algorithms/tests/test_rapidart.py index 69e6334448..9c29648626 100644 --- a/nipype/algorithms/tests/test_rapidart.py +++ b/nipype/algorithms/tests/test_rapidart.py @@ -43,26 +43,31 @@ def test_ad_get_affine_matrix(): # test rotation params = np.array([0, 0, 0, np.pi / 2, np.pi / 2, np.pi / 2]) matrix = ra._get_affine_matrix(params, 'SPM') - out = np.array([0, 0, 1, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]).reshape((4, 4)) + out = np.array([0, 0, 1, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]).reshape( + (4, 4)) npt.assert_almost_equal(matrix, out) # test scaling params = np.array([0, 0, 0, 0, 0, 0, 1, 2, 3]) matrix = ra._get_affine_matrix(params, 'SPM') - out = np.array([1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1]).reshape((4, 4)) + out = np.array([1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1]).reshape( + (4, 4)) npt.assert_equal(matrix, out) # test shear params = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3]) matrix = ra._get_affine_matrix(params, 'SPM') - out = np.array([1, 1, 2, 0, 0, 1, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1]).reshape((4, 4)) + out = np.array([1, 1, 2, 0, 0, 1, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1]).reshape( + (4, 4)) npt.assert_equal(matrix, out) def test_ad_get_norm(): - params = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, np.pi / 4, np.pi / 4, - np.pi / 4, 0, 0, 0, -np.pi / 4, - -np.pi / 4, -np.pi / 4]).reshape((3, 6)) + params = np.array([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, np.pi / 4, np.pi / 4, np.pi / 4, 0, 0, 0, + -np.pi / 4, -np.pi / 4, -np.pi / 4 + ]).reshape((3, 6)) norm, _ = ra._calc_norm(params, False, 'SPM') - npt.assert_almost_equal(norm, np.array([18.86436316, 37.74610158, 31.29780829])) + npt.assert_almost_equal(norm, + np.array([18.86436316, 37.74610158, 31.29780829])) norm, _ = ra._calc_norm(params, True, 'SPM') npt.assert_almost_equal(norm, np.array([0., 143.72192614, 173.92527131])) @@ -74,10 +79,11 @@ def test_sc_init(): def test_sc_populate_inputs(): sc = ra.StimulusCorrelation() - inputs = Bunch(realignment_parameters=None, - intensity_values=None, - spm_mat_file=None, - concatenated_design=None) + inputs = Bunch( + realignment_parameters=None, + intensity_values=None, + spm_mat_file=None, + concatenated_design=None) assert set(sc.inputs.__dict__.keys()) == set(inputs.__dict__.keys()) diff --git a/nipype/algorithms/tests/test_splitmerge.py b/nipype/algorithms/tests/test_splitmerge.py index d7e98a47ba..f05d291028 100644 --- a/nipype/algorithms/tests/test_splitmerge.py +++ b/nipype/algorithms/tests/test_splitmerge.py @@ -21,8 +21,7 @@ def test_split_and_merge(tmpdir): dwshape = (mskdata.shape[0], mskdata.shape[1], mskdata.shape[2], 6) dwdata = np.random.normal(size=dwshape) tmpdir.chdir() - nb.Nifti1Image(dwdata.astype(np.float32), - aff, None).to_filename(dwfile) + nb.Nifti1Image(dwdata.astype(np.float32), aff, None).to_filename(dwfile) resdw, resmsk, resid = split_rois(dwfile, in_mask, roishape=(20, 20, 2)) merged = merge_rois(resdw, resid, in_mask) diff --git a/nipype/caching/memory.py b/nipype/caching/memory.py index f3323180d9..a075ab8286 100644 --- a/nipype/caching/memory.py +++ b/nipype/caching/memory.py @@ -9,7 +9,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object, open import os @@ -23,7 +24,7 @@ from ..pipeline.engine import Node from ..pipeline.engine.utils import modify_paths -################################################################################ +############################################################################### # PipeFunc object: callable interface to nipype.interface objects @@ -51,8 +52,8 @@ def __init__(self, interface, base_dir, callback=None): An optional callable called each time after the function is called. """ - if not (isinstance(interface, type) and - issubclass(interface, BaseInterface)): + if not (isinstance(interface, type) + and issubclass(interface, BaseInterface)): raise ValueError('the interface argument should be a nipype ' 'interface class, but %s (type %s) was passed.' % (interface, type(interface))) @@ -85,8 +86,8 @@ def __call__(self, **kwargs): try: out = node.run() finally: - # node.run() changes to the node directory - if something goes wrong - # before it cds back you would end up in strange places + # node.run() changes to the node directory - if something goes + # wrong before it cds back you would end up in strange places os.chdir(cwd) if self.callback is not None: self.callback(dir_name, job_name) @@ -94,10 +95,11 @@ def __call__(self, **kwargs): def __repr__(self): return '{}({}.{}}, base_dir={})'.format( - self.__class__.__name__, self.interface.__module__, self.interface.__name__, - self.base_dir) + self.__class__.__name__, self.interface.__module__, + self.interface.__name__, self.base_dir) -################################################################################ + +############################################################################### # Memory manager: provide some tracking about what is computed when, to # be able to flush the disk @@ -242,7 +244,8 @@ def _log_name(self, dir_name, job_name): except OSError: "Dir exists" - with open(os.path.join(month_dir, '%02i.log' % t.tm_mday), 'a') as rotatefile: + with open(os.path.join(month_dir, '%02i.log' % t.tm_mday), + 'a') as rotatefile: rotatefile.write('%s/%s\n' % (dir_name, job_name)) def clear_previous_runs(self, warn=True): @@ -278,8 +281,7 @@ def clear_runs_since(self, day=None, month=None, year=None, warn=True): month = month if month is not None else t.tm_mon year = year if year is not None else t.tm_year base_dir = self.base_dir - cut_off_file = '%s/log.%i/%02i/%02i.log' % (base_dir, - year, month, day) + cut_off_file = '%s/log.%i/%02i/%02i.log' % (base_dir, year, month, day) logs_to_flush = list() recent_runs = dict() for log_name in glob.glob('%s/log.*/*/*.log' % base_dir): @@ -297,8 +299,8 @@ def _clear_all_but(self, runs, warn=True): """ rm_all_but(self.base_dir, set(runs.keys()), warn=warn) for dir_name, job_names in list(runs.items()): - rm_all_but(os.path.join(self.base_dir, dir_name), - job_names, warn=warn) + rm_all_but( + os.path.join(self.base_dir, dir_name), job_names, warn=warn) def __repr__(self): return '{}(base_dir={})'.format(self.__class__.__name__, self.base_dir) diff --git a/nipype/caching/tests/test_memory.py b/nipype/caching/tests/test_memory.py index 50f56d4700..3ea594f22a 100644 --- a/nipype/caching/tests/test_memory.py +++ b/nipype/caching/tests/test_memory.py @@ -12,7 +12,6 @@ class SideEffectInterface(EngineTestInterface): - def _run_interface(self, runtime): global nb_runs nb_runs += 1 @@ -40,4 +39,3 @@ def test_caching(tmpdir): assert results.outputs.output1 == [1, 1] finally: config.set('execution', 'stop_on_first_rerun', old_rerun) - diff --git a/nipype/conftest.py b/nipype/conftest.py index 27a3789ea4..ada8e08fb9 100644 --- a/nipype/conftest.py +++ b/nipype/conftest.py @@ -1,12 +1,13 @@ import pytest -import numpy, os +import numpy +import os + @pytest.fixture(autouse=True) def add_np(doctest_namespace): doctest_namespace['np'] = numpy doctest_namespace['os'] = os - filepath = os.path.dirname(os.path.realpath(__file__)) datadir = os.path.realpath(os.path.join(filepath, 'testing/data')) doctest_namespace["datadir"] = datadir diff --git a/nipype/external/cloghandler.py b/nipype/external/cloghandler.py index 3782e19374..5fda934c84 100644 --- a/nipype/external/cloghandler.py +++ b/nipype/external/cloghandler.py @@ -46,14 +46,12 @@ from builtins import range - __version__ = "$Id: cloghandler.py 6175 2009-11-02 18:40:35Z lowell $" __author__ = "Lowell Alleman" __all__ = [ "ConcurrentRotatingFileHandler", ] - import os import sys from random import randint @@ -65,7 +63,6 @@ except ImportError: codecs = None - # Question/TODO: Should we have a fallback mode if we can't load portalocker / # we should still be better off than with the standard RotattingFileHandler # class, right? We do some rename checking... that should prevent some file @@ -74,7 +71,6 @@ # sibling module than handles all the ugly platform-specific details of file locking from .portalocker import lock, unlock, LOCK_EX, LOCK_NB, LockException - # A client can set this to true to automatically convert relative paths to # absolute paths (which will also hide the absolute path warnings) FORCE_ABSOLUTE_PATH = False @@ -87,8 +83,15 @@ class ConcurrentRotatingFileHandler(BaseRotatingHandler): write to the log file concurrently, but this may mean that the file will exceed the given size. """ - def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, - encoding=None, debug=True, supress_abs_warn=False): + + def __init__(self, + filename, + mode='a', + maxBytes=0, + backupCount=0, + encoding=None, + debug=True, + supress_abs_warn=False): """ Open the specified file and use it as the stream for logging. @@ -151,9 +154,10 @@ def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, filename = os.path.abspath(filename) elif not supress_abs_warn: from warnings import warn - warn("The given 'filename' should be an absolute path. If your " - "application calls os.chdir(), your logs may get messed up. " - "Use 'supress_abs_warn=True' to hide this message.") + warn( + "The given 'filename' should be an absolute path. If your " + "application calls os.chdir(), your logs may get messed up. " + "Use 'supress_abs_warn=True' to hide this message.") try: BaseRotatingHandler.__init__(self, filename, mode, encoding) except TypeError: # Due to a different logging release without encoding support (Python 2.4.1 and earlier?) @@ -232,7 +236,7 @@ def flush(self): def _degrade(self, degrade, msg, *args): """ Set degrade mode or not. Ignore msg. """ self._rotateFailed = degrade - del msg, args # avoid pychecker warnings + del msg, args # avoid pychecker warnings def _degrade_debug(self, degrade, msg, *args): """ A more colorful version of _degade(). (This is enabled by passing @@ -264,7 +268,8 @@ def doRollover(self): # Attempt to rename logfile to tempname: There is a slight race-condition here, but it seems unavoidable tmpname = None while not tmpname or os.path.exists(tmpname): - tmpname = "%s.rotate.%08d" % (self.baseFilename, randint(0, 99999999)) + tmpname = "%s.rotate.%08d" % (self.baseFilename, + randint(0, 99999999)) try: # Do a rename test to determine if we can successfully rename the log file os.rename(self.baseFilename, tmpname) @@ -317,15 +322,17 @@ def shouldRollover(self, record): return False def _shouldRollover(self): - if self.maxBytes > 0: # are we rolling over? + if self.maxBytes > 0: # are we rolling over? try: - self.stream.seek(0, 2) # due to non-posix-compliant Windows feature + self.stream.seek( + 0, 2) # due to non-posix-compliant Windows feature except IOError: return True if self.stream.tell() >= self.maxBytes: return True else: - self._degrade(False, "Rotation done or not needed at this time") + self._degrade(False, + "Rotation done or not needed at this time") return False diff --git a/nipype/external/due.py b/nipype/external/due.py index 658ffa0aba..c360435bae 100644 --- a/nipype/external/due.py +++ b/nipype/external/due.py @@ -29,14 +29,17 @@ class InactiveDueCreditCollector(object): """Just a stub at the Collector which would not do anything""" + def _donothing(self, *args, **kwargs): """Perform no good and no bad""" pass def dcite(self, *args, **kwargs): """If I could cite I would""" + def nondecorating_decorator(func): return func + return nondecorating_decorator cite = load = add = _donothing @@ -49,6 +52,7 @@ def _donothing_func(*args, **kwargs): """Perform no good and no bad""" pass + try: from duecredit import due, BibTeX, Doi, Url if 'due' in locals() and not hasattr(due, 'cite'): diff --git a/nipype/external/fsl_imglob.py b/nipype/external/fsl_imglob.py index f77041c575..3b9a4eea4d 100755 --- a/nipype/external/fsl_imglob.py +++ b/nipype/external/fsl_imglob.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # imglob - expand list of image filenames -# Stephen Smith, Mark Jenkinson and Matthew Webster FMRIB Image Analysis Group +# Stephen Smith, Mark Jenkinson & Matthew Webster FMRIB Image Analysis Group # Copyright (C) 2009 University of Oxford # Part of FSL - FMRIB's Software Library # http://www.fmrib.ox.ac.uk/fsl @@ -68,6 +68,7 @@ import glob from builtins import range + def usage(): print("Usage: $0 [-extension/extensions] ") print(" -extension for one image with full extension") @@ -102,7 +103,7 @@ def main(): deleteExtensions = True primaryExtensions = ['.nii.gz', '.nii', '.hdr.gz', '.hdr'] secondaryExtensions = ['.img.gz', '.img'] - allExtensions = primaryExtensions+secondaryExtensions + allExtensions = primaryExtensions + secondaryExtensions validExtensions = primaryExtensions startingArg = 1 @@ -116,18 +117,22 @@ def main(): filelist = [] for arg in range(startingArg, len(sys.argv)): - # if isImage(sys.argv[arg],allExtensions)[0]: #These enable a "pedantic" style mode currently not used + # #These if enables a "pedantic" style mode currently not used + # if isImage(sys.argv[arg],allExtensions)[0]: # filelist.extend(glob.glob(sys.argv[arg])) # else: # for currentExtension in validExtensions: # filelist.extend(glob.glob(sys.argv[arg]+currentExtension)) for currentExtension in validExtensions: filelist.extend( - glob.glob(removeImageExtension(sys.argv[arg], allExtensions)+currentExtension)) + glob.glob( + removeImageExtension(sys.argv[arg], allExtensions) + + currentExtension)) if deleteExtensions: for file in range(0, len(filelist)): - filelist[file] = removeImageExtension(filelist[file], allExtensions) + filelist[file] = removeImageExtension(filelist[file], + allExtensions) if setAvailable: filelist = list(set(filelist)) else: @@ -136,8 +141,9 @@ def main(): for file in range(0, len(filelist)): print(filelist[file], end=' ') - if file < len(filelist)-1: + if file < len(filelist) - 1: print(" ", end=' ') + if __name__ == "__main__": main() diff --git a/nipype/external/portalocker.py b/nipype/external/portalocker.py index 9cb186743c..1da24d894c 100644 --- a/nipype/external/portalocker.py +++ b/nipype/external/portalocker.py @@ -49,7 +49,8 @@ Version: $Id: portalocker.py 5474 2008-05-16 20:53:50Z lowell $ ''' -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open __all__ = [ @@ -68,6 +69,7 @@ class LockException(Exception): # Error codes: LOCK_FAILED = 1 + if os.name == 'nt': import win32con import win32file @@ -86,16 +88,18 @@ class LockException(Exception): raise RuntimeError('PortaLocker only defined for nt and posix platforms') if os.name == 'nt': + def lock(file, flags): hfile = win32file._get_osfhandle(file.fileno()) try: win32file.LockFileEx(hfile, flags, 0, -0x10000, __overlapped) except pywintypes.error as exc_value: - # error: (33, 'LockFileEx', 'The process cannot access the file because another process has locked a portion of the file.') + # error: (33, 'LockFileEx', 'The process cannot access the file + # because another process has locked a portion of the file.') if exc_value[0] == 33: raise LockException(LockException.LOCK_FAILED, exc_value[2]) else: - # Q: Are there exceptions/codes we should be dealing with here? + # Q: Are there exceptions/codes we should be dealing with here? raise def unlock(file): @@ -104,14 +108,16 @@ def unlock(file): win32file.UnlockFileEx(hfile, 0, -0x10000, __overlapped) except pywintypes.error as exc_value: if exc_value[0] == 158: - # error: (158, 'UnlockFileEx', 'The segment is already unlocked.') - # To match the 'posix' implementation, silently ignore this error + # error: (158, 'UnlockFileEx', 'The segment is already + # unlocked.') To match the 'posix' implementation, silently + # ignore this error pass else: - # Q: Are there exceptions/codes we should be dealing with here? + # Q: Are there exceptions/codes we should be dealing with here? raise elif os.name == 'posix': + def lock(file, flags): try: fcntl.flock(file.fileno(), flags) diff --git a/nipype/info.py b/nipype/info.py index 8714f99707..884926f46d 100644 --- a/nipype/info.py +++ b/nipype/info.py @@ -2,7 +2,8 @@ settings in setup.py, the nipy top-level docstring, and for building the docs. In setup.py in particular, we exec this file, so it cannot import nipy """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import sys @@ -25,8 +26,8 @@ def get_nipype_gitversion(): import subprocess try: import nipype - gitpath = os.path.realpath(os.path.join(os.path.dirname(nipype.__file__), - os.path.pardir)) + gitpath = os.path.realpath( + os.path.join(os.path.dirname(nipype.__file__), os.path.pardir)) except: gitpath = os.getcwd() gitpathgit = os.path.join(gitpath, '.git') @@ -34,30 +35,32 @@ def get_nipype_gitversion(): return None ver = None try: - o, _ = subprocess.Popen('git describe', shell=True, cwd=gitpath, - stdout=subprocess.PIPE).communicate() + o, _ = subprocess.Popen( + 'git describe', shell=True, cwd=gitpath, + stdout=subprocess.PIPE).communicate() except Exception: pass else: ver = o.decode().strip().split('-')[-1] return ver + if __version__.endswith('-dev'): gitversion = get_nipype_gitversion() if gitversion: __version__ = '{}+{}'.format(__version__, gitversion) -CLASSIFIERS = ['Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: MacOS :: MacOS X', - 'Operating System :: POSIX :: Linux', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Topic :: Scientific/Engineering'] +CLASSIFIERS = [ + 'Development Status :: 5 - Production/Stable', 'Environment :: Console', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: POSIX :: Linux', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', 'Topic :: Scientific/Engineering' +] description = 'Neuroimaging in Python: Pipelines and Interfaces' @@ -81,9 +84,9 @@ def get_nipype_gitversion(): packages (e.g., AFNI, ANTS, BRAINS, BrainSuite, Camino, FreeSurfer, FSL, MNE, \ MRtrix, MNE, Nipy, Slicer, SPM), eases the design of workflows within and \ between packages, and reduces the learning curve necessary to use different \ -packages. Nipype is creating a collaborative platform for neuroimaging software \ -development in a high-level language and addressing limitations of existing \ -pipeline systems. +packages. Nipype is creating a collaborative platform for neuroimaging \ +software development in a high-level language and addressing limitations of \ +existing pipeline systems. *Nipype* allows you to: @@ -124,8 +127,8 @@ def get_nipype_gitversion(): MAJOR = __version__.split('.')[0] MINOR = __version__.split('.')[1] MICRO = __version__.replace('-', '.').split('.')[2] -ISRELEASE = (len(__version__.replace('-', '.').split('.')) == 3 or - 'post' in __version__.replace('-', '.').split('.')[-1]) +ISRELEASE = (len(__version__.replace('-', '.').split('.')) == 3 + or 'post' in __version__.replace('-', '.').split('.')[-1]) VERSION = __version__ PROVIDES = ['nipype'] REQUIRES = [ @@ -150,19 +153,17 @@ def get_nipype_gitversion(): if sys.version_info <= (3, 4): REQUIRES.append('configparser') -TESTS_REQUIRES = [ - 'pytest-cov', - 'codecov' -] +TESTS_REQUIRES = ['pytest-cov', 'codecov'] EXTRA_REQUIRES = { 'doc': ['Sphinx>=1.4', 'matplotlib', 'pydotplus', 'pydot>=1.2.3'], 'tests': TESTS_REQUIRES, + 'specs': ['yapf'], 'nipy': ['nitime', 'nilearn', 'dipy', 'nipy', 'matplotlib'], 'profiler': ['psutil>=5.0'], 'duecredit': ['duecredit'], 'xvfbwrapper': ['xvfbwrapper'], - 'pybids' : ['pybids'] + 'pybids': ['pybids'] # 'mesh': ['mayavi'] # Enable when it works } diff --git a/nipype/interfaces/__init__.py b/nipype/interfaces/__init__.py index 8f8b5d25c2..afae87d483 100644 --- a/nipype/interfaces/__init__.py +++ b/nipype/interfaces/__init__.py @@ -6,7 +6,8 @@ Requires Packages to be installed """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) __docformat__ = 'restructuredtext' from .io import DataGrabber, DataSink, SelectFiles diff --git a/nipype/interfaces/afni/__init__.py b/nipype/interfaces/afni/__init__.py index 6a1e7df767..751f168b1c 100644 --- a/nipype/interfaces/afni/__init__.py +++ b/nipype/interfaces/afni/__init__.py @@ -8,22 +8,16 @@ """ from .base import Info -from .preprocess import (AlignEpiAnatPy, Allineate, Automask, - AutoTcorrelate, AutoTLRC, - Bandpass, BlurInMask, BlurToFWHM, - ClipLevel, DegreeCentrality, Despike, - Detrend, ECM, Fim, Fourier, Hist, LFCD, - Maskave, Means, OutlierCount, - QualityIndex, ROIStats, Retroicor, - Seg, SkullStrip, TCorr1D, TCorrMap, TCorrelate, - TNorm, - TShift, Volreg, Warp, QwarpPlusMinus, Qwarp) +from .preprocess import ( + AlignEpiAnatPy, Allineate, Automask, AutoTcorrelate, AutoTLRC, Bandpass, + BlurInMask, BlurToFWHM, ClipLevel, DegreeCentrality, Despike, Detrend, ECM, + Fim, Fourier, Hist, LFCD, Maskave, Means, OutlierCount, QualityIndex, + ROIStats, Retroicor, Seg, SkullStrip, TCorr1D, TCorrMap, TCorrelate, TNorm, + TShift, Volreg, Warp, QwarpPlusMinus, Qwarp) from .svm import (SVMTest, SVMTrain) from .utils import (ABoverlap, AFNItoNIFTI, Autobox, Axialize, BrickStat, - Bucket, Calc, Cat, CatMatvec, CenterMass, Copy, Dot, - Edge3, Eval, FWHMx, MaskTool, Merge, Notes, NwarpApply, - NwarpCat, OneDToolPy, - Refit, Resample, TCat, TCatSubBrick, TStat, To3D, Unifize, - Undump, ZCutUp, GCOR, - Zcat, Zeropad) + Bucket, Calc, Cat, CatMatvec, CenterMass, Copy, Dot, Edge3, + Eval, FWHMx, MaskTool, Merge, Notes, NwarpApply, NwarpCat, + OneDToolPy, Refit, Resample, TCat, TCatSubBrick, TStat, + To3D, Unifize, Undump, ZCutUp, GCOR, Zcat, Zeropad) from .model import (Deconvolve, Remlfit, Synthesize) diff --git a/nipype/interfaces/afni/base.py b/nipype/interfaces/afni/base.py index 1097a28d46..becfd828f7 100644 --- a/nipype/interfaces/afni/base.py +++ b/nipype/interfaces/afni/base.py @@ -2,7 +2,8 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Provide interface to AFNI commands.""" -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object, str from future.utils import raise_from @@ -13,9 +14,8 @@ from ... import logging, LooseVersion from ...utils.filemanip import split_filename, fname_presuffix -from ..base import ( - CommandLine, traits, CommandLineInputSpec, isdefined, File, TraitedSpec, - PackageInfo) +from ..base import (CommandLine, traits, CommandLineInputSpec, isdefined, File, + TraitedSpec, PackageInfo) from ...external.due import BibTeX # Use nipype's logging system @@ -26,9 +26,7 @@ class Info(PackageInfo): """Handle afni output type and version information. """ __outputtype = 'AFNI' - ftypes = {'NIFTI': '.nii', - 'AFNI': '', - 'NIFTI_GZ': '.nii.gz'} + ftypes = {'NIFTI': '.nii', 'AFNI': '', 'NIFTI_GZ': '.nii.gz'} version_cmd = 'afni --version' @staticmethod @@ -87,10 +85,11 @@ def standard_image(img_name): '''Grab an image from the standard location. Could be made more fancy to allow for more relocatability''' - clout = CommandLine('which afni', - ignore_exception=True, - resource_monitor=False, - terminal_output='allatonce').run() + clout = CommandLine( + 'which afni', + ignore_exception=True, + resource_monitor=False, + terminal_output='allatonce').run() if clout.runtime.returncode is not 0: return None @@ -104,6 +103,7 @@ class AFNICommandBase(CommandLine): A base class to fix a linking problem in OSX and afni. See http://afni.nimh.nih.gov/afni/community/board/read.php?1,145346,145347#msg-145347 """ + def _run_interface(self, runtime): if platform == 'darwin': runtime.environ['DYLD_FALLBACK_LIBRARY_PATH'] = '/usr/local/afni/' @@ -111,18 +111,19 @@ def _run_interface(self, runtime): class AFNICommandInputSpec(CommandLineInputSpec): - num_threads = traits.Int(1, usedefault=True, nohash=True, - desc='set number of threads') - outputtype = traits.Enum('AFNI', list(Info.ftypes.keys()), - desc='AFNI output filetype') - out_file = File(name_template="%s_afni", desc='output image file name', - argstr='-prefix %s', - name_source=["in_file"]) + num_threads = traits.Int( + 1, usedefault=True, nohash=True, desc='set number of threads') + outputtype = traits.Enum( + 'AFNI', list(Info.ftypes.keys()), desc='AFNI output filetype') + out_file = File( + name_template="%s_afni", + desc='output image file name', + argstr='-prefix %s', + name_source=["in_file"]) class AFNICommandOutputSpec(TraitedSpec): - out_file = File(desc='output file', - exists=True) + out_file = File(desc='output file', exists=True) class AFNICommand(AFNICommandBase): @@ -130,31 +131,34 @@ class AFNICommand(AFNICommandBase): input_spec = AFNICommandInputSpec _outputtype = None - references_ = [{'entry': BibTeX('@article{Cox1996,' - 'author={R.W. Cox},' - 'title={AFNI: software for analysis and ' - 'visualization of functional magnetic ' - 'resonance neuroimages},' - 'journal={Computers and Biomedical research},' - 'volume={29},' - 'number={3},' - 'pages={162-173},' - 'year={1996},' - '}'), - 'tags': ['implementation'], - }, - {'entry': BibTeX('@article{CoxHyde1997,' - 'author={R.W. Cox and J.S. Hyde},' - 'title={Software tools for analysis and ' - 'visualization of fMRI data},' - 'journal={NMR in Biomedicine},' - 'volume={10},' - 'number={45},' - 'pages={171-178},' - 'year={1997},' - '}'), - 'tags': ['implementation'], - }] + references_ = [{ + 'entry': + BibTeX('@article{Cox1996,' + 'author={R.W. Cox},' + 'title={AFNI: software for analysis and ' + 'visualization of functional magnetic ' + 'resonance neuroimages},' + 'journal={Computers and Biomedical research},' + 'volume={29},' + 'number={3},' + 'pages={162-173},' + 'year={1996},' + '}'), + 'tags': ['implementation'], + }, { + 'entry': + BibTeX('@article{CoxHyde1997,' + 'author={R.W. Cox and J.S. Hyde},' + 'title={Software tools for analysis and ' + 'visualization of fMRI data},' + 'journal={NMR in Biomedicine},' + 'volume={10},' + 'number={45},' + 'pages={171-178},' + 'year={1997},' + '}'), + 'tags': ['implementation'], + }] @property def num_threads(self): @@ -207,7 +211,8 @@ def _output_update(self): def _overload_extension(self, value, name=None): path, base, _ = split_filename(value) - return os.path.join(path, base + Info.output_type_to_ext(self.inputs.outputtype)) + return os.path.join( + path, base + Info.output_type_to_ext(self.inputs.outputtype)) def _list_outputs(self): outputs = super(AFNICommand, self)._list_outputs() @@ -221,7 +226,11 @@ def _list_outputs(self): outputs[name] = outputs[name] + "+orig.BRIK" return outputs - def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, + def _gen_fname(self, + basename, + cwd=None, + suffix=None, + change_ext=True, ext=None): """Generate a filename based on the given parameters. @@ -263,8 +272,8 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, suffix = ext if suffix is None: suffix = '' - fname = fname_presuffix(basename, suffix=suffix, - use_ext=False, newpath=cwd) + fname = fname_presuffix( + basename, suffix=suffix, use_ext=False, newpath=cwd) return fname @@ -276,21 +285,22 @@ def no_afni(): class AFNIPythonCommandInputSpec(CommandLineInputSpec): - outputtype = traits.Enum('AFNI', list(Info.ftypes.keys()), - desc='AFNI output filetype') - py27_path = traits.Either('python2', File(exists=True), - usedefault=True, - default='python2') + outputtype = traits.Enum( + 'AFNI', list(Info.ftypes.keys()), desc='AFNI output filetype') + py27_path = traits.Either( + 'python2', File(exists=True), usedefault=True, default='python2') class AFNIPythonCommand(AFNICommand): @property def cmd(self): - if spawn.find_executable(super(AFNIPythonCommand, self).cmd) is not None: + if spawn.find_executable(super(AFNIPythonCommand, + self).cmd) is not None: return spawn.find_executable(super(AFNIPythonCommand, self).cmd) else: return super(AFNIPythonCommand, self).cmd @property def cmdline(self): - return "{} {}".format(self.inputs.py27_path, super(AFNIPythonCommand, self).cmdline) + return "{} {}".format(self.inputs.py27_path, + super(AFNIPythonCommand, self).cmdline) diff --git a/nipype/interfaces/afni/model.py b/nipype/interfaces/afni/model.py index d5730d15f9..b64c97d4f1 100644 --- a/nipype/interfaces/afni/model.py +++ b/nipype/interfaces/afni/model.py @@ -12,74 +12,73 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os -from ..base import ( - CommandLineInputSpec, CommandLine, Directory, TraitedSpec, - traits, isdefined, File, InputMultiPath, Undefined, Str) +from ..base import (CommandLineInputSpec, CommandLine, Directory, TraitedSpec, + traits, isdefined, File, InputMultiPath, Undefined, Str) from ...external.due import BibTeX -from .base import ( - AFNICommandBase, AFNICommand, AFNICommandInputSpec, AFNICommandOutputSpec) +from .base import (AFNICommandBase, AFNICommand, AFNICommandInputSpec, + AFNICommandOutputSpec) + class DeconvolveInputSpec(AFNICommandInputSpec): in_files = InputMultiPath( - File( - exists=True), + File(exists=True), desc='filenames of 3D+time input datasets. More than one filename can ' - 'be given and the datasets will be auto-catenated in time. ' - 'You can input a 1D time series file here, but the time axis ' - 'should run along the ROW direction, not the COLUMN direction as ' - 'in the \'input1D\' option.', + 'be given and the datasets will be auto-catenated in time. ' + 'You can input a 1D time series file here, but the time axis ' + 'should run along the ROW direction, not the COLUMN direction as ' + 'in the \'input1D\' option.', argstr='-input %s', copyfile=False, sep=" ", position=0) sat = traits.Bool( desc='check the dataset time series for initial saturation transients,' - ' which should normally have been excised before data analysis.', + ' which should normally have been excised before data analysis.', argstr='-sat', xor=['trans']) trans = traits.Bool( desc='check the dataset time series for initial saturation transients,' - ' which should normally have been excised before data analysis.', + ' which should normally have been excised before data analysis.', argstr='-trans', xor=['sat']) noblock = traits.Bool( desc='normally, if you input multiple datasets with \'input\', then ' - 'the separate datasets are taken to be separate image runs that ' - 'get separate baseline models. Use this options if you want to ' - 'have the program consider these to be all one big run.' - '* If any of the input dataset has only 1 sub-brick, then this ' - 'option is automatically invoked!' - '* If the auto-catenation feature isn\'t used, then this option ' - 'has no effect, no how, no way.', + 'the separate datasets are taken to be separate image runs that ' + 'get separate baseline models. Use this options if you want to ' + 'have the program consider these to be all one big run.' + '* If any of the input dataset has only 1 sub-brick, then this ' + 'option is automatically invoked!' + '* If the auto-catenation feature isn\'t used, then this option ' + 'has no effect, no how, no way.', argstr='-noblock') force_TR = traits.Int( desc='use this value instead of the TR in the \'input\' ' - 'dataset. (It\'s better to fix the input using Refit.)', + 'dataset. (It\'s better to fix the input using Refit.)', argstr='-force_TR %d') input1D = File( desc='filename of single (fMRI) .1D time series where time runs down ' - 'the column.', + 'the column.', argstr='-input1D %s', exists=True) TR_1D = traits.Float( desc='TR to use with \'input1D\'. This option has no effect if you do ' - 'not also use \'input1D\'.', + 'not also use \'input1D\'.', argstr='-TR_1D %f') legendre = traits.Bool( desc='use Legendre polynomials for null hypothesis (baseline model)', argstr='-legendre') nolegendre = traits.Bool( desc='use power polynomials for null hypotheses. Don\'t do this ' - 'unless you are crazy!', + 'unless you are crazy!', argstr='-nolegendre') nodmbase = traits.Bool( - desc='don\'t de-mean baseline time series', - argstr='-nodmbase') + desc='don\'t de-mean baseline time series', argstr='-nodmbase') dmbase = traits.Bool( desc='de-mean baseline time series (default if \'polort\' >= 0)', argstr='-dmbase') @@ -87,94 +86,81 @@ class DeconvolveInputSpec(AFNICommandInputSpec): desc='use SVD instead of Gaussian elimination (default)', argstr='-svd') nosvd = traits.Bool( - desc='use Gaussian elimination instead of SVD', - argstr='-nosvd') + desc='use Gaussian elimination instead of SVD', argstr='-nosvd') rmsmin = traits.Float( desc='minimum rms error to reject reduced model (default = 0; don\'t ' - 'use this option normally!)', + 'use this option normally!)', argstr='-rmsmin %f') nocond = traits.Bool( - desc='DON\'T calculate matrix condition number', - argstr='-nocond') + desc='DON\'T calculate matrix condition number', argstr='-nocond') singvals = traits.Bool( - desc='print out the matrix singular values', - argstr='-singvals') + desc='print out the matrix singular values', argstr='-singvals') goforit = traits.Int( desc='use this to proceed even if the matrix has bad problems (e.g., ' - 'duplicate columns, large condition number, etc.).', + 'duplicate columns, large condition number, etc.).', argstr='-GOFORIT %i') allzero_OK = traits.Bool( desc='don\'t consider all zero matrix columns to be the type of error ' - 'that \'gotforit\' is needed to ignore.', + 'that \'gotforit\' is needed to ignore.', argstr='-allzero_OK') dname = traits.Tuple( - Str, Str, + Str, + Str, desc='set environmental variable to provided value', argstr='-D%s=%s') mask = File( desc='filename of 3D mask dataset; only data time series from within ' - 'the mask will be analyzed; results for voxels outside the mask ' - 'will be set to zero.', + 'the mask will be analyzed; results for voxels outside the mask ' + 'will be set to zero.', argstr='-mask %s', exists=True) automask = traits.Bool( desc='build a mask automatically from input data (will be slow for ' - 'long time series datasets)', + 'long time series datasets)', argstr='-automask') STATmask = File( desc='build a mask from provided file, and use this mask for the ' - 'purpose of reporting truncation-to float issues AND for ' - 'computing the FDR curves. The actual results ARE not masked ' - 'with this option (only with \'mask\' or \'automask\' options).', + 'purpose of reporting truncation-to float issues AND for ' + 'computing the FDR curves. The actual results ARE not masked ' + 'with this option (only with \'mask\' or \'automask\' options).', argstr='-STATmask %s', exists=True) censor = File( desc='filename of censor .1D time series. This is a file of 1s and ' - '0s, indicating which time points are to be included (1) and ' - 'which are to be excluded (0).', + '0s, indicating which time points are to be included (1) and ' + 'which are to be excluded (0).', argstr='-censor %s', exists=True) polort = traits.Int( desc='degree of polynomial corresponding to the null hypothesis ' - '[default: 1]', + '[default: 1]', argstr='-polort %d') ortvec = traits.Tuple( - File( - desc='filename', - exists=True), - Str( - desc='label'), + File(desc='filename', exists=True), + Str(desc='label'), desc='this option lets you input a rectangular array of 1 or more ' - 'baseline vectors from a file. This method is a fast way to ' - 'include a lot of baseline regressors in one step. ', + 'baseline vectors from a file. This method is a fast way to ' + 'include a lot of baseline regressors in one step. ', argstr='ortvec %s') - x1D = File( - desc='specify name for saved X matrix', - argstr='-x1D %s') + x1D = File(desc='specify name for saved X matrix', argstr='-x1D %s') x1D_stop = traits.Bool( - desc='stop running after writing .xmat.1D file', - argstr='-x1D_stop') + desc='stop running after writing .xmat.1D file', argstr='-x1D_stop') cbucket = traits.Str( desc='Name for dataset in which to save the regression ' - 'coefficients (no statistics). This dataset ' - 'will be used in a -xrestore run [not yet implemented] ' - 'instead of the bucket dataset, if possible.', + 'coefficients (no statistics). This dataset ' + 'will be used in a -xrestore run [not yet implemented] ' + 'instead of the bucket dataset, if possible.', argstr='-cbucket %s') - out_file = File( - desc='output statistics file', - argstr='-bucket %s') + out_file = File(desc='output statistics file', argstr='-bucket %s') jobs = traits.Int( desc='run the program with provided number of sub-processes', argstr='-jobs %d') fout = traits.Bool( - desc='output F-statistic for each stimulus', - argstr='-fout') + desc='output F-statistic for each stimulus', argstr='-fout') rout = traits.Bool( - desc='output the R^2 statistic for each stimulus', - argstr='-rout') + desc='output the R^2 statistic for each stimulus', argstr='-rout') tout = traits.Bool( - desc='output the T-statistic for each stimulus', - argstr='-tout') + desc='output the T-statistic for each stimulus', argstr='-tout') vout = traits.Bool( desc='output the sample variance (MSE) for each stimulus', argstr='-vout') @@ -191,25 +177,27 @@ class DeconvolveInputSpec(AFNICommandInputSpec): argstr='-num_stimts %d', position=-6) stim_times = traits.List( - traits.Tuple(traits.Int(desc='k-th response model'), - File(desc='stimulus timing file',exists=True), - Str(desc='model')), + traits.Tuple( + traits.Int(desc='k-th response model'), + File(desc='stimulus timing file', exists=True), + Str(desc='model')), desc='generate a response model from a set of stimulus times' - ' given in file.', + ' given in file.', argstr='-stim_times %d %s \'%s\'...', position=-5) stim_label = traits.List( - traits.Tuple(traits.Int(desc='k-th input stimulus'), - Str(desc='stimulus label')), + traits.Tuple( + traits.Int(desc='k-th input stimulus'), + Str(desc='stimulus label')), desc='label for kth input stimulus (e.g., Label1)', argstr='-stim_label %d %s...', requires=['stim_times'], position=-4) stim_times_subtract = traits.Float( desc='this option means to subtract specified seconds from each time ' - 'encountered in any \'stim_times\' option. The purpose of this ' - 'option is to make it simple to adjust timing files for the ' - 'removal of images from the start of each imaging run.', + 'encountered in any \'stim_times\' option. The purpose of this ' + 'option is to make it simple to adjust timing files for the ' + 'removal of images from the start of each imaging run.', argstr='-stim_times_subtract %f') num_glt = traits.Int( desc='number of general linear tests (i.e., contrasts)', @@ -218,12 +206,13 @@ class DeconvolveInputSpec(AFNICommandInputSpec): gltsym = traits.List( Str(desc='symbolic general linear test'), desc='general linear tests (i.e., contrasts) using symbolic ' - 'conventions (e.g., \'+Label1 -Label2\')', + 'conventions (e.g., \'+Label1 -Label2\')', argstr='-gltsym \'SYM: %s\'...', position=-2) glt_label = traits.List( - traits.Tuple(traits.Int(desc='k-th general linear test'), - Str(desc='GLT label')), + traits.Tuple( + traits.Int(desc='k-th general linear test'), + Str(desc='GLT label')), desc='general linear test (i.e., contrast) labels', argstr='-glt_label %d %s...', requires=['gltsym'], @@ -231,14 +220,11 @@ class DeconvolveInputSpec(AFNICommandInputSpec): class DeconvolveOutputSpec(TraitedSpec): - out_file = File( - desc='output statistics file', exists=True) + out_file = File(desc='output statistics file', exists=True) reml_script = File( desc='automatical generated script to run 3dREMLfit', exists=True) - x1D = File( - desc='save out X matrix', exists=True) - cbucket = File( - desc='output regression coefficients file (if generated)') + x1D = File(desc='save out X matrix', exists=True) + cbucket = File(desc='output regression coefficients file (if generated)') class Deconvolve(AFNICommand): @@ -275,12 +261,13 @@ def _format_arg(self, name, trait_spec, value): if val.startswith('SYM: '): value[n] = val.lstrip('SYM: ') - return super(Deconvolve,self)._format_arg(name, trait_spec, value) + return super(Deconvolve, self)._format_arg(name, trait_spec, value) def _parse_inputs(self, skip=None): if skip is None: skip = [] - if len(self.inputs.stim_times) and not isdefined(self.inputs.num_stimts): + if len(self.inputs.stim_times) and not isdefined( + self.inputs.num_stimts): self.inputs.num_stimts = len(self.inputs.stim_times) if len(self.inputs.gltsym) and not isdefined(self.inputs.num_glt): self.inputs.num_glt = len(self.inputs.gltsym) @@ -302,9 +289,11 @@ def _list_outputs(self): else: outputs['x1D'] = os.path.abspath(self.inputs.x1D) else: - outputs['x1D'] = self._gen_fname(suffix='.xmat.1D', **_gen_fname_opts) + outputs['x1D'] = self._gen_fname( + suffix='.xmat.1D', **_gen_fname_opts) - outputs['reml_script'] = self._gen_fname(suffix='.REML_cmd', **_gen_fname_opts) + outputs['reml_script'] = self._gen_fname( + suffix='.REML_cmd', **_gen_fname_opts) outputs['out_file'] = os.path.abspath(self.inputs.out_file) return outputs @@ -313,8 +302,7 @@ def _list_outputs(self): class RemlfitInputSpec(AFNICommandInputSpec): # mandatory files in_files = InputMultiPath( - File( - exists=True), + File(exists=True), desc='Read time series dataset', argstr='-input "%s"', mandatory=True, @@ -322,42 +310,42 @@ class RemlfitInputSpec(AFNICommandInputSpec): sep=" ") matrix = File( desc='the design matrix file, which should have been output from ' - 'Deconvolve via the \'x1D\' option', + 'Deconvolve via the \'x1D\' option', argstr='-matrix %s', mandatory=True) # "Semi-Hidden Alternative Ways to Define the Matrix" polort = traits.Int( desc='if no \'matrix\' option is given, AND no \'matim\' option, ' - 'create a matrix with Legendre polynomial regressors' - 'up to the specified order. The default value is 0, which' - 'produces a matrix with a single column of all ones', + 'create a matrix with Legendre polynomial regressors' + 'up to the specified order. The default value is 0, which' + 'produces a matrix with a single column of all ones', argstr='-polort %d', xor=['matrix']) matim = traits.File( desc='read a standard file as the matrix. You can use only Col as ' - 'a name in GLTs with these nonstandard matrix input methods, ' - 'since the other names come from the \'matrix\' file. ' - 'These mutually exclusive options are ignored if \'matrix\' ' - 'is used.', + 'a name in GLTs with these nonstandard matrix input methods, ' + 'since the other names come from the \'matrix\' file. ' + 'These mutually exclusive options are ignored if \'matrix\' ' + 'is used.', argstr='-matim %s', xor=['matrix']) # Other arguments mask = File( desc='filename of 3D mask dataset; only data time series from within ' - 'the mask will be analyzed; results for voxels outside the mask ' - 'will be set to zero.', + 'the mask will be analyzed; results for voxels outside the mask ' + 'will be set to zero.', argstr='-mask %s', exists=True) automask = traits.Bool( usedefault=True, argstr='-automask', desc='build a mask automatically from input data (will be slow for ' - 'long time series datasets)') + 'long time series datasets)') STATmask = File( desc='filename of 3D mask dataset to be used for the purpose ' - 'of reporting truncation-to float issues AND for computing the ' - 'FDR curves. The actual results ARE not masked with this option ' - '(only with \'mask\' or \'automask\' options).', + 'of reporting truncation-to float issues AND for computing the ' + 'FDR curves. The actual results ARE not masked with this option ' + '(only with \'mask\' or \'automask\' options).', argstr='-STATmask %s', exists=True) addbase = InputMultiPath( @@ -365,9 +353,9 @@ class RemlfitInputSpec(AFNICommandInputSpec): exists=True, desc='file containing columns to add to regression matrix'), desc='file(s) to add baseline model columns to the matrix with this ' - 'option. Each column in the specified file(s) will be appended ' - 'to the matrix. File(s) must have at least as many rows as the ' - 'matrix does.', + 'option. Each column in the specified file(s) will be appended ' + 'to the matrix. File(s) must have at least as many rows as the ' + 'matrix does.', copyfile=False, sep=" ", argstr='-addbase %s') @@ -376,44 +364,44 @@ class RemlfitInputSpec(AFNICommandInputSpec): exists=True, desc='file containing columns to add to regression matrix'), desc='similar to \'addbase\' in concept, BUT each specified file ' - 'must have an integer multiple of the number of slices ' - 'in the input dataset(s); then, separate regression ' - 'matrices are generated for each slice, with the ' - 'first column of the file appended to the matrix for ' - 'the first slice of the dataset, the second column of the file ' - 'appended to the matrix for the first slice of the dataset, ' - 'and so on. Intended to help model physiological noise in FMRI, ' - 'or other effects you want to regress out that might ' - 'change significantly in the inter-slice time intervals. This ' - 'will slow the program down, and make it use a lot more memory ' - '(to hold all the matrix stuff).', + 'must have an integer multiple of the number of slices ' + 'in the input dataset(s); then, separate regression ' + 'matrices are generated for each slice, with the ' + 'first column of the file appended to the matrix for ' + 'the first slice of the dataset, the second column of the file ' + 'appended to the matrix for the first slice of the dataset, ' + 'and so on. Intended to help model physiological noise in FMRI, ' + 'or other effects you want to regress out that might ' + 'change significantly in the inter-slice time intervals. This ' + 'will slow the program down, and make it use a lot more memory ' + '(to hold all the matrix stuff).', argstr='-slibase %s') slibase_sm = InputMultiPath( File( exists=True, desc='file containing columns to add to regression matrix'), desc='similar to \'slibase\', BUT each file much be in slice major ' - 'order (i.e. all slice0 columns come first, then all slice1 ' - 'columns, etc).', + 'order (i.e. all slice0 columns come first, then all slice1 ' + 'columns, etc).', argstr='-slibase_sm %s') usetemp = traits.Bool( desc='write intermediate stuff to disk, to economize on RAM. ' - 'Using this option might be necessary to run with ' - '\'slibase\' and with \'Grid\' values above the default, ' - 'since the program has to store a large number of ' - 'matrices for such a problem: two for every slice and ' - 'for every (a,b) pair in the ARMA parameter grid. Temporary ' - 'files are written to the directory given in environment ' - 'variable TMPDIR, or in /tmp, or in ./ (preference is in that ' - 'order)', + 'Using this option might be necessary to run with ' + '\'slibase\' and with \'Grid\' values above the default, ' + 'since the program has to store a large number of ' + 'matrices for such a problem: two for every slice and ' + 'for every (a,b) pair in the ARMA parameter grid. Temporary ' + 'files are written to the directory given in environment ' + 'variable TMPDIR, or in /tmp, or in ./ (preference is in that ' + 'order)', argstr='-usetemp') nodmbase = traits.Bool( desc='by default, baseline columns added to the matrix via ' - '\'addbase\' or \'slibase\' or \'dsort\' will each have their ' - 'mean removed (as is done in Deconvolve); this option turns this ' - 'centering off', + '\'addbase\' or \'slibase\' or \'dsort\' will each have their ' + 'mean removed (as is done in Deconvolve); this option turns this ' + 'centering off', argstr='-nodmbase', - requires=['addbase','dsort']) + requires=['addbase', 'dsort']) dsort = File( desc='4D dataset to be used as voxelwise baseline regressor', exists=True, @@ -421,79 +409,75 @@ class RemlfitInputSpec(AFNICommandInputSpec): argstr='-dsort %s') dsort_nods = traits.Bool( desc='if \'dsort\' option is used, this command will output ' - 'additional results files excluding the \'dsort\' file', + 'additional results files excluding the \'dsort\' file', argstr='-dsort_nods', requires=['dsort']) fout = traits.Bool( - desc='output F-statistic for each stimulus', - argstr='-fout') + desc='output F-statistic for each stimulus', argstr='-fout') rout = traits.Bool( - desc='output the R^2 statistic for each stimulus', - argstr='-rout') + desc='output the R^2 statistic for each stimulus', argstr='-rout') tout = traits.Bool( desc='output the T-statistic for each stimulus; if you use ' - '\'out_file\' and do not give any of \'fout\', \'tout\',' - 'or \'rout\', then the program assumes \'fout\' is activated.', + '\'out_file\' and do not give any of \'fout\', \'tout\',' + 'or \'rout\', then the program assumes \'fout\' is activated.', argstr='-tout') nofdr = traits.Bool( desc='do NOT add FDR curve data to bucket datasets; FDR curves can ' - 'take a long time if \'tout\' is used', + 'take a long time if \'tout\' is used', argstr='-noFDR') nobout = traits.Bool( desc='do NOT add baseline (null hypothesis) regressor betas ' - 'to the \'rbeta_file\' and/or \'obeta_file\' output datasets.', + 'to the \'rbeta_file\' and/or \'obeta_file\' output datasets.', argstr='-nobout') gltsym = traits.List( - traits.Either(traits.Tuple(File(exists=True), Str()), - traits.Tuple(Str(), Str())), + traits.Either( + traits.Tuple(File(exists=True), Str()), traits.Tuple(Str(), + Str())), desc='read a symbolic GLT from input file and associate it with a ' - 'label. As in Deconvolve, you can also use the \'SYM:\' method ' - 'to provide the definition of the GLT directly as a string ' - '(e.g., with \'SYM: +Label1 -Label2\'). Unlike Deconvolve, you ' - 'MUST specify \'SYM: \' if providing the GLT directly as a ' - 'string instead of from a file', + 'label. As in Deconvolve, you can also use the \'SYM:\' method ' + 'to provide the definition of the GLT directly as a string ' + '(e.g., with \'SYM: +Label1 -Label2\'). Unlike Deconvolve, you ' + 'MUST specify \'SYM: \' if providing the GLT directly as a ' + 'string instead of from a file', argstr='-gltsym "%s" %s...') out_file = File( desc='output dataset for beta + statistics from the REML estimation; ' - 'also contains the results of any GLT analysis requested ' - 'in the Deconvolve setup, similar to the \'bucket\' output ' - 'from Deconvolve. This dataset does NOT get the betas ' - '(or statistics) of those regressors marked as \'baseline\' ' - 'in the matrix file.', + 'also contains the results of any GLT analysis requested ' + 'in the Deconvolve setup, similar to the \'bucket\' output ' + 'from Deconvolve. This dataset does NOT get the betas ' + '(or statistics) of those regressors marked as \'baseline\' ' + 'in the matrix file.', argstr='-Rbuck %s') var_file = File( - desc='output dataset for REML variance parameters', - argstr='-Rvar %s') + desc='output dataset for REML variance parameters', argstr='-Rvar %s') rbeta_file = File( desc='output dataset for beta weights from the REML estimation, ' - 'similar to the \'cbucket\' output from Deconvolve. This dataset ' - 'will contain all the beta weights, for baseline and stimulus ' - 'regressors alike, unless the \'-nobout\' option is given -- ' - 'in that case, this dataset will only get the betas for the ' - 'stimulus regressors.', + 'similar to the \'cbucket\' output from Deconvolve. This dataset ' + 'will contain all the beta weights, for baseline and stimulus ' + 'regressors alike, unless the \'-nobout\' option is given -- ' + 'in that case, this dataset will only get the betas for the ' + 'stimulus regressors.', argstr='-Rbeta %s') glt_file = File( desc='output dataset for beta + statistics from the REML estimation, ' - 'but ONLY for the GLTs added on the REMLfit command line itself ' - 'via \'gltsym\'; GLTs from Deconvolve\'s command line will NOT ' - 'be included.', + 'but ONLY for the GLTs added on the REMLfit command line itself ' + 'via \'gltsym\'; GLTs from Deconvolve\'s command line will NOT ' + 'be included.', argstr='-Rglt %s') fitts_file = File( - desc='ouput dataset for REML fitted model', - argstr='-Rfitts %s') + desc='ouput dataset for REML fitted model', argstr='-Rfitts %s') errts_file = File( desc='output dataset for REML residuals = data - fitted model', argstr='-Rerrts %s') wherr_file = File( desc='dataset for REML residual, whitened using the estimated ' - 'ARMA(1,1) correlation matrix of the noise', + 'ARMA(1,1) correlation matrix of the noise', argstr='-Rwherr %s') quiet = traits.Bool( - desc='turn off most progress messages', - argstr='-quiet') + desc='turn off most progress messages', argstr='-quiet') verb = traits.Bool( desc='turns on more progress messages, including memory usage ' - 'progress reports at various stages', + 'progress reports at various stages', argstr='-verb') ovar = File( desc='dataset for OLSQ st.dev. parameter (kind of boring)', @@ -507,9 +491,7 @@ class RemlfitInputSpec(AFNICommandInputSpec): oglt = File( desc='dataset for beta + statistics from \'gltsym\' options', argstr='-Oglt %s') - ofitts = File( - desc='dataset for OLSQ fitted model', - argstr='-Ofitts %s') + ofitts = File(desc='dataset for OLSQ fitted model', argstr='-Ofitts %s') oerrts = File( desc='dataset for OLSQ residuals (data - fitted model)', argstr='-Oerrts %s') @@ -518,43 +500,38 @@ class RemlfitInputSpec(AFNICommandInputSpec): class RemlfitOutputSpec(AFNICommandOutputSpec): out_file = File( desc='dataset for beta + statistics from the REML estimation (if ' - 'generated') - var_file = File( - desc='dataset for REML variance parameters (if generated)') + 'generated') + var_file = File(desc='dataset for REML variance parameters (if generated)') rbeta_file = File( desc='dataset for beta weights from the REML estimation (if ' - 'generated)') + 'generated)') rbeta_file = File( desc='output dataset for beta weights from the REML estimation (if ' - 'generated') + 'generated') glt_file = File( desc='output dataset for beta + statistics from the REML estimation, ' - 'but ONLY for the GLTs added on the REMLfit command ' - 'line itself via \'gltsym\' (if generated)') + 'but ONLY for the GLTs added on the REMLfit command ' + 'line itself via \'gltsym\' (if generated)') fitts_file = File( desc='ouput dataset for REML fitted model (if generated)') errts_file = File( desc='output dataset for REML residuals = data - fitted model (if ' - 'generated') + 'generated') wherr_file = File( desc='dataset for REML residual, whitened using the estimated ' - 'ARMA(1,1) correlation matrix of the noise (if generated)') - ovar = File( - desc='dataset for OLSQ st.dev. parameter (if generated)') - obeta = File( - desc='dataset for beta weights from the OLSQ estimation (if ' - 'generated)') + 'ARMA(1,1) correlation matrix of the noise (if generated)') + ovar = File(desc='dataset for OLSQ st.dev. parameter (if generated)') + obeta = File(desc='dataset for beta weights from the OLSQ estimation (if ' + 'generated)') obuck = File( desc='dataset for beta + statistics from the OLSQ estimation (if ' - 'generated)') + 'generated)') oglt = File( desc='dataset for beta + statistics from \'gltsym\' options (if ' - 'generated') - ofitts = File( - desc='dataset for OLSQ fitted model (if generated)') - oerrts = File( - desc='dataset for OLSQ residuals = data - fitted model (if ' - 'generated') + 'generated') + ofitts = File(desc='dataset for OLSQ fitted model (if generated)') + oerrts = File(desc='dataset for OLSQ residuals = data - fitted model (if ' + 'generated') class Remlfit(AFNICommand): @@ -601,13 +578,13 @@ def _list_outputs(self): class SynthesizeInputSpec(AFNICommandInputSpec): cbucket = File( desc='Read the dataset output from ' - '3dDeconvolve via the \'-cbucket\' option.', + '3dDeconvolve via the \'-cbucket\' option.', argstr='-cbucket %s', copyfile=False, mandatory=True) matrix = File( desc='Read the matrix output from ' - '3dDeconvolve via the \'-x1D\' option.', + '3dDeconvolve via the \'-x1D\' option.', argstr='-matrix %s', copyfile=False, mandatory=True) @@ -615,14 +592,14 @@ class SynthesizeInputSpec(AFNICommandInputSpec): Str(desc='selected columns to synthesize'), argstr='-select %s', desc='A list of selected columns from the matrix (and the ' - 'corresponding coefficient sub-bricks from the ' - 'cbucket). Valid types include \'baseline\', ' - ' \'polort\', \'allfunc\', \'allstim\', \'all\', ' - 'Can also provide \'something\' where something matches ' - 'a stim_label from 3dDeconvolve, and \'digits\' where digits ' - 'are the numbers of the select matrix columns by ' - 'numbers (starting at 0), or number ranges of the form ' - '\'3..7\' and \'3-7\'.', + 'corresponding coefficient sub-bricks from the ' + 'cbucket). Valid types include \'baseline\', ' + ' \'polort\', \'allfunc\', \'allstim\', \'all\', ' + 'Can also provide \'something\' where something matches ' + 'a stim_label from 3dDeconvolve, and \'digits\' where digits ' + 'are the numbers of the select matrix columns by ' + 'numbers (starting at 0), or number ranges of the form ' + '\'3..7\' and \'3-7\'.', mandatory=True) out_file = File( name_template='syn', @@ -630,18 +607,20 @@ class SynthesizeInputSpec(AFNICommandInputSpec): argstr='-prefix %s') dry_run = traits.Bool( desc='Don\'t compute the output, just ' - 'check the inputs.', + 'check the inputs.', argstr='-dry') TR = traits.Float( desc='TR to set in the output. The default value of ' - 'TR is read from the header of the matrix file.', + 'TR is read from the header of the matrix file.', argstr='-TR %f') cenfill = traits.Enum( - 'zero','nbhr','none', + 'zero', + 'nbhr', + 'none', argstr='-cenfill %s', desc='Determines how censored time points from the ' - '3dDeconvolve run will be filled. Valid types ' - 'are \'zero\', \'nbhr\' and \'none\'.') + '3dDeconvolve run will be filled. Valid types ' + 'are \'zero\', \'nbhr\' and \'none\'.') class Synthesize(AFNICommand): diff --git a/nipype/interfaces/afni/preprocess.py b/nipype/interfaces/afni/preprocess.py index 5d90591953..f8bb57e06d 100644 --- a/nipype/interfaces/afni/preprocess.py +++ b/nipype/interfaces/afni/preprocess.py @@ -9,7 +9,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -17,13 +18,12 @@ from ...utils.filemanip import (load_json, save_json, split_filename, fname_presuffix) -from ..base import ( - CommandLineInputSpec, CommandLine, TraitedSpec, - traits, isdefined, File, InputMultiPath, Undefined, Str) +from ..base import (CommandLineInputSpec, CommandLine, TraitedSpec, traits, + isdefined, File, InputMultiPath, Undefined, Str) -from .base import ( - AFNICommandBase, AFNICommand, AFNICommandInputSpec, AFNICommandOutputSpec, - AFNIPythonCommandInputSpec, AFNIPythonCommand, Info, no_afni) +from .base import (AFNICommandBase, AFNICommand, AFNICommandInputSpec, + AFNICommandOutputSpec, AFNIPythonCommandInputSpec, + AFNIPythonCommand, Info, no_afni) class CentralityInputSpec(AFNICommandInputSpec): @@ -31,15 +31,11 @@ class CentralityInputSpec(AFNICommandInputSpec): """ mask = File( - desc='mask file to mask input data', - argstr='-mask %s', - exists=True) + desc='mask file to mask input data', argstr='-mask %s', exists=True) thresh = traits.Float( desc='threshold to exclude connections where corr <= thresh', argstr='-thresh %f') - polort = traits.Int( - desc='', - argstr='-polort %d') + polort = traits.Int(desc='', argstr='-polort %d') autoclip = traits.Bool( desc='Clip off low-intensity regions in the dataset', argstr='-autoclip') @@ -47,6 +43,7 @@ class CentralityInputSpec(AFNICommandInputSpec): desc='Mask the dataset to target brain-only voxels', argstr='-automask') + class AlignEpiAnatPyInputSpec(AFNIPythonCommandInputSpec): in_file = File( desc='EPI dataset to align', @@ -64,40 +61,39 @@ class AlignEpiAnatPyInputSpec(AFNIPythonCommandInputSpec): traits.Range(low=0), traits.Enum('mean', 'median', 'max'), desc='the epi base used in alignment' - 'should be one of (0/mean/median/max/subbrick#)', + 'should be one of (0/mean/median/max/subbrick#)', mandatory=True, argstr='-epi_base %s') anat2epi = traits.Bool( - desc='align anatomical to EPI dataset (default)', - argstr='-anat2epi') + desc='align anatomical to EPI dataset (default)', argstr='-anat2epi') epi2anat = traits.Bool( - desc='align EPI to anatomical dataset', - argstr='-epi2anat') + desc='align EPI to anatomical dataset', argstr='-epi2anat') save_skullstrip = traits.Bool( - desc='save skull-stripped (not aligned)', - argstr='-save_skullstrip') + desc='save skull-stripped (not aligned)', argstr='-save_skullstrip') suffix = traits.Str( '_al', desc='append suffix to the original anat/epi dataset to use' - 'in the resulting dataset names (default is "_al")', + 'in the resulting dataset names (default is "_al")', usedefault=True, argstr='-suffix %s') epi_strip = traits.Enum( ('3dSkullStrip', '3dAutomask', 'None'), desc='method to mask brain in EPI data' - 'should be one of[3dSkullStrip]/3dAutomask/None)', + 'should be one of[3dSkullStrip]/3dAutomask/None)', argstr='-epi_strip %s') volreg = traits.Enum( - 'on', 'off', + 'on', + 'off', usedefault=True, desc='do volume registration on EPI dataset before alignment' - 'should be \'on\' or \'off\', defaults to \'on\'', + 'should be \'on\' or \'off\', defaults to \'on\'', argstr='-volreg %s') tshift = traits.Enum( - 'on', 'off', + 'on', + 'off', usedefault=True, desc='do time shifting of EPI dataset before alignment' - 'should be \'on\' or \'off\', defaults to \'on\'', + 'should be \'on\' or \'off\', defaults to \'on\'', argstr='-tshift %s') @@ -108,23 +104,18 @@ class AlignEpiAnatPyOutputSpec(TraitedSpec): desc="A version of the EPI dataset aligned to the anatomy") epi_tlrc_al = File( desc="A version of the EPI dataset aligned to a standard template") - anat_al_mat = File( - desc="matrix to align anatomy to the EPI") - epi_al_mat = File( - desc="matrix to align EPI to anatomy") - epi_vr_al_mat = File( - desc="matrix to volume register EPI") + anat_al_mat = File(desc="matrix to align anatomy to the EPI") + epi_al_mat = File(desc="matrix to align EPI to anatomy") + epi_vr_al_mat = File(desc="matrix to volume register EPI") epi_reg_al_mat = File( desc="matrix to volume register and align epi to anatomy") - epi_al_tlrc_mat = File( - desc="matrix to volume register and align epi" - "to anatomy and put into standard space") - epi_vr_motion = File( - desc="motion parameters from EPI time-series" - "registration (tsh included in name if slice" - "timing correction is also included).") - skullstrip = File( - desc="skull-stripped (not aligned) volume") + epi_al_tlrc_mat = File(desc="matrix to volume register and align epi" + "to anatomy and put into standard space") + epi_vr_motion = File(desc="motion parameters from EPI time-series" + "registration (tsh included in name if slice" + "timing correction is also included).") + skullstrip = File(desc="skull-stripped (not aligned) volume") + class AlignEpiAnatPy(AFNIPythonCommand): """Align EPI to anatomical datasets or vice versa @@ -179,8 +170,10 @@ class AlignEpiAnatPy(AFNIPythonCommand): def _list_outputs(self): outputs = self.output_spec().get() - anat_prefix = ''.join(self._gen_fname(self.inputs.anat).split('+')[:-1]) - epi_prefix = ''.join(self._gen_fname(self.inputs.in_file).split('+')[:-1]) + anat_prefix = ''.join( + self._gen_fname(self.inputs.anat).split('+')[:-1]) + epi_prefix = ''.join( + self._gen_fname(self.inputs.in_file).split('+')[:-1]) outputtype = self.inputs.outputtype if outputtype == 'AFNI': ext = '.HEAD' @@ -189,23 +182,33 @@ def _list_outputs(self): matext = '.1D' suffix = self.inputs.suffix if self.inputs.anat2epi: - outputs['anat_al_orig'] = self._gen_fname(anat_prefix, suffix=suffix+'+orig', ext=ext) - outputs['anat_al_mat'] = self._gen_fname(anat_prefix, suffix=suffix+'_mat.aff12', ext=matext) + outputs['anat_al_orig'] = self._gen_fname( + anat_prefix, suffix=suffix + '+orig', ext=ext) + outputs['anat_al_mat'] = self._gen_fname( + anat_prefix, suffix=suffix + '_mat.aff12', ext=matext) if self.inputs.epi2anat: - outputs['epi_al_orig'] = self._gen_fname(epi_prefix, suffix=suffix+'+orig', ext=ext) - outputs['epi_al_mat'] = self._gen_fname(epi_prefix, suffix=suffix+'_mat.aff12', ext=matext) + outputs['epi_al_orig'] = self._gen_fname( + epi_prefix, suffix=suffix + '+orig', ext=ext) + outputs['epi_al_mat'] = self._gen_fname( + epi_prefix, suffix=suffix + '_mat.aff12', ext=matext) if self.inputs.volreg == 'on': - outputs['epi_vr_al_mat'] = self._gen_fname(epi_prefix, suffix='_vr'+suffix+'_mat.aff12', ext=matext) + outputs['epi_vr_al_mat'] = self._gen_fname( + epi_prefix, suffix='_vr' + suffix + '_mat.aff12', ext=matext) if self.inputs.tshift == 'on': - outputs['epi_vr_motion'] = self._gen_fname(epi_prefix, suffix='tsh_vr_motion', ext=matext) + outputs['epi_vr_motion'] = self._gen_fname( + epi_prefix, suffix='tsh_vr_motion', ext=matext) elif self.inputs.tshift == 'off': - outputs['epi_vr_motion'] = self._gen_fname(epi_prefix, suffix='vr_motion', ext=matext) + outputs['epi_vr_motion'] = self._gen_fname( + epi_prefix, suffix='vr_motion', ext=matext) if self.inputs.volreg == 'on' and self.inputs.epi2anat: - outputs['epi_reg_al_mat'] = self._gen_fname(epi_prefix, suffix='_reg'+suffix+'_mat.aff12', ext=matext) + outputs['epi_reg_al_mat'] = self._gen_fname( + epi_prefix, suffix='_reg' + suffix + '_mat.aff12', ext=matext) if self.inputs.save_skullstrip: - outputs.skullstrip = self._gen_fname(anat_prefix, suffix='_ns'+'+orig', ext=ext) + outputs.skullstrip = self._gen_fname( + anat_prefix, suffix='_ns' + '+orig', ext=ext) return outputs + class AllineateInputSpec(AFNICommandInputSpec): in_file = File( desc='input file to 3dAllineate', @@ -217,7 +220,7 @@ class AllineateInputSpec(AFNICommandInputSpec): exists=True, argstr='-base %s', desc='file to be used as reference, the first volume will be used if ' - 'not given the reference will be the first volume of in_file.') + 'not given the reference will be the first volume of in_file.') out_file = File( desc='output file from 3dAllineate', argstr='-prefix %s', @@ -226,48 +229,46 @@ class AllineateInputSpec(AFNICommandInputSpec): out_param_file = File( argstr='-1Dparam_save %s', desc='Save the warp parameters in ASCII (.1D) format.', - xor=['in_param_file','allcostx']) + xor=['in_param_file', 'allcostx']) in_param_file = File( exists=True, argstr='-1Dparam_apply %s', desc='Read warp parameters from file and apply them to ' - 'the source dataset, and produce a new dataset', + 'the source dataset, and produce a new dataset', xor=['out_param_file']) out_matrix = File( argstr='-1Dmatrix_save %s', desc='Save the transformation matrix for each volume.', - xor=['in_matrix','allcostx']) + xor=['in_matrix', 'allcostx']) in_matrix = File( desc='matrix to align input file', argstr='-1Dmatrix_apply %s', position=-3, xor=['out_matrix']) overwrite = traits.Bool( - desc='overwrite output file if it already exists', - argstr='-overwrite') + desc='overwrite output file if it already exists', argstr='-overwrite') - allcostx= File( - desc='Compute and print ALL available cost functionals for the un-warped inputs' - 'AND THEN QUIT. If you use this option none of the other expected outputs will be produced', + allcostx = File( + desc= + 'Compute and print ALL available cost functionals for the un-warped inputs' + 'AND THEN QUIT. If you use this option none of the other expected outputs will be produced', argstr='-allcostx |& tee %s', position=-1, xor=['out_file', 'out_matrix', 'out_param_file', 'out_weight_file']) _cost_funcs = [ - 'leastsq', 'ls', - 'mutualinfo', 'mi', - 'corratio_mul', 'crM', - 'norm_mutualinfo', 'nmi', - 'hellinger', 'hel', - 'corratio_add', 'crA', - 'corratio_uns', 'crU'] + 'leastsq', 'ls', 'mutualinfo', 'mi', 'corratio_mul', 'crM', + 'norm_mutualinfo', 'nmi', 'hellinger', 'hel', 'corratio_add', 'crA', + 'corratio_uns', 'crU' + ] cost = traits.Enum( *_cost_funcs, argstr='-cost %s', desc='Defines the \'cost\' function that defines the matching between ' - 'the source and the base') + 'the source and the base') _interp_funcs = [ - 'nearestneighbour', 'linear', 'cubic', 'quintic', 'wsinc5'] + 'nearestneighbour', 'linear', 'cubic', 'quintic', 'wsinc5' + ] interpolation = traits.Enum( *_interp_funcs[:-1], argstr='-interp %s', @@ -282,105 +283,105 @@ class AllineateInputSpec(AFNICommandInputSpec): argstr='-nmatch %d', desc='Use at most n scattered points to match the datasets.') no_pad = traits.Bool( - argstr='-nopad', - desc='Do not use zero-padding on the base image.') + argstr='-nopad', desc='Do not use zero-padding on the base image.') zclip = traits.Bool( argstr='-zclip', desc='Replace negative values in the input datasets (source & base) ' - 'with zero.') + 'with zero.') convergence = traits.Float( argstr='-conv %f', desc='Convergence test in millimeters (default 0.05mm).') - usetemp = traits.Bool( - argstr='-usetemp', - desc='temporary file use') + usetemp = traits.Bool(argstr='-usetemp', desc='temporary file use') check = traits.List( traits.Enum(*_cost_funcs), argstr='-check %s', desc='After cost functional optimization is done, start at the final ' - 'parameters and RE-optimize using this new cost functions. If ' - 'the results are too different, a warning message will be ' - 'printed. However, the final parameters from the original ' - 'optimization will be used to create the output dataset.') + 'parameters and RE-optimize using this new cost functions. If ' + 'the results are too different, a warning message will be ' + 'printed. However, the final parameters from the original ' + 'optimization will be used to create the output dataset.') # ** PARAMETERS THAT AFFECT THE COST OPTIMIZATION STRATEGY ** one_pass = traits.Bool( argstr='-onepass', desc='Use only the refining pass -- do not try a coarse resolution ' - 'pass first. Useful if you know that only small amounts of ' - 'image alignment are needed.') + 'pass first. Useful if you know that only small amounts of ' + 'image alignment are needed.') two_pass = traits.Bool( argstr='-twopass', desc='Use a two pass alignment strategy for all volumes, searching ' - 'for a large rotation+shift and then refining the alignment.') + 'for a large rotation+shift and then refining the alignment.') two_blur = traits.Float( argstr='-twoblur %f', desc='Set the blurring radius for the first pass in mm.') two_first = traits.Bool( argstr='-twofirst', desc='Use -twopass on the first image to be registered, and ' - 'then on all subsequent images from the source dataset, ' - 'use results from the first image\'s coarse pass to start ' - 'the fine pass.') + 'then on all subsequent images from the source dataset, ' + 'use results from the first image\'s coarse pass to start ' + 'the fine pass.') two_best = traits.Int( argstr='-twobest %d', desc='In the coarse pass, use the best \'bb\' set of initial' - 'points to search for the starting point for the fine' - 'pass. If bb==0, then no search is made for the best' - 'starting point, and the identity transformation is' - 'used as the starting point. [Default=5; min=0 max=11]') + 'points to search for the starting point for the fine' + 'pass. If bb==0, then no search is made for the best' + 'starting point, and the identity transformation is' + 'used as the starting point. [Default=5; min=0 max=11]') fine_blur = traits.Float( argstr='-fineblur %f', desc='Set the blurring radius to use in the fine resolution ' - 'pass to \'x\' mm. A small amount (1-2 mm?) of blurring at ' - 'the fine step may help with convergence, if there is ' - 'some problem, especially if the base volume is very noisy. ' - '[Default == 0 mm = no blurring at the final alignment pass]') + 'pass to \'x\' mm. A small amount (1-2 mm?) of blurring at ' + 'the fine step may help with convergence, if there is ' + 'some problem, especially if the base volume is very noisy. ' + '[Default == 0 mm = no blurring at the final alignment pass]') center_of_mass = Str( argstr='-cmass%s', desc='Use the center-of-mass calculation to bracket the shifts.') autoweight = Str( argstr='-autoweight%s', desc='Compute a weight function using the 3dAutomask ' - 'algorithm plus some blurring of the base image.') + 'algorithm plus some blurring of the base image.') automask = traits.Int( argstr='-automask+%d', desc='Compute a mask function, set a value for dilation or 0.') autobox = traits.Bool( argstr='-autobox', desc='Expand the -automask function to enclose a rectangular ' - 'box that holds the irregular mask.') + 'box that holds the irregular mask.') nomask = traits.Bool( argstr='-nomask', desc='Don\'t compute the autoweight/mask; if -weight is not ' - 'also used, then every voxel will be counted equally.') + 'also used, then every voxel will be counted equally.') weight_file = File( argstr='-weight %s', exists=True, - deprecated='1.0.0', new_name='weight', + deprecated='1.0.0', + new_name='weight', desc='Set the weighting for each voxel in the base dataset; ' - 'larger weights mean that voxel count more in the cost function. ' - 'Must be defined on the same grid as the base dataset') + 'larger weights mean that voxel count more in the cost function. ' + 'Must be defined on the same grid as the base dataset') weight = traits.Either( - File(exists=True), traits.Float(), + File(exists=True), + traits.Float(), argstr='-weight %s', desc='Set the weighting for each voxel in the base dataset; ' - 'larger weights mean that voxel count more in the cost function. ' - 'If an image file is given, the volume must be defined on the ' - 'same grid as the base dataset') + 'larger weights mean that voxel count more in the cost function. ' + 'If an image file is given, the volume must be defined on the ' + 'same grid as the base dataset') out_weight_file = traits.File( argstr='-wtprefix %s', desc='Write the weight volume to disk as a dataset', xor=['allcostx']) source_mask = File( - exists=True, - argstr='-source_mask %s', - desc='mask the input dataset') + exists=True, argstr='-source_mask %s', desc='mask the input dataset') source_automask = traits.Int( argstr='-source_automask+%d', desc='Automatically mask the source dataset with dilation or 0.') warp_type = traits.Enum( - 'shift_only', 'shift_rotate', 'shift_rotate_scale', 'affine_general', + 'shift_only', + 'shift_rotate', + 'shift_rotate_scale', + 'affine_general', argstr='-warp %s', desc='Set the warp type.') warpfreeze = traits.Bool( @@ -389,30 +390,26 @@ class AllineateInputSpec(AFNICommandInputSpec): replacebase = traits.Bool( argstr='-replacebase', desc='If the source has more than one volume, then after the first ' - 'volume is aligned to the base.') + 'volume is aligned to the base.') replacemeth = traits.Enum( *_cost_funcs, argstr='-replacemeth %s', desc='After first volume is aligned, switch method for later volumes. ' - 'For use with \'-replacebase\'.') + 'For use with \'-replacebase\'.') epi = traits.Bool( argstr='-EPI', desc='Treat the source dataset as being composed of warped ' - 'EPI slices, and the base as comprising anatomically ' - '\'true\' images. Only phase-encoding direction image ' - 'shearing and scaling will be allowed with this option.') + 'EPI slices, and the base as comprising anatomically ' + '\'true\' images. Only phase-encoding direction image ' + 'shearing and scaling will be allowed with this option.') maxrot = traits.Float( - argstr='-maxrot %f', - desc='Maximum allowed rotation in degrees.') + argstr='-maxrot %f', desc='Maximum allowed rotation in degrees.') maxshf = traits.Float( - argstr='-maxshf %f', - desc='Maximum allowed shift in mm.') + argstr='-maxshf %f', desc='Maximum allowed shift in mm.') maxscl = traits.Float( - argstr='-maxscl %f', - desc='Maximum allowed scaling factor.') + argstr='-maxscl %f', desc='Maximum allowed scaling factor.') maxshr = traits.Float( - argstr='-maxshr %f', - desc='Maximum allowed shearing factor.') + argstr='-maxshr %f', desc='Maximum allowed shearing factor.') master = File( exists=True, argstr='-master %s', @@ -422,9 +419,10 @@ class AllineateInputSpec(AFNICommandInputSpec): desc='Write the output dataset using isotropic grid spacing in mm.') # Non-linear experimental - _nwarp_types = ['bilinear', - 'cubic', 'quintic', 'heptic', 'nonic', - 'poly3', 'poly5', 'poly7', 'poly9'] # same non-hellenistic + _nwarp_types = [ + 'bilinear', 'cubic', 'quintic', 'heptic', 'nonic', 'poly3', 'poly5', + 'poly7', 'poly9' + ] # same non-hellenistic nwarp = traits.Enum( *_nwarp_types, argstr='-nwarp %s', @@ -439,11 +437,9 @@ class AllineateInputSpec(AFNICommandInputSpec): argstr='-nwarp_fixdep%s', desc='To fix non-linear warp dependency along directions.') verbose = traits.Bool( - argstr='-verb', - desc='Print out verbose progress reports.') + argstr='-verb', desc='Print out verbose progress reports.') quiet = traits.Bool( - argstr='-quiet', - desc="Don't print out verbose progress reports.") + argstr='-quiet', desc="Don't print out verbose progress reports.") class AllineateOutputSpec(TraitedSpec): @@ -451,7 +447,10 @@ class AllineateOutputSpec(TraitedSpec): out_matrix = File(exists=True, desc='matrix to align input file') out_param_file = File(exists=True, desc='warp parameters') out_weight_file = File(exists=True, desc='weight volume') - allcostx = File(desc='Compute and print ALL available cost functionals for the un-warped inputs') + allcostx = File( + desc= + 'Compute and print ALL available cost functionals for the un-warped inputs' + ) class Allineate(AFNICommand): @@ -499,27 +498,29 @@ def _list_outputs(self): outputs['out_file'] = op.abspath(self.inputs.out_file) if self.inputs.out_weight_file: - outputs['out_weight_file'] = op.abspath(self.inputs.out_weight_file) + outputs['out_weight_file'] = op.abspath( + self.inputs.out_weight_file) if self.inputs.out_matrix: path, base, ext = split_filename(self.inputs.out_matrix) if ext.lower() not in ['.1d', '.1D']: - outputs['out_matrix'] = self._gen_fname(self.inputs.out_matrix, - suffix='.aff12.1D') + outputs['out_matrix'] = self._gen_fname( + self.inputs.out_matrix, suffix='.aff12.1D') else: outputs['out_matrix'] = op.abspath(self.inputs.out_matrix) if self.inputs.out_param_file: path, base, ext = split_filename(self.inputs.out_param_file) if ext.lower() not in ['.1d', '.1D']: - outputs['out_param_file'] = self._gen_fname(self.inputs.out_param_file, - suffix='.param.1D') + outputs['out_param_file'] = self._gen_fname( + self.inputs.out_param_file, suffix='.param.1D') else: - outputs['out_param_file'] = op.abspath(self.inputs.out_param_file) + outputs['out_param_file'] = op.abspath( + self.inputs.out_param_file) if isdefined(self.inputs.allcostx): - outputs['allcostX'] = os.path.abspath(os.path.join(os.getcwd(), - self.inputs.allcostx)) + outputs['allcostX'] = os.path.abspath( + os.path.join(os.getcwd(), self.inputs.allcostx)) return outputs def _gen_filename(self, name): @@ -539,13 +540,8 @@ class AutoTcorrelateInputSpec(AFNICommandInputSpec): polort = traits.Int( desc='Remove polynomical trend of order m or -1 for no detrending', argstr='-polort %d') - eta2 = traits.Bool( - desc='eta^2 similarity', - argstr='-eta2') - mask = File( - exists=True, - desc='mask of voxels', - argstr='-mask %s') + eta2 = traits.Bool(desc='eta^2 similarity', argstr='-eta2') + mask = File(exists=True, desc='mask of voxels', argstr='-mask %s') mask_only_targets = traits.Bool( desc='use mask only on targets voxels', argstr='-mask_only_targets', @@ -616,23 +612,15 @@ class AutomaskInputSpec(AFNICommandInputSpec): name_source='in_file') clfrac = traits.Float( desc='sets the clip level fraction (must be 0.1-0.9). A small value ' - 'will tend to make the mask larger [default = 0.5].', + 'will tend to make the mask larger [default = 0.5].', argstr='-clfrac %s') - dilate = traits.Int( - desc='dilate the mask outwards', - argstr='-dilate %s') - erode = traits.Int( - desc='erode the mask inwards', - argstr='-erode %s') + dilate = traits.Int(desc='dilate the mask outwards', argstr='-dilate %s') + erode = traits.Int(desc='erode the mask inwards', argstr='-erode %s') class AutomaskOutputSpec(TraitedSpec): - out_file = File( - desc='mask file', - exists=True) - brain_file = File( - desc='brain file (skull stripped)', - exists=True) + out_file = File(desc='mask file', exists=True) + brain_file = File(desc='brain file (skull stripped)', exists=True) class Automask(AFNICommand): @@ -659,77 +647,79 @@ class Automask(AFNICommand): input_spec = AutomaskInputSpec output_spec = AutomaskOutputSpec + class AutoTLRCInputSpec(CommandLineInputSpec): - outputtype = traits.Enum('AFNI', list(Info.ftypes.keys()), - desc='AFNI output filetype') + outputtype = traits.Enum( + 'AFNI', list(Info.ftypes.keys()), desc='AFNI output filetype') in_file = File( desc='Original anatomical volume (+orig).' - 'The skull is removed by this script' - 'unless instructed otherwise (-no_ss).', + 'The skull is removed by this script' + 'unless instructed otherwise (-no_ss).', argstr='-input %s', mandatory=True, exists=True, copyfile=False) base = traits.Str( - desc = ' Reference anatomical volume' - ' Usually this volume is in some standard space like' - ' TLRC or MNI space and with afni dataset view of' - ' (+tlrc).' - ' Preferably, this reference volume should have had' - ' the skull removed but that is not mandatory.' - ' AFNI\'s distribution contains several templates.' - ' For a longer list, use "whereami -show_templates"' - 'TT_N27+tlrc --> Single subject, skull stripped volume.' - ' This volume is also known as ' - ' N27_SurfVol_NoSkull+tlrc elsewhere in ' - ' AFNI and SUMA land.' - ' (www.loni.ucla.edu, www.bic.mni.mcgill.ca)' - ' This template has a full set of FreeSurfer' - ' (surfer.nmr.mgh.harvard.edu)' - ' surface models that can be used in SUMA. ' - ' For details, see Talairach-related link:' - ' https://afni.nimh.nih.gov/afni/suma' - 'TT_icbm452+tlrc --> Average volume of 452 normal brains.' - ' Skull Stripped. (www.loni.ucla.edu)' - 'TT_avg152T1+tlrc --> Average volume of 152 normal brains.' - ' Skull Stripped.(www.bic.mni.mcgill.ca)' - 'TT_EPI+tlrc --> EPI template from spm2, masked as TT_avg152T1' - ' TT_avg152 and TT_EPI volume sources are from' - ' SPM\'s distribution. (www.fil.ion.ucl.ac.uk/spm/)' - 'If you do not specify a path for the template, the script' - 'will attempt to locate the template AFNI\'s binaries directory.' - 'NOTE: These datasets have been slightly modified from' - ' their original size to match the standard TLRC' - ' dimensions (Jean Talairach and Pierre Tournoux' - ' Co-Planar Stereotaxic Atlas of the Human Brain' - ' Thieme Medical Publishers, New York, 1988). ' - ' That was done for internal consistency in AFNI.' - ' You may use the original form of these' - ' volumes if you choose but your TLRC coordinates' - ' will not be consistent with AFNI\'s TLRC database' - ' (San Antonio Talairach Daemon database), for example.', - mandatory = True, + desc=' Reference anatomical volume' + ' Usually this volume is in some standard space like' + ' TLRC or MNI space and with afni dataset view of' + ' (+tlrc).' + ' Preferably, this reference volume should have had' + ' the skull removed but that is not mandatory.' + ' AFNI\'s distribution contains several templates.' + ' For a longer list, use "whereami -show_templates"' + 'TT_N27+tlrc --> Single subject, skull stripped volume.' + ' This volume is also known as ' + ' N27_SurfVol_NoSkull+tlrc elsewhere in ' + ' AFNI and SUMA land.' + ' (www.loni.ucla.edu, www.bic.mni.mcgill.ca)' + ' This template has a full set of FreeSurfer' + ' (surfer.nmr.mgh.harvard.edu)' + ' surface models that can be used in SUMA. ' + ' For details, see Talairach-related link:' + ' https://afni.nimh.nih.gov/afni/suma' + 'TT_icbm452+tlrc --> Average volume of 452 normal brains.' + ' Skull Stripped. (www.loni.ucla.edu)' + 'TT_avg152T1+tlrc --> Average volume of 152 normal brains.' + ' Skull Stripped.(www.bic.mni.mcgill.ca)' + 'TT_EPI+tlrc --> EPI template from spm2, masked as TT_avg152T1' + ' TT_avg152 and TT_EPI volume sources are from' + ' SPM\'s distribution. (www.fil.ion.ucl.ac.uk/spm/)' + 'If you do not specify a path for the template, the script' + 'will attempt to locate the template AFNI\'s binaries directory.' + 'NOTE: These datasets have been slightly modified from' + ' their original size to match the standard TLRC' + ' dimensions (Jean Talairach and Pierre Tournoux' + ' Co-Planar Stereotaxic Atlas of the Human Brain' + ' Thieme Medical Publishers, New York, 1988). ' + ' That was done for internal consistency in AFNI.' + ' You may use the original form of these' + ' volumes if you choose but your TLRC coordinates' + ' will not be consistent with AFNI\'s TLRC database' + ' (San Antonio Talairach Daemon database), for example.', + mandatory=True, argstr='-base %s') no_ss = traits.Bool( desc='Do not strip skull of input data set' - '(because skull has already been removed' - 'or because template still has the skull)' - 'NOTE: The -no_ss option is not all that optional.' - ' Here is a table of when you should and should not use -no_ss' - ' Template Template' - ' WITH skull WITHOUT skull' - ' Dset.' - ' WITH skull -no_ss xxx ' - ' ' - ' WITHOUT skull No Cigar -no_ss' - ' ' - ' Template means: Your template of choice' - ' Dset. means: Your anatomical dataset' - ' -no_ss means: Skull stripping should not be attempted on Dset' - ' xxx means: Don\'t put anything, the script will strip Dset' - ' No Cigar means: Don\'t try that combination, it makes no sense.', + '(because skull has already been removed' + 'or because template still has the skull)' + 'NOTE: The -no_ss option is not all that optional.' + ' Here is a table of when you should and should not use -no_ss' + ' Template Template' + ' WITH skull WITHOUT skull' + ' Dset.' + ' WITH skull -no_ss xxx ' + ' ' + ' WITHOUT skull No Cigar -no_ss' + ' ' + ' Template means: Your template of choice' + ' Dset. means: Your anatomical dataset' + ' -no_ss means: Skull stripping should not be attempted on Dset' + ' xxx means: Don\'t put anything, the script will strip Dset' + ' No Cigar means: Don\'t try that combination, it makes no sense.', argstr='-no_ss') + class AutoTLRC(AFNICommand): """A minmal wrapper for the AutoTLRC script The only option currently supported is no_ss. @@ -751,12 +741,15 @@ class AutoTLRC(AFNICommand): _cmd = '@auto_tlrc' input_spec = AutoTLRCInputSpec output_spec = AFNICommandOutputSpec + def _list_outputs(self): outputs = self.output_spec().get() ext = '.HEAD' - outputs['out_file'] = os.path.abspath(self._gen_fname(self.inputs.in_file, suffix='+tlrc')+ext) + outputs['out_file'] = os.path.abspath( + self._gen_fname(self.inputs.in_file, suffix='+tlrc') + ext) return outputs + class BandpassInputSpec(AFNICommandInputSpec): in_file = File( desc='input file to 3dBandpass', @@ -773,70 +766,58 @@ class BandpassInputSpec(AFNICommandInputSpec): name_source='in_file', genfile=True) lowpass = traits.Float( - desc='lowpass', - argstr='%f', - position=-2, - mandatory=True) + desc='lowpass', argstr='%f', position=-2, mandatory=True) highpass = traits.Float( - desc='highpass', - argstr='%f', - position=-3, - mandatory=True) - mask = File( - desc='mask file', - position=2, - argstr='-mask %s', - exists=True) + desc='highpass', argstr='%f', position=-3, mandatory=True) + mask = File(desc='mask file', position=2, argstr='-mask %s', exists=True) despike = traits.Bool( argstr='-despike', desc='Despike each time series before other processing. Hopefully, ' - 'you don\'t actually need to do this, which is why it is ' - 'optional.') + 'you don\'t actually need to do this, which is why it is ' + 'optional.') orthogonalize_file = InputMultiPath( File(exists=True), argstr='-ort %s', desc='Also orthogonalize input to columns in f.1D. Multiple \'-ort\' ' - 'options are allowed.') + 'options are allowed.') orthogonalize_dset = File( exists=True, argstr='-dsort %s', desc='Orthogonalize each voxel to the corresponding voxel time series ' - 'in dataset \'fset\', which must have the same spatial and ' - 'temporal grid structure as the main input dataset. At present, ' - 'only one \'-dsort\' option is allowed.') + 'in dataset \'fset\', which must have the same spatial and ' + 'temporal grid structure as the main input dataset. At present, ' + 'only one \'-dsort\' option is allowed.') no_detrend = traits.Bool( argstr='-nodetrend', desc='Skip the quadratic detrending of the input that occurs before ' - 'the FFT-based bandpassing. You would only want to do this if ' - 'the dataset had been detrended already in some other program.') + 'the FFT-based bandpassing. You would only want to do this if ' + 'the dataset had been detrended already in some other program.') tr = traits.Float( argstr='-dt %f', desc='Set time step (TR) in sec [default=from dataset header].') nfft = traits.Int( - argstr='-nfft %d', - desc='Set the FFT length [must be a legal value].') + argstr='-nfft %d', desc='Set the FFT length [must be a legal value].') normalize = traits.Bool( argstr='-norm', desc='Make all output time series have L2 norm = 1 (i.e., sum of ' - 'squares = 1).') + 'squares = 1).') automask = traits.Bool( - argstr='-automask', - desc='Create a mask from the input dataset.') + argstr='-automask', desc='Create a mask from the input dataset.') blur = traits.Float( argstr='-blur %f', desc='Blur (inside the mask only) with a filter width (FWHM) of ' - '\'fff\' millimeters.') + '\'fff\' millimeters.') localPV = traits.Float( argstr='-localPV %f', desc='Replace each vector by the local Principal Vector (AKA first ' - 'singular vector) from a neighborhood of radius \'rrr\' ' - 'millimeters. Note that the PV time series is L2 normalized. ' - 'This option is mostly for Bob Cox to have fun with.') + 'singular vector) from a neighborhood of radius \'rrr\' ' + 'millimeters. Note that the PV time series is L2 normalized. ' + 'This option is mostly for Bob Cox to have fun with.') notrans = traits.Bool( argstr='-notrans', desc='Don\'t check for initial positive transients in the data. ' - 'The test is a little slow, so skipping it is OK, if you KNOW ' - 'the data time series are transient-free.') + 'The test is a little slow, so skipping it is OK, if you KNOW ' + 'the data time series are transient-free.') class Bandpass(AFNICommand): @@ -882,31 +863,25 @@ class BlurInMaskInputSpec(AFNICommandInputSpec): position=-1) mask = File( desc='Mask dataset, if desired. Blurring will occur only within the ' - 'mask. Voxels NOT in the mask will be set to zero in the output.', + 'mask. Voxels NOT in the mask will be set to zero in the output.', argstr='-mask %s') multimask = File( desc='Multi-mask dataset -- each distinct nonzero value in dataset ' - 'will be treated as a separate mask for blurring purposes.', + 'will be treated as a separate mask for blurring purposes.', argstr='-Mmask %s') automask = traits.Bool( - desc='Create an automask from the input dataset.', - argstr='-automask') + desc='Create an automask from the input dataset.', argstr='-automask') fwhm = traits.Float( - desc='fwhm kernel size', - argstr='-FWHM %f', - mandatory=True) + desc='fwhm kernel size', argstr='-FWHM %f', mandatory=True) preserve = traits.Bool( desc='Normally, voxels not in the mask will be set to zero in the ' - 'output. If you want the original values in the dataset to be ' - 'preserved in the output, use this option.', + 'output. If you want the original values in the dataset to be ' + 'preserved in the output, use this option.', argstr='-preserve') float_out = traits.Bool( desc='Save dataset as floats, no matter what the input data type is.', argstr='-float') - options = Str( - desc='options', - argstr='%s', - position=2) + options = Str(desc='options', argstr='%s', position=2) class BlurInMask(AFNICommand): @@ -941,8 +916,7 @@ class BlurToFWHMInputSpec(AFNICommandInputSpec): mandatory=True, exists=True) automask = traits.Bool( - desc='Create an automask from the input dataset.', - argstr='-automask') + desc='Create an automask from the input dataset.', argstr='-automask') fwhm = traits.Float( desc='Blur until the 3D FWHM reaches this value (in mm)', argstr='-FWHM %f') @@ -955,7 +929,7 @@ class BlurToFWHMInputSpec(AFNICommandInputSpec): exists=True) mask = File( desc='Mask dataset, if desired. Voxels NOT in mask will be set to zero ' - 'in output.', + 'in output.', argstr='-blurmaster %s', exists=True) @@ -1002,7 +976,7 @@ class ClipLevelInputSpec(CommandLineInputSpec): xor=('grad')) grad = traits.File( desc='Also compute a \'gradual\' clip level as a function of voxel ' - 'position, and output that to a dataset.', + 'position, and output that to a dataset.', argstr='-grad %s', position=3, xor=('doall')) @@ -1075,8 +1049,7 @@ class DegreeCentralityInputSpec(CentralityInputSpec): exists=True, copyfile=False) sparsity = traits.Float( - desc='only take the top percent of connections', - argstr='-sparsity %f') + desc='only take the top percent of connections', argstr='-sparsity %f') oned_file = Str( desc='output filepath to text dump of correlation matrix', argstr='-out1D %s') @@ -1088,8 +1061,8 @@ class DegreeCentralityOutputSpec(AFNICommandOutputSpec): oned_file = File( desc='The text output of the similarity matrix computed after ' - 'thresholding with one-dimensional and ijk voxel indices, ' - 'correlations, image extents, and affine matrix.') + 'thresholding with one-dimensional and ijk voxel indices, ' + 'correlations, image extents, and affine matrix.') class DegreeCentrality(AFNICommand): @@ -1222,36 +1195,35 @@ class ECMInputSpec(CentralityInputSpec): exists=True, copyfile=False) sparsity = traits.Float( - desc='only take the top percent of connections', - argstr='-sparsity %f') + desc='only take the top percent of connections', argstr='-sparsity %f') full = traits.Bool( desc='Full power method; enables thresholding; automatically selected ' - 'if -thresh or -sparsity are set', + 'if -thresh or -sparsity are set', argstr='-full') fecm = traits.Bool( desc='Fast centrality method; substantial speed increase but cannot ' - 'accomodate thresholding; automatically selected if -thresh or ' - '-sparsity are not set', + 'accomodate thresholding; automatically selected if -thresh or ' + '-sparsity are not set', argstr='-fecm') shift = traits.Float( desc='shift correlation coefficients in similarity matrix to enforce ' - 'non-negativity, s >= 0.0; default = 0.0 for -full, 1.0 for -fecm', + 'non-negativity, s >= 0.0; default = 0.0 for -full, 1.0 for -fecm', argstr='-shift %f') scale = traits.Float( desc='scale correlation coefficients in similarity matrix to after ' - 'shifting, x >= 0.0; default = 1.0 for -full, 0.5 for -fecm', + 'shifting, x >= 0.0; default = 1.0 for -full, 0.5 for -fecm', argstr='-scale %f') eps = traits.Float( desc='sets the stopping criterion for the power iteration; ' - 'l2|v_old - v_new| < eps*|v_old|; default = 0.001', + 'l2|v_old - v_new| < eps*|v_old|; default = 0.001', argstr='-eps %f') max_iter = traits.Int( desc='sets the maximum number of iterations to use in the power ' - 'iteration; default = 1000', + 'iteration; default = 1000', argstr='-max_iter %d') memory = traits.Float( desc='Limit memory consumption on system by setting the amount of GB ' - 'to limit the algorithm to; default = 2GB', + 'to limit the algorithm to; default = 2GB', argstr='-memory %f') @@ -1353,16 +1325,12 @@ class FourierInputSpec(AFNICommandInputSpec): argstr='-prefix %s', name_source='in_file') lowpass = traits.Float( - desc='lowpass', - argstr='-lowpass %f', - mandatory=True) + desc='lowpass', argstr='-lowpass %f', mandatory=True) highpass = traits.Float( - desc='highpass', - argstr='-highpass %f', - mandatory=True) + desc='highpass', argstr='-highpass %f', mandatory=True) retrend = traits.Bool( desc='Any mean and linear trend are removed before filtering. This ' - 'will restore the trend after filtering.', + 'will restore the trend after filtering.', argstr='-retrend') @@ -1420,21 +1388,11 @@ class HistInputSpec(CommandLineInputSpec): name_source='in_file', position=-1) mask = File( - desc='matrix to align input file', - argstr='-mask %s', - exists=True) - nbin = traits.Int( - desc='number of bins', - argstr='-nbin %d') - max_value = traits.Float( - argstr='-max %f', - desc='maximum intensity value') - min_value = traits.Float( - argstr='-min %f', - desc='minimum intensity value') - bin_width = traits.Float( - argstr='-binwidth %f', - desc='bin width') + desc='matrix to align input file', argstr='-mask %s', exists=True) + nbin = traits.Int(desc='number of bins', argstr='-nbin %d') + max_value = traits.Float(argstr='-max %f', desc='maximum intensity value') + min_value = traits.Float(argstr='-min %f', desc='minimum intensity value') + bin_width = traits.Float(argstr='-binwidth %f', desc='bin width') class HistOutputSpec(TraitedSpec): @@ -1482,7 +1440,6 @@ def _parse_inputs(self, skip=None): skip += ['out_show'] return super(Hist, self)._parse_inputs(skip=skip) - def _list_outputs(self): outputs = super(Hist, self)._list_outputs() outputs['out_file'] += '.niml.hist' @@ -1495,12 +1452,13 @@ class LFCDInputSpec(CentralityInputSpec): """LFCD inputspec """ - in_file = File(desc='input file to 3dLFCD', - argstr='%s', - position=-1, - mandatory=True, - exists=True, - copyfile=False) + in_file = File( + desc='input file to 3dLFCD', + argstr='%s', + position=-1, + mandatory=True, + exists=True, + copyfile=False) class LFCD(AFNICommand): @@ -1550,9 +1508,7 @@ class MaskaveInputSpec(AFNICommandInputSpec): position=1, exists=True) quiet = traits.Bool( - desc='matrix to align input file', - argstr='-quiet', - position=2) + desc='matrix to align input file', argstr='-quiet', position=2) class Maskave(AFNICommand): @@ -1594,37 +1550,22 @@ class MeansInputSpec(AFNICommandInputSpec): position=-1, exists=True) datum = traits.Str( - desc='Sets the data type of the output dataset', - argstr='-datum %s') + desc='Sets the data type of the output dataset', argstr='-datum %s') out_file = File( name_template='%s_mean', desc='output image file name', argstr='-prefix %s', name_source='in_file_a') - scale = Str( - desc='scaling of output', - argstr='-%sscale') - non_zero = traits.Bool( - desc='use only non-zero values', - argstr='-non_zero') - std_dev = traits.Bool( - desc='calculate std dev', - argstr='-stdev') - sqr = traits.Bool( - desc='mean square instead of value', - argstr='-sqr') - summ = traits.Bool( - desc='take sum, (not average)', - argstr='-sum') + scale = Str(desc='scaling of output', argstr='-%sscale') + non_zero = traits.Bool(desc='use only non-zero values', argstr='-non_zero') + std_dev = traits.Bool(desc='calculate std dev', argstr='-stdev') + sqr = traits.Bool(desc='mean square instead of value', argstr='-sqr') + summ = traits.Bool(desc='take sum, (not average)', argstr='-sum') count = traits.Bool( - desc='compute count of non-zero voxels', - argstr='-count') + desc='compute count of non-zero voxels', argstr='-count') mask_inter = traits.Bool( - desc='create intersection mask', - argstr='-mask_inter') - mask_union = traits.Bool( - desc='create union mask', - argstr='-mask_union') + desc='create intersection mask', argstr='-mask_inter') + mask_union = traits.Bool(desc='create union mask', argstr='-mask_union') class Means(AFNICommand): @@ -1696,17 +1637,15 @@ class OutlierCountInputSpec(CommandLineInputSpec): usedefault=True, argstr='-fraction', desc='write out the fraction of masked voxels which are outliers at ' - 'each timepoint') + 'each timepoint') interval = traits.Bool( False, usedefault=True, argstr='-range', desc='write out the median + 3.5 MAD of outlier count with each ' - 'timepoint') + 'timepoint') save_outliers = traits.Bool( - False, - usedefault=True, - desc='enables out_file option') + False, usedefault=True, desc='enables out_file option') outliers_file = File( name_template='%s_outliers', argstr='-save %s', @@ -1730,8 +1669,7 @@ class OutlierCountInputSpec(CommandLineInputSpec): class OutlierCountOutputSpec(TraitedSpec): - out_outliers = File(exists=True, - desc='output image file name') + out_outliers = File(exists=True, desc='output image file name') out_file = File(desc='capture standard output') @@ -1805,14 +1743,14 @@ class QualityIndexInputSpec(CommandLineInputSpec): usedefault=True, argstr='-spearman', desc='Quality index is 1 minus the Spearman (rank) correlation ' - 'coefficient of each sub-brick with the median sub-brick. ' - '(default).') + 'coefficient of each sub-brick with the median sub-brick. ' + '(default).') quadrant = traits.Bool( False, usedefault=True, argstr='-quadrant', desc='Similar to -spearman, but using 1 minus the quadrant correlation ' - 'coefficient as the quality index.') + 'coefficient as the quality index.') autoclip = traits.Bool( False, usedefault=True, @@ -1825,15 +1763,13 @@ class QualityIndexInputSpec(CommandLineInputSpec): argstr='-automask', xor=['mask'], desc='clip off small voxels') - clip = traits.Float( - argstr='-clip %f', - desc='clip off values below') + clip = traits.Float(argstr='-clip %f', desc='clip off values below') interval = traits.Bool( False, usedefault=True, argstr='-range', desc='write out the median + 3.5 MAD of outlier count with each ' - 'timepoint') + 'timepoint') out_file = File( name_template='%s_tqual', name_source=['in_file'], @@ -1878,30 +1814,23 @@ class ROIStatsInputSpec(CommandLineInputSpec): position=-1, mandatory=True, exists=True) - mask = File( - desc='input mask', - argstr='-mask %s', - position=3, - exists=True) + mask = File(desc='input mask', argstr='-mask %s', position=3, exists=True) mask_f2short = traits.Bool( desc='Tells the program to convert a float mask to short integers, ' - 'by simple rounding.', + 'by simple rounding.', argstr='-mask_f2short', position=2) - quiet = traits.Bool( - desc='execute quietly', - argstr='-quiet', - position=1) - terminal_output = traits.Enum('allatonce', deprecated='1.0.0', + quiet = traits.Bool(desc='execute quietly', argstr='-quiet', position=1) + terminal_output = traits.Enum( + 'allatonce', + deprecated='1.0.0', desc='Control terminal output:`allatonce` - waits till command is ' - 'finished to display output', + 'finished to display output', nohash=True) class ROIStatsOutputSpec(TraitedSpec): - stats = File( - desc='output tab separated values file', - exists=True) + stats = File(desc='output tab separated values file', exists=True) class ROIStats(AFNICommandBase): @@ -1932,7 +1861,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): outputs = self._outputs() output_filename = 'roi_stats.csv' with open(output_filename, 'w') as f: - f.write(runtime.stdout) + f.write(runtime.stdout) outputs.stats = os.path.abspath(output_filename) return outputs @@ -1964,8 +1893,8 @@ class RetroicorInputSpec(AFNICommandInputSpec): exists=True) threshold = traits.Int( desc='Threshold for detection of R-wave peaks in input (Make sure it ' - 'is above the background noise level, Try 3/4 or 4/5 times range ' - 'plus minimum)', + 'is above the background noise level, Try 3/4 or 4/5 times range ' + 'plus minimum)', argstr='-threshold %d', position=-4) order = traits.Int( @@ -2025,7 +1954,8 @@ class Retroicor(AFNICommand): def _format_arg(self, name, trait_spec, value): if name == 'in_file': - if not isdefined(self.inputs.card) and not isdefined(self.inputs.resp): + if not isdefined(self.inputs.card) and not isdefined( + self.inputs.resp): return None return super(Retroicor, self)._format_arg(name, trait_spec, value) @@ -2042,43 +1972,43 @@ class SegInputSpec(CommandLineInputSpec): traits.Enum('AUTO'), File(exists=True), desc='only non-zero voxels in mask are analyzed. mask can either be a ' - 'dataset or the string "AUTO" which would use AFNI\'s automask ' - 'function to create the mask.', + 'dataset or the string "AUTO" which would use AFNI\'s automask ' + 'function to create the mask.', argstr='-mask %s', position=-2, mandatory=True) blur_meth = traits.Enum( - 'BFT', 'BIM', + 'BFT', + 'BIM', argstr='-blur_meth %s', desc='set the blurring method for bias field estimation') bias_fwhm = traits.Float( desc='The amount of blurring used when estimating the field bias with ' - 'the Wells method', + 'the Wells method', argstr='-bias_fwhm %f') classes = Str( desc='CLASS_STRING is a semicolon delimited string of class labels', argstr='-classes %s') bmrf = traits.Float( desc='Weighting factor controlling spatial homogeneity of the ' - 'classifications', + 'classifications', argstr='-bmrf %f') bias_classes = Str( desc='A semicolon delimited string of classes that contribute to the ' - 'estimation of the bias field', + 'estimation of the bias field', argstr='-bias_classes %s') prefix = Str( desc='the prefix for the output folder containing all output volumes', argstr='-prefix %s') mixfrac = Str( desc='MIXFRAC sets up the volume-wide (within mask) tissue fractions ' - 'while initializing the segmentation (see IGNORE for exception)', + 'while initializing the segmentation (see IGNORE for exception)', argstr='-mixfrac %s') mixfloor = traits.Float( desc='Set the minimum value for any class\'s mixing fraction', argstr='-mixfloor %f') main_N = traits.Int( - desc='Number of iterations to perform.', - argstr='-main_N %d') + desc='Number of iterations to perform.', argstr='-main_N %d') class Seg(AFNICommandBase): @@ -2113,7 +2043,8 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): outputs = self._outputs() if isdefined(self.inputs.prefix): - outfile = os.path.join(os.getcwd(), self.inputs.prefix, 'Classes+*.BRIK') + outfile = os.path.join(os.getcwd(), self.inputs.prefix, + 'Classes+*.BRIK') else: outfile = os.path.join(os.getcwd(), 'Segsy', 'Classes+*.BRIK') @@ -2216,8 +2147,7 @@ class TCorr1DInputSpec(AFNICommandInputSpec): class TCorr1DOutputSpec(TraitedSpec): - out_file = File(desc='output file containing correlations', - exists=True) + out_file = File(desc='output file containing correlations', exists=True) class TCorr1D(AFNICommand): @@ -2244,56 +2174,26 @@ class TCorr1D(AFNICommand): class TCorrMapInputSpec(AFNICommandInputSpec): in_file = File( - exists=True, - argstr='-input %s', - mandatory=True, - copyfile=False) - seeds = File( - exists=True, - argstr='-seed %s', - xor=('seeds_width')) - mask = File( - exists=True, - argstr='-mask %s') - automask = traits.Bool( - argstr='-automask') - polort = traits.Int( - argstr='-polort %d') + exists=True, argstr='-input %s', mandatory=True, copyfile=False) + seeds = File(exists=True, argstr='-seed %s', xor=('seeds_width')) + mask = File(exists=True, argstr='-mask %s') + automask = traits.Bool(argstr='-automask') + polort = traits.Int(argstr='-polort %d') bandpass = traits.Tuple( - (traits.Float(), traits.Float()), - argstr='-bpass %f %f') - regress_out_timeseries = traits.File( - exists=True, - argstr='-ort %s') - blur_fwhm = traits.Float( - argstr='-Gblur %f') - seeds_width = traits.Float( - argstr='-Mseed %f', - xor=('seeds')) + (traits.Float(), traits.Float()), argstr='-bpass %f %f') + regress_out_timeseries = traits.File(exists=True, argstr='-ort %s') + blur_fwhm = traits.Float(argstr='-Gblur %f') + seeds_width = traits.Float(argstr='-Mseed %f', xor=('seeds')) # outputs - mean_file = File( - argstr='-Mean %s', - suffix='_mean', - name_source='in_file') - zmean = File( - argstr='-Zmean %s', - suffix='_zmean', - name_source='in_file') - qmean = File( - argstr='-Qmean %s', - suffix='_qmean', - name_source='in_file') - pmean = File( - argstr='-Pmean %s', - suffix='_pmean', - name_source='in_file') + mean_file = File(argstr='-Mean %s', suffix='_mean', name_source='in_file') + zmean = File(argstr='-Zmean %s', suffix='_zmean', name_source='in_file') + qmean = File(argstr='-Qmean %s', suffix='_qmean', name_source='in_file') + pmean = File(argstr='-Pmean %s', suffix='_pmean', name_source='in_file') - _thresh_opts = ('absolute_threshold', - 'var_absolute_threshold', + _thresh_opts = ('absolute_threshold', 'var_absolute_threshold', 'var_absolute_threshold_normalize') - thresholds = traits.List( - traits.Int()) + thresholds = traits.List(traits.Int()) absolute_threshold = File( argstr='-Thresh %f %s', suffix='_thresh', @@ -2310,12 +2210,9 @@ class TCorrMapInputSpec(AFNICommandInputSpec): name_source='in_file', xor=_thresh_opts) - correlation_maps = File( - argstr='-CorrMap %s', - name_source='in_file') + correlation_maps = File(argstr='-CorrMap %s', name_source='in_file') correlation_maps_masked = File( - argstr='-CorrMask %s', - name_source='in_file') + argstr='-CorrMask %s', name_source='in_file') _expr_opts = ('average_expr', 'average_expr_nonzero', 'sum_expr') expr = Str() @@ -2336,9 +2233,7 @@ class TCorrMapInputSpec(AFNICommandInputSpec): xor=_expr_opts) histogram_bin_numbers = traits.Int() histogram = File( - name_source='in_file', - argstr='-Hist %d %s', - suffix='_hist') + name_source='in_file', argstr='-Hist %d %s', suffix='_hist') class TCorrMapOutputSpec(TraitedSpec): @@ -2420,8 +2315,7 @@ class TCorrelateInputSpec(AFNICommandInputSpec): desc='Correlation is the normal Pearson correlation coefficient', argstr='-pearson') polort = traits.Int( - desc='Remove polynomical trend of order m', - argstr='-polort %d') + desc='Remove polynomical trend of order m', argstr='-polort %d') class TCorrelate(AFNICommand): @@ -2466,14 +2360,13 @@ class TNormInputSpec(AFNICommandInputSpec): argstr='-prefix %s', name_source='in_file') norm2 = traits.Bool( - desc='L2 normalize (sum of squares = 1) [DEFAULT]', - argstr='-norm2') + desc='L2 normalize (sum of squares = 1) [DEFAULT]', argstr='-norm2') normR = traits.Bool( - desc='normalize so sum of squares = number of time points * e.g., so RMS = 1.', + desc= + 'normalize so sum of squares = number of time points * e.g., so RMS = 1.', argstr='-normR') norm1 = traits.Bool( - desc='L1 normalize (sum of absolute values = 1)', - argstr='-norm1') + desc='L1 normalize (sum of absolute values = 1)', argstr='-norm1') normx = traits.Bool( desc='Scale so max absolute value = 1 (L_infinity norm)', argstr='-normx') @@ -2528,7 +2421,7 @@ class TShiftInputSpec(AFNICommandInputSpec): name_source='in_file') tr = Str( desc='manually set the TR. You can attach suffix "s" for seconds ' - 'or "ms" for milliseconds.', + 'or "ms" for milliseconds.', argstr='-TR %s') tzero = traits.Float( desc='align each slice to given time offset', @@ -2539,12 +2432,11 @@ class TShiftInputSpec(AFNICommandInputSpec): argstr='-slice %s', xor=['tzero']) ignore = traits.Int( - desc='ignore the first set of points specified', - argstr='-ignore %s') + desc='ignore the first set of points specified', argstr='-ignore %s') interp = traits.Enum( ('Fourier', 'linear', 'cubic', 'quintic', 'heptic'), desc='different interpolation methods (see 3dTShift for details) ' - 'default = Fourier', + 'default = Fourier', argstr='-%s') tpattern = Str( desc='use specified slice time pattern rather than one in header', @@ -2554,7 +2446,7 @@ class TShiftInputSpec(AFNICommandInputSpec): argstr='-rlt') rltplus = traits.Bool( desc='Before shifting, remove the mean and linear trend and later put ' - 'back the mean', + 'back the mean', argstr='-rlt+') @@ -2619,14 +2511,11 @@ class VolregInputSpec(AFNICommandInputSpec): name_source='in_file', keep_extension=True) verbose = traits.Bool( - desc='more detailed description of the process', - argstr='-verbose') + desc='more detailed description of the process', argstr='-verbose') timeshift = traits.Bool( - desc='time shift to mean slice time offset', - argstr='-tshift 0') + desc='time shift to mean slice time offset', argstr='-tshift 0') copyorigin = traits.Bool( - desc='copy base file origin coords to output', - argstr='-twodup') + desc='copy base file origin coords to output', argstr='-twodup') oned_matrix_save = File( name_template='%s.aff12.1D', desc='Save the matrix transformation', @@ -2634,24 +2523,17 @@ class VolregInputSpec(AFNICommandInputSpec): keep_extension=True, name_source='in_file') interp = traits.Enum( - ('Fourier', 'cubic', 'heptic', 'quintic','linear'), + ('Fourier', 'cubic', 'heptic', 'quintic', 'linear'), desc='spatial interpolation methods [default = heptic]', argstr='-%s') class VolregOutputSpec(TraitedSpec): - out_file = File( - desc='registered file', - exists=True) - md1d_file = File( - desc='max displacement info file', - exists=True) - oned_file = File( - desc='movement parameters info file', - exists=True) + out_file = File(desc='registered file', exists=True) + md1d_file = File(desc='max displacement info file', exists=True) + oned_file = File(desc='movement parameters info file', exists=True) oned_matrix_save = File( - desc='matrix transformation from base to input', - exists=True) + desc='matrix transformation from base to input', exists=True) class Volreg(AFNICommand): @@ -2708,23 +2590,20 @@ class WarpInputSpec(AFNICommandInputSpec): argstr='-prefix %s', name_source='in_file') tta2mni = traits.Bool( - desc='transform dataset from Talairach to MNI152', - argstr='-tta2mni') + desc='transform dataset from Talairach to MNI152', argstr='-tta2mni') mni2tta = traits.Bool( - desc='transform dataset from MNI152 to Talaraich', - argstr='-mni2tta') + desc='transform dataset from MNI152 to Talaraich', argstr='-mni2tta') matparent = File( desc='apply transformation from 3dWarpDrive', argstr='-matparent %s', exists=True) oblique_parent = File( desc='Read in the oblique transformation matrix from an oblique ' - 'dataset and make cardinal dataset oblique to match', + 'dataset and make cardinal dataset oblique to match', argstr='-oblique_parent %s', exists=True) deoblique = traits.Bool( - desc='transform dataset from oblique to cardinal', - argstr='-deoblique') + desc='transform dataset from oblique to cardinal', argstr='-deoblique') interp = traits.Enum( ('linear', 'cubic', 'NN', 'quintic'), desc='spatial interpolation methods [default = linear]', @@ -2734,14 +2613,12 @@ class WarpInputSpec(AFNICommandInputSpec): argstr='-gridset %s', exists=True) newgrid = traits.Float( - desc='specify grid of this size (mm)', - argstr='-newgrid %f') + desc='specify grid of this size (mm)', argstr='-newgrid %f') zpad = traits.Int( desc='pad input dataset with N planes of zero on all sides.', argstr='-zpad %d') verbose = traits.Bool( - desc='Print out some information along the way.', - argstr='-verb') + desc='Print out some information along the way.', argstr='-verb') class Warp(AFNICommand): @@ -2778,13 +2655,15 @@ class Warp(AFNICommand): class QwarpPlusMinusInputSpec(CommandLineInputSpec): source_file = File( - desc='Source image (opposite phase encoding direction than base image).', + desc= + 'Source image (opposite phase encoding direction than base image).', argstr='-source %s', mandatory=True, exists=True, copyfile=False) base_file = File( - desc='Base image (opposite phase encoding direction than source image).', + desc= + 'Base image (opposite phase encoding direction than source image).', argstr='-base %s', mandatory=True, exists=True, @@ -2792,51 +2671,47 @@ class QwarpPlusMinusInputSpec(CommandLineInputSpec): pblur = traits.List( traits.Float(), desc='The fraction of the patch size that' - 'is used for the progressive blur by providing a ' - 'value between 0 and 0.25. If you provide TWO ' - 'values, the first fraction is used for ' - 'progressively blurring the base image and the ' - 'second for the source image.', + 'is used for the progressive blur by providing a ' + 'value between 0 and 0.25. If you provide TWO ' + 'values, the first fraction is used for ' + 'progressively blurring the base image and the ' + 'second for the source image.', argstr='-pblur %s', minlen=1, maxlen=2) blur = traits.List( traits.Float(), desc="Gaussian blur the input images by (FWHM) voxels " - "before doing the alignment (the output dataset " - "will not be blurred). The default is 2.345 (for " - "no good reason). Optionally, you can provide 2 " - "values, and then the first one is applied to the " - "base volume, the second to the source volume. A " - "negative blur radius means to use 3D median " - "filtering, rather than Gaussian blurring. This " - "type of filtering will better preserve edges, " - "which can be important in alignment.", + "before doing the alignment (the output dataset " + "will not be blurred). The default is 2.345 (for " + "no good reason). Optionally, you can provide 2 " + "values, and then the first one is applied to the " + "base volume, the second to the source volume. A " + "negative blur radius means to use 3D median " + "filtering, rather than Gaussian blurring. This " + "type of filtering will better preserve edges, " + "which can be important in alignment.", argstr='-blur %s', minlen=1, maxlen=2) noweight = traits.Bool( desc='If you want a binary weight (the old default), use this option.' - 'That is, each voxel in the base volume automask will be' - 'weighted the same in the computation of the cost functional.', + 'That is, each voxel in the base volume automask will be' + 'weighted the same in the computation of the cost functional.', argstr='-noweight') minpatch = traits.Int( desc="Set the minimum patch size for warp searching to 'mm' voxels.", argstr='-minpatch %d') nopadWARP = traits.Bool( desc='If for some reason you require the warp volume to' - 'match the base volume, then use this option to have the output' - 'WARP dataset(s) truncated.', + 'match the base volume, then use this option to have the output' + 'WARP dataset(s) truncated.', argstr='-nopadWARP') class QwarpPlusMinusOutputSpec(TraitedSpec): - warped_source = File( - desc='Undistorted source file.', - exists=True) - warped_base = File( - desc='Undistorted base file.', - exists=True) + warped_source = File(desc='Undistorted source file.', exists=True) + warped_base = File(desc='Undistorted base file.', exists=True) source_warp = File( desc="Field suceptibility correction warp (in 'mm') for source image.", exists=True) @@ -2881,186 +2756,185 @@ def _list_outputs(self): class QwarpInputSpec(AFNICommandInputSpec): in_file = File( - desc='Source image (opposite phase encoding direction than base image).', + desc= + 'Source image (opposite phase encoding direction than base image).', argstr='-source %s', mandatory=True, exists=True, copyfile=False) base_file = File( - desc='Base image (opposite phase encoding direction than source image).', + desc= + 'Base image (opposite phase encoding direction than source image).', argstr='-base %s', mandatory=True, exists=True, copyfile=False) - out_file = File(argstr='-prefix %s', - name_template='%s_QW', - name_source=['in_file'], - genfile=True, - desc='out_file ppp' - 'Sets the prefix for the output datasets.' - '* The source dataset is warped to match the base' - 'and gets prefix \'ppp\'. (Except if \'-plusminus\' is used.)' - '* The final interpolation to this output dataset is' - 'done using the \'wsinc5\' method. See the output of' - ' 3dAllineate -HELP' - '(in the "Modifying \'-final wsinc5\'" section) for' - 'the lengthy technical details.' - '* The 3D warp used is saved in a dataset with' - 'prefix \'ppp_WARP\' -- this dataset can be used' - 'with 3dNwarpApply and 3dNwarpCat, for example.' - '* To be clear, this is the warp from source dataset' - ' coordinates to base dataset coordinates, where the' - ' values at each base grid point are the xyz displacments' - ' needed to move that grid point\'s xyz values to the' - ' corresponding xyz values in the source dataset:' - ' base( (x,y,z) + WARP(x,y,z) ) matches source(x,y,z)' - ' Another way to think of this warp is that it \'pulls\'' - ' values back from source space to base space.' - '* 3dNwarpApply would use \'ppp_WARP\' to transform datasets' - 'aligned with the source dataset to be aligned with the' - 'base dataset.' - '** If you do NOT want this warp saved, use the option \'-nowarp\'.' - '-->> (However, this warp is usually the most valuable possible output!)' - '* If you want to calculate and save the inverse 3D warp,' - 'use the option \'-iwarp\'. This inverse warp will then be' - 'saved in a dataset with prefix \'ppp_WARPINV\'.' - '* This inverse warp could be used to transform data from base' - 'space to source space, if you need to do such an operation.' - '* You can easily compute the inverse later, say by a command like' - ' 3dNwarpCat -prefix Z_WARPINV \'INV(Z_WARP+tlrc)\'' - 'or the inverse can be computed as needed in 3dNwarpApply, like' - ' 3dNwarpApply -nwarp \'INV(Z_WARP+tlrc)\' -source Dataset.nii ...') + out_file = File( + argstr='-prefix %s', + name_template='%s_QW', + name_source=['in_file'], + genfile=True, + desc='out_file ppp' + 'Sets the prefix for the output datasets.' + '* The source dataset is warped to match the base' + 'and gets prefix \'ppp\'. (Except if \'-plusminus\' is used.)' + '* The final interpolation to this output dataset is' + 'done using the \'wsinc5\' method. See the output of' + ' 3dAllineate -HELP' + '(in the "Modifying \'-final wsinc5\'" section) for' + 'the lengthy technical details.' + '* The 3D warp used is saved in a dataset with' + 'prefix \'ppp_WARP\' -- this dataset can be used' + 'with 3dNwarpApply and 3dNwarpCat, for example.' + '* To be clear, this is the warp from source dataset' + ' coordinates to base dataset coordinates, where the' + ' values at each base grid point are the xyz displacments' + ' needed to move that grid point\'s xyz values to the' + ' corresponding xyz values in the source dataset:' + ' base( (x,y,z) + WARP(x,y,z) ) matches source(x,y,z)' + ' Another way to think of this warp is that it \'pulls\'' + ' values back from source space to base space.' + '* 3dNwarpApply would use \'ppp_WARP\' to transform datasets' + 'aligned with the source dataset to be aligned with the' + 'base dataset.' + '** If you do NOT want this warp saved, use the option \'-nowarp\'.' + '-->> (However, this warp is usually the most valuable possible output!)' + '* If you want to calculate and save the inverse 3D warp,' + 'use the option \'-iwarp\'. This inverse warp will then be' + 'saved in a dataset with prefix \'ppp_WARPINV\'.' + '* This inverse warp could be used to transform data from base' + 'space to source space, if you need to do such an operation.' + '* You can easily compute the inverse later, say by a command like' + ' 3dNwarpCat -prefix Z_WARPINV \'INV(Z_WARP+tlrc)\'' + 'or the inverse can be computed as needed in 3dNwarpApply, like' + ' 3dNwarpApply -nwarp \'INV(Z_WARP+tlrc)\' -source Dataset.nii ...') resample = traits.Bool( desc='This option simply resamples the source dataset to match the' - 'base dataset grid. You can use this if the two datasets' - 'overlap well (as seen in the AFNI GUI), but are not on the' - 'same 3D grid.' - '* If they don\'t overlap well, allineate them first' - '* The reampling here is done with the' - '\'wsinc5\' method, which has very little blurring artifact.' - '* If the base and source datasets ARE on the same 3D grid,' - 'then the -resample option will be ignored.' - '* You CAN use -resample with these 3dQwarp options:' - '-plusminus -inilev -iniwarp -duplo', + 'base dataset grid. You can use this if the two datasets' + 'overlap well (as seen in the AFNI GUI), but are not on the' + 'same 3D grid.' + '* If they don\'t overlap well, allineate them first' + '* The reampling here is done with the' + '\'wsinc5\' method, which has very little blurring artifact.' + '* If the base and source datasets ARE on the same 3D grid,' + 'then the -resample option will be ignored.' + '* You CAN use -resample with these 3dQwarp options:' + '-plusminus -inilev -iniwarp -duplo', argstr='-resample') allineate = traits.Bool( desc='This option will make 3dQwarp run 3dAllineate first, to align ' - 'the source dataset to the base with an affine transformation. ' - 'It will then use that alignment as a starting point for the ' - 'nonlinear warping.', + 'the source dataset to the base with an affine transformation. ' + 'It will then use that alignment as a starting point for the ' + 'nonlinear warping.', argstr='-allineate') allineate_opts = traits.Str( desc='add extra options to the 3dAllineate command to be run by ' - '3dQwarp.', + '3dQwarp.', argstr='-allineate_opts %s', - xand=['allineate']) - nowarp = traits.Bool( - desc='Do not save the _WARP file.', - argstr='-nowarp') + requires=['allineate']) + nowarp = traits.Bool(desc='Do not save the _WARP file.', argstr='-nowarp') iwarp = traits.Bool( desc='Do compute and save the _WARPINV file.', argstr='-iwarp', xor=['plusminus']) pear = traits.Bool( desc='Use strict Pearson correlation for matching.' - '* Not usually recommended, since the \'clipped Pearson\' method' - 'used by default will reduce the impact of outlier values.', + '* Not usually recommended, since the \'clipped Pearson\' method' + 'used by default will reduce the impact of outlier values.', argstr='-pear') noneg = traits.Bool( desc='Replace negative values in either input volume with 0.' - '* If there ARE negative input values, and you do NOT use -noneg,' - 'then strict Pearson correlation will be used, since the \'clipped\'' - 'method only is implemented for non-negative volumes.' - '* \'-noneg\' is not the default, since there might be situations where' - 'you want to align datasets with positive and negative values mixed.' - '* But, in many cases, the negative values in a dataset are just the' - 'result of interpolation artifacts (or other peculiarities), and so' - 'they should be ignored. That is what \'-noneg\' is for.', + '* If there ARE negative input values, and you do NOT use -noneg,' + 'then strict Pearson correlation will be used, since the \'clipped\'' + 'method only is implemented for non-negative volumes.' + '* \'-noneg\' is not the default, since there might be situations where' + 'you want to align datasets with positive and negative values mixed.' + '* But, in many cases, the negative values in a dataset are just the' + 'result of interpolation artifacts (or other peculiarities), and so' + 'they should be ignored. That is what \'-noneg\' is for.', argstr='-noneg') nopenalty = traits.Bool( desc='Replace negative values in either input volume with 0.' - '* If there ARE negative input values, and you do NOT use -noneg,' - 'then strict Pearson correlation will be used, since the \'clipped\'' - 'method only is implemented for non-negative volumes.' - '* \'-noneg\' is not the default, since there might be situations where' - 'you want to align datasets with positive and negative values mixed.' - '* But, in many cases, the negative values in a dataset are just the' - 'result of interpolation artifacts (or other peculiarities), and so' - 'they should be ignored. That is what \'-noneg\' is for.', + '* If there ARE negative input values, and you do NOT use -noneg,' + 'then strict Pearson correlation will be used, since the \'clipped\'' + 'method only is implemented for non-negative volumes.' + '* \'-noneg\' is not the default, since there might be situations where' + 'you want to align datasets with positive and negative values mixed.' + '* But, in many cases, the negative values in a dataset are just the' + 'result of interpolation artifacts (or other peculiarities), and so' + 'they should be ignored. That is what \'-noneg\' is for.', argstr='-nopenalty') penfac = traits.Float( desc='Use this value to weight the penalty.' - 'The default value is 1.Larger values mean the' - 'penalty counts more, reducing grid distortions,' - 'insha\'Allah; \'-nopenalty\' is the same as \'-penfac 0\'.' - ' -->>* [23 Sep 2013] -- Zhark increased the default value of' - ' the penalty by a factor of 5, and also made it get' - ' progressively larger with each level of refinement.' - ' Thus, warping results will vary from earlier instances' - ' of 3dQwarp.' - ' * The progressive increase in the penalty at higher levels' - ' means that the \'cost function\' can actually look like the' - ' alignment is getting worse when the levels change.' - ' * IF you wish to turn off this progression, for whatever' - ' reason (e.g., to keep compatibility with older results),' - ' use the option \'-penold\'.To be completely compatible with' - ' the older 3dQwarp, you\'ll also have to use \'-penfac 0.2\'.', + 'The default value is 1.Larger values mean the' + 'penalty counts more, reducing grid distortions,' + 'insha\'Allah; \'-nopenalty\' is the same as \'-penfac 0\'.' + ' -->>* [23 Sep 2013] -- Zhark increased the default value of' + ' the penalty by a factor of 5, and also made it get' + ' progressively larger with each level of refinement.' + ' Thus, warping results will vary from earlier instances' + ' of 3dQwarp.' + ' * The progressive increase in the penalty at higher levels' + ' means that the \'cost function\' can actually look like the' + ' alignment is getting worse when the levels change.' + ' * IF you wish to turn off this progression, for whatever' + ' reason (e.g., to keep compatibility with older results),' + ' use the option \'-penold\'.To be completely compatible with' + ' the older 3dQwarp, you\'ll also have to use \'-penfac 0.2\'.', argstr='-penfac %f') noweight = traits.Bool( desc='If you want a binary weight (the old default), use this option.' - 'That is, each voxel in the base volume automask will be' - 'weighted the same in the computation of the cost functional.', + 'That is, each voxel in the base volume automask will be' + 'weighted the same in the computation of the cost functional.', argstr='-noweight') weight = File( desc='Instead of computing the weight from the base dataset,' - 'directly input the weight volume from dataset \'www\'.' - '* Useful if you know what over parts of the base image you' - 'want to emphasize or de-emphasize the matching functional.', + 'directly input the weight volume from dataset \'www\'.' + '* Useful if you know what over parts of the base image you' + 'want to emphasize or de-emphasize the matching functional.', argstr='-weight %s', exists=True) wball = traits.List( traits.Int(), desc='-wball x y z r f' - 'Enhance automatic weight from \'-useweight\' by a factor' - 'of 1+f*Gaussian(FWHM=r) centered in the base image at' - 'DICOM coordinates (x,y,z) and with radius \'r\'. The' - 'goal of this option is to try and make the alignment' - 'better in a specific part of the brain.' - '* Example: -wball 0 14 6 30 40' - 'to emphasize the thalamic area (in MNI/Talairach space).' - '* The \'r\' parameter must be positive!' - '* The \'f\' parameter must be between 1 and 100 (inclusive).' - '* \'-wball\' does nothing if you input your own weight' - 'with the \'-weight\' option.' - '* \'-wball\' does change the binary weight created by' - 'the \'-noweight\' option.' - '* You can only use \'-wball\' once in a run of 3dQwarp.' - '*** The effect of \'-wball\' is not dramatic. The example' - 'above makes the average brain image across a collection' - 'of subjects a little sharper in the thalamic area, which' - 'might have some small value. If you care enough about' - 'alignment to use \'-wball\', then you should examine the' - 'results from 3dQwarp for each subject, to see if the' - 'alignments are good enough for your purposes.', + 'Enhance automatic weight from \'-useweight\' by a factor' + 'of 1+f*Gaussian(FWHM=r) centered in the base image at' + 'DICOM coordinates (x,y,z) and with radius \'r\'. The' + 'goal of this option is to try and make the alignment' + 'better in a specific part of the brain.' + '* Example: -wball 0 14 6 30 40' + 'to emphasize the thalamic area (in MNI/Talairach space).' + '* The \'r\' parameter must be positive!' + '* The \'f\' parameter must be between 1 and 100 (inclusive).' + '* \'-wball\' does nothing if you input your own weight' + 'with the \'-weight\' option.' + '* \'-wball\' does change the binary weight created by' + 'the \'-noweight\' option.' + '* You can only use \'-wball\' once in a run of 3dQwarp.' + '*** The effect of \'-wball\' is not dramatic. The example' + 'above makes the average brain image across a collection' + 'of subjects a little sharper in the thalamic area, which' + 'might have some small value. If you care enough about' + 'alignment to use \'-wball\', then you should examine the' + 'results from 3dQwarp for each subject, to see if the' + 'alignments are good enough for your purposes.', argstr='-wball %s', minlen=5, maxlen=5) - traits.Tuple( - (traits.Float(), traits.Float()), - argstr='-bpass %f %f') + traits.Tuple((traits.Float(), traits.Float()), argstr='-bpass %f %f') wmask = traits.Tuple( (File(exists=True), traits.Float()), desc='-wmask ws f' - 'Similar to \'-wball\', but here, you provide a dataset \'ws\'' - 'that indicates where to increase the weight.' - '* The \'ws\' dataset must be on the same 3D grid as the base dataset.' - '* \'ws\' is treated as a mask -- it only matters where it' - 'is nonzero -- otherwise, the values inside are not used.' - '* After \'ws\' comes the factor \'f\' by which to increase the' - 'automatically computed weight. Where \'ws\' is nonzero,' - 'the weighting will be multiplied by (1+f).' - '* As with \'-wball\', the factor \'f\' should be between 1 and 100.' - '* You cannot use \'-wball\' and \'-wmask\' together!', + 'Similar to \'-wball\', but here, you provide a dataset \'ws\'' + 'that indicates where to increase the weight.' + '* The \'ws\' dataset must be on the same 3D grid as the base dataset.' + '* \'ws\' is treated as a mask -- it only matters where it' + 'is nonzero -- otherwise, the values inside are not used.' + '* After \'ws\' comes the factor \'f\' by which to increase the' + 'automatically computed weight. Where \'ws\' is nonzero,' + 'the weighting will be multiplied by (1+f).' + '* As with \'-wball\', the factor \'f\' should be between 1 and 100.' + '* You cannot use \'-wball\' and \'-wmask\' together!', argstr='-wpass %s %f') out_weight_file = traits.File( argstr='-wtprefix %s', @@ -3068,285 +2942,284 @@ class QwarpInputSpec(AFNICommandInputSpec): blur = traits.List( traits.Float(), desc='Gaussian blur the input images by \'bb\' (FWHM) voxels before' - 'doing the alignment (the output dataset will not be blurred).' - 'The default is 2.345 (for no good reason).' - '* Optionally, you can provide 2 values for \'bb\', and then' - 'the first one is applied to the base volume, the second' - 'to the source volume.' - '-->>* e.g., \'-blur 0 3\' to skip blurring the base image' - '(if the base is a blurry template, for example).' - '* A negative blur radius means to use 3D median filtering,' - 'rather than Gaussian blurring. This type of filtering will' - 'better preserve edges, which can be important in alignment.' - '* If the base is a template volume that is already blurry,' - 'you probably don\'t want to blur it again, but blurring' - 'the source volume a little is probably a good idea, to' - 'help the program avoid trying to match tiny features.' - '* Note that -duplo will blur the volumes some extra' - 'amount for the initial small-scale warping, to make' - 'that phase of the program converge more rapidly.', + 'doing the alignment (the output dataset will not be blurred).' + 'The default is 2.345 (for no good reason).' + '* Optionally, you can provide 2 values for \'bb\', and then' + 'the first one is applied to the base volume, the second' + 'to the source volume.' + '-->>* e.g., \'-blur 0 3\' to skip blurring the base image' + '(if the base is a blurry template, for example).' + '* A negative blur radius means to use 3D median filtering,' + 'rather than Gaussian blurring. This type of filtering will' + 'better preserve edges, which can be important in alignment.' + '* If the base is a template volume that is already blurry,' + 'you probably don\'t want to blur it again, but blurring' + 'the source volume a little is probably a good idea, to' + 'help the program avoid trying to match tiny features.' + '* Note that -duplo will blur the volumes some extra' + 'amount for the initial small-scale warping, to make' + 'that phase of the program converge more rapidly.', argstr='-blur %s', minlen=1, maxlen=2) pblur = traits.List( traits.Float(), desc='Use progressive blurring; that is, for larger patch sizes,' - 'the amount of blurring is larger. The general idea is to' - 'avoid trying to match finer details when the patch size' - 'and incremental warps are coarse. When \'-blur\' is used' - 'as well, it sets a minimum amount of blurring that will' - 'be used. [06 Aug 2014 -- \'-pblur\' may become the default someday].' - '* You can optionally give the fraction of the patch size that' - 'is used for the progressive blur by providing a value between' - '0 and 0.25 after \'-pblur\'. If you provide TWO values, the' - 'the first fraction is used for progressively blurring the' - 'base image and the second for the source image. The default' - 'parameters when just \'-pblur\' is given is the same as giving' - 'the options as \'-pblur 0.09 0.09\'.' - '* \'-pblur\' is useful when trying to match 2 volumes with high' - 'amounts of detail; e.g, warping one subject\'s brain image to' - 'match another\'s, or trying to warp to match a detailed template.' - '* Note that using negative values with \'-blur\' means that the' - 'progressive blurring will be done with median filters, rather' - 'than Gaussian linear blurring.' - '-->>*** The combination of the -allineate and -pblur options will make' - 'the results of using 3dQwarp to align to a template somewhat' - 'less sensitive to initial head position and scaling.', + 'the amount of blurring is larger. The general idea is to' + 'avoid trying to match finer details when the patch size' + 'and incremental warps are coarse. When \'-blur\' is used' + 'as well, it sets a minimum amount of blurring that will' + 'be used. [06 Aug 2014 -- \'-pblur\' may become the default someday].' + '* You can optionally give the fraction of the patch size that' + 'is used for the progressive blur by providing a value between' + '0 and 0.25 after \'-pblur\'. If you provide TWO values, the' + 'the first fraction is used for progressively blurring the' + 'base image and the second for the source image. The default' + 'parameters when just \'-pblur\' is given is the same as giving' + 'the options as \'-pblur 0.09 0.09\'.' + '* \'-pblur\' is useful when trying to match 2 volumes with high' + 'amounts of detail; e.g, warping one subject\'s brain image to' + 'match another\'s, or trying to warp to match a detailed template.' + '* Note that using negative values with \'-blur\' means that the' + 'progressive blurring will be done with median filters, rather' + 'than Gaussian linear blurring.' + '-->>*** The combination of the -allineate and -pblur options will make' + 'the results of using 3dQwarp to align to a template somewhat' + 'less sensitive to initial head position and scaling.', argstr='-pblur %s', minlen=1, maxlen=2) emask = File( desc='Here, \'ee\' is a dataset to specify a mask of voxels' - 'to EXCLUDE from the analysis -- all voxels in \'ee\'' - 'that are NONZERO will not be used in the alignment.' - '* The base image always automasked -- the emask is' - 'extra, to indicate voxels you definitely DON\'T want' - 'included in the matching process, even if they are' - 'inside the brain.', + 'to EXCLUDE from the analysis -- all voxels in \'ee\'' + 'that are NONZERO will not be used in the alignment.' + '* The base image always automasked -- the emask is' + 'extra, to indicate voxels you definitely DON\'T want' + 'included in the matching process, even if they are' + 'inside the brain.', argstr='-emask %s', exists=True, copyfile=False) noXdis = traits.Bool( - desc='Warp will not displace in x directoin', - argstr='-noXdis') + desc='Warp will not displace in x directoin', argstr='-noXdis') noYdis = traits.Bool( - desc='Warp will not displace in y directoin', - argstr='-noYdis') + desc='Warp will not displace in y directoin', argstr='-noYdis') noZdis = traits.Bool( - desc='Warp will not displace in z directoin', - argstr='-noZdis') + desc='Warp will not displace in z directoin', argstr='-noZdis') iniwarp = traits.List( File(exists=True, copyfile=False), desc='A dataset with an initial nonlinear warp to use.' - '* If this option is not used, the initial warp is the identity.' - '* You can specify a catenation of warps (in quotes) here, as in' - 'program 3dNwarpApply.' - '* As a special case, if you just input an affine matrix in a .1D' - 'file, that will work also -- it is treated as giving the initial' - 'warp via the string "IDENT(base_dataset) matrix_file.aff12.1D".' - '* You CANNOT use this option with -duplo !!' - '* -iniwarp is usually used with -inilev to re-start 3dQwarp from' - 'a previous stopping point.', + '* If this option is not used, the initial warp is the identity.' + '* You can specify a catenation of warps (in quotes) here, as in' + 'program 3dNwarpApply.' + '* As a special case, if you just input an affine matrix in a .1D' + 'file, that will work also -- it is treated as giving the initial' + 'warp via the string "IDENT(base_dataset) matrix_file.aff12.1D".' + '* You CANNOT use this option with -duplo !!' + '* -iniwarp is usually used with -inilev to re-start 3dQwarp from' + 'a previous stopping point.', argstr='-iniwarp %s', xor=['duplo']) inilev = traits.Int( desc='The initial refinement \'level\' at which to start.' - '* Usually used with -iniwarp; CANNOT be used with -duplo.' - '* The combination of -inilev and -iniwarp lets you take the' - 'results of a previous 3dQwarp run and refine them further:' - 'Note that the source dataset in the second run is the SAME as' - 'in the first run. If you don\'t see why this is necessary,' - 'then you probably need to seek help from an AFNI guru.', + '* Usually used with -iniwarp; CANNOT be used with -duplo.' + '* The combination of -inilev and -iniwarp lets you take the' + 'results of a previous 3dQwarp run and refine them further:' + 'Note that the source dataset in the second run is the SAME as' + 'in the first run. If you don\'t see why this is necessary,' + 'then you probably need to seek help from an AFNI guru.', argstr='-inilev %d', xor=['duplo']) minpatch = traits.Int( desc='* The value of mm should be an odd integer.' - '* The default value of mm is 25.' - '* For more accurate results than mm=25, try 19 or 13.' - '* The smallest allowed patch size is 5.' - '* You may want stop at a larger patch size (say 7 or 9) and use' - 'the -Qfinal option to run that final level with quintic warps,' - 'which might run faster and provide the same degree of warp detail.' - '* Trying to make two different brain volumes match in fine detail' - 'is usually a waste of time, especially in humans. There is too' - 'much variability in anatomy to match gyrus to gyrus accurately.' - 'For this reason, the default minimum patch size is 25 voxels.' - 'Using a smaller \'-minpatch\' might try to force the warp to' - 'match features that do not match, and the result can be useless' - 'image distortions -- another reason to LOOK AT THE RESULTS.', + '* The default value of mm is 25.' + '* For more accurate results than mm=25, try 19 or 13.' + '* The smallest allowed patch size is 5.' + '* You may want stop at a larger patch size (say 7 or 9) and use' + 'the -Qfinal option to run that final level with quintic warps,' + 'which might run faster and provide the same degree of warp detail.' + '* Trying to make two different brain volumes match in fine detail' + 'is usually a waste of time, especially in humans. There is too' + 'much variability in anatomy to match gyrus to gyrus accurately.' + 'For this reason, the default minimum patch size is 25 voxels.' + 'Using a smaller \'-minpatch\' might try to force the warp to' + 'match features that do not match, and the result can be useless' + 'image distortions -- another reason to LOOK AT THE RESULTS.', argstr='-minpatch %d') maxlev = traits.Int( desc='The initial refinement \'level\' at which to start.' - '* Usually used with -iniwarp; CANNOT be used with -duplo.' - '* The combination of -inilev and -iniwarp lets you take the' - 'results of a previous 3dQwarp run and refine them further:' - 'Note that the source dataset in the second run is the SAME as' - 'in the first run. If you don\'t see why this is necessary,' - 'then you probably need to seek help from an AFNI guru.', + '* Usually used with -iniwarp; CANNOT be used with -duplo.' + '* The combination of -inilev and -iniwarp lets you take the' + 'results of a previous 3dQwarp run and refine them further:' + 'Note that the source dataset in the second run is the SAME as' + 'in the first run. If you don\'t see why this is necessary,' + 'then you probably need to seek help from an AFNI guru.', argstr='-maxlev %d', xor=['duplo'], position=-1) gridlist = File( desc='This option provides an alternate way to specify the patch' - 'grid sizes used in the warp optimization process. \'gl\' is' - 'a 1D file with a list of patches to use -- in most cases,' - 'you will want to use it in the following form:' - '-gridlist \'1D: 0 151 101 75 51\'' - '* Here, a 0 patch size means the global domain. Patch sizes' - 'otherwise should be odd integers >= 5.' - '* If you use the \'0\' patch size again after the first position,' - 'you will actually get an iteration at the size of the' - 'default patch level 1, where the patch sizes are 75% of' - 'the volume dimension. There is no way to force the program' - 'to literally repeat the sui generis step of lev=0.' - '* You cannot use -gridlist with -duplo or -plusminus!', + 'grid sizes used in the warp optimization process. \'gl\' is' + 'a 1D file with a list of patches to use -- in most cases,' + 'you will want to use it in the following form:' + '-gridlist \'1D: 0 151 101 75 51\'' + '* Here, a 0 patch size means the global domain. Patch sizes' + 'otherwise should be odd integers >= 5.' + '* If you use the \'0\' patch size again after the first position,' + 'you will actually get an iteration at the size of the' + 'default patch level 1, where the patch sizes are 75% of' + 'the volume dimension. There is no way to force the program' + 'to literally repeat the sui generis step of lev=0.' + '* You cannot use -gridlist with -duplo or -plusminus!', argstr='-gridlist %s', exists=True, copyfile=False, xor=['duplo', 'plusminus']) allsave = traits.Bool( desc='This option lets you save the output warps from each level' - 'of the refinement process. Mostly used for experimenting.' - '* Cannot be used with -nopadWARP, -duplo, or -plusminus.' - '* Will only save all the outputs if the program terminates' - 'normally -- if it crashes, or freezes, then all these' - 'warps are lost.', + 'of the refinement process. Mostly used for experimenting.' + '* Cannot be used with -nopadWARP, -duplo, or -plusminus.' + '* Will only save all the outputs if the program terminates' + 'normally -- if it crashes, or freezes, then all these' + 'warps are lost.', argstr='-allsave', xor=['nopadWARP', 'duplo', 'plusminus']) duplo = traits.Bool( desc='Start off with 1/2 scale versions of the volumes,' - 'for getting a speedy coarse first alignment.' - '* Then scales back up to register the full volumes.' - 'The goal is greater speed, and it seems to help this' - 'positively piggish program to be more expeditious.' - '* However, accuracy is somewhat lower with \'-duplo\',' - 'for reasons that currenly elude Zhark; for this reason,' - 'the Emperor does not usually use \'-duplo\'.', + 'for getting a speedy coarse first alignment.' + '* Then scales back up to register the full volumes.' + 'The goal is greater speed, and it seems to help this' + 'positively piggish program to be more expeditious.' + '* However, accuracy is somewhat lower with \'-duplo\',' + 'for reasons that currenly elude Zhark; for this reason,' + 'the Emperor does not usually use \'-duplo\'.', argstr='-duplo', - xor=['gridlist', 'maxlev', 'inilev', 'iniwarp', 'plusminus', 'allsave']) + xor=[ + 'gridlist', 'maxlev', 'inilev', 'iniwarp', 'plusminus', 'allsave' + ]) workhard = traits.Bool( desc='Iterate more times, which can help when the volumes are' - 'hard to align at all, or when you hope to get a more precise' - 'alignment.' - '* Slows the program down (possibly a lot), of course.' - '* When you combine \'-workhard\' with \'-duplo\', only the' - 'full size volumes get the extra iterations.' - '* For finer control over which refinement levels work hard,' - 'you can use this option in the form (for example)' - ' -workhard:4:7' - 'which implies the extra iterations will be done at levels' - '4, 5, 6, and 7, but not otherwise.' - '* You can also use \'-superhard\' to iterate even more, but' - 'this extra option will REALLY slow things down.' - '-->>* Under most circumstances, you should not need to use either' - '-workhard or -superhard.' - '-->>* The fastest way to register to a template image is via the' - '-duplo option, and without the -workhard or -superhard options.' - '-->>* If you use this option in the form \'-Workhard\' (first letter' - 'in upper case), then the second iteration at each level is' - 'done with quintic polynomial warps.', + 'hard to align at all, or when you hope to get a more precise' + 'alignment.' + '* Slows the program down (possibly a lot), of course.' + '* When you combine \'-workhard\' with \'-duplo\', only the' + 'full size volumes get the extra iterations.' + '* For finer control over which refinement levels work hard,' + 'you can use this option in the form (for example)' + ' -workhard:4:7' + 'which implies the extra iterations will be done at levels' + '4, 5, 6, and 7, but not otherwise.' + '* You can also use \'-superhard\' to iterate even more, but' + 'this extra option will REALLY slow things down.' + '-->>* Under most circumstances, you should not need to use either' + '-workhard or -superhard.' + '-->>* The fastest way to register to a template image is via the' + '-duplo option, and without the -workhard or -superhard options.' + '-->>* If you use this option in the form \'-Workhard\' (first letter' + 'in upper case), then the second iteration at each level is' + 'done with quintic polynomial warps.', argstr='-workhard', xor=['boxopt', 'ballopt']) Qfinal = traits.Bool( desc='At the finest patch size (the final level), use Hermite' - 'quintic polynomials for the warp instead of cubic polynomials.' - '* In a 3D \'patch\', there are 2x2x2x3=24 cubic polynomial basis' - 'function parameters over which to optimize (2 polynomials' - 'dependent on each of the x,y,z directions, and 3 different' - 'directions of displacement).' - '* There are 3x3x3x3=81 quintic polynomial parameters per patch.' - '* With -Qfinal, the final level will have more detail in' - 'the allowed warps, at the cost of yet more CPU time.' - '* However, no patch below 7x7x7 in size will be done with quintic' - 'polynomials.' - '* This option is also not usually needed, and is experimental.', + 'quintic polynomials for the warp instead of cubic polynomials.' + '* In a 3D \'patch\', there are 2x2x2x3=24 cubic polynomial basis' + 'function parameters over which to optimize (2 polynomials' + 'dependent on each of the x,y,z directions, and 3 different' + 'directions of displacement).' + '* There are 3x3x3x3=81 quintic polynomial parameters per patch.' + '* With -Qfinal, the final level will have more detail in' + 'the allowed warps, at the cost of yet more CPU time.' + '* However, no patch below 7x7x7 in size will be done with quintic' + 'polynomials.' + '* This option is also not usually needed, and is experimental.', argstr='-Qfinal') Qonly = traits.Bool( desc='Use Hermite quintic polynomials at all levels.' - '* Very slow (about 4 times longer). Also experimental.' - '* Will produce a (discrete representation of a) C2 warp.', + '* Very slow (about 4 times longer). Also experimental.' + '* Will produce a (discrete representation of a) C2 warp.', argstr='-Qonly') plusminus = traits.Bool( desc='Normally, the warp displacements dis(x) are defined to match' - 'base(x) to source(x+dis(x)). With this option, the match' - 'is between base(x-dis(x)) and source(x+dis(x)) -- the two' - 'images \'meet in the middle\'.' - '* One goal is to mimic the warping done to MRI EPI data by' - 'field inhomogeneities, when registering between a \'blip up\'' - 'and a \'blip down\' down volume, which will have opposite' - 'distortions.' - '* Define Wp(x) = x+dis(x) and Wm(x) = x-dis(x). Then since' - 'base(Wm(x)) matches source(Wp(x)), by substituting INV(Wm(x))' - 'wherever we see x, we have base(x) matches source(Wp(INV(Wm(x))));' - 'that is, the warp V(x) that one would get from the \'usual\' way' - 'of running 3dQwarp is V(x) = Wp(INV(Wm(x))).' - '* Conversely, we can calculate Wp(x) in terms of V(x) as follows:' - 'If V(x) = x + dv(x), define Vh(x) = x + dv(x)/2;' - 'then Wp(x) = V(INV(Vh(x)))' - '* With the above formulas, it is possible to compute Wp(x) from' - 'V(x) and vice-versa, using program 3dNwarpCalc. The requisite' - 'commands are left as an exercise for the aspiring AFNI Jedi Master.' - '* You can use the semi-secret \'-pmBASE\' option to get the V(x)' - 'warp and the source dataset warped to base space, in addition to' - 'the Wp(x) \'_PLUS\' and Wm(x) \'_MINUS\' warps.' - '-->>* Alas: -plusminus does not work with -duplo or -allineate :-(' - '* However, you can use -iniwarp with -plusminus :-)' - '-->>* The outputs have _PLUS (from the source dataset) and _MINUS' - '(from the base dataset) in their filenames, in addition to' - 'the prefix. The -iwarp option, if present, will be ignored.', + 'base(x) to source(x+dis(x)). With this option, the match' + 'is between base(x-dis(x)) and source(x+dis(x)) -- the two' + 'images \'meet in the middle\'.' + '* One goal is to mimic the warping done to MRI EPI data by' + 'field inhomogeneities, when registering between a \'blip up\'' + 'and a \'blip down\' down volume, which will have opposite' + 'distortions.' + '* Define Wp(x) = x+dis(x) and Wm(x) = x-dis(x). Then since' + 'base(Wm(x)) matches source(Wp(x)), by substituting INV(Wm(x))' + 'wherever we see x, we have base(x) matches source(Wp(INV(Wm(x))));' + 'that is, the warp V(x) that one would get from the \'usual\' way' + 'of running 3dQwarp is V(x) = Wp(INV(Wm(x))).' + '* Conversely, we can calculate Wp(x) in terms of V(x) as follows:' + 'If V(x) = x + dv(x), define Vh(x) = x + dv(x)/2;' + 'then Wp(x) = V(INV(Vh(x)))' + '* With the above formulas, it is possible to compute Wp(x) from' + 'V(x) and vice-versa, using program 3dNwarpCalc. The requisite' + 'commands are left as an exercise for the aspiring AFNI Jedi Master.' + '* You can use the semi-secret \'-pmBASE\' option to get the V(x)' + 'warp and the source dataset warped to base space, in addition to' + 'the Wp(x) \'_PLUS\' and Wm(x) \'_MINUS\' warps.' + '-->>* Alas: -plusminus does not work with -duplo or -allineate :-(' + '* However, you can use -iniwarp with -plusminus :-)' + '-->>* The outputs have _PLUS (from the source dataset) and _MINUS' + '(from the base dataset) in their filenames, in addition to' + 'the prefix. The -iwarp option, if present, will be ignored.', argstr='-plusminus', xor=['duplo', 'allsave', 'iwarp']) nopad = traits.Bool( desc='Do NOT use zero-padding on the 3D base and source images.' - '[Default == zero-pad, if needed]' - '* The underlying model for deformations goes to zero at the' - 'edge of the volume being warped. However, if there is' - 'significant data near an edge of the volume, then it won\'t' - 'get displaced much, and so the results might not be good.' - '* Zero padding is designed as a way to work around this potential' - 'problem. You should NOT need the \'-nopad\' option for any' - 'reason that Zhark can think of, but it is here to be symmetrical' - 'with 3dAllineate.' - '* Note that the output (warped from source) dataset will be on the' - 'base dataset grid whether or not zero-padding is allowed. However,' - 'unless you use the following option, allowing zero-padding (i.e.,' - 'the default operation) will make the output WARP dataset(s) be' - 'on a larger grid (also see \'-expad\' below).', + '[Default == zero-pad, if needed]' + '* The underlying model for deformations goes to zero at the' + 'edge of the volume being warped. However, if there is' + 'significant data near an edge of the volume, then it won\'t' + 'get displaced much, and so the results might not be good.' + '* Zero padding is designed as a way to work around this potential' + 'problem. You should NOT need the \'-nopad\' option for any' + 'reason that Zhark can think of, but it is here to be symmetrical' + 'with 3dAllineate.' + '* Note that the output (warped from source) dataset will be on the' + 'base dataset grid whether or not zero-padding is allowed. However,' + 'unless you use the following option, allowing zero-padding (i.e.,' + 'the default operation) will make the output WARP dataset(s) be' + 'on a larger grid (also see \'-expad\' below).', argstr='-nopad') nopadWARP = traits.Bool( desc='If for some reason you require the warp volume to' - 'match the base volume, then use this option to have the output' - 'WARP dataset(s) truncated.', + 'match the base volume, then use this option to have the output' + 'WARP dataset(s) truncated.', argstr='-nopadWARP', xor=['allsave', 'expad']) expad = traits.Int( desc='This option instructs the program to pad the warp by an extra' - '\'EE\' voxels (and then 3dQwarp starts optimizing it).' - '* This option is seldom needed, but can be useful if you' - 'might later catenate the nonlinear warp -- via 3dNwarpCat --' - 'with an affine transformation that contains a large shift.' - 'Under that circumstance, the nonlinear warp might be shifted' - 'partially outside its original grid, so expanding that grid' - 'can avoid this problem.' - '* Note that this option perforce turns off \'-nopadWARP\'.', + '\'EE\' voxels (and then 3dQwarp starts optimizing it).' + '* This option is seldom needed, but can be useful if you' + 'might later catenate the nonlinear warp -- via 3dNwarpCat --' + 'with an affine transformation that contains a large shift.' + 'Under that circumstance, the nonlinear warp might be shifted' + 'partially outside its original grid, so expanding that grid' + 'can avoid this problem.' + '* Note that this option perforce turns off \'-nopadWARP\'.', argstr='-expad %d', xor=['nopadWARP']) ballopt = traits.Bool( desc='Normally, the incremental warp parameters are optimized inside' - 'a rectangular \'box\' (24 dimensional for cubic patches, 81 for' - 'quintic patches), whose limits define the amount of distortion' - 'allowed at each step. Using \'-ballopt\' switches these limits' - 'to be applied to a \'ball\' (interior of a hypersphere), which' - 'can allow for larger incremental displacements. Use this' - 'option if you think things need to be able to move farther.', + 'a rectangular \'box\' (24 dimensional for cubic patches, 81 for' + 'quintic patches), whose limits define the amount of distortion' + 'allowed at each step. Using \'-ballopt\' switches these limits' + 'to be applied to a \'ball\' (interior of a hypersphere), which' + 'can allow for larger incremental displacements. Use this' + 'option if you think things need to be able to move farther.', argstr='-ballopt', xor=['workhard', 'boxopt']) baxopt = traits.Bool( desc='Use the \'box\' optimization limits instead of the \'ball\'' - '[this is the default at present].' - '* Note that if \'-workhard\' is used, then ball and box optimization' - 'are alternated in the different iterations at each level, so' - 'these two options have no effect in that case.', + '[this is the default at present].' + '* Note that if \'-workhard\' is used, then ball and box optimization' + 'are alternated in the different iterations at each level, so' + 'these two options have no effect in that case.', argstr='-boxopt', xor=['workhard', 'ballopt']) verb = traits.Bool( @@ -3358,62 +3231,59 @@ class QwarpInputSpec(AFNICommandInputSpec): argstr='-quiet', xor=['verb']) # Hidden and semi-hidden options - overwrite = traits.Bool( - desc='Overwrite outputs', - argstr='-overwrite') + overwrite = traits.Bool(desc='Overwrite outputs', argstr='-overwrite') lpc = traits.Bool( desc='Local Pearson minimization (i.e., EPI-T1 registration)' - 'This option has not be extensively tested' - 'If you use \'-lpc\', then \'-maxlev 0\' is automatically set.' - 'If you want to go to more refined levels, you can set \'-maxlev\'' - 'This should be set up to have lpc as the second to last argument' - 'and maxlev as the second to last argument, as needed by AFNI' - 'Using maxlev > 1 is not recommended for EPI-T1 alignment.', + 'This option has not be extensively tested' + 'If you use \'-lpc\', then \'-maxlev 0\' is automatically set.' + 'If you want to go to more refined levels, you can set \'-maxlev\'' + 'This should be set up to have lpc as the second to last argument' + 'and maxlev as the second to last argument, as needed by AFNI' + 'Using maxlev > 1 is not recommended for EPI-T1 alignment.', argstr='-lpc', xor=['nmi', 'mi', 'hel', 'lpa', 'pear'], position=-2) lpa = traits.Bool( desc='Local Pearson maximization' - 'This option has not be extensively tested', + 'This option has not be extensively tested', argstr='-lpa', xor=['nmi', 'mi', 'lpc', 'hel', 'pear']) hel = traits.Bool( desc='Hellinger distance: a matching function for the adventurous' - 'This option has NOT be extensively tested for usefullness' - 'and should be considered experimental at this infundibulum.', + 'This option has NOT be extensively tested for usefullness' + 'and should be considered experimental at this infundibulum.', argstr='-hel', xor=['nmi', 'mi', 'lpc', 'lpa', 'pear']) mi = traits.Bool( desc='Mutual Information: a matching function for the adventurous' - 'This option has NOT be extensively tested for usefullness' - 'and should be considered experimental at this infundibulum.', + 'This option has NOT be extensively tested for usefullness' + 'and should be considered experimental at this infundibulum.', argstr='-mi', xor=['mi', 'hel', 'lpc', 'lpa', 'pear']) nmi = traits.Bool( - desc='Normalized Mutual Information: a matching function for the adventurous' - 'This option has NOT be extensively tested for usefullness' - 'and should be considered experimental at this infundibulum.', + desc= + 'Normalized Mutual Information: a matching function for the adventurous' + 'This option has NOT be extensively tested for usefullness' + 'and should be considered experimental at this infundibulum.', argstr='-nmi', xor=['nmi', 'hel', 'lpc', 'lpa', 'pear']) - class QwarpOutputSpec(TraitedSpec): warped_source = File( desc='Warped source file. If plusminus is used, this is the undistorted' - 'source file.') + 'source file.') warped_base = File(desc='Undistorted base file.') source_warp = File( desc="Displacement in mm for the source image." - "If plusminus is used this is the field suceptibility correction" - "warp (in 'mm') for source image.") + "If plusminus is used this is the field suceptibility correction" + "warp (in 'mm') for source image.") base_warp = File( desc="Displacement in mm for the base image." - "If plus minus is used, this is the field suceptibility correction" - "warp (in 'mm') for base image. This is only output if plusminus" - "or iwarp options are passed") - weights = File( - desc="Auto-computed weight volume.") + "If plus minus is used, this is the field suceptibility correction" + "warp (in 'mm') for base image. This is only output if plusminus" + "or iwarp options are passed") + weights = File(desc="Auto-computed weight volume.") class Qwarp(AFNICommand): @@ -3514,37 +3384,39 @@ def _list_outputs(self): if not isdefined(self.inputs.out_file): prefix = self._gen_fname(self.inputs.in_file, suffix='_QW') ext = '.HEAD' - suffix ='+tlrc' + suffix = '+tlrc' else: prefix = self.inputs.out_file - ext_ind = max([prefix.lower().rfind('.nii.gz'), - prefix.lower().rfind('.nii.')]) + ext_ind = max([ + prefix.lower().rfind('.nii.gz'), + prefix.lower().rfind('.nii.') + ]) if ext_ind == -1: ext = '.HEAD' suffix = '+tlrc' else: ext = prefix[ext_ind:] suffix = '' - outputs['warped_source'] = fname_presuffix(prefix, suffix=suffix, - use_ext=False) + ext + outputs['warped_source'] = fname_presuffix( + prefix, suffix=suffix, use_ext=False) + ext if not self.inputs.nowarp: - outputs['source_warp'] = fname_presuffix(prefix, - suffix='_WARP' + suffix, use_ext=False) + ext + outputs['source_warp'] = fname_presuffix( + prefix, suffix='_WARP' + suffix, use_ext=False) + ext if self.inputs.iwarp: - outputs['base_warp'] = fname_presuffix(prefix, - suffix='_WARPINV' + suffix, use_ext=False) + ext + outputs['base_warp'] = fname_presuffix( + prefix, suffix='_WARPINV' + suffix, use_ext=False) + ext if isdefined(self.inputs.out_weight_file): outputs['weights'] = os.path.abspath(self.inputs.out_weight_file) if self.inputs.plusminus: - outputs['warped_source'] = fname_presuffix(prefix, - suffix='_PLUS' + suffix, use_ext=False) + ext - outputs['warped_base'] = fname_presuffix(prefix, - suffix='_MINUS' + suffix, use_ext=False) + ext - outputs['source_warp'] = fname_presuffix(prefix, - suffix='_PLUS_WARP' + suffix, use_ext=False) + ext - outputs['base_warp'] = fname_presuffix(prefix, - suffix='_MINUS_WARP' + suffix, use_ext=False) + ext + outputs['warped_source'] = fname_presuffix( + prefix, suffix='_PLUS' + suffix, use_ext=False) + ext + outputs['warped_base'] = fname_presuffix( + prefix, suffix='_MINUS' + suffix, use_ext=False) + ext + outputs['source_warp'] = fname_presuffix( + prefix, suffix='_PLUS_WARP' + suffix, use_ext=False) + ext + outputs['base_warp'] = fname_presuffix( + prefix, suffix='_MINUS_WARP' + suffix, use_ext=False) + ext return outputs def _gen_filename(self, name): diff --git a/nipype/interfaces/afni/svm.py b/nipype/interfaces/afni/svm.py index e9ea02a57b..2e6c53ce53 100644 --- a/nipype/interfaces/afni/svm.py +++ b/nipype/interfaces/afni/svm.py @@ -9,7 +9,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from ..base import TraitedSpec, traits, File from .base import AFNICommand, AFNICommandInputSpec, AFNICommandOutputSpec @@ -17,48 +18,62 @@ class SVMTrainInputSpec(AFNICommandInputSpec): # training options - ttype = traits.Str(desc='tname: classification or regression', - argstr='-type %s', - mandatory=True) - in_file = File(desc='A 3D+t AFNI brik dataset to be used for training.', - argstr='-trainvol %s', - mandatory=True, - exists=True, - copyfile=False) - out_file = File(name_template="%s_vectors", - desc='output sum of weighted linear support vectors file name', - argstr='-bucket %s', - suffix='_bucket', - name_source="in_file") - model = File(name_template="%s_model", - desc='basename for the brik containing the SVM model', - argstr='-model %s', - suffix='_model', - name_source="in_file") - alphas = File(name_template="%s_alphas", - desc='output alphas file name', - argstr='-alpha %s', - suffix='_alphas', - name_source="in_file") - mask = File(desc='byte-format brik file used to mask voxels in the analysis', - argstr='-mask %s', - position=-1, - exists=True, - copyfile=False) - nomodelmask = traits.Bool(desc='Flag to enable the omission of a mask file', - argstr='-nomodelmask') - trainlabels = File(desc='.1D labels corresponding to the stimulus paradigm for the training data.', - argstr='-trainlabels %s', - exists=True) - censor = File(desc='.1D censor file that allows the user to ignore certain samples in the training data.', - argstr='-censor %s', - exists=True) - kernel = traits.Str(desc='string specifying type of kernel function:linear, polynomial, rbf, sigmoid', - argstr='-kernel %s') - max_iterations = traits.Int(desc='Specify the maximum number of iterations for the optimization.', - argstr='-max_iterations %d') - w_out = traits.Bool(desc='output sum of weighted linear support vectors', - argstr='-wout') + ttype = traits.Str( + desc='tname: classification or regression', + argstr='-type %s', + mandatory=True) + in_file = File( + desc='A 3D+t AFNI brik dataset to be used for training.', + argstr='-trainvol %s', + mandatory=True, + exists=True, + copyfile=False) + out_file = File( + name_template="%s_vectors", + desc='output sum of weighted linear support vectors file name', + argstr='-bucket %s', + suffix='_bucket', + name_source="in_file") + model = File( + name_template="%s_model", + desc='basename for the brik containing the SVM model', + argstr='-model %s', + suffix='_model', + name_source="in_file") + alphas = File( + name_template="%s_alphas", + desc='output alphas file name', + argstr='-alpha %s', + suffix='_alphas', + name_source="in_file") + mask = File( + desc='byte-format brik file used to mask voxels in the analysis', + argstr='-mask %s', + position=-1, + exists=True, + copyfile=False) + nomodelmask = traits.Bool( + desc='Flag to enable the omission of a mask file', + argstr='-nomodelmask') + trainlabels = File( + desc= + '.1D labels corresponding to the stimulus paradigm for the training data.', + argstr='-trainlabels %s', + exists=True) + censor = File( + desc= + '.1D censor file that allows the user to ignore certain samples in the training data.', + argstr='-censor %s', + exists=True) + kernel = traits.Str( + desc= + 'string specifying type of kernel function:linear, polynomial, rbf, sigmoid', + argstr='-kernel %s') + max_iterations = traits.Int( + desc='Specify the maximum number of iterations for the optimization.', + argstr='-max_iterations %d') + w_out = traits.Bool( + desc='output sum of weighted linear support vectors', argstr='-wout') options = traits.Str(desc='additional options for SVM-light', argstr='%s') @@ -100,27 +115,39 @@ def _format_arg(self, name, trait_spec, value): class SVMTestInputSpec(AFNICommandInputSpec): # testing options - model = traits.Str(desc='modname is the basename for the brik containing the SVM model', - argstr='-model %s', - mandatory=True) - in_file = File(desc='A 3D or 3D+t AFNI brik dataset to be used for testing.', - argstr='-testvol %s', - exists=True, - mandatory=True) - out_file = File(name_template="%s_predictions", - desc='filename for .1D prediction file(s).', - argstr='-predictions %s') - testlabels = File(desc='*true* class category .1D labels for the test dataset. It is used to calculate the prediction accuracy performance', - exists=True, - argstr='-testlabels %s') - classout = traits.Bool(desc='Flag to specify that pname files should be integer-valued, corresponding to class category decisions.', - argstr='-classout') - nopredcensord = traits.Bool(desc='Flag to prevent writing predicted values for censored time-points', - argstr='-nopredcensord') - nodetrend = traits.Bool(desc='Flag to specify that pname files should not be linearly detrended', - argstr='-nodetrend') - multiclass = traits.Bool(desc='Specifies multiclass algorithm for classification', - argstr='-multiclass %s') + model = traits.Str( + desc='modname is the basename for the brik containing the SVM model', + argstr='-model %s', + mandatory=True) + in_file = File( + desc='A 3D or 3D+t AFNI brik dataset to be used for testing.', + argstr='-testvol %s', + exists=True, + mandatory=True) + out_file = File( + name_template="%s_predictions", + desc='filename for .1D prediction file(s).', + argstr='-predictions %s') + testlabels = File( + desc= + '*true* class category .1D labels for the test dataset. It is used to calculate the prediction accuracy performance', + exists=True, + argstr='-testlabels %s') + classout = traits.Bool( + desc= + 'Flag to specify that pname files should be integer-valued, corresponding to class category decisions.', + argstr='-classout') + nopredcensord = traits.Bool( + desc= + 'Flag to prevent writing predicted values for censored time-points', + argstr='-nopredcensord') + nodetrend = traits.Bool( + desc= + 'Flag to specify that pname files should not be linearly detrended', + argstr='-nodetrend') + multiclass = traits.Bool( + desc='Specifies multiclass algorithm for classification', + argstr='-multiclass %s') options = traits.Str(desc='additional options for SVM-light', argstr='%s') diff --git a/nipype/interfaces/afni/tests/test_auto_ABoverlap.py b/nipype/interfaces/afni/tests/test_auto_ABoverlap.py index 9baf98d246..9c12e12c83 100644 --- a/nipype/interfaces/afni/tests/test_auto_ABoverlap.py +++ b/nipype/interfaces/afni/tests/test_auto_ABoverlap.py @@ -4,52 +4,53 @@ def test_ABoverlap_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file_a=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-3, - ), - in_file_b=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-2, - ), - no_automask=dict(argstr='-no_automask', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr=' |& tee %s', - position=-1, - ), - outputtype=dict(), - quiet=dict(argstr='-quiet', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verb=dict(argstr='-verb', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file_a=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-3, + ), + in_file_b=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-2, + ), + no_automask=dict(argstr='-no_automask', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr=' |& tee %s', + position=-1, + ), + outputtype=dict(), + quiet=dict(argstr='-quiet', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verb=dict(argstr='-verb', ), ) inputs = ABoverlap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ABoverlap_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ABoverlap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_AFNICommand.py b/nipype/interfaces/afni/tests/test_auto_AFNICommand.py index 0f670fa2f4..3ce91a13fe 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNICommand.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNICommand.py @@ -4,30 +4,34 @@ def test_AFNICommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_afni', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_afni', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AFNICommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py b/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py index 8ab19a670a..47f2d86d4b 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py @@ -4,22 +4,24 @@ def test_AFNICommandBase_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AFNICommandBase.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py b/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py index 664237b4d7..388c236cd4 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py @@ -4,30 +4,34 @@ def test_AFNIPythonCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_afni', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_afni', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AFNIPythonCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py b/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py index e01cc9dd28..a578d7dede 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py @@ -4,53 +4,56 @@ def test_AFNItoNIFTI_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - denote=dict(argstr='-denote', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - newid=dict(argstr='-newid', - xor=['oldid'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - oldid=dict(argstr='-oldid', - xor=['newid'], - ), - out_file=dict(argstr='-prefix %s', - hash_files=False, - name_source='in_file', - name_template='%s.nii', - ), - outputtype=dict(), - pure=dict(argstr='-pure', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + denote=dict(argstr='-denote', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + newid=dict( + argstr='-newid', + xor=['oldid'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oldid=dict( + argstr='-oldid', + xor=['newid'], + ), + out_file=dict( + argstr='-prefix %s', + hash_files=False, + name_source='in_file', + name_template='%s.nii', + ), + outputtype=dict(), + pure=dict(argstr='-pure', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AFNItoNIFTI.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AFNItoNIFTI_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = AFNItoNIFTI.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py b/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py index adf8750b1c..6f14fb6418 100644 --- a/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py +++ b/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py @@ -4,68 +4,71 @@ def test_AlignEpiAnatPy_inputs(): - input_map = dict(anat=dict(argstr='-anat %s', - copyfile=False, - mandatory=True, - ), - anat2epi=dict(argstr='-anat2epi', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - epi2anat=dict(argstr='-epi2anat', - ), - epi_base=dict(argstr='-epi_base %s', - mandatory=True, - ), - epi_strip=dict(argstr='-epi_strip %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-epi %s', - copyfile=False, - mandatory=True, - ), - outputtype=dict(), - py27_path=dict(usedefault=True, - ), - save_skullstrip=dict(argstr='-save_skullstrip', - ), - suffix=dict(argstr='-suffix %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tshift=dict(argstr='-tshift %s', - usedefault=True, - ), - volreg=dict(argstr='-volreg %s', - usedefault=True, - ), + input_map = dict( + anat=dict( + argstr='-anat %s', + copyfile=False, + mandatory=True, + ), + anat2epi=dict(argstr='-anat2epi', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi2anat=dict(argstr='-epi2anat', ), + epi_base=dict( + argstr='-epi_base %s', + mandatory=True, + ), + epi_strip=dict(argstr='-epi_strip %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-epi %s', + copyfile=False, + mandatory=True, + ), + outputtype=dict(), + py27_path=dict(usedefault=True, ), + save_skullstrip=dict(argstr='-save_skullstrip', ), + suffix=dict( + argstr='-suffix %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tshift=dict( + argstr='-tshift %s', + usedefault=True, + ), + volreg=dict( + argstr='-volreg %s', + usedefault=True, + ), ) inputs = AlignEpiAnatPy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AlignEpiAnatPy_outputs(): - output_map = dict(anat_al_mat=dict(), - anat_al_orig=dict(), - epi_al_mat=dict(), - epi_al_orig=dict(), - epi_al_tlrc_mat=dict(), - epi_reg_al_mat=dict(), - epi_tlrc_al=dict(), - epi_vr_al_mat=dict(), - epi_vr_motion=dict(), - skullstrip=dict(), + output_map = dict( + anat_al_mat=dict(), + anat_al_orig=dict(), + epi_al_mat=dict(), + epi_al_orig=dict(), + epi_al_tlrc_mat=dict(), + epi_reg_al_mat=dict(), + epi_tlrc_al=dict(), + epi_vr_al_mat=dict(), + epi_vr_motion=dict(), + skullstrip=dict(), ) outputs = AlignEpiAnatPy.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Allineate.py b/nipype/interfaces/afni/tests/test_auto_Allineate.py index 73ecc66414..59b1929fbe 100644 --- a/nipype/interfaces/afni/tests/test_auto_Allineate.py +++ b/nipype/interfaces/afni/tests/test_auto_Allineate.py @@ -4,150 +4,123 @@ def test_Allineate_inputs(): - input_map = dict(allcostx=dict(argstr='-allcostx |& tee %s', - position=-1, - xor=['out_file', 'out_matrix', 'out_param_file', 'out_weight_file'], - ), - args=dict(argstr='%s', - ), - autobox=dict(argstr='-autobox', - ), - automask=dict(argstr='-automask+%d', - ), - autoweight=dict(argstr='-autoweight%s', - ), - center_of_mass=dict(argstr='-cmass%s', - ), - check=dict(argstr='-check %s', - ), - convergence=dict(argstr='-conv %f', - ), - cost=dict(argstr='-cost %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - epi=dict(argstr='-EPI', - ), - final_interpolation=dict(argstr='-final %s', - ), - fine_blur=dict(argstr='-fineblur %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-source %s', - copyfile=False, - mandatory=True, - ), - in_matrix=dict(argstr='-1Dmatrix_apply %s', - position=-3, - xor=['out_matrix'], - ), - in_param_file=dict(argstr='-1Dparam_apply %s', - xor=['out_param_file'], - ), - interpolation=dict(argstr='-interp %s', - ), - master=dict(argstr='-master %s', - ), - maxrot=dict(argstr='-maxrot %f', - ), - maxscl=dict(argstr='-maxscl %f', - ), - maxshf=dict(argstr='-maxshf %f', - ), - maxshr=dict(argstr='-maxshr %f', - ), - newgrid=dict(argstr='-newgrid %f', - ), - nmatch=dict(argstr='-nmatch %d', - ), - no_pad=dict(argstr='-nopad', - ), - nomask=dict(argstr='-nomask', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - nwarp=dict(argstr='-nwarp %s', - ), - nwarp_fixdep=dict(argstr='-nwarp_fixdep%s', - ), - nwarp_fixmot=dict(argstr='-nwarp_fixmot%s', - ), - one_pass=dict(argstr='-onepass', - ), - out_file=dict(argstr='-prefix %s', - genfile=True, - xor=['allcostx'], - ), - out_matrix=dict(argstr='-1Dmatrix_save %s', - xor=['in_matrix', 'allcostx'], - ), - out_param_file=dict(argstr='-1Dparam_save %s', - xor=['in_param_file', 'allcostx'], - ), - out_weight_file=dict(argstr='-wtprefix %s', - xor=['allcostx'], - ), - outputtype=dict(), - overwrite=dict(argstr='-overwrite', - ), - quiet=dict(argstr='-quiet', - ), - reference=dict(argstr='-base %s', - ), - replacebase=dict(argstr='-replacebase', - ), - replacemeth=dict(argstr='-replacemeth %s', - ), - source_automask=dict(argstr='-source_automask+%d', - ), - source_mask=dict(argstr='-source_mask %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - two_best=dict(argstr='-twobest %d', - ), - two_blur=dict(argstr='-twoblur %f', - ), - two_first=dict(argstr='-twofirst', - ), - two_pass=dict(argstr='-twopass', - ), - usetemp=dict(argstr='-usetemp', - ), - verbose=dict(argstr='-verb', - ), - warp_type=dict(argstr='-warp %s', - ), - warpfreeze=dict(argstr='-warpfreeze', - ), - weight=dict(argstr='-weight %s', - ), - weight_file=dict(argstr='-weight %s', - deprecated='1.0.0', - new_name='weight', - ), - zclip=dict(argstr='-zclip', - ), + input_map = dict( + allcostx=dict( + argstr='-allcostx |& tee %s', + position=-1, + xor=[ + 'out_file', 'out_matrix', 'out_param_file', 'out_weight_file' + ], + ), + args=dict(argstr='%s', ), + autobox=dict(argstr='-autobox', ), + automask=dict(argstr='-automask+%d', ), + autoweight=dict(argstr='-autoweight%s', ), + center_of_mass=dict(argstr='-cmass%s', ), + check=dict(argstr='-check %s', ), + convergence=dict(argstr='-conv %f', ), + cost=dict(argstr='-cost %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi=dict(argstr='-EPI', ), + final_interpolation=dict(argstr='-final %s', ), + fine_blur=dict(argstr='-fineblur %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-source %s', + copyfile=False, + mandatory=True, + ), + in_matrix=dict( + argstr='-1Dmatrix_apply %s', + position=-3, + xor=['out_matrix'], + ), + in_param_file=dict( + argstr='-1Dparam_apply %s', + xor=['out_param_file'], + ), + interpolation=dict(argstr='-interp %s', ), + master=dict(argstr='-master %s', ), + maxrot=dict(argstr='-maxrot %f', ), + maxscl=dict(argstr='-maxscl %f', ), + maxshf=dict(argstr='-maxshf %f', ), + maxshr=dict(argstr='-maxshr %f', ), + newgrid=dict(argstr='-newgrid %f', ), + nmatch=dict(argstr='-nmatch %d', ), + no_pad=dict(argstr='-nopad', ), + nomask=dict(argstr='-nomask', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + nwarp=dict(argstr='-nwarp %s', ), + nwarp_fixdep=dict(argstr='-nwarp_fixdep%s', ), + nwarp_fixmot=dict(argstr='-nwarp_fixmot%s', ), + one_pass=dict(argstr='-onepass', ), + out_file=dict( + argstr='-prefix %s', + genfile=True, + xor=['allcostx'], + ), + out_matrix=dict( + argstr='-1Dmatrix_save %s', + xor=['in_matrix', 'allcostx'], + ), + out_param_file=dict( + argstr='-1Dparam_save %s', + xor=['in_param_file', 'allcostx'], + ), + out_weight_file=dict( + argstr='-wtprefix %s', + xor=['allcostx'], + ), + outputtype=dict(), + overwrite=dict(argstr='-overwrite', ), + quiet=dict(argstr='-quiet', ), + reference=dict(argstr='-base %s', ), + replacebase=dict(argstr='-replacebase', ), + replacemeth=dict(argstr='-replacemeth %s', ), + source_automask=dict(argstr='-source_automask+%d', ), + source_mask=dict(argstr='-source_mask %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + two_best=dict(argstr='-twobest %d', ), + two_blur=dict(argstr='-twoblur %f', ), + two_first=dict(argstr='-twofirst', ), + two_pass=dict(argstr='-twopass', ), + usetemp=dict(argstr='-usetemp', ), + verbose=dict(argstr='-verb', ), + warp_type=dict(argstr='-warp %s', ), + warpfreeze=dict(argstr='-warpfreeze', ), + weight=dict(argstr='-weight %s', ), + weight_file=dict( + argstr='-weight %s', + deprecated='1.0.0', + new_name='weight', + ), + zclip=dict(argstr='-zclip', ), ) inputs = Allineate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Allineate_outputs(): - output_map = dict(allcostx=dict(), - out_file=dict(), - out_matrix=dict(), - out_param_file=dict(), - out_weight_file=dict(), + output_map = dict( + allcostx=dict(), + out_file=dict(), + out_matrix=dict(), + out_param_file=dict(), + out_weight_file=dict(), ) outputs = Allineate.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py b/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py index cc87a813b3..8a2f35f51f 100644 --- a/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py +++ b/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py @@ -4,39 +4,40 @@ def test_AutoTLRC_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - base=dict(argstr='-base %s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - ), - no_ss=dict(argstr='-no_ss', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + base=dict( + argstr='-base %s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + ), + no_ss=dict(argstr='-no_ss', ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AutoTLRC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AutoTLRC_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = AutoTLRC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py b/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py index dab38ec832..fc1f477c36 100644 --- a/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py +++ b/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py @@ -4,54 +4,56 @@ def test_AutoTcorrelate_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - eta2=dict(argstr='-eta2', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - ), - mask_only_targets=dict(argstr='-mask_only_targets', - xor=['mask_source'], - ), - mask_source=dict(argstr='-mask_source %s', - xor=['mask_only_targets'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_similarity_matrix.1D', - ), - outputtype=dict(), - polort=dict(argstr='-polort %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + eta2=dict(argstr='-eta2', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + mask=dict(argstr='-mask %s', ), + mask_only_targets=dict( + argstr='-mask_only_targets', + xor=['mask_source'], + ), + mask_source=dict( + argstr='-mask_source %s', + xor=['mask_only_targets'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_similarity_matrix.1D', + ), + outputtype=dict(), + polort=dict(argstr='-polort %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AutoTcorrelate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AutoTcorrelate_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = AutoTcorrelate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Autobox.py b/nipype/interfaces/afni/tests/test_auto_Autobox.py index 968bcf5839..519f5685da 100644 --- a/nipype/interfaces/afni/tests/test_auto_Autobox.py +++ b/nipype/interfaces/afni/tests/test_auto_Autobox.py @@ -4,50 +4,53 @@ def test_Autobox_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - ), - no_clustering=dict(argstr='-noclust', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_autobox', - ), - outputtype=dict(), - padding=dict(argstr='-npad %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + ), + no_clustering=dict(argstr='-noclust', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_autobox', + ), + outputtype=dict(), + padding=dict(argstr='-npad %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Autobox.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Autobox_outputs(): - output_map = dict(out_file=dict(), - x_max=dict(), - x_min=dict(), - y_max=dict(), - y_min=dict(), - z_max=dict(), - z_min=dict(), + output_map = dict( + out_file=dict(), + x_max=dict(), + x_min=dict(), + y_max=dict(), + y_min=dict(), + z_max=dict(), + z_min=dict(), ) outputs = Autobox.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Automask.py b/nipype/interfaces/afni/tests/test_auto_Automask.py index afc4c7dad5..6ee4cf5f99 100644 --- a/nipype/interfaces/afni/tests/test_auto_Automask.py +++ b/nipype/interfaces/afni/tests/test_auto_Automask.py @@ -4,52 +4,55 @@ def test_Automask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - brain_file=dict(argstr='-apply_prefix %s', - name_source='in_file', - name_template='%s_masked', - ), - clfrac=dict(argstr='-clfrac %s', - ), - dilate=dict(argstr='-dilate %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - erode=dict(argstr='-erode %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_mask', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + brain_file=dict( + argstr='-apply_prefix %s', + name_source='in_file', + name_template='%s_masked', + ), + clfrac=dict(argstr='-clfrac %s', ), + dilate=dict(argstr='-dilate %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + erode=dict(argstr='-erode %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_mask', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Automask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Automask_outputs(): - output_map = dict(brain_file=dict(), - out_file=dict(), + output_map = dict( + brain_file=dict(), + out_file=dict(), ) outputs = Automask.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Axialize.py b/nipype/interfaces/afni/tests/test_auto_Axialize.py index 2b8f1a76be..80c0231344 100644 --- a/nipype/interfaces/afni/tests/test_auto_Axialize.py +++ b/nipype/interfaces/afni/tests/test_auto_Axialize.py @@ -4,55 +4,59 @@ def test_Axialize_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - axial=dict(argstr='-axial', - xor=['coronal', 'sagittal'], - ), - coronal=dict(argstr='-coronal', - xor=['sagittal', 'axial'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-2, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - orientation=dict(argstr='-orient %s', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_axialize', - ), - outputtype=dict(), - sagittal=dict(argstr='-sagittal', - xor=['coronal', 'axial'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verb=dict(argstr='-verb', - ), + input_map = dict( + args=dict(argstr='%s', ), + axial=dict( + argstr='-axial', + xor=['coronal', 'sagittal'], + ), + coronal=dict( + argstr='-coronal', + xor=['sagittal', 'axial'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orientation=dict(argstr='-orient %s', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_axialize', + ), + outputtype=dict(), + sagittal=dict( + argstr='-sagittal', + xor=['coronal', 'axial'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verb=dict(argstr='-verb', ), ) inputs = Axialize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Axialize_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Axialize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Bandpass.py b/nipype/interfaces/afni/tests/test_auto_Bandpass.py index 289c5abe4f..58c57a223a 100644 --- a/nipype/interfaces/afni/tests/test_auto_Bandpass.py +++ b/nipype/interfaces/afni/tests/test_auto_Bandpass.py @@ -4,77 +4,72 @@ def test_Bandpass_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - automask=dict(argstr='-automask', - ), - blur=dict(argstr='-blur %f', - ), - despike=dict(argstr='-despike', - ), - environ=dict(nohash=True, - usedefault=True, - ), - highpass=dict(argstr='%f', - mandatory=True, - position=-3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - localPV=dict(argstr='-localPV %f', - ), - lowpass=dict(argstr='%f', - mandatory=True, - position=-2, - ), - mask=dict(argstr='-mask %s', - position=2, - ), - nfft=dict(argstr='-nfft %d', - ), - no_detrend=dict(argstr='-nodetrend', - ), - normalize=dict(argstr='-norm', - ), - notrans=dict(argstr='-notrans', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - orthogonalize_dset=dict(argstr='-dsort %s', - ), - orthogonalize_file=dict(argstr='-ort %s', - ), - out_file=dict(argstr='-prefix %s', - genfile=True, - name_source='in_file', - name_template='%s_bp', - position=1, - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tr=dict(argstr='-dt %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + automask=dict(argstr='-automask', ), + blur=dict(argstr='-blur %f', ), + despike=dict(argstr='-despike', ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass=dict( + argstr='%f', + mandatory=True, + position=-3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + localPV=dict(argstr='-localPV %f', ), + lowpass=dict( + argstr='%f', + mandatory=True, + position=-2, + ), + mask=dict( + argstr='-mask %s', + position=2, + ), + nfft=dict(argstr='-nfft %d', ), + no_detrend=dict(argstr='-nodetrend', ), + normalize=dict(argstr='-norm', ), + notrans=dict(argstr='-notrans', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orthogonalize_dset=dict(argstr='-dsort %s', ), + orthogonalize_file=dict(argstr='-ort %s', ), + out_file=dict( + argstr='-prefix %s', + genfile=True, + name_source='in_file', + name_template='%s_bp', + position=1, + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tr=dict(argstr='-dt %f', ), ) inputs = Bandpass.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Bandpass_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Bandpass.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_BlurInMask.py b/nipype/interfaces/afni/tests/test_auto_BlurInMask.py index 1311e237cf..4081ee9894 100644 --- a/nipype/interfaces/afni/tests/test_auto_BlurInMask.py +++ b/nipype/interfaces/afni/tests/test_auto_BlurInMask.py @@ -4,59 +4,59 @@ def test_BlurInMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - automask=dict(argstr='-automask', - ), - environ=dict(nohash=True, - usedefault=True, - ), - float_out=dict(argstr='-float', - ), - fwhm=dict(argstr='-FWHM %f', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=1, - ), - mask=dict(argstr='-mask %s', - ), - multimask=dict(argstr='-Mmask %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - options=dict(argstr='%s', - position=2, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_blur', - position=-1, - ), - outputtype=dict(), - preserve=dict(argstr='-preserve', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + automask=dict(argstr='-automask', ), + environ=dict( + nohash=True, + usedefault=True, + ), + float_out=dict(argstr='-float', ), + fwhm=dict( + argstr='-FWHM %f', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=1, + ), + mask=dict(argstr='-mask %s', ), + multimask=dict(argstr='-Mmask %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict( + argstr='%s', + position=2, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_blur', + position=-1, + ), + outputtype=dict(), + preserve=dict(argstr='-preserve', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BlurInMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BlurInMask_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = BlurInMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py b/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py index 5b5c2a34b9..32f72d869d 100644 --- a/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py +++ b/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py @@ -4,50 +4,48 @@ def test_BlurToFWHM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - automask=dict(argstr='-automask', - ), - blurmaster=dict(argstr='-blurmaster %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm=dict(argstr='-FWHM %f', - ), - fwhmxy=dict(argstr='-FWHMxy %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - mandatory=True, - ), - mask=dict(argstr='-blurmaster %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_afni', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + automask=dict(argstr='-automask', ), + blurmaster=dict(argstr='-blurmaster %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict(argstr='-FWHM %f', ), + fwhmxy=dict(argstr='-FWHMxy %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + mandatory=True, + ), + mask=dict(argstr='-blurmaster %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_afni', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BlurToFWHM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BlurToFWHM_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = BlurToFWHM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_BrickStat.py b/nipype/interfaces/afni/tests/test_auto_BrickStat.py index 55abae4c6d..2d81f19b1a 100644 --- a/nipype/interfaces/afni/tests/test_auto_BrickStat.py +++ b/nipype/interfaces/afni/tests/test_auto_BrickStat.py @@ -4,51 +4,48 @@ def test_BrickStat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - position=2, - ), - max=dict(argstr='-max', - ), - mean=dict(argstr='-mean', - ), - min=dict(argstr='-min', - position=1, - ), - percentile=dict(argstr='-percentile %.3f %.3f %.3f', - ), - slow=dict(argstr='-slow', - ), - sum=dict(argstr='-sum', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - var=dict(argstr='-var', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + mask=dict( + argstr='-mask %s', + position=2, + ), + max=dict(argstr='-max', ), + mean=dict(argstr='-mean', ), + min=dict( + argstr='-min', + position=1, + ), + percentile=dict(argstr='-percentile %.3f %.3f %.3f', ), + slow=dict(argstr='-slow', ), + sum=dict(argstr='-sum', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + var=dict(argstr='-var', ), ) inputs = BrickStat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BrickStat_outputs(): - output_map = dict(min_val=dict(), - ) + output_map = dict(min_val=dict(), ) outputs = BrickStat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Bucket.py b/nipype/interfaces/afni/tests/test_auto_Bucket.py index 63ebbc6d5c..6a5cb6613c 100644 --- a/nipype/interfaces/afni/tests/test_auto_Bucket.py +++ b/nipype/interfaces/afni/tests/test_auto_Bucket.py @@ -4,40 +4,43 @@ def test_Bucket_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_template='buck', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_template='buck', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Bucket.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Bucket_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Bucket.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Calc.py b/nipype/interfaces/afni/tests/test_auto_Calc.py index 09fd99c753..0a72baffee 100644 --- a/nipype/interfaces/afni/tests/test_auto_Calc.py +++ b/nipype/interfaces/afni/tests/test_auto_Calc.py @@ -4,60 +4,62 @@ def test_Calc_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - expr=dict(argstr='-expr "%s"', - mandatory=True, - position=3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file_a=dict(argstr='-a %s', - mandatory=True, - position=0, - ), - in_file_b=dict(argstr='-b %s', - position=1, - ), - in_file_c=dict(argstr='-c %s', - position=2, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - other=dict(argstr='', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file_a', - name_template='%s_calc', - ), - outputtype=dict(), - overwrite=dict(argstr='-overwrite', - ), - single_idx=dict(), - start_idx=dict(requires=['stop_idx'], - ), - stop_idx=dict(requires=['start_idx'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + expr=dict( + argstr='-expr "%s"', + mandatory=True, + position=3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file_a=dict( + argstr='-a %s', + mandatory=True, + position=0, + ), + in_file_b=dict( + argstr='-b %s', + position=1, + ), + in_file_c=dict( + argstr='-c %s', + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + other=dict(argstr='', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file_a', + name_template='%s_calc', + ), + outputtype=dict(), + overwrite=dict(argstr='-overwrite', ), + single_idx=dict(), + start_idx=dict(requires=['stop_idx'], ), + stop_idx=dict(requires=['start_idx'], ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Calc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Calc_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Calc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Cat.py b/nipype/interfaces/afni/tests/test_auto_Cat.py index 857c9ade60..d42d87cc67 100644 --- a/nipype/interfaces/afni/tests/test_auto_Cat.py +++ b/nipype/interfaces/afni/tests/test_auto_Cat.py @@ -4,66 +4,78 @@ def test_Cat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=-2, - ), - keepfree=dict(argstr='-nonfixed', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - omitconst=dict(argstr='-nonconst', - ), - out_cint=dict(xor=['out_format', 'out_nice', 'out_double', 'out_fint', 'out_int'], - ), - out_double=dict(argstr='-d', - xor=['out_format', 'out_nice', 'out_int', 'out_fint', 'out_cint'], - ), - out_file=dict(argstr='> %s', - mandatory=True, - position=-1, - ), - out_fint=dict(argstr='-f', - xor=['out_format', 'out_nice', 'out_double', 'out_int', 'out_cint'], - ), - out_format=dict(argstr='-form %s', - xor=['out_int', 'out_nice', 'out_double', 'out_fint', 'out_cint'], - ), - out_int=dict(argstr='-i', - xor=['out_format', 'out_nice', 'out_double', 'out_fint', 'out_cint'], - ), - out_nice=dict(argstr='-n', - xor=['out_format', 'out_int', 'out_double', 'out_fint', 'out_cint'], - ), - outputtype=dict(), - sel=dict(argstr='-sel %s', - ), - stack=dict(argstr='-stack', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + keepfree=dict(argstr='-nonfixed', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + omitconst=dict(argstr='-nonconst', ), + out_cint=dict( + xor=[ + 'out_format', 'out_nice', 'out_double', 'out_fint', 'out_int' + ], ), + out_double=dict( + argstr='-d', + xor=['out_format', 'out_nice', 'out_int', 'out_fint', 'out_cint'], + ), + out_file=dict( + argstr='> %s', + mandatory=True, + position=-1, + ), + out_fint=dict( + argstr='-f', + xor=[ + 'out_format', 'out_nice', 'out_double', 'out_int', 'out_cint' + ], + ), + out_format=dict( + argstr='-form %s', + xor=['out_int', 'out_nice', 'out_double', 'out_fint', 'out_cint'], + ), + out_int=dict( + argstr='-i', + xor=[ + 'out_format', 'out_nice', 'out_double', 'out_fint', 'out_cint' + ], + ), + out_nice=dict( + argstr='-n', + xor=[ + 'out_format', 'out_int', 'out_double', 'out_fint', 'out_cint' + ], + ), + outputtype=dict(), + sel=dict(argstr='-sel %s', ), + stack=dict(argstr='-stack', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Cat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Cat_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Cat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_CatMatvec.py b/nipype/interfaces/afni/tests/test_auto_CatMatvec.py index e94fa12df3..dc1c981bb3 100644 --- a/nipype/interfaces/afni/tests/test_auto_CatMatvec.py +++ b/nipype/interfaces/afni/tests/test_auto_CatMatvec.py @@ -4,55 +4,56 @@ def test_CatMatvec_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fourxfour=dict(argstr='-4x4', - descr='Output matrix in augmented form (last row is 0 0 0 1)This option does not work with -MATRIX or -ONELINE', - xor=['matrix', 'oneline'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - descr='list of tuples of mfiles and associated opkeys', - mandatory=True, - position=-2, - ), - matrix=dict(argstr='-MATRIX', - descr="indicates that the resulting matrix willbe written to outfile in the 'MATRIX(...)' format (FORM 3).This feature could be used, with clever scripting, to inputa matrix directly on the command line to program 3dWarp.", - xor=['oneline', 'fourxfour'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - oneline=dict(argstr='-ONELINE', - descr='indicates that the resulting matrixwill simply be written as 12 numbers on one line.', - xor=['matrix', 'fourxfour'], - ), - out_file=dict(argstr=' > %s', - descr='File to write concattenated matvecs to', - mandatory=True, - position=-1, - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fourxfour=dict( + argstr='-4x4', + xor=['matrix', 'oneline'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + matrix=dict( + argstr='-MATRIX', + xor=['oneline', 'fourxfour'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oneline=dict( + argstr='-ONELINE', + xor=['matrix', 'fourxfour'], + ), + out_file=dict( + argstr=' > %s', + mandatory=True, + position=-1, + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = CatMatvec.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CatMatvec_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = CatMatvec.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_CenterMass.py b/nipype/interfaces/afni/tests/test_auto_CenterMass.py index 34d6d5ec2f..38267a38e9 100644 --- a/nipype/interfaces/afni/tests/test_auto_CenterMass.py +++ b/nipype/interfaces/afni/tests/test_auto_CenterMass.py @@ -4,55 +4,52 @@ def test_CenterMass_inputs(): - input_map = dict(all_rois=dict(argstr='-all_rois', - ), - args=dict(argstr='%s', - ), - automask=dict(argstr='-automask', - ), - cm_file=dict(argstr='> %s', - descr='File to write center of mass to', - hash_files=False, - keep_extension=False, - name_source='in_file', - name_template='%s_cm.out', - position=-1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-2, - ), - local_ijk=dict(argstr='-local_ijk', - ), - mask_file=dict(argstr='-mask %s', - ), - roi_vals=dict(argstr='-roi_vals %s', - ), - set_cm=dict(argstr='-set %f %f %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + all_rois=dict(argstr='-all_rois', ), + args=dict(argstr='%s', ), + automask=dict(argstr='-automask', ), + cm_file=dict( + argstr='> %s', + hash_files=False, + keep_extension=False, + name_source='in_file', + name_template='%s_cm.out', + position=-1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-2, + ), + local_ijk=dict(argstr='-local_ijk', ), + mask_file=dict(argstr='-mask %s', ), + roi_vals=dict(argstr='-roi_vals %s', ), + set_cm=dict(argstr='-set %f %f %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = CenterMass.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CenterMass_outputs(): - output_map = dict(cm=dict(), - cm_file=dict(), - out_file=dict(), + output_map = dict( + cm=dict(), + cm_file=dict(), + out_file=dict(), ) outputs = CenterMass.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_ClipLevel.py b/nipype/interfaces/afni/tests/test_auto_ClipLevel.py index 815d8530ce..6198a48794 100644 --- a/nipype/interfaces/afni/tests/test_auto_ClipLevel.py +++ b/nipype/interfaces/afni/tests/test_auto_ClipLevel.py @@ -4,44 +4,48 @@ def test_ClipLevel_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - doall=dict(argstr='-doall', - position=3, - xor='grad', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad=dict(argstr='-grad %s', - position=3, - xor='doall', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - mfrac=dict(argstr='-mfrac %s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + doall=dict( + argstr='-doall', + position=3, + xor='grad', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad=dict( + argstr='-grad %s', + position=3, + xor='doall', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + mfrac=dict( + argstr='-mfrac %s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ClipLevel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ClipLevel_outputs(): - output_map = dict(clip_val=dict(), - ) + output_map = dict(clip_val=dict(), ) outputs = ClipLevel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Copy.py b/nipype/interfaces/afni/tests/test_auto_Copy.py index 43fa537eb4..25a460a92d 100644 --- a/nipype/interfaces/afni/tests/test_auto_Copy.py +++ b/nipype/interfaces/afni/tests/test_auto_Copy.py @@ -4,45 +4,47 @@ def test_Copy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-2, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='%s', - name_source='in_file', - name_template='%s_copy', - position=-1, - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verb', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='%s', + name_source='in_file', + name_template='%s_copy', + position=-1, + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verb', ), ) inputs = Copy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Copy_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Copy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Deconvolve.py b/nipype/interfaces/afni/tests/test_auto_Deconvolve.py index 972b9a0128..fd3539cd53 100644 --- a/nipype/interfaces/afni/tests/test_auto_Deconvolve.py +++ b/nipype/interfaces/afni/tests/test_auto_Deconvolve.py @@ -4,136 +4,118 @@ def test_Deconvolve_inputs(): - input_map = dict(STATmask=dict(argstr='-STATmask %s', - ), - TR_1D=dict(argstr='-TR_1D %f', - ), - allzero_OK=dict(argstr='-allzero_OK', - ), - args=dict(argstr='%s', - ), - automask=dict(argstr='-automask', - ), - cbucket=dict(argstr='-cbucket %s', - ), - censor=dict(argstr='-censor %s', - ), - dmbase=dict(argstr='-dmbase', - ), - dname=dict(argstr='-D%s=%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - force_TR=dict(argstr='-force_TR %d', - ), - fout=dict(argstr='-fout', - ), - global_times=dict(argstr='-global_times', - xor=['local_times'], - ), - glt_label=dict(argstr='-glt_label %d %s...', - position=-1, - requires=['gltsym'], - ), - gltsym=dict(argstr="-gltsym 'SYM: %s'...", - position=-2, - ), - goforit=dict(argstr='-GOFORIT %i', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='-input %s', - copyfile=False, - position=0, - sep=' ', - ), - input1D=dict(argstr='-input1D %s', - ), - jobs=dict(argstr='-jobs %d', - ), - legendre=dict(argstr='-legendre', - ), - local_times=dict(argstr='-local_times', - xor=['global_times'], - ), - mask=dict(argstr='-mask %s', - ), - noblock=dict(argstr='-noblock', - ), - nocond=dict(argstr='-nocond', - ), - nodmbase=dict(argstr='-nodmbase', - ), - nolegendre=dict(argstr='-nolegendre', - ), - nosvd=dict(argstr='-nosvd', - ), - num_glt=dict(argstr='-num_glt %d', - position=-3, - ), - num_stimts=dict(argstr='-num_stimts %d', - position=-6, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - ortvec=dict(argstr='ortvec %s', - ), - out_file=dict(argstr='-bucket %s', - ), - outputtype=dict(), - polort=dict(argstr='-polort %d', - ), - rmsmin=dict(argstr='-rmsmin %f', - ), - rout=dict(argstr='-rout', - ), - sat=dict(argstr='-sat', - xor=['trans'], - ), - singvals=dict(argstr='-singvals', - ), - stim_label=dict(argstr='-stim_label %d %s...', - position=-4, - requires=['stim_times'], - ), - stim_times=dict(argstr="-stim_times %d %s '%s'...", - position=-5, - ), - stim_times_subtract=dict(argstr='-stim_times_subtract %f', - ), - svd=dict(argstr='-svd', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tout=dict(argstr='-tout', - ), - trans=dict(argstr='-trans', - xor=['sat'], - ), - vout=dict(argstr='-vout', - ), - x1D=dict(argstr='-x1D %s', - ), - x1D_stop=dict(argstr='-x1D_stop', - ), + input_map = dict( + STATmask=dict(argstr='-STATmask %s', ), + TR_1D=dict(argstr='-TR_1D %f', ), + allzero_OK=dict(argstr='-allzero_OK', ), + args=dict(argstr='%s', ), + automask=dict(argstr='-automask', ), + cbucket=dict(argstr='-cbucket %s', ), + censor=dict(argstr='-censor %s', ), + dmbase=dict(argstr='-dmbase', ), + dname=dict(argstr='-D%s=%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_TR=dict(argstr='-force_TR %d', ), + fout=dict(argstr='-fout', ), + global_times=dict( + argstr='-global_times', + xor=['local_times'], + ), + glt_label=dict( + argstr='-glt_label %d %s...', + position=-1, + requires=['gltsym'], + ), + gltsym=dict( + argstr="-gltsym 'SYM: %s'...", + position=-2, + ), + goforit=dict(argstr='-GOFORIT %i', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='-input %s', + copyfile=False, + position=0, + sep=' ', + ), + input1D=dict(argstr='-input1D %s', ), + jobs=dict(argstr='-jobs %d', ), + legendre=dict(argstr='-legendre', ), + local_times=dict( + argstr='-local_times', + xor=['global_times'], + ), + mask=dict(argstr='-mask %s', ), + noblock=dict(argstr='-noblock', ), + nocond=dict(argstr='-nocond', ), + nodmbase=dict(argstr='-nodmbase', ), + nolegendre=dict(argstr='-nolegendre', ), + nosvd=dict(argstr='-nosvd', ), + num_glt=dict( + argstr='-num_glt %d', + position=-3, + ), + num_stimts=dict( + argstr='-num_stimts %d', + position=-6, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + ortvec=dict(argstr='ortvec %s', ), + out_file=dict(argstr='-bucket %s', ), + outputtype=dict(), + polort=dict(argstr='-polort %d', ), + rmsmin=dict(argstr='-rmsmin %f', ), + rout=dict(argstr='-rout', ), + sat=dict( + argstr='-sat', + xor=['trans'], + ), + singvals=dict(argstr='-singvals', ), + stim_label=dict( + argstr='-stim_label %d %s...', + position=-4, + requires=['stim_times'], + ), + stim_times=dict( + argstr="-stim_times %d %s '%s'...", + position=-5, + ), + stim_times_subtract=dict(argstr='-stim_times_subtract %f', ), + svd=dict(argstr='-svd', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tout=dict(argstr='-tout', ), + trans=dict( + argstr='-trans', + xor=['sat'], + ), + vout=dict(argstr='-vout', ), + x1D=dict(argstr='-x1D %s', ), + x1D_stop=dict(argstr='-x1D_stop', ), ) inputs = Deconvolve.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Deconvolve_outputs(): - output_map = dict(cbucket=dict(), - out_file=dict(), - reml_script=dict(), - x1D=dict(), + output_map = dict( + cbucket=dict(), + out_file=dict(), + reml_script=dict(), + x1D=dict(), ) outputs = Deconvolve.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py b/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py index a9b41f29ad..97b76071eb 100644 --- a/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py +++ b/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py @@ -4,56 +4,54 @@ def test_DegreeCentrality_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - autoclip=dict(argstr='-autoclip', - ), - automask=dict(argstr='-automask', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - oned_file=dict(argstr='-out1D %s', - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_afni', - ), - outputtype=dict(), - polort=dict(argstr='-polort %d', - ), - sparsity=dict(argstr='-sparsity %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresh=dict(argstr='-thresh %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + autoclip=dict(argstr='-autoclip', ), + automask=dict(argstr='-automask', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + mask=dict(argstr='-mask %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oned_file=dict(argstr='-out1D %s', ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_afni', + ), + outputtype=dict(), + polort=dict(argstr='-polort %d', ), + sparsity=dict(argstr='-sparsity %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresh=dict(argstr='-thresh %f', ), ) inputs = DegreeCentrality.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DegreeCentrality_outputs(): - output_map = dict(oned_file=dict(), - out_file=dict(), + output_map = dict( + oned_file=dict(), + out_file=dict(), ) outputs = DegreeCentrality.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Despike.py b/nipype/interfaces/afni/tests/test_auto_Despike.py index 21891fb546..078d6072e4 100644 --- a/nipype/interfaces/afni/tests/test_auto_Despike.py +++ b/nipype/interfaces/afni/tests/test_auto_Despike.py @@ -4,42 +4,45 @@ def test_Despike_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_despike', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_despike', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Despike.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Despike_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Despike.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Detrend.py b/nipype/interfaces/afni/tests/test_auto_Detrend.py index 16a1d1fd77..93bb1f359f 100644 --- a/nipype/interfaces/afni/tests/test_auto_Detrend.py +++ b/nipype/interfaces/afni/tests/test_auto_Detrend.py @@ -4,42 +4,45 @@ def test_Detrend_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_detrend', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_detrend', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Detrend.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Detrend_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Detrend.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Dot.py b/nipype/interfaces/afni/tests/test_auto_Dot.py index 9042c7a8f7..360c44f033 100644 --- a/nipype/interfaces/afni/tests/test_auto_Dot.py +++ b/nipype/interfaces/afni/tests/test_auto_Dot.py @@ -4,63 +4,54 @@ def test_Dot_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - demean=dict(argstr='-demean', - ), - docoef=dict(argstr='-docoef', - ), - docor=dict(argstr='-docor', - ), - dodice=dict(argstr='-dodice', - ), - dodot=dict(argstr='-dodot', - ), - doeta2=dict(argstr='-doeta2', - ), - dosums=dict(argstr='-dosums', - ), - environ=dict(nohash=True, - usedefault=True, - ), - full=dict(argstr='-full', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s ...', - position=-2, - ), - mask=dict(argstr='-mask %s', - ), - mrange=dict(argstr='-mrange %s %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr=' |& tee %s', - position=-1, - ), - outputtype=dict(), - show_labels=dict(argstr='-show_labels', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upper=dict(argstr='-upper', - ), + input_map = dict( + args=dict(argstr='%s', ), + demean=dict(argstr='-demean', ), + docoef=dict(argstr='-docoef', ), + docor=dict(argstr='-docor', ), + dodice=dict(argstr='-dodice', ), + dodot=dict(argstr='-dodot', ), + doeta2=dict(argstr='-doeta2', ), + dosums=dict(argstr='-dosums', ), + environ=dict( + nohash=True, + usedefault=True, + ), + full=dict(argstr='-full', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s ...', + position=-2, + ), + mask=dict(argstr='-mask %s', ), + mrange=dict(argstr='-mrange %s %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr=' |& tee %s', + position=-1, + ), + outputtype=dict(), + show_labels=dict(argstr='-show_labels', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upper=dict(argstr='-upper', ), ) inputs = Dot.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Dot_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Dot.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_ECM.py b/nipype/interfaces/afni/tests/test_auto_ECM.py index 4c923ea494..f660681cc4 100644 --- a/nipype/interfaces/afni/tests/test_auto_ECM.py +++ b/nipype/interfaces/afni/tests/test_auto_ECM.py @@ -4,68 +4,58 @@ def test_ECM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - autoclip=dict(argstr='-autoclip', - ), - automask=dict(argstr='-automask', - ), - environ=dict(nohash=True, - usedefault=True, - ), - eps=dict(argstr='-eps %f', - ), - fecm=dict(argstr='-fecm', - ), - full=dict(argstr='-full', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - ), - max_iter=dict(argstr='-max_iter %d', - ), - memory=dict(argstr='-memory %f', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_afni', - ), - outputtype=dict(), - polort=dict(argstr='-polort %d', - ), - scale=dict(argstr='-scale %f', - ), - shift=dict(argstr='-shift %f', - ), - sparsity=dict(argstr='-sparsity %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresh=dict(argstr='-thresh %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + autoclip=dict(argstr='-autoclip', ), + automask=dict(argstr='-automask', ), + environ=dict( + nohash=True, + usedefault=True, + ), + eps=dict(argstr='-eps %f', ), + fecm=dict(argstr='-fecm', ), + full=dict(argstr='-full', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + mask=dict(argstr='-mask %s', ), + max_iter=dict(argstr='-max_iter %d', ), + memory=dict(argstr='-memory %f', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_afni', + ), + outputtype=dict(), + polort=dict(argstr='-polort %d', ), + scale=dict(argstr='-scale %f', ), + shift=dict(argstr='-shift %f', ), + sparsity=dict(argstr='-sparsity %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresh=dict(argstr='-thresh %f', ), ) inputs = ECM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ECM_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ECM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Edge3.py b/nipype/interfaces/afni/tests/test_auto_Edge3.py index 7889b82551..6271826c63 100644 --- a/nipype/interfaces/afni/tests/test_auto_Edge3.py +++ b/nipype/interfaces/afni/tests/test_auto_Edge3.py @@ -4,57 +4,62 @@ def test_Edge3_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - datum=dict(argstr='-datum %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fscale=dict(argstr='-fscale', - xor=['gscale', 'nscale', 'scale_floats'], - ), - gscale=dict(argstr='-gscale', - xor=['fscale', 'nscale', 'scale_floats'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=0, - ), - nscale=dict(argstr='-nscale', - xor=['fscale', 'gscale', 'scale_floats'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - position=-1, - ), - outputtype=dict(), - scale_floats=dict(argstr='-scale_floats %f', - xor=['fscale', 'gscale', 'nscale'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + datum=dict(argstr='-datum %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fscale=dict( + argstr='-fscale', + xor=['gscale', 'nscale', 'scale_floats'], + ), + gscale=dict( + argstr='-gscale', + xor=['fscale', 'nscale', 'scale_floats'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=0, + ), + nscale=dict( + argstr='-nscale', + xor=['fscale', 'gscale', 'scale_floats'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + position=-1, + ), + outputtype=dict(), + scale_floats=dict( + argstr='-scale_floats %f', + xor=['fscale', 'gscale', 'nscale'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = Edge3.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Edge3_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Edge3.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Eval.py b/nipype/interfaces/afni/tests/test_auto_Eval.py index d317f48627..6f1a34f64e 100644 --- a/nipype/interfaces/afni/tests/test_auto_Eval.py +++ b/nipype/interfaces/afni/tests/test_auto_Eval.py @@ -4,60 +4,62 @@ def test_Eval_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - expr=dict(argstr='-expr "%s"', - mandatory=True, - position=3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file_a=dict(argstr='-a %s', - mandatory=True, - position=0, - ), - in_file_b=dict(argstr='-b %s', - position=1, - ), - in_file_c=dict(argstr='-c %s', - position=2, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - other=dict(argstr='', - ), - out1D=dict(argstr='-1D', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file_a', - name_template='%s_calc', - ), - outputtype=dict(), - single_idx=dict(), - start_idx=dict(requires=['stop_idx'], - ), - stop_idx=dict(requires=['start_idx'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + expr=dict( + argstr='-expr "%s"', + mandatory=True, + position=3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file_a=dict( + argstr='-a %s', + mandatory=True, + position=0, + ), + in_file_b=dict( + argstr='-b %s', + position=1, + ), + in_file_c=dict( + argstr='-c %s', + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + other=dict(argstr='', ), + out1D=dict(argstr='-1D', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file_a', + name_template='%s_calc', + ), + outputtype=dict(), + single_idx=dict(), + start_idx=dict(requires=['stop_idx'], ), + stop_idx=dict(requires=['start_idx'], ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Eval.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Eval_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Eval.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_FWHMx.py b/nipype/interfaces/afni/tests/test_auto_FWHMx.py index 669ea278e8..3c119e9dcf 100644 --- a/nipype/interfaces/afni/tests/test_auto_FWHMx.py +++ b/nipype/interfaces/afni/tests/test_auto_FWHMx.py @@ -4,79 +4,87 @@ def test_FWHMx_inputs(): - input_map = dict(acf=dict(argstr='-acf', - usedefault=True, - ), - args=dict(argstr='%s', - ), - arith=dict(argstr='-arith', - xor=['geom'], - ), - automask=dict(argstr='-automask', - usedefault=True, - ), - combine=dict(argstr='-combine', - ), - compat=dict(argstr='-compat', - ), - demed=dict(argstr='-demed', - xor=['detrend'], - ), - detrend=dict(argstr='-detrend', - usedefault=True, - xor=['demed'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - geom=dict(argstr='-geom', - xor=['arith'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - mandatory=True, - ), - mask=dict(argstr='-mask %s', - ), - out_detrend=dict(argstr='-detprefix %s', - keep_extension=False, - name_source='in_file', - name_template='%s_detrend', - ), - out_file=dict(argstr='> %s', - keep_extension=False, - name_source='in_file', - name_template='%s_fwhmx.out', - position=-1, - ), - out_subbricks=dict(argstr='-out %s', - keep_extension=False, - name_source='in_file', - name_template='%s_subbricks.out', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unif=dict(argstr='-unif', - ), + input_map = dict( + acf=dict( + argstr='-acf', + usedefault=True, + ), + args=dict(argstr='%s', ), + arith=dict( + argstr='-arith', + xor=['geom'], + ), + automask=dict( + argstr='-automask', + usedefault=True, + ), + combine=dict(argstr='-combine', ), + compat=dict(argstr='-compat', ), + demed=dict( + argstr='-demed', + xor=['detrend'], + ), + detrend=dict( + argstr='-detrend', + usedefault=True, + xor=['demed'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + geom=dict( + argstr='-geom', + xor=['arith'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + mandatory=True, + ), + mask=dict(argstr='-mask %s', ), + out_detrend=dict( + argstr='-detprefix %s', + keep_extension=False, + name_source='in_file', + name_template='%s_detrend', + ), + out_file=dict( + argstr='> %s', + keep_extension=False, + name_source='in_file', + name_template='%s_fwhmx.out', + position=-1, + ), + out_subbricks=dict( + argstr='-out %s', + keep_extension=False, + name_source='in_file', + name_template='%s_subbricks.out', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unif=dict(argstr='-unif', ), ) inputs = FWHMx.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FWHMx_outputs(): - output_map = dict(acf_param=dict(), - fwhm=dict(), - out_acf=dict(), - out_detrend=dict(), - out_file=dict(), - out_subbricks=dict(), + output_map = dict( + acf_param=dict(), + fwhm=dict(), + out_acf=dict(), + out_detrend=dict(), + out_file=dict(), + out_subbricks=dict(), ) outputs = FWHMx.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Fim.py b/nipype/interfaces/afni/tests/test_auto_Fim.py index e9a60c1d3e..5b0dee2656 100644 --- a/nipype/interfaces/afni/tests/test_auto_Fim.py +++ b/nipype/interfaces/afni/tests/test_auto_Fim.py @@ -4,52 +4,58 @@ def test_Fim_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fim_thr=dict(argstr='-fim_thr %f', - position=3, - ), - ideal_file=dict(argstr='-ideal_file %s', - mandatory=True, - position=2, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out=dict(argstr='-out %s', - position=4, - ), - out_file=dict(argstr='-bucket %s', - name_source='in_file', - name_template='%s_fim', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fim_thr=dict( + argstr='-fim_thr %f', + position=3, + ), + ideal_file=dict( + argstr='-ideal_file %s', + mandatory=True, + position=2, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out=dict( + argstr='-out %s', + position=4, + ), + out_file=dict( + argstr='-bucket %s', + name_source='in_file', + name_template='%s_fim', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Fim.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Fim_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Fim.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Fourier.py b/nipype/interfaces/afni/tests/test_auto_Fourier.py index 02cb81bccc..6f3675dbc1 100644 --- a/nipype/interfaces/afni/tests/test_auto_Fourier.py +++ b/nipype/interfaces/afni/tests/test_auto_Fourier.py @@ -4,50 +4,54 @@ def test_Fourier_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - highpass=dict(argstr='-highpass %f', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - lowpass=dict(argstr='-lowpass %f', - mandatory=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_fourier', - ), - outputtype=dict(), - retrend=dict(argstr='-retrend', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass=dict( + argstr='-highpass %f', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + lowpass=dict( + argstr='-lowpass %f', + mandatory=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_fourier', + ), + outputtype=dict(), + retrend=dict(argstr='-retrend', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Fourier.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Fourier_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Fourier.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_GCOR.py b/nipype/interfaces/afni/tests/test_auto_GCOR.py index b4f2679556..b7163c893a 100644 --- a/nipype/interfaces/afni/tests/test_auto_GCOR.py +++ b/nipype/interfaces/afni/tests/test_auto_GCOR.py @@ -4,41 +4,41 @@ def test_GCOR_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - copyfile=False, - ), - nfirst=dict(argstr='-nfirst %d', - ), - no_demean=dict(argstr='-no_demean', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=-1, + ), + mask=dict( + argstr='-mask %s', + copyfile=False, + ), + nfirst=dict(argstr='-nfirst %d', ), + no_demean=dict(argstr='-no_demean', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GCOR.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GCOR_outputs(): - output_map = dict(out=dict(), - ) + output_map = dict(out=dict(), ) outputs = GCOR.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Hist.py b/nipype/interfaces/afni/tests/test_auto_Hist.py index 64952d334e..2b9ffe4311 100644 --- a/nipype/interfaces/afni/tests/test_auto_Hist.py +++ b/nipype/interfaces/afni/tests/test_auto_Hist.py @@ -4,58 +4,59 @@ def test_Hist_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bin_width=dict(argstr='-binwidth %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=1, - ), - mask=dict(argstr='-mask %s', - ), - max_value=dict(argstr='-max %f', - ), - min_value=dict(argstr='-min %f', - ), - nbin=dict(argstr='-nbin %d', - ), - out_file=dict(argstr='-prefix %s', - keep_extension=False, - name_source=['in_file'], - name_template='%s_hist', - ), - out_show=dict(argstr='> %s', - keep_extension=False, - name_source='in_file', - name_template='%s_hist.out', - position=-1, - ), - showhist=dict(argstr='-showhist', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bin_width=dict(argstr='-binwidth %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=1, + ), + mask=dict(argstr='-mask %s', ), + max_value=dict(argstr='-max %f', ), + min_value=dict(argstr='-min %f', ), + nbin=dict(argstr='-nbin %d', ), + out_file=dict( + argstr='-prefix %s', + keep_extension=False, + name_source=['in_file'], + name_template='%s_hist', + ), + out_show=dict( + argstr='> %s', + keep_extension=False, + name_source='in_file', + name_template='%s_hist.out', + position=-1, + ), + showhist=dict( + argstr='-showhist', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Hist.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Hist_outputs(): - output_map = dict(out_file=dict(), - out_show=dict(), + output_map = dict( + out_file=dict(), + out_show=dict(), ) outputs = Hist.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_LFCD.py b/nipype/interfaces/afni/tests/test_auto_LFCD.py index 7cacf5f728..737ca54002 100644 --- a/nipype/interfaces/afni/tests/test_auto_LFCD.py +++ b/nipype/interfaces/afni/tests/test_auto_LFCD.py @@ -4,52 +4,50 @@ def test_LFCD_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - autoclip=dict(argstr='-autoclip', - ), - automask=dict(argstr='-automask', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_afni', - ), - outputtype=dict(), - polort=dict(argstr='-polort %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresh=dict(argstr='-thresh %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + autoclip=dict(argstr='-autoclip', ), + automask=dict(argstr='-automask', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + mask=dict(argstr='-mask %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_afni', + ), + outputtype=dict(), + polort=dict(argstr='-polort %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresh=dict(argstr='-thresh %f', ), ) inputs = LFCD.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LFCD_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = LFCD.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_MaskTool.py b/nipype/interfaces/afni/tests/test_auto_MaskTool.py index eeaef55562..66ad36e797 100644 --- a/nipype/interfaces/afni/tests/test_auto_MaskTool.py +++ b/nipype/interfaces/afni/tests/test_auto_MaskTool.py @@ -4,64 +4,61 @@ def test_MaskTool_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - count=dict(argstr='-count', - position=2, - ), - datum=dict(argstr='-datum %s', - ), - dilate_inputs=dict(argstr='-dilate_inputs %s', - ), - dilate_results=dict(argstr='-dilate_results %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fill_dirs=dict(argstr='-fill_dirs %s', - requires=['fill_holes'], - ), - fill_holes=dict(argstr='-fill_holes', - ), - frac=dict(argstr='-frac %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=-1, - ), - inter=dict(argstr='-inter', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_mask', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - union=dict(argstr='-union', - ), - verbose=dict(argstr='-verb %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + count=dict( + argstr='-count', + position=2, + ), + datum=dict(argstr='-datum %s', ), + dilate_inputs=dict(argstr='-dilate_inputs %s', ), + dilate_results=dict(argstr='-dilate_results %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_dirs=dict( + argstr='-fill_dirs %s', + requires=['fill_holes'], + ), + fill_holes=dict(argstr='-fill_holes', ), + frac=dict(argstr='-frac %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=-1, + ), + inter=dict(argstr='-inter', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_mask', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + union=dict(argstr='-union', ), + verbose=dict(argstr='-verb %s', ), ) inputs = MaskTool.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MaskTool_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MaskTool.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Maskave.py b/nipype/interfaces/afni/tests/test_auto_Maskave.py index ef7ef9f983..d5b8f25abb 100644 --- a/nipype/interfaces/afni/tests/test_auto_Maskave.py +++ b/nipype/interfaces/afni/tests/test_auto_Maskave.py @@ -4,50 +4,55 @@ def test_Maskave_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-2, - ), - mask=dict(argstr='-mask %s', - position=1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='> %s', - keep_extension=True, - name_source='in_file', - name_template='%s_maskave.1D', - position=-1, - ), - outputtype=dict(), - quiet=dict(argstr='-quiet', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-2, + ), + mask=dict( + argstr='-mask %s', + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='> %s', + keep_extension=True, + name_source='in_file', + name_template='%s_maskave.1D', + position=-1, + ), + outputtype=dict(), + quiet=dict( + argstr='-quiet', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Maskave.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Maskave_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Maskave.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Means.py b/nipype/interfaces/afni/tests/test_auto_Means.py index b1ab57c9b9..466e1e190f 100644 --- a/nipype/interfaces/afni/tests/test_auto_Means.py +++ b/nipype/interfaces/afni/tests/test_auto_Means.py @@ -4,62 +4,57 @@ def test_Means_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - count=dict(argstr='-count', - ), - datum=dict(argstr='-datum %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file_a=dict(argstr='%s', - mandatory=True, - position=-2, - ), - in_file_b=dict(argstr='%s', - position=-1, - ), - mask_inter=dict(argstr='-mask_inter', - ), - mask_union=dict(argstr='-mask_union', - ), - non_zero=dict(argstr='-non_zero', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file_a', - name_template='%s_mean', - ), - outputtype=dict(), - scale=dict(argstr='-%sscale', - ), - sqr=dict(argstr='-sqr', - ), - std_dev=dict(argstr='-stdev', - ), - summ=dict(argstr='-sum', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + count=dict(argstr='-count', ), + datum=dict(argstr='-datum %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file_a=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + in_file_b=dict( + argstr='%s', + position=-1, + ), + mask_inter=dict(argstr='-mask_inter', ), + mask_union=dict(argstr='-mask_union', ), + non_zero=dict(argstr='-non_zero', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file_a', + name_template='%s_mean', + ), + outputtype=dict(), + scale=dict(argstr='-%sscale', ), + sqr=dict(argstr='-sqr', ), + std_dev=dict(argstr='-stdev', ), + summ=dict(argstr='-sum', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Means.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Means_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Means.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Merge.py b/nipype/interfaces/afni/tests/test_auto_Merge.py index efb4a8f301..02c8f9ca27 100644 --- a/nipype/interfaces/afni/tests/test_auto_Merge.py +++ b/nipype/interfaces/afni/tests/test_auto_Merge.py @@ -4,47 +4,50 @@ def test_Merge_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - blurfwhm=dict(argstr='-1blur_fwhm %d', - units='mm', - ), - doall=dict(argstr='-doall', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_merge', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + blurfwhm=dict( + argstr='-1blur_fwhm %d', + units='mm', + ), + doall=dict(argstr='-doall', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_merge', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Merge.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Merge_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Notes.py b/nipype/interfaces/afni/tests/test_auto_Notes.py index 1724c1c7a5..c3a5e1bbaf 100644 --- a/nipype/interfaces/afni/tests/test_auto_Notes.py +++ b/nipype/interfaces/afni/tests/test_auto_Notes.py @@ -4,52 +4,52 @@ def test_Notes_inputs(): - input_map = dict(add=dict(argstr='-a "%s"', - ), - add_history=dict(argstr='-h "%s"', - xor=['rep_history'], - ), - args=dict(argstr='%s', - ), - delete=dict(argstr='-d %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='%s', - ), - outputtype=dict(), - rep_history=dict(argstr='-HH "%s"', - xor=['add_history'], - ), - ses=dict(argstr='-ses', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + add=dict(argstr='-a "%s"', ), + add_history=dict( + argstr='-h "%s"', + xor=['rep_history'], + ), + args=dict(argstr='%s', ), + delete=dict(argstr='-d %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict(argstr='%s', ), + outputtype=dict(), + rep_history=dict( + argstr='-HH "%s"', + xor=['add_history'], + ), + ses=dict(argstr='-ses', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Notes.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Notes_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Notes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_NwarpApply.py b/nipype/interfaces/afni/tests/test_auto_NwarpApply.py index 1df8eb30ea..68ec40b6f0 100644 --- a/nipype/interfaces/afni/tests/test_auto_NwarpApply.py +++ b/nipype/interfaces/afni/tests/test_auto_NwarpApply.py @@ -4,55 +4,55 @@ def test_NwarpApply_inputs(): - input_map = dict(ainterp=dict(argstr='-ainterp %s', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-source %s', - mandatory=True, - ), - interp=dict(argstr='-interp %s', - ), - inv_warp=dict(argstr='-iwarp', - ), - master=dict(argstr='-master %s', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_Nwarp', - ), - quiet=dict(argstr='-quiet', - xor=['verb'], - ), - short=dict(argstr='-short', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verb=dict(argstr='-verb', - xor=['quiet'], - ), - warp=dict(argstr='-nwarp %s', - mandatory=True, - ), + input_map = dict( + ainterp=dict(argstr='-ainterp %s', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-source %s', + mandatory=True, + ), + interp=dict(argstr='-interp %s', ), + inv_warp=dict(argstr='-iwarp', ), + master=dict(argstr='-master %s', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_Nwarp', + ), + quiet=dict( + argstr='-quiet', + xor=['verb'], + ), + short=dict(argstr='-short', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verb=dict( + argstr='-verb', + xor=['quiet'], + ), + warp=dict( + argstr='-nwarp %s', + mandatory=True, + ), ) inputs = NwarpApply.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NwarpApply_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = NwarpApply.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_NwarpCat.py b/nipype/interfaces/afni/tests/test_auto_NwarpCat.py index fcfae528cf..065e2b8b61 100644 --- a/nipype/interfaces/afni/tests/test_auto_NwarpCat.py +++ b/nipype/interfaces/afni/tests/test_auto_NwarpCat.py @@ -4,52 +4,49 @@ def test_NwarpCat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - expad=dict(argstr='-expad %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - descr='list of tuples of 3D warps and associated functions', - mandatory=True, - position=-1, - ), - interp=dict(argstr='-interp %s', - ), - inv_warp=dict(argstr='-iwarp', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_files', - name_template='%s_NwarpCat', - ), - outputtype=dict(), - space=dict(argstr='-space %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verb=dict(argstr='-verb', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + expad=dict(argstr='-expad %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + interp=dict(argstr='-interp %s', ), + inv_warp=dict(argstr='-iwarp', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_files', + name_template='%s_NwarpCat', + ), + outputtype=dict(), + space=dict(argstr='-space %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verb=dict(argstr='-verb', ), ) inputs = NwarpCat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NwarpCat_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = NwarpCat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py b/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py index ae62f3924a..1404e58eca 100644 --- a/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py +++ b/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py @@ -4,61 +4,54 @@ def test_OneDToolPy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - censor_motion=dict(argstr='-censor_motion %f %s', - ), - censor_prev_TR=dict(argstr='-censor_prev_TR', - ), - demean=dict(argstr='-demean', - ), - derivative=dict(argstr='-derivative', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-infile %s', - mandatory=True, - ), - out_file=dict(argstr='-write %s', - xor=['show_cormat_warnings'], - ), - outputtype=dict(), - py27_path=dict(usedefault=True, - ), - set_nruns=dict(argstr='-set_nruns %d', - ), - show_censor_count=dict(argstr='-show_censor_count', - ), - show_cormat_warnings=dict(argstr='-show_cormat_warnings |& tee %s', - position=-1, - usedefault=False, - xor=['out_file'], - ), - show_indices_interest=dict(argstr='-show_indices_interest', - ), - show_trs_run=dict(argstr='-show_trs_run %d', - ), - show_trs_uncensored=dict(argstr='-show_trs_uncensored %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + censor_motion=dict(argstr='-censor_motion %f %s', ), + censor_prev_TR=dict(argstr='-censor_prev_TR', ), + demean=dict(argstr='-demean', ), + derivative=dict(argstr='-derivative', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-infile %s', + mandatory=True, + ), + out_file=dict( + argstr='-write %s', + xor=['show_cormat_warnings'], + ), + outputtype=dict(), + py27_path=dict(usedefault=True, ), + set_nruns=dict(argstr='-set_nruns %d', ), + show_censor_count=dict(argstr='-show_censor_count', ), + show_cormat_warnings=dict( + argstr='-show_cormat_warnings |& tee %s', + position=-1, + usedefault=False, + xor=['out_file'], + ), + show_indices_interest=dict(argstr='-show_indices_interest', ), + show_trs_run=dict(argstr='-show_trs_run %d', ), + show_trs_uncensored=dict(argstr='-show_trs_uncensored %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = OneDToolPy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_OneDToolPy_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = OneDToolPy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_OutlierCount.py b/nipype/interfaces/afni/tests/test_auto_OutlierCount.py index 7d8b28ab65..3fd22356ed 100644 --- a/nipype/interfaces/afni/tests/test_auto_OutlierCount.py +++ b/nipype/interfaces/afni/tests/test_auto_OutlierCount.py @@ -4,69 +4,77 @@ def test_OutlierCount_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - autoclip=dict(argstr='-autoclip', - usedefault=True, - xor=['mask'], - ), - automask=dict(argstr='-automask', - usedefault=True, - xor=['mask'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - fraction=dict(argstr='-fraction', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - interval=dict(argstr='-range', - usedefault=True, - ), - legendre=dict(argstr='-legendre', - usedefault=True, - ), - mask=dict(argstr='-mask %s', - xor=['autoclip', 'automask'], - ), - out_file=dict(keep_extension=False, - name_source=['in_file'], - name_template='%s_outliers', - ), - outliers_file=dict(argstr='-save %s', - keep_extension=True, - name_source=['in_file'], - name_template='%s_outliers', - output_name='out_outliers', - ), - polort=dict(argstr='-polort %d', - ), - qthr=dict(argstr='-qthr %.5f', - ), - save_outliers=dict(usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + autoclip=dict( + argstr='-autoclip', + usedefault=True, + xor=['mask'], + ), + automask=dict( + argstr='-automask', + usedefault=True, + xor=['mask'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fraction=dict( + argstr='-fraction', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + interval=dict( + argstr='-range', + usedefault=True, + ), + legendre=dict( + argstr='-legendre', + usedefault=True, + ), + mask=dict( + argstr='-mask %s', + xor=['autoclip', 'automask'], + ), + out_file=dict( + keep_extension=False, + name_source=['in_file'], + name_template='%s_outliers', + ), + outliers_file=dict( + argstr='-save %s', + keep_extension=True, + name_source=['in_file'], + name_template='%s_outliers', + output_name='out_outliers', + ), + polort=dict(argstr='-polort %d', ), + qthr=dict(argstr='-qthr %.5f', ), + save_outliers=dict(usedefault=True, ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = OutlierCount.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_OutlierCount_outputs(): - output_map = dict(out_file=dict(), - out_outliers=dict(), + output_map = dict( + out_file=dict(), + out_outliers=dict(), ) outputs = OutlierCount.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_QualityIndex.py b/nipype/interfaces/afni/tests/test_auto_QualityIndex.py index 09a3855b92..2cd76eacfe 100644 --- a/nipype/interfaces/afni/tests/test_auto_QualityIndex.py +++ b/nipype/interfaces/afni/tests/test_auto_QualityIndex.py @@ -4,61 +4,68 @@ def test_QualityIndex_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - autoclip=dict(argstr='-autoclip', - usedefault=True, - xor=['mask'], - ), - automask=dict(argstr='-automask', - usedefault=True, - xor=['mask'], - ), - clip=dict(argstr='-clip %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - interval=dict(argstr='-range', - usedefault=True, - ), - mask=dict(argstr='-mask %s', - xor=['autoclip', 'automask'], - ), - out_file=dict(argstr='> %s', - keep_extension=False, - name_source=['in_file'], - name_template='%s_tqual', - position=-1, - ), - quadrant=dict(argstr='-quadrant', - usedefault=True, - ), - spearman=dict(argstr='-spearman', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + autoclip=dict( + argstr='-autoclip', + usedefault=True, + xor=['mask'], + ), + automask=dict( + argstr='-automask', + usedefault=True, + xor=['mask'], + ), + clip=dict(argstr='-clip %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + interval=dict( + argstr='-range', + usedefault=True, + ), + mask=dict( + argstr='-mask %s', + xor=['autoclip', 'automask'], + ), + out_file=dict( + argstr='> %s', + keep_extension=False, + name_source=['in_file'], + name_template='%s_tqual', + position=-1, + ), + quadrant=dict( + argstr='-quadrant', + usedefault=True, + ), + spearman=dict( + argstr='-spearman', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = QualityIndex.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_QualityIndex_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = QualityIndex.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Qwarp.py b/nipype/interfaces/afni/tests/test_auto_Qwarp.py index 8a40687a10..0558fdcd1f 100644 --- a/nipype/interfaces/afni/tests/test_auto_Qwarp.py +++ b/nipype/interfaces/afni/tests/test_auto_Qwarp.py @@ -4,162 +4,171 @@ def test_Qwarp_inputs(): - input_map = dict(Qfinal=dict(argstr='-Qfinal', - ), - Qonly=dict(argstr='-Qonly', - ), - allineate=dict(argstr='-allineate', - ), - allineate_opts=dict(argstr='-allineate_opts %s', - xand=['allineate'], - ), - allsave=dict(argstr='-allsave', - xor=['nopadWARP', 'duplo', 'plusminus'], - ), - args=dict(argstr='%s', - ), - ballopt=dict(argstr='-ballopt', - xor=['workhard', 'boxopt'], - ), - base_file=dict(argstr='-base %s', - copyfile=False, - mandatory=True, - ), - baxopt=dict(argstr='-boxopt', - xor=['workhard', 'ballopt'], - ), - blur=dict(argstr='-blur %s', - ), - duplo=dict(argstr='-duplo', - xor=['gridlist', 'maxlev', 'inilev', 'iniwarp', 'plusminus', 'allsave'], - ), - emask=dict(argstr='-emask %s', - copyfile=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - expad=dict(argstr='-expad %d', - xor=['nopadWARP'], - ), - gridlist=dict(argstr='-gridlist %s', - copyfile=False, - xor=['duplo', 'plusminus'], - ), - hel=dict(argstr='-hel', - xor=['nmi', 'mi', 'lpc', 'lpa', 'pear'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-source %s', - copyfile=False, - mandatory=True, - ), - inilev=dict(argstr='-inilev %d', - xor=['duplo'], - ), - iniwarp=dict(argstr='-iniwarp %s', - xor=['duplo'], - ), - iwarp=dict(argstr='-iwarp', - xor=['plusminus'], - ), - lpa=dict(argstr='-lpa', - xor=['nmi', 'mi', 'lpc', 'hel', 'pear'], - ), - lpc=dict(argstr='-lpc', - position=-2, - xor=['nmi', 'mi', 'hel', 'lpa', 'pear'], - ), - maxlev=dict(argstr='-maxlev %d', - position=-1, - xor=['duplo'], - ), - mi=dict(argstr='-mi', - xor=['mi', 'hel', 'lpc', 'lpa', 'pear'], - ), - minpatch=dict(argstr='-minpatch %d', - ), - nmi=dict(argstr='-nmi', - xor=['nmi', 'hel', 'lpc', 'lpa', 'pear'], - ), - noXdis=dict(argstr='-noXdis', - ), - noYdis=dict(argstr='-noYdis', - ), - noZdis=dict(argstr='-noZdis', - ), - noneg=dict(argstr='-noneg', - ), - nopad=dict(argstr='-nopad', - ), - nopadWARP=dict(argstr='-nopadWARP', - xor=['allsave', 'expad'], - ), - nopenalty=dict(argstr='-nopenalty', - ), - nowarp=dict(argstr='-nowarp', - ), - noweight=dict(argstr='-noweight', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - genfile=True, - name_source=['in_file'], - name_template='%s_QW', - ), - out_weight_file=dict(argstr='-wtprefix %s', - ), - outputtype=dict(), - overwrite=dict(argstr='-overwrite', - ), - pblur=dict(argstr='-pblur %s', - ), - pear=dict(argstr='-pear', - ), - penfac=dict(argstr='-penfac %f', - ), - plusminus=dict(argstr='-plusminus', - xor=['duplo', 'allsave', 'iwarp'], - ), - quiet=dict(argstr='-quiet', - xor=['verb'], - ), - resample=dict(argstr='-resample', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verb=dict(argstr='-verb', - xor=['quiet'], - ), - wball=dict(argstr='-wball %s', - ), - weight=dict(argstr='-weight %s', - ), - wmask=dict(argstr='-wpass %s %f', - ), - workhard=dict(argstr='-workhard', - xor=['boxopt', 'ballopt'], - ), + input_map = dict( + Qfinal=dict(argstr='-Qfinal', ), + Qonly=dict(argstr='-Qonly', ), + allineate=dict(argstr='-allineate', ), + allineate_opts=dict( + argstr='-allineate_opts %s', + requires=['allineate'], + ), + allsave=dict( + argstr='-allsave', + xor=['nopadWARP', 'duplo', 'plusminus'], + ), + args=dict(argstr='%s', ), + ballopt=dict( + argstr='-ballopt', + xor=['workhard', 'boxopt'], + ), + base_file=dict( + argstr='-base %s', + copyfile=False, + mandatory=True, + ), + baxopt=dict( + argstr='-boxopt', + xor=['workhard', 'ballopt'], + ), + blur=dict(argstr='-blur %s', ), + duplo=dict( + argstr='-duplo', + xor=[ + 'gridlist', 'maxlev', 'inilev', 'iniwarp', 'plusminus', + 'allsave' + ], + ), + emask=dict( + argstr='-emask %s', + copyfile=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expad=dict( + argstr='-expad %d', + xor=['nopadWARP'], + ), + gridlist=dict( + argstr='-gridlist %s', + copyfile=False, + xor=['duplo', 'plusminus'], + ), + hel=dict( + argstr='-hel', + xor=['nmi', 'mi', 'lpc', 'lpa', 'pear'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-source %s', + copyfile=False, + mandatory=True, + ), + inilev=dict( + argstr='-inilev %d', + xor=['duplo'], + ), + iniwarp=dict( + argstr='-iniwarp %s', + xor=['duplo'], + ), + iwarp=dict( + argstr='-iwarp', + xor=['plusminus'], + ), + lpa=dict( + argstr='-lpa', + xor=['nmi', 'mi', 'lpc', 'hel', 'pear'], + ), + lpc=dict( + argstr='-lpc', + position=-2, + xor=['nmi', 'mi', 'hel', 'lpa', 'pear'], + ), + maxlev=dict( + argstr='-maxlev %d', + position=-1, + xor=['duplo'], + ), + mi=dict( + argstr='-mi', + xor=['mi', 'hel', 'lpc', 'lpa', 'pear'], + ), + minpatch=dict(argstr='-minpatch %d', ), + nmi=dict( + argstr='-nmi', + xor=['nmi', 'hel', 'lpc', 'lpa', 'pear'], + ), + noXdis=dict(argstr='-noXdis', ), + noYdis=dict(argstr='-noYdis', ), + noZdis=dict(argstr='-noZdis', ), + noneg=dict(argstr='-noneg', ), + nopad=dict(argstr='-nopad', ), + nopadWARP=dict( + argstr='-nopadWARP', + xor=['allsave', 'expad'], + ), + nopenalty=dict(argstr='-nopenalty', ), + nowarp=dict(argstr='-nowarp', ), + noweight=dict(argstr='-noweight', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + genfile=True, + name_source=['in_file'], + name_template='%s_QW', + ), + out_weight_file=dict(argstr='-wtprefix %s', ), + outputtype=dict(), + overwrite=dict(argstr='-overwrite', ), + pblur=dict(argstr='-pblur %s', ), + pear=dict(argstr='-pear', ), + penfac=dict(argstr='-penfac %f', ), + plusminus=dict( + argstr='-plusminus', + xor=['duplo', 'allsave', 'iwarp'], + ), + quiet=dict( + argstr='-quiet', + xor=['verb'], + ), + resample=dict(argstr='-resample', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verb=dict( + argstr='-verb', + xor=['quiet'], + ), + wball=dict(argstr='-wball %s', ), + weight=dict(argstr='-weight %s', ), + wmask=dict(argstr='-wpass %s %f', ), + workhard=dict( + argstr='-workhard', + xor=['boxopt', 'ballopt'], + ), ) inputs = Qwarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Qwarp_outputs(): - output_map = dict(base_warp=dict(), - source_warp=dict(), - warped_base=dict(), - warped_source=dict(), - weights=dict(), + output_map = dict( + base_warp=dict(), + source_warp=dict(), + warped_base=dict(), + warped_source=dict(), + weights=dict(), ) outputs = Qwarp.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py b/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py index b0c4f00c74..176541d936 100644 --- a/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py +++ b/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py @@ -4,49 +4,48 @@ def test_QwarpPlusMinus_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - base_file=dict(argstr='-base %s', - copyfile=False, - mandatory=True, - ), - blur=dict(argstr='-blur %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - minpatch=dict(argstr='-minpatch %d', - ), - nopadWARP=dict(argstr='-nopadWARP', - ), - noweight=dict(argstr='-noweight', - ), - pblur=dict(argstr='-pblur %s', - ), - source_file=dict(argstr='-source %s', - copyfile=False, - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + base_file=dict( + argstr='-base %s', + copyfile=False, + mandatory=True, + ), + blur=dict(argstr='-blur %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + minpatch=dict(argstr='-minpatch %d', ), + nopadWARP=dict(argstr='-nopadWARP', ), + noweight=dict(argstr='-noweight', ), + pblur=dict(argstr='-pblur %s', ), + source_file=dict( + argstr='-source %s', + copyfile=False, + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = QwarpPlusMinus.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_QwarpPlusMinus_outputs(): - output_map = dict(base_warp=dict(), - source_warp=dict(), - warped_base=dict(), - warped_source=dict(), + output_map = dict( + base_warp=dict(), + source_warp=dict(), + warped_base=dict(), + warped_source=dict(), ) outputs = QwarpPlusMinus.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_ROIStats.py b/nipype/interfaces/afni/tests/test_auto_ROIStats.py index 2b720fb0c6..1b13234549 100644 --- a/nipype/interfaces/afni/tests/test_auto_ROIStats.py +++ b/nipype/interfaces/afni/tests/test_auto_ROIStats.py @@ -4,42 +4,46 @@ def test_ROIStats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - position=3, - ), - mask_f2short=dict(argstr='-mask_f2short', - position=2, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + mask=dict( + argstr='-mask %s', + position=3, + ), + mask_f2short=dict( + argstr='-mask_f2short', + position=2, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ROIStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ROIStats_outputs(): - output_map = dict(stats=dict(), - ) + output_map = dict(stats=dict(), ) outputs = ROIStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Refit.py b/nipype/interfaces/afni/tests/test_auto_Refit.py index 81b72ea2cb..5380fa1af9 100644 --- a/nipype/interfaces/afni/tests/test_auto_Refit.py +++ b/nipype/interfaces/afni/tests/test_auto_Refit.py @@ -4,66 +4,51 @@ def test_Refit_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - atrcopy=dict(argstr='-atrcopy %s %s', - ), - atrfloat=dict(argstr='-atrfloat %s %s', - ), - atrint=dict(argstr='-atrint %s %s', - ), - atrstring=dict(argstr='-atrstring %s %s', - ), - deoblique=dict(argstr='-deoblique', - ), - duporigin_file=dict(argstr='-duporigin %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-1, - ), - nosaveatr=dict(argstr='-nosaveatr', - ), - saveatr=dict(argstr='-saveatr', - ), - space=dict(argstr='-space %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xdel=dict(argstr='-xdel %f', - ), - xorigin=dict(argstr='-xorigin %s', - ), - xyzscale=dict(argstr='-xyzscale %f', - ), - ydel=dict(argstr='-ydel %f', - ), - yorigin=dict(argstr='-yorigin %s', - ), - zdel=dict(argstr='-zdel %f', - ), - zorigin=dict(argstr='-zorigin %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + atrcopy=dict(argstr='-atrcopy %s %s', ), + atrfloat=dict(argstr='-atrfloat %s %s', ), + atrint=dict(argstr='-atrint %s %s', ), + atrstring=dict(argstr='-atrstring %s %s', ), + deoblique=dict(argstr='-deoblique', ), + duporigin_file=dict(argstr='-duporigin %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-1, + ), + nosaveatr=dict(argstr='-nosaveatr', ), + saveatr=dict(argstr='-saveatr', ), + space=dict(argstr='-space %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xdel=dict(argstr='-xdel %f', ), + xorigin=dict(argstr='-xorigin %s', ), + xyzscale=dict(argstr='-xyzscale %f', ), + ydel=dict(argstr='-ydel %f', ), + yorigin=dict(argstr='-yorigin %s', ), + zdel=dict(argstr='-zdel %f', ), + zorigin=dict(argstr='-zorigin %s', ), ) inputs = Refit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Refit_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Refit.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Remlfit.py b/nipype/interfaces/afni/tests/test_auto_Remlfit.py index 3511414f11..44a04db20f 100644 --- a/nipype/interfaces/afni/tests/test_auto_Remlfit.py +++ b/nipype/interfaces/afni/tests/test_auto_Remlfit.py @@ -4,126 +4,112 @@ def test_Remlfit_inputs(): - input_map = dict(STATmask=dict(argstr='-STATmask %s', - ), - addbase=dict(argstr='-addbase %s', - copyfile=False, - sep=' ', - ), - args=dict(argstr='%s', - ), - automask=dict(argstr='-automask', - usedefault=True, - ), - dsort=dict(argstr='-dsort %s', - copyfile=False, - ), - dsort_nods=dict(argstr='-dsort_nods', - requires=['dsort'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - errts_file=dict(argstr='-Rerrts %s', - ), - fitts_file=dict(argstr='-Rfitts %s', - ), - fout=dict(argstr='-fout', - ), - glt_file=dict(argstr='-Rglt %s', - ), - gltsym=dict(argstr='-gltsym "%s" %s...', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='-input "%s"', - copyfile=False, - mandatory=True, - sep=' ', - ), - mask=dict(argstr='-mask %s', - ), - matim=dict(argstr='-matim %s', - xor=['matrix'], - ), - matrix=dict(argstr='-matrix %s', - mandatory=True, - ), - nobout=dict(argstr='-nobout', - ), - nodmbase=dict(argstr='-nodmbase', - requires=['addbase', 'dsort'], - ), - nofdr=dict(argstr='-noFDR', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - obeta=dict(argstr='-Obeta %s', - ), - obuck=dict(argstr='-Obuck %s', - ), - oerrts=dict(argstr='-Oerrts %s', - ), - ofitts=dict(argstr='-Ofitts %s', - ), - oglt=dict(argstr='-Oglt %s', - ), - out_file=dict(argstr='-Rbuck %s', - ), - outputtype=dict(), - ovar=dict(argstr='-Ovar %s', - ), - polort=dict(argstr='-polort %d', - xor=['matrix'], - ), - quiet=dict(argstr='-quiet', - ), - rbeta_file=dict(argstr='-Rbeta %s', - ), - rout=dict(argstr='-rout', - ), - slibase=dict(argstr='-slibase %s', - ), - slibase_sm=dict(argstr='-slibase_sm %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tout=dict(argstr='-tout', - ), - usetemp=dict(argstr='-usetemp', - ), - var_file=dict(argstr='-Rvar %s', - ), - verb=dict(argstr='-verb', - ), - wherr_file=dict(argstr='-Rwherr %s', - ), + input_map = dict( + STATmask=dict(argstr='-STATmask %s', ), + addbase=dict( + argstr='-addbase %s', + copyfile=False, + sep=' ', + ), + args=dict(argstr='%s', ), + automask=dict( + argstr='-automask', + usedefault=True, + ), + dsort=dict( + argstr='-dsort %s', + copyfile=False, + ), + dsort_nods=dict( + argstr='-dsort_nods', + requires=['dsort'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + errts_file=dict(argstr='-Rerrts %s', ), + fitts_file=dict(argstr='-Rfitts %s', ), + fout=dict(argstr='-fout', ), + glt_file=dict(argstr='-Rglt %s', ), + gltsym=dict(argstr='-gltsym "%s" %s...', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='-input "%s"', + copyfile=False, + mandatory=True, + sep=' ', + ), + mask=dict(argstr='-mask %s', ), + matim=dict( + argstr='-matim %s', + xor=['matrix'], + ), + matrix=dict( + argstr='-matrix %s', + mandatory=True, + ), + nobout=dict(argstr='-nobout', ), + nodmbase=dict( + argstr='-nodmbase', + requires=['addbase', 'dsort'], + ), + nofdr=dict(argstr='-noFDR', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + obeta=dict(argstr='-Obeta %s', ), + obuck=dict(argstr='-Obuck %s', ), + oerrts=dict(argstr='-Oerrts %s', ), + ofitts=dict(argstr='-Ofitts %s', ), + oglt=dict(argstr='-Oglt %s', ), + out_file=dict(argstr='-Rbuck %s', ), + outputtype=dict(), + ovar=dict(argstr='-Ovar %s', ), + polort=dict( + argstr='-polort %d', + xor=['matrix'], + ), + quiet=dict(argstr='-quiet', ), + rbeta_file=dict(argstr='-Rbeta %s', ), + rout=dict(argstr='-rout', ), + slibase=dict(argstr='-slibase %s', ), + slibase_sm=dict(argstr='-slibase_sm %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tout=dict(argstr='-tout', ), + usetemp=dict(argstr='-usetemp', ), + var_file=dict(argstr='-Rvar %s', ), + verb=dict(argstr='-verb', ), + wherr_file=dict(argstr='-Rwherr %s', ), ) inputs = Remlfit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Remlfit_outputs(): - output_map = dict(errts_file=dict(), - fitts_file=dict(), - glt_file=dict(), - obeta=dict(), - obuck=dict(), - oerrts=dict(), - ofitts=dict(), - oglt=dict(), - out_file=dict(), - ovar=dict(), - rbeta_file=dict(), - var_file=dict(), - wherr_file=dict(), + output_map = dict( + errts_file=dict(), + fitts_file=dict(), + glt_file=dict(), + obeta=dict(), + obuck=dict(), + oerrts=dict(), + ofitts=dict(), + oglt=dict(), + out_file=dict(), + ovar=dict(), + rbeta_file=dict(), + var_file=dict(), + wherr_file=dict(), ) outputs = Remlfit.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Resample.py b/nipype/interfaces/afni/tests/test_auto_Resample.py index 21215f56f1..077fe68805 100644 --- a/nipype/interfaces/afni/tests/test_auto_Resample.py +++ b/nipype/interfaces/afni/tests/test_auto_Resample.py @@ -4,50 +4,49 @@ def test_Resample_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inset %s', - copyfile=False, - mandatory=True, - position=-1, - ), - master=dict(argstr='-master %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - orientation=dict(argstr='-orient %s', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_resample', - ), - outputtype=dict(), - resample_mode=dict(argstr='-rmode %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel_size=dict(argstr='-dxyz %f %f %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inset %s', + copyfile=False, + mandatory=True, + position=-1, + ), + master=dict(argstr='-master %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orientation=dict(argstr='-orient %s', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_resample', + ), + outputtype=dict(), + resample_mode=dict(argstr='-rmode %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel_size=dict(argstr='-dxyz %f %f %f', ), ) inputs = Resample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Resample_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Retroicor.py b/nipype/interfaces/afni/tests/test_auto_Retroicor.py index 57b23f6a18..1fcab2d471 100644 --- a/nipype/interfaces/afni/tests/test_auto_Retroicor.py +++ b/nipype/interfaces/afni/tests/test_auto_Retroicor.py @@ -4,63 +4,72 @@ def test_Retroicor_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - card=dict(argstr='-card %s', - position=-2, - ), - cardphase=dict(argstr='-cardphase %s', - hash_files=False, - position=-6, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - order=dict(argstr='-order %s', - position=-5, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_retroicor', - position=1, - ), - outputtype=dict(), - resp=dict(argstr='-resp %s', - position=-3, - ), - respphase=dict(argstr='-respphase %s', - hash_files=False, - position=-7, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='-threshold %d', - position=-4, - ), + input_map = dict( + args=dict(argstr='%s', ), + card=dict( + argstr='-card %s', + position=-2, + ), + cardphase=dict( + argstr='-cardphase %s', + hash_files=False, + position=-6, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + order=dict( + argstr='-order %s', + position=-5, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_retroicor', + position=1, + ), + outputtype=dict(), + resp=dict( + argstr='-resp %s', + position=-3, + ), + respphase=dict( + argstr='-respphase %s', + hash_files=False, + position=-7, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict( + argstr='-threshold %d', + position=-4, + ), ) inputs = Retroicor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Retroicor_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Retroicor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_SVMTest.py b/nipype/interfaces/afni/tests/test_auto_SVMTest.py index dbda1b28c5..709e2fb533 100644 --- a/nipype/interfaces/afni/tests/test_auto_SVMTest.py +++ b/nipype/interfaces/afni/tests/test_auto_SVMTest.py @@ -4,54 +4,52 @@ def test_SVMTest_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - classout=dict(argstr='-classout', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-testvol %s', - mandatory=True, - ), - model=dict(argstr='-model %s', - mandatory=True, - ), - multiclass=dict(argstr='-multiclass %s', - ), - nodetrend=dict(argstr='-nodetrend', - ), - nopredcensord=dict(argstr='-nopredcensord', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - options=dict(argstr='%s', - ), - out_file=dict(argstr='-predictions %s', - name_template='%s_predictions', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - testlabels=dict(argstr='-testlabels %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + classout=dict(argstr='-classout', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-testvol %s', + mandatory=True, + ), + model=dict( + argstr='-model %s', + mandatory=True, + ), + multiclass=dict(argstr='-multiclass %s', ), + nodetrend=dict(argstr='-nodetrend', ), + nopredcensord=dict(argstr='-nopredcensord', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict(argstr='%s', ), + out_file=dict( + argstr='-predictions %s', + name_template='%s_predictions', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + testlabels=dict(argstr='-testlabels %s', ), ) inputs = SVMTest.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SVMTest_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SVMTest.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_SVMTrain.py b/nipype/interfaces/afni/tests/test_auto_SVMTrain.py index a0ba4dba42..80858d4faa 100644 --- a/nipype/interfaces/afni/tests/test_auto_SVMTrain.py +++ b/nipype/interfaces/afni/tests/test_auto_SVMTrain.py @@ -4,74 +4,76 @@ def test_SVMTrain_inputs(): - input_map = dict(alphas=dict(argstr='-alpha %s', - name_source='in_file', - name_template='%s_alphas', - suffix='_alphas', - ), - args=dict(argstr='%s', - ), - censor=dict(argstr='-censor %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-trainvol %s', - copyfile=False, - mandatory=True, - ), - kernel=dict(argstr='-kernel %s', - ), - mask=dict(argstr='-mask %s', - copyfile=False, - position=-1, - ), - max_iterations=dict(argstr='-max_iterations %d', - ), - model=dict(argstr='-model %s', - name_source='in_file', - name_template='%s_model', - suffix='_model', - ), - nomodelmask=dict(argstr='-nomodelmask', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - options=dict(argstr='%s', - ), - out_file=dict(argstr='-bucket %s', - name_source='in_file', - name_template='%s_vectors', - suffix='_bucket', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trainlabels=dict(argstr='-trainlabels %s', - ), - ttype=dict(argstr='-type %s', - mandatory=True, - ), - w_out=dict(argstr='-wout', - ), + input_map = dict( + alphas=dict( + argstr='-alpha %s', + name_source='in_file', + name_template='%s_alphas', + suffix='_alphas', + ), + args=dict(argstr='%s', ), + censor=dict(argstr='-censor %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-trainvol %s', + copyfile=False, + mandatory=True, + ), + kernel=dict(argstr='-kernel %s', ), + mask=dict( + argstr='-mask %s', + copyfile=False, + position=-1, + ), + max_iterations=dict(argstr='-max_iterations %d', ), + model=dict( + argstr='-model %s', + name_source='in_file', + name_template='%s_model', + suffix='_model', + ), + nomodelmask=dict(argstr='-nomodelmask', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict(argstr='%s', ), + out_file=dict( + argstr='-bucket %s', + name_source='in_file', + name_template='%s_vectors', + suffix='_bucket', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trainlabels=dict(argstr='-trainlabels %s', ), + ttype=dict( + argstr='-type %s', + mandatory=True, + ), + w_out=dict(argstr='-wout', ), ) inputs = SVMTrain.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SVMTrain_outputs(): - output_map = dict(alphas=dict(), - model=dict(), - out_file=dict(), + output_map = dict( + alphas=dict(), + model=dict(), + out_file=dict(), ) outputs = SVMTrain.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Seg.py b/nipype/interfaces/afni/tests/test_auto_Seg.py index 1069121f79..176eb09501 100644 --- a/nipype/interfaces/afni/tests/test_auto_Seg.py +++ b/nipype/interfaces/afni/tests/test_auto_Seg.py @@ -4,56 +4,49 @@ def test_Seg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bias_classes=dict(argstr='-bias_classes %s', - ), - bias_fwhm=dict(argstr='-bias_fwhm %f', - ), - blur_meth=dict(argstr='-blur_meth %s', - ), - bmrf=dict(argstr='-bmrf %f', - ), - classes=dict(argstr='-classes %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-anat %s', - copyfile=True, - mandatory=True, - position=-1, - ), - main_N=dict(argstr='-main_N %d', - ), - mask=dict(argstr='-mask %s', - mandatory=True, - position=-2, - ), - mixfloor=dict(argstr='-mixfloor %f', - ), - mixfrac=dict(argstr='-mixfrac %s', - ), - prefix=dict(argstr='-prefix %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bias_classes=dict(argstr='-bias_classes %s', ), + bias_fwhm=dict(argstr='-bias_fwhm %f', ), + blur_meth=dict(argstr='-blur_meth %s', ), + bmrf=dict(argstr='-bmrf %f', ), + classes=dict(argstr='-classes %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-anat %s', + copyfile=True, + mandatory=True, + position=-1, + ), + main_N=dict(argstr='-main_N %d', ), + mask=dict( + argstr='-mask %s', + mandatory=True, + position=-2, + ), + mixfloor=dict(argstr='-mixfloor %f', ), + mixfrac=dict(argstr='-mixfrac %s', ), + prefix=dict(argstr='-prefix %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Seg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Seg_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Seg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_SkullStrip.py b/nipype/interfaces/afni/tests/test_auto_SkullStrip.py index 97277301c3..8ce7fb8af2 100644 --- a/nipype/interfaces/afni/tests/test_auto_SkullStrip.py +++ b/nipype/interfaces/afni/tests/test_auto_SkullStrip.py @@ -4,42 +4,45 @@ def test_SkullStrip_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_skullstrip', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_skullstrip', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SkullStrip.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SkullStrip_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SkullStrip.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Synthesize.py b/nipype/interfaces/afni/tests/test_auto_Synthesize.py index bd95eca3a5..921c2a8688 100644 --- a/nipype/interfaces/afni/tests/test_auto_Synthesize.py +++ b/nipype/interfaces/afni/tests/test_auto_Synthesize.py @@ -4,53 +4,55 @@ def test_Synthesize_inputs(): - input_map = dict(TR=dict(argstr='-TR %f', - ), - args=dict(argstr='%s', - ), - cbucket=dict(argstr='-cbucket %s', - copyfile=False, - mandatory=True, - ), - cenfill=dict(argstr='-cenfill %s', - ), - dry_run=dict(argstr='-dry', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matrix=dict(argstr='-matrix %s', - copyfile=False, - mandatory=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_template='syn', - ), - outputtype=dict(), - select=dict(argstr='-select %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + TR=dict(argstr='-TR %f', ), + args=dict(argstr='%s', ), + cbucket=dict( + argstr='-cbucket %s', + copyfile=False, + mandatory=True, + ), + cenfill=dict(argstr='-cenfill %s', ), + dry_run=dict(argstr='-dry', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matrix=dict( + argstr='-matrix %s', + copyfile=False, + mandatory=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_template='syn', + ), + outputtype=dict(), + select=dict( + argstr='-select %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Synthesize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Synthesize_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Synthesize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCat.py b/nipype/interfaces/afni/tests/test_auto_TCat.py index f74a122828..b0b79166c1 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCat.py +++ b/nipype/interfaces/afni/tests/test_auto_TCat.py @@ -4,47 +4,50 @@ def test_TCat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr=' %s', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_files', - name_template='%s_tcat', - ), - outputtype=dict(), - rlt=dict(argstr='-rlt%s', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verb', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr=' %s', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_files', + name_template='%s_tcat', + ), + outputtype=dict(), + rlt=dict( + argstr='-rlt%s', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verb', ), ) inputs = TCat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TCat_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TCat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py b/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py index 58fc2108e3..18ebfe6782 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py +++ b/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py @@ -4,44 +4,48 @@ def test_TCatSubBrick_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s%s ...', - copyfile=False, - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - genfile=True, - ), - outputtype=dict(), - rlt=dict(argstr='-rlt%s', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s%s ...', + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + genfile=True, + ), + outputtype=dict(), + rlt=dict( + argstr='-rlt%s', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TCatSubBrick.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TCatSubBrick_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TCatSubBrick.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCorr1D.py b/nipype/interfaces/afni/tests/test_auto_TCorr1D.py index a57d8a6a10..a0c5a026ed 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCorr1D.py +++ b/nipype/interfaces/afni/tests/test_auto_TCorr1D.py @@ -4,63 +4,71 @@ def test_TCorr1D_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ktaub=dict(argstr=' -ktaub', - position=1, - xor=['pearson', 'spearman', 'quadrant'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - keep_extension=True, - name_source='xset', - name_template='%s_correlation.nii.gz', - ), - outputtype=dict(), - pearson=dict(argstr=' -pearson', - position=1, - xor=['spearman', 'quadrant', 'ktaub'], - ), - quadrant=dict(argstr=' -quadrant', - position=1, - xor=['pearson', 'spearman', 'ktaub'], - ), - spearman=dict(argstr=' -spearman', - position=1, - xor=['pearson', 'quadrant', 'ktaub'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xset=dict(argstr=' %s', - copyfile=False, - mandatory=True, - position=-2, - ), - y_1d=dict(argstr=' %s', - mandatory=True, - position=-1, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ktaub=dict( + argstr=' -ktaub', + position=1, + xor=['pearson', 'spearman', 'quadrant'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + keep_extension=True, + name_source='xset', + name_template='%s_correlation.nii.gz', + ), + outputtype=dict(), + pearson=dict( + argstr=' -pearson', + position=1, + xor=['spearman', 'quadrant', 'ktaub'], + ), + quadrant=dict( + argstr=' -quadrant', + position=1, + xor=['pearson', 'spearman', 'ktaub'], + ), + spearman=dict( + argstr=' -spearman', + position=1, + xor=['pearson', 'quadrant', 'ktaub'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xset=dict( + argstr=' %s', + copyfile=False, + mandatory=True, + position=-2, + ), + y_1d=dict( + argstr=' %s', + mandatory=True, + position=-1, + ), ) inputs = TCorr1D.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TCorr1D_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TCorr1D.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCorrMap.py b/nipype/interfaces/afni/tests/test_auto_TCorrMap.py index 17f5e4ff19..de25cd2dc0 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCorrMap.py +++ b/nipype/interfaces/afni/tests/test_auto_TCorrMap.py @@ -4,129 +4,146 @@ def test_TCorrMap_inputs(): - input_map = dict(absolute_threshold=dict(argstr='-Thresh %f %s', - name_source='in_file', - suffix='_thresh', - xor=('absolute_threshold', 'var_absolute_threshold', 'var_absolute_threshold_normalize'), - ), - args=dict(argstr='%s', - ), - automask=dict(argstr='-automask', - ), - average_expr=dict(argstr='-Aexpr %s %s', - name_source='in_file', - suffix='_aexpr', - xor=('average_expr', 'average_expr_nonzero', 'sum_expr'), - ), - average_expr_nonzero=dict(argstr='-Cexpr %s %s', - name_source='in_file', - suffix='_cexpr', - xor=('average_expr', 'average_expr_nonzero', 'sum_expr'), - ), - bandpass=dict(argstr='-bpass %f %f', - ), - blur_fwhm=dict(argstr='-Gblur %f', - ), - correlation_maps=dict(argstr='-CorrMap %s', - name_source='in_file', - ), - correlation_maps_masked=dict(argstr='-CorrMask %s', - name_source='in_file', - ), - environ=dict(nohash=True, - usedefault=True, - ), - expr=dict(), - histogram=dict(argstr='-Hist %d %s', - name_source='in_file', - suffix='_hist', - ), - histogram_bin_numbers=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - ), - mask=dict(argstr='-mask %s', - ), - mean_file=dict(argstr='-Mean %s', - name_source='in_file', - suffix='_mean', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_file'], - name_template='%s_afni', - ), - outputtype=dict(), - pmean=dict(argstr='-Pmean %s', - name_source='in_file', - suffix='_pmean', - ), - polort=dict(argstr='-polort %d', - ), - qmean=dict(argstr='-Qmean %s', - name_source='in_file', - suffix='_qmean', - ), - regress_out_timeseries=dict(argstr='-ort %s', - ), - seeds=dict(argstr='-seed %s', - xor='seeds_width', - ), - seeds_width=dict(argstr='-Mseed %f', - xor='seeds', - ), - sum_expr=dict(argstr='-Sexpr %s %s', - name_source='in_file', - suffix='_sexpr', - xor=('average_expr', 'average_expr_nonzero', 'sum_expr'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresholds=dict(), - var_absolute_threshold=dict(argstr='-VarThresh %f %f %f %s', - name_source='in_file', - suffix='_varthresh', - xor=('absolute_threshold', 'var_absolute_threshold', 'var_absolute_threshold_normalize'), - ), - var_absolute_threshold_normalize=dict(argstr='-VarThreshN %f %f %f %s', - name_source='in_file', - suffix='_varthreshn', - xor=('absolute_threshold', 'var_absolute_threshold', 'var_absolute_threshold_normalize'), - ), - zmean=dict(argstr='-Zmean %s', - name_source='in_file', - suffix='_zmean', - ), + input_map = dict( + absolute_threshold=dict( + argstr='-Thresh %f %s', + name_source='in_file', + suffix='_thresh', + xor=('absolute_threshold', 'var_absolute_threshold', + 'var_absolute_threshold_normalize'), + ), + args=dict(argstr='%s', ), + automask=dict(argstr='-automask', ), + average_expr=dict( + argstr='-Aexpr %s %s', + name_source='in_file', + suffix='_aexpr', + xor=('average_expr', 'average_expr_nonzero', 'sum_expr'), + ), + average_expr_nonzero=dict( + argstr='-Cexpr %s %s', + name_source='in_file', + suffix='_cexpr', + xor=('average_expr', 'average_expr_nonzero', 'sum_expr'), + ), + bandpass=dict(argstr='-bpass %f %f', ), + blur_fwhm=dict(argstr='-Gblur %f', ), + correlation_maps=dict( + argstr='-CorrMap %s', + name_source='in_file', + ), + correlation_maps_masked=dict( + argstr='-CorrMask %s', + name_source='in_file', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expr=dict(), + histogram=dict( + argstr='-Hist %d %s', + name_source='in_file', + suffix='_hist', + ), + histogram_bin_numbers=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + ), + mask=dict(argstr='-mask %s', ), + mean_file=dict( + argstr='-Mean %s', + name_source='in_file', + suffix='_mean', + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_file'], + name_template='%s_afni', + ), + outputtype=dict(), + pmean=dict( + argstr='-Pmean %s', + name_source='in_file', + suffix='_pmean', + ), + polort=dict(argstr='-polort %d', ), + qmean=dict( + argstr='-Qmean %s', + name_source='in_file', + suffix='_qmean', + ), + regress_out_timeseries=dict(argstr='-ort %s', ), + seeds=dict( + argstr='-seed %s', + xor='seeds_width', + ), + seeds_width=dict( + argstr='-Mseed %f', + xor='seeds', + ), + sum_expr=dict( + argstr='-Sexpr %s %s', + name_source='in_file', + suffix='_sexpr', + xor=('average_expr', 'average_expr_nonzero', 'sum_expr'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresholds=dict(), + var_absolute_threshold=dict( + argstr='-VarThresh %f %f %f %s', + name_source='in_file', + suffix='_varthresh', + xor=('absolute_threshold', 'var_absolute_threshold', + 'var_absolute_threshold_normalize'), + ), + var_absolute_threshold_normalize=dict( + argstr='-VarThreshN %f %f %f %s', + name_source='in_file', + suffix='_varthreshn', + xor=('absolute_threshold', 'var_absolute_threshold', + 'var_absolute_threshold_normalize'), + ), + zmean=dict( + argstr='-Zmean %s', + name_source='in_file', + suffix='_zmean', + ), ) inputs = TCorrMap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TCorrMap_outputs(): - output_map = dict(absolute_threshold=dict(), - average_expr=dict(), - average_expr_nonzero=dict(), - correlation_maps=dict(), - correlation_maps_masked=dict(), - histogram=dict(), - mean_file=dict(), - pmean=dict(), - qmean=dict(), - sum_expr=dict(), - var_absolute_threshold=dict(), - var_absolute_threshold_normalize=dict(), - zmean=dict(), + output_map = dict( + absolute_threshold=dict(), + average_expr=dict(), + average_expr_nonzero=dict(), + correlation_maps=dict(), + correlation_maps_masked=dict(), + histogram=dict(), + mean_file=dict(), + pmean=dict(), + qmean=dict(), + sum_expr=dict(), + var_absolute_threshold=dict(), + var_absolute_threshold_normalize=dict(), + zmean=dict(), ) outputs = TCorrMap.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_TCorrelate.py b/nipype/interfaces/afni/tests/test_auto_TCorrelate.py index 8857a2affe..ebea4ff1d9 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCorrelate.py +++ b/nipype/interfaces/afni/tests/test_auto_TCorrelate.py @@ -4,51 +4,53 @@ def test_TCorrelate_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='xset', - name_template='%s_tcorr', - ), - outputtype=dict(), - pearson=dict(argstr='-pearson', - ), - polort=dict(argstr='-polort %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xset=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-2, - ), - yset=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='xset', + name_template='%s_tcorr', + ), + outputtype=dict(), + pearson=dict(argstr='-pearson', ), + polort=dict(argstr='-polort %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xset=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-2, + ), + yset=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), ) inputs = TCorrelate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TCorrelate_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TCorrelate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TNorm.py b/nipype/interfaces/afni/tests/test_auto_TNorm.py index fbb11ec746..b581134fae 100644 --- a/nipype/interfaces/afni/tests/test_auto_TNorm.py +++ b/nipype/interfaces/afni/tests/test_auto_TNorm.py @@ -4,54 +4,51 @@ def test_TNorm_inputs(): - input_map = dict(L1fit=dict(argstr='-L1fit', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - norm1=dict(argstr='-norm1', - ), - norm2=dict(argstr='-norm2', - ), - normR=dict(argstr='-normR', - ), - normx=dict(argstr='-normx', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_tnorm', - ), - outputtype=dict(), - polort=dict(argstr='-polort %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + L1fit=dict(argstr='-L1fit', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + norm1=dict(argstr='-norm1', ), + norm2=dict(argstr='-norm2', ), + normR=dict(argstr='-normR', ), + normx=dict(argstr='-normx', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_tnorm', + ), + outputtype=dict(), + polort=dict(argstr='-polort %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TNorm.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TNorm_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TNorm.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TShift.py b/nipype/interfaces/afni/tests/test_auto_TShift.py index ee7663bbd6..a1c6acea41 100644 --- a/nipype/interfaces/afni/tests/test_auto_TShift.py +++ b/nipype/interfaces/afni/tests/test_auto_TShift.py @@ -4,60 +4,59 @@ def test_TShift_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore=dict(argstr='-ignore %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - interp=dict(argstr='-%s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_tshift', - ), - outputtype=dict(), - rlt=dict(argstr='-rlt', - ), - rltplus=dict(argstr='-rlt+', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tpattern=dict(argstr='-tpattern %s', - ), - tr=dict(argstr='-TR %s', - ), - tslice=dict(argstr='-slice %s', - xor=['tzero'], - ), - tzero=dict(argstr='-tzero %s', - xor=['tslice'], - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore=dict(argstr='-ignore %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + interp=dict(argstr='-%s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_tshift', + ), + outputtype=dict(), + rlt=dict(argstr='-rlt', ), + rltplus=dict(argstr='-rlt+', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tpattern=dict(argstr='-tpattern %s', ), + tr=dict(argstr='-TR %s', ), + tslice=dict( + argstr='-slice %s', + xor=['tzero'], + ), + tzero=dict( + argstr='-tzero %s', + xor=['tslice'], + ), ) inputs = TShift.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TShift_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TShift.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TStat.py b/nipype/interfaces/afni/tests/test_auto_TStat.py index 2315d81512..df10637f54 100644 --- a/nipype/interfaces/afni/tests/test_auto_TStat.py +++ b/nipype/interfaces/afni/tests/test_auto_TStat.py @@ -4,46 +4,47 @@ def test_TStat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - mask=dict(argstr='-mask %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - options=dict(argstr='%s', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_tstat', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + mask=dict(argstr='-mask %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict(argstr='%s', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_tstat', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TStat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TStat_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TStat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_To3D.py b/nipype/interfaces/afni/tests/test_auto_To3D.py index 5f39148167..e4f14c26f5 100644 --- a/nipype/interfaces/afni/tests/test_auto_To3D.py +++ b/nipype/interfaces/afni/tests/test_auto_To3D.py @@ -4,51 +4,49 @@ def test_To3D_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - assumemosaic=dict(argstr='-assume_dicom_mosaic', - ), - datatype=dict(argstr='-datum %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - filetype=dict(argstr='-%s', - ), - funcparams=dict(argstr='-time:zt %s alt+z2', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_folder=dict(argstr='%s/*.dcm', - mandatory=True, - position=-1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source=['in_folder'], - name_template='%s', - ), - outputtype=dict(), - skipoutliers=dict(argstr='-skip_outliers', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + assumemosaic=dict(argstr='-assume_dicom_mosaic', ), + datatype=dict(argstr='-datum %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + filetype=dict(argstr='-%s', ), + funcparams=dict(argstr='-time:zt %s alt+z2', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_folder=dict( + argstr='%s/*.dcm', + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source=['in_folder'], + name_template='%s', + ), + outputtype=dict(), + skipoutliers=dict(argstr='-skip_outliers', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = To3D.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_To3D_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = To3D.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Undump.py b/nipype/interfaces/afni/tests/test_auto_Undump.py index b5f1041b60..43cf4f9b2a 100644 --- a/nipype/interfaces/afni/tests/test_auto_Undump.py +++ b/nipype/interfaces/afni/tests/test_auto_Undump.py @@ -4,57 +4,52 @@ def test_Undump_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - coordinates_specification=dict(argstr='-%s', - ), - datatype=dict(argstr='-datum %s', - ), - default_value=dict(argstr='-dval %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fill_value=dict(argstr='-fval %f', - ), - head_only=dict(argstr='-head_only', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-master %s', - copyfile=False, - mandatory=True, - position=-1, - ), - mask_file=dict(argstr='-mask %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - orient=dict(argstr='-orient %s', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - ), - outputtype=dict(), - srad=dict(argstr='-srad %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + coordinates_specification=dict(argstr='-%s', ), + datatype=dict(argstr='-datum %s', ), + default_value=dict(argstr='-dval %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_value=dict(argstr='-fval %f', ), + head_only=dict(argstr='-head_only', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-master %s', + copyfile=False, + mandatory=True, + position=-1, + ), + mask_file=dict(argstr='-mask %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orient=dict(argstr='-orient %s', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + ), + outputtype=dict(), + srad=dict(argstr='-srad %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Undump.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Undump_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Undump.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Unifize.py b/nipype/interfaces/afni/tests/test_auto_Unifize.py index 1d82e5aed5..266dc2ff92 100644 --- a/nipype/interfaces/afni/tests/test_auto_Unifize.py +++ b/nipype/interfaces/afni/tests/test_auto_Unifize.py @@ -4,64 +4,61 @@ def test_Unifize_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cl_frac=dict(argstr='-clfrac %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - epi=dict(argstr='-EPI', - requires=['no_duplo', 't2'], - xor=['gm'], - ), - gm=dict(argstr='-GM', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-input %s', - copyfile=False, - mandatory=True, - position=-1, - ), - no_duplo=dict(argstr='-noduplo', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_unifized', - ), - outputtype=dict(), - quiet=dict(argstr='-quiet', - ), - rbt=dict(argstr='-rbt %f %f %f', - ), - scale_file=dict(argstr='-ssave %s', - ), - t2=dict(argstr='-T2', - ), - t2_up=dict(argstr='-T2up %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - urad=dict(argstr='-Urad %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + cl_frac=dict(argstr='-clfrac %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi=dict( + argstr='-EPI', + requires=['no_duplo', 't2'], + xor=['gm'], + ), + gm=dict(argstr='-GM', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-input %s', + copyfile=False, + mandatory=True, + position=-1, + ), + no_duplo=dict(argstr='-noduplo', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_unifized', + ), + outputtype=dict(), + quiet=dict(argstr='-quiet', ), + rbt=dict(argstr='-rbt %f %f %f', ), + scale_file=dict(argstr='-ssave %s', ), + t2=dict(argstr='-T2', ), + t2_up=dict(argstr='-T2up %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + urad=dict(argstr='-Urad %s', ), ) inputs = Unifize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Unifize_outputs(): - output_map = dict(out_file=dict(), - scale_file=dict(), + output_map = dict( + out_file=dict(), + scale_file=dict(), ) outputs = Unifize.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Volreg.py b/nipype/interfaces/afni/tests/test_auto_Volreg.py index a8aa8a8832..89878ad107 100644 --- a/nipype/interfaces/afni/tests/test_auto_Volreg.py +++ b/nipype/interfaces/afni/tests/test_auto_Volreg.py @@ -4,74 +4,80 @@ def test_Volreg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - basefile=dict(argstr='-base %s', - position=-6, - ), - copyorigin=dict(argstr='-twodup', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - interp=dict(argstr='-%s', - ), - md1d_file=dict(argstr='-maxdisp1D %s', - keep_extension=True, - name_source='in_file', - name_template='%s_md.1D', - position=-4, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - oned_file=dict(argstr='-1Dfile %s', - keep_extension=True, - name_source='in_file', - name_template='%s.1D', - ), - oned_matrix_save=dict(argstr='-1Dmatrix_save %s', - keep_extension=True, - name_source='in_file', - name_template='%s.aff12.1D', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_volreg', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timeshift=dict(argstr='-tshift 0', - ), - verbose=dict(argstr='-verbose', - ), - zpad=dict(argstr='-zpad %d', - position=-5, - ), + input_map = dict( + args=dict(argstr='%s', ), + basefile=dict( + argstr='-base %s', + position=-6, + ), + copyorigin=dict(argstr='-twodup', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + interp=dict(argstr='-%s', ), + md1d_file=dict( + argstr='-maxdisp1D %s', + keep_extension=True, + name_source='in_file', + name_template='%s_md.1D', + position=-4, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oned_file=dict( + argstr='-1Dfile %s', + keep_extension=True, + name_source='in_file', + name_template='%s.1D', + ), + oned_matrix_save=dict( + argstr='-1Dmatrix_save %s', + keep_extension=True, + name_source='in_file', + name_template='%s.aff12.1D', + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_volreg', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timeshift=dict(argstr='-tshift 0', ), + verbose=dict(argstr='-verbose', ), + zpad=dict( + argstr='-zpad %d', + position=-5, + ), ) inputs = Volreg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Volreg_outputs(): - output_map = dict(md1d_file=dict(), - oned_file=dict(), - oned_matrix_save=dict(), - out_file=dict(), + output_map = dict( + md1d_file=dict(), + oned_file=dict(), + oned_matrix_save=dict(), + out_file=dict(), ) outputs = Volreg.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Warp.py b/nipype/interfaces/afni/tests/test_auto_Warp.py index ef2d23d460..442a5de6c7 100644 --- a/nipype/interfaces/afni/tests/test_auto_Warp.py +++ b/nipype/interfaces/afni/tests/test_auto_Warp.py @@ -4,62 +4,55 @@ def test_Warp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - deoblique=dict(argstr='-deoblique', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gridset=dict(argstr='-gridset %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - interp=dict(argstr='-%s', - ), - matparent=dict(argstr='-matparent %s', - ), - mni2tta=dict(argstr='-mni2tta', - ), - newgrid=dict(argstr='-newgrid %f', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - oblique_parent=dict(argstr='-oblique_parent %s', - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_warp', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tta2mni=dict(argstr='-tta2mni', - ), - verbose=dict(argstr='-verb', - ), - zpad=dict(argstr='-zpad %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + deoblique=dict(argstr='-deoblique', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridset=dict(argstr='-gridset %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + interp=dict(argstr='-%s', ), + matparent=dict(argstr='-matparent %s', ), + mni2tta=dict(argstr='-mni2tta', ), + newgrid=dict(argstr='-newgrid %f', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oblique_parent=dict(argstr='-oblique_parent %s', ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_warp', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tta2mni=dict(argstr='-tta2mni', ), + verbose=dict(argstr='-verb', ), + zpad=dict(argstr='-zpad %d', ), ) inputs = Warp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Warp_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Warp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_ZCutUp.py b/nipype/interfaces/afni/tests/test_auto_ZCutUp.py index 70cb544bc5..3243e9e7a0 100644 --- a/nipype/interfaces/afni/tests/test_auto_ZCutUp.py +++ b/nipype/interfaces/afni/tests/test_auto_ZCutUp.py @@ -4,44 +4,46 @@ def test_ZCutUp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - keep=dict(argstr='-keep %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_source='in_file', - name_template='%s_zcutup', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + keep=dict(argstr='-keep %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_source='in_file', + name_template='%s_zcutup', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ZCutUp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ZCutUp_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ZCutUp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Zcat.py b/nipype/interfaces/afni/tests/test_auto_Zcat.py index 6de330b5ae..d15deb91f0 100644 --- a/nipype/interfaces/afni/tests/test_auto_Zcat.py +++ b/nipype/interfaces/afni/tests/test_auto_Zcat.py @@ -4,51 +4,54 @@ def test_Zcat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - datum=dict(argstr='-datum %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fscale=dict(argstr='-fscale', - xor=['nscale'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - nscale=dict(argstr='-nscale', - xor=['fscale'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_template='zcat', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verb=dict(argstr='-verb', - ), + input_map = dict( + args=dict(argstr='%s', ), + datum=dict(argstr='-datum %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fscale=dict( + argstr='-fscale', + xor=['nscale'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + nscale=dict( + argstr='-nscale', + xor=['fscale'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_template='zcat', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verb=dict(argstr='-verb', ), ) inputs = Zcat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Zcat_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Zcat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Zeropad.py b/nipype/interfaces/afni/tests/test_auto_Zeropad.py index 5a23c1a46d..669431dbb3 100644 --- a/nipype/interfaces/afni/tests/test_auto_Zeropad.py +++ b/nipype/interfaces/afni/tests/test_auto_Zeropad.py @@ -4,77 +4,92 @@ def test_Zeropad_inputs(): - input_map = dict(A=dict(argstr='-A %i', - xor=['master'], - ), - AP=dict(argstr='-AP %i', - xor=['master'], - ), - I=dict(argstr='-I %i', - xor=['master'], - ), - IS=dict(argstr='-IS %i', - xor=['master'], - ), - L=dict(argstr='-L %i', - xor=['master'], - ), - P=dict(argstr='-P %i', - xor=['master'], - ), - R=dict(argstr='-R %i', - xor=['master'], - ), - RL=dict(argstr='-RL %i', - xor=['master'], - ), - S=dict(argstr='-S %i', - xor=['master'], - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - master=dict(argstr='-master %s', - xor=['I', 'S', 'A', 'P', 'L', 'R', 'z', 'RL', 'AP', 'IS', 'mm'], - ), - mm=dict(argstr='-mm', - xor=['master'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='-prefix %s', - name_template='zeropad', - ), - outputtype=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - z=dict(argstr='-z %i', - xor=['master'], - ), + input_map = dict( + A=dict( + argstr='-A %i', + xor=['master'], + ), + AP=dict( + argstr='-AP %i', + xor=['master'], + ), + I=dict( + argstr='-I %i', + xor=['master'], + ), + IS=dict( + argstr='-IS %i', + xor=['master'], + ), + L=dict( + argstr='-L %i', + xor=['master'], + ), + P=dict( + argstr='-P %i', + xor=['master'], + ), + R=dict( + argstr='-R %i', + xor=['master'], + ), + RL=dict( + argstr='-RL %i', + xor=['master'], + ), + S=dict( + argstr='-S %i', + xor=['master'], + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + master=dict( + argstr='-master %s', + xor=['I', 'S', 'A', 'P', 'L', 'R', 'z', 'RL', 'AP', 'IS', 'mm'], + ), + mm=dict( + argstr='-mm', + xor=['master'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='-prefix %s', + name_template='zeropad', + ), + outputtype=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + z=dict( + argstr='-z %i', + xor=['master'], + ), ) inputs = Zeropad.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Zeropad_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Zeropad.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/utils.py b/nipype/interfaces/afni/utils.py index 5b5dc79d7f..65bb734ff7 100644 --- a/nipype/interfaces/afni/utils.py +++ b/nipype/interfaces/afni/utils.py @@ -12,7 +12,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, bytes import os @@ -21,13 +22,13 @@ import numpy as np from ...utils.filemanip import (load_json, save_json, split_filename) -from ..base import ( - CommandLineInputSpec, CommandLine, Directory, TraitedSpec, - traits, isdefined, File, InputMultiPath, Undefined, Str) +from ..base import (CommandLineInputSpec, CommandLine, Directory, TraitedSpec, + traits, isdefined, File, InputMultiPath, Undefined, Str) from ...external.due import BibTeX -from .base import ( - AFNICommandBase, AFNICommand, AFNICommandInputSpec, AFNICommandOutputSpec, - AFNIPythonCommandInputSpec, AFNIPythonCommand) +from .base import (AFNICommandBase, AFNICommand, AFNICommandInputSpec, + AFNICommandOutputSpec, AFNIPythonCommandInputSpec, + AFNIPythonCommand) + class ABoverlapInputSpec(AFNICommandInputSpec): in_file_a = File( @@ -45,18 +46,14 @@ class ABoverlapInputSpec(AFNICommandInputSpec): exists=True, copyfile=False) out_file = File( - desc='collect output to a file', - argstr=' |& tee %s', - position=-1) + desc='collect output to a file', argstr=' |& tee %s', position=-1) no_automask = traits.Bool( - desc='consider input datasets as masks', - argstr='-no_automask') + desc='consider input datasets as masks', argstr='-no_automask') quiet = traits.Bool( desc='be as quiet as possible (without being entirely mute)', argstr='-quiet') verb = traits.Bool( - desc='print out some progress reports (to stderr)', - argstr='-verb') + desc='print out some progress reports (to stderr)', argstr='-verb') class ABoverlap(AFNICommand): @@ -101,26 +98,27 @@ class AFNItoNIFTIInputSpec(AFNICommandInputSpec): hash_files=False) float_ = traits.Bool( desc='Force the output dataset to be 32-bit floats. This option ' - 'should be used when the input AFNI dataset has different float ' - 'scale factors for different sub-bricks, an option that ' - 'NIfTI-1.1 does not support.', + 'should be used when the input AFNI dataset has different float ' + 'scale factors for different sub-bricks, an option that ' + 'NIfTI-1.1 does not support.', argstr='-float') pure = traits.Bool( desc='Do NOT write an AFNI extension field into the output file. Only ' - 'use this option if needed. You can also use the \'nifti_tool\' ' - 'program to strip extensions from a file.', + 'use this option if needed. You can also use the \'nifti_tool\' ' + 'program to strip extensions from a file.', argstr='-pure') denote = traits.Bool( desc='When writing the AFNI extension field, remove text notes that ' - 'might contain subject identifying information.', + 'might contain subject identifying information.', argstr='-denote') oldid = traits.Bool( - desc='Give the new dataset the input dataset''s AFNI ID code.', + desc='Give the new dataset the input dataset' + 's AFNI ID code.', argstr='-oldid', xor=['newid']) newid = traits.Bool( desc='Give the new dataset a new AFNI ID code, to distinguish it from ' - 'the input dataset.', + 'the input dataset.', argstr='-newid', xor=['oldid']) @@ -170,15 +168,13 @@ class AutoboxInputSpec(AFNICommandInputSpec): argstr='-npad %d', desc='Number of extra voxels to pad on each side of box') out_file = File( - argstr='-prefix %s', - name_source='in_file', - name_template='%s_autobox') + argstr='-prefix %s', name_source='in_file', name_template='%s_autobox') no_clustering = traits.Bool( argstr='-noclust', desc='Don\'t do any clustering to find box. Any non-zero voxel will ' - 'be preserved in the cropped volume. The default method uses ' - 'some clustering to find the cropping box, and will clip off ' - 'small isolated blobs.') + 'be preserved in the cropped volume. The default method uses ' + 'some clustering to find the cropping box, and will clip off ' + 'small isolated blobs.') class AutoboxOutputSpec(TraitedSpec): # out_file not mandatory @@ -189,8 +185,7 @@ class AutoboxOutputSpec(TraitedSpec): # out_file not mandatory z_min = traits.Int() z_max = traits.Int() - out_file = File( - desc='output file') + out_file = File(desc='output file') class Autobox(AFNICommand): @@ -218,7 +213,8 @@ class Autobox(AFNICommand): output_spec = AutoboxOutputSpec def aggregate_outputs(self, runtime=None, needed_outputs=None): - outputs = super(Autobox, self).aggregate_outputs(runtime, needed_outputs) + outputs = super(Autobox, self).aggregate_outputs( + runtime, needed_outputs) pattern = 'x=(?P-?\d+)\.\.(?P-?\d+) '\ 'y=(?P-?\d+)\.\.(?P-?\d+) '\ 'z=(?P-?\d+)\.\.(?P-?\d+)' @@ -243,34 +239,29 @@ class BrickStatInputSpec(CommandLineInputSpec): position=2, exists=True) min = traits.Bool( - desc='print the minimum value in dataset', - argstr='-min', - position=1) + desc='print the minimum value in dataset', argstr='-min', position=1) slow = traits.Bool( desc='read the whole dataset to find the min and max values', argstr='-slow') max = traits.Bool( - desc='print the maximum value in the dataset', - argstr='-max') + desc='print the maximum value in the dataset', argstr='-max') mean = traits.Bool( - desc='print the mean value in the dataset', - argstr='-mean') + desc='print the mean value in the dataset', argstr='-mean') sum = traits.Bool( - desc='print the sum of values in the dataset', - argstr='-sum') - var = traits.Bool( - desc='print the variance in the dataset', - argstr='-var') - percentile = traits.Tuple(traits.Float, traits.Float, traits.Float, + desc='print the sum of values in the dataset', argstr='-sum') + var = traits.Bool(desc='print the variance in the dataset', argstr='-var') + percentile = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, desc='p0 ps p1 write the percentile values starting ' - 'at p0% and ending at p1% at a step of ps%. ' - 'only one sub-brick is accepted.', + 'at p0% and ending at p1% at a step of ps%. ' + 'only one sub-brick is accepted.', argstr='-percentile %.3f %.3f %.3f') class BrickStatOutputSpec(TraitedSpec): - min_val = traits.Float( - desc='output') + min_val = traits.Float(desc='output') class BrickStat(AFNICommandBase): @@ -325,60 +316,56 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): return outputs + class BucketInputSpec(AFNICommandInputSpec): in_file = traits.List( traits.Tuple( - (File( - exists=True, - copyfile=False), - traits.Str(argstr="'%s'")), + (File(exists=True, copyfile=False), traits.Str(argstr="'%s'")), artstr="%s%s"), position=-1, mandatory=True, argstr="%s", desc='List of tuples of input datasets and subbrick selection strings' - 'as described in more detail in the following afni help string' - 'Input dataset specified using one of these forms:' - ' \'prefix+view\', \'prefix+view.HEAD\', or \'prefix+view.BRIK\'.' - 'You can also add a sub-brick selection list after the end of the' - 'dataset name. This allows only a subset of the sub-bricks to be' - 'included into the output (by default, all of the input dataset' - 'is copied into the output). A sub-brick selection list looks like' - 'one of the following forms:' - ' fred+orig[5] ==> use only sub-brick #5' - ' fred+orig[5,9,17] ==> use #5, #9, and #17' - ' fred+orig[5..8] or [5-8] ==> use #5, #6, #7, and #8' - ' fred+orig[5..13(2)] or [5-13(2)] ==> use #5, #7, #9, #11, and #13' - 'Sub-brick indexes start at 0. You can use the character \'$\'' - 'to indicate the last sub-brick in a dataset; for example, you' - 'can select every third sub-brick by using the selection list' - ' fred+orig[0..$(3)]' - 'N.B.: The sub-bricks are output in the order specified, which may' - ' not be the order in the original datasets. For example, using' - ' fred+orig[0..$(2),1..$(2)]' - ' will cause the sub-bricks in fred+orig to be output into the' - ' new dataset in an interleaved fashion. Using' - ' fred+orig[$..0]' - ' will reverse the order of the sub-bricks in the output.' - 'N.B.: Bucket datasets have multiple sub-bricks, but do NOT have' - ' a time dimension. You can input sub-bricks from a 3D+time dataset' - ' into a bucket dataset. You can use the \'3dinfo\' program to see' - ' how many sub-bricks a 3D+time or a bucket dataset contains.' - 'N.B.: In non-bucket functional datasets (like the \'fico\' datasets' - ' output by FIM, or the \'fitt\' datasets output by 3dttest), sub-brick' - ' [0] is the \'intensity\' and sub-brick [1] is the statistical parameter' - ' used as a threshold. Thus, to create a bucket dataset using the' - ' intensity from dataset A and the threshold from dataset B, and' - ' calling the output dataset C, you would type' - ' 3dbucket -prefix C -fbuc \'A+orig[0]\' -fbuc \'B+orig[1]\'' - 'WARNING: using this program, it is possible to create a dataset that' - ' has different basic datum types for different sub-bricks' - ' (e.g., shorts for brick 0, floats for brick 1).' - ' Do NOT do this! Very few AFNI programs will work correctly' - ' with such datasets!') - out_file = File( - argstr='-prefix %s', - name_template='buck') + 'as described in more detail in the following afni help string' + 'Input dataset specified using one of these forms:' + ' \'prefix+view\', \'prefix+view.HEAD\', or \'prefix+view.BRIK\'.' + 'You can also add a sub-brick selection list after the end of the' + 'dataset name. This allows only a subset of the sub-bricks to be' + 'included into the output (by default, all of the input dataset' + 'is copied into the output). A sub-brick selection list looks like' + 'one of the following forms:' + ' fred+orig[5] ==> use only sub-brick #5' + ' fred+orig[5,9,17] ==> use #5, #9, and #17' + ' fred+orig[5..8] or [5-8] ==> use #5, #6, #7, and #8' + ' fred+orig[5..13(2)] or [5-13(2)] ==> use #5, #7, #9, #11, and #13' + 'Sub-brick indexes start at 0. You can use the character \'$\'' + 'to indicate the last sub-brick in a dataset; for example, you' + 'can select every third sub-brick by using the selection list' + ' fred+orig[0..$(3)]' + 'N.B.: The sub-bricks are output in the order specified, which may' + ' not be the order in the original datasets. For example, using' + ' fred+orig[0..$(2),1..$(2)]' + ' will cause the sub-bricks in fred+orig to be output into the' + ' new dataset in an interleaved fashion. Using' + ' fred+orig[$..0]' + ' will reverse the order of the sub-bricks in the output.' + 'N.B.: Bucket datasets have multiple sub-bricks, but do NOT have' + ' a time dimension. You can input sub-bricks from a 3D+time dataset' + ' into a bucket dataset. You can use the \'3dinfo\' program to see' + ' how many sub-bricks a 3D+time or a bucket dataset contains.' + 'N.B.: In non-bucket functional datasets (like the \'fico\' datasets' + ' output by FIM, or the \'fitt\' datasets output by 3dttest), sub-brick' + ' [0] is the \'intensity\' and sub-brick [1] is the statistical parameter' + ' used as a threshold. Thus, to create a bucket dataset using the' + ' intensity from dataset A and the threshold from dataset B, and' + ' calling the output dataset C, you would type' + ' 3dbucket -prefix C -fbuc \'A+orig[0]\' -fbuc \'B+orig[1]\'' + 'WARNING: using this program, it is possible to create a dataset that' + ' has different basic datum types for different sub-bricks' + ' (e.g., shorts for brick 0, floats for brick 1).' + ' Do NOT do this! Very few AFNI programs will work correctly' + ' with such datasets!') + out_file = File(argstr='-prefix %s', name_template='buck') class Bucket(AFNICommand): @@ -407,9 +394,11 @@ class Bucket(AFNICommand): def _format_arg(self, name, spec, value): if name == 'in_file': - return spec.argstr%(' '.join([i[0]+"'"+i[1]+"'" for i in value])) + return spec.argstr % ( + ' '.join([i[0] + "'" + i[1] + "'" for i in value])) return super(Bucket, self)._format_arg(name, spec, value) + class CalcInputSpec(AFNICommandInputSpec): in_file_a = File( desc='input file to 3dcalc', @@ -418,39 +407,22 @@ class CalcInputSpec(AFNICommandInputSpec): mandatory=True, exists=True) in_file_b = File( - desc='operand file to 3dcalc', - argstr='-b %s', - position=1, - exists=True) + desc='operand file to 3dcalc', argstr='-b %s', position=1, exists=True) in_file_c = File( - desc='operand file to 3dcalc', - argstr='-c %s', - position=2, - exists=True) + desc='operand file to 3dcalc', argstr='-c %s', position=2, exists=True) out_file = File( name_template='%s_calc', desc='output image file name', argstr='-prefix %s', name_source='in_file_a') - expr = Str( - desc='expr', - argstr='-expr "%s"', - position=3, - mandatory=True) + expr = Str(desc='expr', argstr='-expr "%s"', position=3, mandatory=True) start_idx = traits.Int( - desc='start index for in_file_a', - requires=['stop_idx']) + desc='start index for in_file_a', requires=['stop_idx']) stop_idx = traits.Int( - desc='stop index for in_file_a', - requires=['start_idx']) - single_idx = traits.Int( - desc='volume index for in_file_a') - overwrite = traits.Bool( - desc='overwrite output', - argstr='-overwrite') - other = File( - desc='other options', - argstr='') + desc='stop index for in_file_a', requires=['start_idx']) + single_idx = traits.Int(desc='volume index for in_file_a') + overwrite = traits.Bool(desc='overwrite output', argstr='-overwrite') + other = File(desc='other options', argstr='') class Calc(AFNICommand): @@ -503,13 +475,13 @@ def _format_arg(self, name, trait_spec, value): def _parse_inputs(self, skip=None): """Skip the arguments without argstr metadata """ - return super(Calc, self)._parse_inputs( - skip=('start_idx', 'stop_idx', 'other')) + return super( + Calc, self)._parse_inputs(skip=('start_idx', 'stop_idx', 'other')) class CatInputSpec(AFNICommandInputSpec): - in_files = traits.List(File(exists=True), argstr="%s", - mandatory=True, position=-2) + in_files = traits.List( + File(exists=True), argstr="%s", mandatory=True, position=-2) out_file = File( argstr='> %s', default='catout.1d', @@ -521,41 +493,45 @@ class CatInputSpec(AFNICommandInputSpec): argstr='-nonconst') keepfree = traits.Bool( desc='Keep only columns that are marked as \'free\' in the ' - '3dAllineate header from \'-1Dparam_save\'. ' - 'If there is no such header, all columns are kept.', + '3dAllineate header from \'-1Dparam_save\'. ' + 'If there is no such header, all columns are kept.', argstr='-nonfixed') out_format = traits.Enum( - 'int','nice','double','fint','cint', + 'int', + 'nice', + 'double', + 'fint', + 'cint', argstr='-form %s', desc='specify data type for output. Valid types are \'int\', ' - '\'nice\', \'double\', \'fint\', and \'cint\'.', - xor=['out_int','out_nice','out_double','out_fint','out_cint']) + '\'nice\', \'double\', \'fint\', and \'cint\'.', + xor=['out_int', 'out_nice', 'out_double', 'out_fint', 'out_cint']) stack = traits.Bool( desc='Stack the columns of the resultant matrix in the output.', argstr='-stack') sel = traits.Str( desc='Apply the same column/row selection string to all filenames ' - 'on the command line.', + 'on the command line.', argstr='-sel %s') out_int = traits.Bool( desc='specifiy int data type for output', argstr='-i', - xor=['out_format','out_nice','out_double','out_fint','out_cint']) + xor=['out_format', 'out_nice', 'out_double', 'out_fint', 'out_cint']) out_nice = traits.Bool( desc='specifiy nice data type for output', argstr='-n', - xor=['out_format','out_int','out_double','out_fint','out_cint']) + xor=['out_format', 'out_int', 'out_double', 'out_fint', 'out_cint']) out_double = traits.Bool( desc='specifiy double data type for output', argstr='-d', - xor=['out_format','out_nice','out_int','out_fint','out_cint']) + xor=['out_format', 'out_nice', 'out_int', 'out_fint', 'out_cint']) out_fint = traits.Bool( desc='specifiy int, rounded down, data type for output', argstr='-f', - xor=['out_format','out_nice','out_double','out_int','out_cint']) + xor=['out_format', 'out_nice', 'out_double', 'out_int', 'out_cint']) out_cint = traits.Bool( desc='specifiy int, rounded up, data type for output', - xor=['out_format','out_nice','out_double','out_fint','out_int']) + xor=['out_format', 'out_nice', 'out_double', 'out_fint', 'out_int']) class Cat(AFNICommand): @@ -584,35 +560,37 @@ class Cat(AFNICommand): input_spec = CatInputSpec output_spec = AFNICommandOutputSpec + class CatMatvecInputSpec(AFNICommandInputSpec): in_file = traits.List( traits.Tuple(traits.Str(), traits.Str()), - descr="list of tuples of mfiles and associated opkeys", + desc="list of tuples of mfiles and associated opkeys", mandatory=True, argstr="%s", position=-2) out_file = File( - descr="File to write concattenated matvecs to", + desc="File to write concattenated matvecs to", argstr=" > %s", position=-1, mandatory=True) matrix = traits.Bool( - descr="indicates that the resulting matrix will" - "be written to outfile in the 'MATRIX(...)' format (FORM 3)." - "This feature could be used, with clever scripting, to input" - "a matrix directly on the command line to program 3dWarp.", + desc="indicates that the resulting matrix will" + "be written to outfile in the 'MATRIX(...)' format (FORM 3)." + "This feature could be used, with clever scripting, to input" + "a matrix directly on the command line to program 3dWarp.", argstr="-MATRIX", xor=['oneline', 'fourxfour']) oneline = traits.Bool( - descr="indicates that the resulting matrix" - "will simply be written as 12 numbers on one line.", + desc="indicates that the resulting matrix" + "will simply be written as 12 numbers on one line.", argstr="-ONELINE", xor=['matrix', 'fourxfour']) fourxfour = traits.Bool( - descr="Output matrix in augmented form (last row is 0 0 0 1)" - "This option does not work with -MATRIX or -ONELINE", + desc="Output matrix in augmented form (last row is 0 0 0 1)" + "This option does not work with -MATRIX or -ONELINE", argstr="-4x4", - xor=['matrix','oneline']) + xor=['matrix', 'oneline']) + class CatMatvec(AFNICommand): """Catenates 3D rotation+shift matrix+vector transformations. @@ -639,7 +617,8 @@ class CatMatvec(AFNICommand): def _format_arg(self, name, spec, value): if name == 'in_file': - return spec.argstr%(' '.join([i[0]+' -'+i[1] for i in value])) + return spec.argstr % (' '.join([i[0] + ' -' + i[1] + for i in value])) return super(CatMatvec, self)._format_arg(name, spec, value) @@ -652,26 +631,25 @@ class CenterMassInputSpec(CommandLineInputSpec): exists=True, copyfile=True) cm_file = File( - name_source='in_file', - name_template='%s_cm.out', - hash_files=False, - keep_extension=False, - descr="File to write center of mass to", - argstr="> %s", - position=-1) + name_source='in_file', + name_template='%s_cm.out', + hash_files=False, + keep_extension=False, + desc="File to write center of mass to", + argstr="> %s", + position=-1) mask_file = File( desc='Only voxels with nonzero values in the provided mask will be ' - 'averaged.', + 'averaged.', argstr='-mask %s', exists=True) automask = traits.Bool( - desc='Generate the mask automatically', - argstr='-automask') + desc='Generate the mask automatically', argstr='-automask') set_cm = traits.Tuple( (traits.Float(), traits.Float(), traits.Float()), desc='After computing the center of mass, set the origin fields in ' - 'the header so that the center of mass will be at (x,y,z) in ' - 'DICOM coords.', + 'the header so that the center of mass will be at (x,y,z) in ' + 'DICOM coords.', argstr='-set %f %f %f') local_ijk = traits.Bool( desc='Output values as (i,j,k) in local orienation', @@ -679,21 +657,18 @@ class CenterMassInputSpec(CommandLineInputSpec): roi_vals = traits.List( traits.Int, desc='Compute center of mass for each blob with voxel value of v0, ' - 'v1, v2, etc. This option is handy for getting ROI centers of ' - 'mass.', + 'v1, v2, etc. This option is handy for getting ROI centers of ' + 'mass.', argstr='-roi_vals %s') all_rois = traits.Bool( desc='Don\'t bother listing the values of ROIs you want: The program ' - 'will find all of them and produce a full list', + 'will find all of them and produce a full list', argstr='-all_rois') class CenterMassOutputSpec(TraitedSpec): - out_file = File( - exists=True, - desc='output file') - cm_file = File( - desc='file with the center of mass coordinates') + out_file = File(exists=True, desc='output file') + cm_file = File(desc='file with the center of mass coordinates') cm = traits.List( traits.Tuple(traits.Float(), traits.Float(), traits.Float()), desc='center of mass') @@ -732,7 +707,7 @@ def _list_outputs(self): outputs = super(CenterMass, self)._list_outputs() outputs['out_file'] = os.path.abspath(self.inputs.in_file) outputs['cm_file'] = os.path.abspath(self.inputs.cm_file) - sout = np.loadtxt(outputs['cm_file'], ndmin=2) # pylint: disable=E1101 + sout = np.loadtxt(outputs['cm_file'], ndmin=2) outputs['cm'] = [tuple(s) for s in sout] return outputs @@ -751,9 +726,7 @@ class CopyInputSpec(AFNICommandInputSpec): argstr='%s', position=-1, name_source='in_file') - verbose = traits.Bool( - desc='print progress reports', - argstr='-verb') + verbose = traits.Bool(desc='print progress reports', argstr='-verb') class Copy(AFNICommand): @@ -798,6 +771,7 @@ class Copy(AFNICommand): input_spec = CopyInputSpec output_spec = AFNICommandOutputSpec + class DotInputSpec(AFNICommandInputSpec): in_files = traits.List( (File()), @@ -805,47 +779,46 @@ class DotInputSpec(AFNICommandInputSpec): argstr="%s ...", position=-2) out_file = File( - desc='collect output to a file', - argstr=' |& tee %s', - position=-1) - mask = File( - desc='Use this dataset as a mask', - argstr='-mask %s') - mrange = traits.Tuple((traits.Float(),traits.Float()), + desc='collect output to a file', argstr=' |& tee %s', position=-1) + mask = File(desc='Use this dataset as a mask', argstr='-mask %s') + mrange = traits.Tuple( + (traits.Float(), traits.Float()), desc='Means to further restrict the voxels from \'mset\' so that' - 'only those mask values within this range (inclusive) willbe used.', + 'only those mask values within this range (inclusive) willbe used.', argstr='-mrange %s %s') demean = traits.Bool( - desc='Remove the mean from each volume prior to computing the correlation', + desc= + 'Remove the mean from each volume prior to computing the correlation', argstr='-demean') docor = traits.Bool( - desc='Return the correlation coefficient (default).', - argstr='-docor') + desc='Return the correlation coefficient (default).', argstr='-docor') dodot = traits.Bool( - desc='Return the dot product (unscaled).', - argstr='-dodot') + desc='Return the dot product (unscaled).', argstr='-dodot') docoef = traits.Bool( - desc='Return the least square fit coefficients {{a,b}} so that dset2 is approximately a + b*dset1', + desc= + 'Return the least square fit coefficients {{a,b}} so that dset2 is approximately a + b*dset1', argstr='-docoef') dosums = traits.Bool( - desc='Return the 6 numbers xbar= ybar= <(x-xbar)^2> <(y-ybar)^2> <(x-xbar)(y-ybar)> and the correlation coefficient.', + desc= + 'Return the 6 numbers xbar= ybar= <(x-xbar)^2> <(y-ybar)^2> <(x-xbar)(y-ybar)> and the correlation coefficient.', argstr='-dosums') dodice = traits.Bool( desc='Return the Dice coefficient (the Sorensen-Dice index).', argstr='-dodice') doeta2 = traits.Bool( - desc='Return eta-squared (Cohen, NeuroImage 2008).', - argstr='-doeta2') + desc='Return eta-squared (Cohen, NeuroImage 2008).', argstr='-doeta2') full = traits.Bool( - desc='Compute the whole matrix. A waste of time, but handy for parsing.', + desc= + 'Compute the whole matrix. A waste of time, but handy for parsing.', argstr='-full') show_labels = traits.Bool( - desc='Print sub-brick labels to help identify what is being correlated. This option is useful when' - 'you have more than 2 sub-bricks at input.', + desc= + 'Print sub-brick labels to help identify what is being correlated. This option is useful when' + 'you have more than 2 sub-bricks at input.', argstr='-show_labels') upper = traits.Bool( - desc='Compute upper triangular matrix', - argstr='-upper') + desc='Compute upper triangular matrix', argstr='-upper') + class Dot(AFNICommand): """Correlation coefficient between sub-brick pairs. @@ -869,6 +842,7 @@ class Dot(AFNICommand): input_spec = DotInputSpec output_spec = AFNICommandOutputSpec + class Edge3InputSpec(AFNICommandInputSpec): in_file = File( desc='input file to 3dedge3', @@ -878,21 +852,21 @@ class Edge3InputSpec(AFNICommandInputSpec): exists=True, copyfile=False) out_file = File( - desc='output image file name', - position=-1, - argstr='-prefix %s') + desc='output image file name', position=-1, argstr='-prefix %s') datum = traits.Enum( - 'byte', 'short', 'float', + 'byte', + 'short', + 'float', argstr='-datum %s', desc='specify data type for output. Valid types are \'byte\', ' - '\'short\' and \'float\'.') + '\'short\' and \'float\'.') fscale = traits.Bool( desc='Force scaling of the output to the maximum integer range.', argstr='-fscale', xor=['gscale', 'nscale', 'scale_floats']) gscale = traits.Bool( desc='Same as \'-fscale\', but also forces each output sub-brick to ' - 'to get the same scaling factor.', + 'to get the same scaling factor.', argstr='-gscale', xor=['fscale', 'nscale', 'scale_floats']) nscale = traits.Bool( @@ -901,17 +875,16 @@ class Edge3InputSpec(AFNICommandInputSpec): xor=['fscale', 'gscale', 'scale_floats']) scale_floats = traits.Float( desc='Multiply input by VAL, but only if the input datum is ' - 'float. This is needed when the input dataset ' - 'has a small range, like 0 to 2.0 for instance. ' - 'With such a range, very few edges are detected due to ' - 'what I suspect to be truncation problems. ' - 'Multiplying such a dataset by 10000 fixes the problem ' - 'and the scaling is undone at the output.', + 'float. This is needed when the input dataset ' + 'has a small range, like 0 to 2.0 for instance. ' + 'With such a range, very few edges are detected due to ' + 'what I suspect to be truncation problems. ' + 'Multiplying such a dataset by 10000 fixes the problem ' + 'and the scaling is undone at the output.', argstr='-scale_floats %f', xor=['fscale', 'gscale', 'nscale']) verbose = traits.Bool( - desc='Print out some information along the way.', - argstr='-verbose') + desc='Print out some information along the way.', argstr='-verbose') class Edge3(AFNICommand): @@ -970,39 +943,22 @@ class EvalInputSpec(AFNICommandInputSpec): mandatory=True, exists=True) in_file_b = File( - desc='operand file to 1deval', - argstr='-b %s', - position=1, - exists=True) + desc='operand file to 1deval', argstr='-b %s', position=1, exists=True) in_file_c = File( - desc='operand file to 1deval', - argstr='-c %s', - position=2, - exists=True) + desc='operand file to 1deval', argstr='-c %s', position=2, exists=True) out_file = File( name_template='%s_calc', desc='output image file name', argstr='-prefix %s', name_source='in_file_a') - out1D = traits.Bool( - desc='output in 1D', - argstr='-1D') - expr = Str( - desc='expr', - argstr='-expr "%s"', - position=3, - mandatory=True) + out1D = traits.Bool(desc='output in 1D', argstr='-1D') + expr = Str(desc='expr', argstr='-expr "%s"', position=3, mandatory=True) start_idx = traits.Int( - desc='start index for in_file_a', - requires=['stop_idx']) + desc='start index for in_file_a', requires=['stop_idx']) stop_idx = traits.Int( - desc='stop index for in_file_a', - requires=['start_idx']) - single_idx = traits.Int( - desc='volume index for in_file_a') - other = File( - desc='other options', - argstr='') + desc='stop index for in_file_a', requires=['start_idx']) + single_idx = traits.Int(desc='volume index for in_file_a') + other = File(desc='other options', argstr='') class Eval(AFNICommand): @@ -1046,16 +1002,13 @@ def _format_arg(self, name, trait_spec, value): def _parse_inputs(self, skip=None): """Skip the arguments without argstr metadata """ - return super(Eval, self)._parse_inputs( - skip=('start_idx', 'stop_idx', 'other')) + return super( + Eval, self)._parse_inputs(skip=('start_idx', 'stop_idx', 'other')) class FWHMxInputSpec(CommandLineInputSpec): in_file = File( - desc='input dataset', - argstr='-input %s', - mandatory=True, - exists=True) + desc='input dataset', argstr='-input %s', mandatory=True, exists=True) out_file = File( argstr='> %s', name_source='in_file', @@ -1079,28 +1032,29 @@ class FWHMxInputSpec(CommandLineInputSpec): argstr='-automask', desc='compute a mask from THIS dataset, a la 3dAutomask') detrend = traits.Either( - traits.Bool(), traits.Int(), + traits.Bool(), + traits.Int(), default=False, argstr='-detrend', xor=['demed'], usedefault=True, desc='instead of demed (0th order detrending), detrend to the ' - 'specified order. If order is not given, the program picks ' - 'q=NT/30. -detrend disables -demed, and includes -unif.') + 'specified order. If order is not given, the program picks ' + 'q=NT/30. -detrend disables -demed, and includes -unif.') demed = traits.Bool( False, argstr='-demed', xor=['detrend'], desc='If the input dataset has more than one sub-brick (e.g., has a ' - 'time axis), then subtract the median of each voxel\'s time ' - 'series before processing FWHM. This will tend to remove ' - 'intrinsic spatial structure and leave behind the noise.') + 'time axis), then subtract the median of each voxel\'s time ' + 'series before processing FWHM. This will tend to remove ' + 'intrinsic spatial structure and leave behind the noise.') unif = traits.Bool( False, argstr='-unif', desc='If the input dataset has more than one sub-brick, then ' - 'normalize each voxel\'s time series to have the same MAD before ' - 'processing FWHM.') + 'normalize each voxel\'s time series to have the same MAD before ' + 'processing FWHM.') out_detrend = File( argstr='-detprefix %s', name_source='in_file', @@ -1111,22 +1065,23 @@ class FWHMxInputSpec(CommandLineInputSpec): argstr='-geom', xor=['arith'], desc='if in_file has more than one sub-brick, compute the final ' - 'estimate as the geometric mean of the individual sub-brick FWHM ' - 'estimates') + 'estimate as the geometric mean of the individual sub-brick FWHM ' + 'estimates') arith = traits.Bool( argstr='-arith', xor=['geom'], desc='if in_file has more than one sub-brick, compute the final ' - 'estimate as the arithmetic mean of the individual sub-brick ' - 'FWHM estimates') + 'estimate as the arithmetic mean of the individual sub-brick ' + 'FWHM estimates') combine = traits.Bool( argstr='-combine', desc='combine the final measurements along each axis') compat = traits.Bool( - argstr='-compat', - desc='be compatible with the older 3dFWHM') + argstr='-compat', desc='be compatible with the older 3dFWHM') acf = traits.Either( - traits.Bool(), File(), traits.Tuple(File(exists=True), traits.Float()), + traits.Bool(), + File(), + traits.Tuple(File(exists=True), traits.Float()), default=False, usedefault=True, argstr='-acf', @@ -1134,25 +1089,20 @@ class FWHMxInputSpec(CommandLineInputSpec): class FWHMxOutputSpec(TraitedSpec): - out_file = File( - exists=True, - desc='output file') - out_subbricks = File( - exists=True, - desc='output file (subbricks)') - out_detrend = File( - desc='output file, detrended') + out_file = File(exists=True, desc='output file') + out_subbricks = File(exists=True, desc='output file (subbricks)') + out_detrend = File(desc='output file, detrended') fwhm = traits.Either( traits.Tuple(traits.Float(), traits.Float(), traits.Float()), - traits.Tuple(traits.Float(), traits.Float(), traits.Float(), traits.Float()), + traits.Tuple(traits.Float(), traits.Float(), traits.Float(), + traits.Float()), desc='FWHM along each axis') acf_param = traits.Either( traits.Tuple(traits.Float(), traits.Float(), traits.Float()), - traits.Tuple(traits.Float(), traits.Float(), traits.Float(), traits.Float()), + traits.Tuple(traits.Float(), traits.Float(), traits.Float(), + traits.Float()), desc='fitted ACF model parameters') - out_acf = File( - exists=True, - desc='output acf file') + out_acf = File(exists=True, desc='output acf file') class FWHMx(AFNICommandBase): @@ -1261,15 +1211,18 @@ class FWHMx(AFNICommandBase): input_spec = FWHMxInputSpec output_spec = FWHMxOutputSpec - references_ = [{'entry': BibTeX('@article{CoxReynoldsTaylor2016,' - 'author={R.W. Cox, R.C. Reynolds, and P.A. Taylor},' - 'title={AFNI and clustering: false positive rates redux},' - 'journal={bioRxiv},' - 'year={2016},' - '}'), - 'tags': ['method'], - }, - ] + references_ = [ + { + 'entry': + BibTeX('@article{CoxReynoldsTaylor2016,' + 'author={R.W. Cox, R.C. Reynolds, and P.A. Taylor},' + 'title={AFNI and clustering: false positive rates redux},' + 'journal={bioRxiv},' + 'year={2016},' + '}'), + 'tags': ['method'], + }, + ] _acf = True def _parse_inputs(self, skip=None): @@ -1314,7 +1267,7 @@ def _list_outputs(self): else: outputs['out_detrend'] = Undefined - sout = np.loadtxt(outputs['out_file']) #pylint: disable=E1101 + sout = np.loadtxt(outputs['out_file']) # handle newer versions of AFNI if sout.size == 8: @@ -1348,52 +1301,49 @@ class MaskToolInputSpec(AFNICommandInputSpec): name_source='in_file') count = traits.Bool( desc='Instead of created a binary 0/1 mask dataset, create one with ' - 'counts of voxel overlap, i.e., each voxel will contain the ' - 'number of masks that it is set in.', + 'counts of voxel overlap, i.e., each voxel will contain the ' + 'number of masks that it is set in.', argstr='-count', position=2) datum = traits.Enum( - 'byte','short','float', + 'byte', + 'short', + 'float', argstr='-datum %s', desc='specify data type for output. Valid types are \'byte\', ' - '\'short\' and \'float\'.') + '\'short\' and \'float\'.') dilate_inputs = Str( desc='Use this option to dilate and/or erode datasets as they are ' - 'read. ex. \'5 -5\' to dilate and erode 5 times', + 'read. ex. \'5 -5\' to dilate and erode 5 times', argstr='-dilate_inputs %s') dilate_results = Str( desc='dilate and/or erode combined mask at the given levels.', argstr='-dilate_results %s') frac = traits.Float( desc='When combining masks (across datasets and sub-bricks), use ' - 'this option to restrict the result to a certain fraction of the ' - 'set of volumes', + 'this option to restrict the result to a certain fraction of the ' + 'set of volumes', argstr='-frac %s') inter = traits.Bool( - desc='intersection, this means -frac 1.0', - argstr='-inter') - union = traits.Bool( - desc='union, this means -frac 0', - argstr='-union') + desc='intersection, this means -frac 1.0', argstr='-inter') + union = traits.Bool(desc='union, this means -frac 0', argstr='-union') fill_holes = traits.Bool( desc='This option can be used to fill holes in the resulting mask, ' - 'i.e. after all other processing has been done.', + 'i.e. after all other processing has been done.', argstr='-fill_holes') fill_dirs = Str( desc='fill holes only in the given directions. This option is for use ' - 'with -fill holes. should be a single string that specifies ' - '1-3 of the axes using {x,y,z} labels (i.e. dataset axis order), ' - 'or using the labels in {R,L,A,P,I,S}.', + 'with -fill holes. should be a single string that specifies ' + '1-3 of the axes using {x,y,z} labels (i.e. dataset axis order), ' + 'or using the labels in {R,L,A,P,I,S}.', argstr='-fill_dirs %s', requires=['fill_holes']) verbose = traits.Int( - desc='specify verbosity level, for 0 to 3', - argstr='-verb %s') + desc='specify verbosity level, for 0 to 3', argstr='-verb %s') class MaskToolOutputSpec(TraitedSpec): - out_file = File(desc='mask file', - exists=True) + out_file = File(desc='mask file', exists=True) class MaskTool(AFNICommand): @@ -1422,9 +1372,7 @@ class MaskTool(AFNICommand): class MergeInputSpec(AFNICommandInputSpec): in_files = InputMultiPath( - File( - desc='input file to 3dmerge', - exists=True), + File(desc='input file to 3dmerge', exists=True), argstr='%s', position=-1, mandatory=True, @@ -1435,12 +1383,9 @@ class MergeInputSpec(AFNICommandInputSpec): argstr='-prefix %s', name_source='in_file') doall = traits.Bool( - desc='apply options to all sub-bricks in dataset', - argstr='-doall') + desc='apply options to all sub-bricks in dataset', argstr='-doall') blurfwhm = traits.Int( - desc='FWHM blur value (mm)', - argstr='-1blur_fwhm %d', - units='mm') + desc='FWHM blur value (mm)', argstr='-1blur_fwhm %d', units='mm') class Merge(AFNICommand): @@ -1477,26 +1422,16 @@ class NotesInputSpec(AFNICommandInputSpec): mandatory=True, exists=True, copyfile=False) - add = Str( - desc='note to add', - argstr='-a "%s"') + add = Str(desc='note to add', argstr='-a "%s"') add_history = Str( - desc='note to add to history', - argstr='-h "%s"', - xor=['rep_history']) + desc='note to add to history', argstr='-h "%s"', xor=['rep_history']) rep_history = Str( desc='note with which to replace history', argstr='-HH "%s"', xor=['add_history']) - delete = traits.Int( - desc='delete note number num', - argstr='-d %d') - ses = traits.Bool( - desc='print to stdout the expanded notes', - argstr='-ses') - out_file = File( - desc='output image file name', - argstr='%s') + delete = traits.Int(desc='delete note number num', argstr='-d %d') + ses = traits.Bool(desc='print to stdout the expanded notes', argstr='-ses') + out_file = File(desc='output image file name', argstr='%s') class Notes(CommandLine): @@ -1529,31 +1464,52 @@ def _list_outputs(self): class NwarpApplyInputSpec(CommandLineInputSpec): - in_file = traits.Either(File(exists=True), traits.List(File(exists=True)), + in_file = traits.Either( + File(exists=True), + traits.List(File(exists=True)), mandatory=True, argstr='-source %s', desc='the name of the dataset to be warped ' - 'can be multiple datasets') + 'can be multiple datasets') warp = traits.String( desc='the name of the warp dataset. ' - 'multiple warps can be concatenated (make sure they exist)', + 'multiple warps can be concatenated (make sure they exist)', argstr='-nwarp %s', mandatory=True) inv_warp = traits.Bool( desc='After the warp specified in \'-nwarp\' is computed, invert it', argstr='-iwarp') - master = traits.File(exists=True, + master = traits.File( + exists=True, desc='the name of the master dataset, which defines the output grid', argstr='-master %s') - interp = traits.Enum('NN','nearestneighbour','nearestneighbor','linear', - 'trilinear','cubic','tricubic','quintic','triquintic','wsinc5', + interp = traits.Enum( + 'NN', + 'nearestneighbour', + 'nearestneighbor', + 'linear', + 'trilinear', + 'cubic', + 'tricubic', + 'quintic', + 'triquintic', + 'wsinc5', desc='defines interpolation method to use during warp', argstr='-interp %s', default='wsinc5') - ainterp = traits.Enum('NN','nearestneighbour','nearestneighbor','linear', - 'trilinear','cubic','tricubic','quintic','triquintic','wsinc5', + ainterp = traits.Enum( + 'NN', + 'nearestneighbour', + 'nearestneighbor', + 'linear', + 'trilinear', + 'cubic', + 'tricubic', + 'quintic', + 'triquintic', + 'wsinc5', desc='specify a different interpolation method than might ' - 'be used for the warp', + 'be used for the warp', argstr='-ainterp %s', default='wsinc5') out_file = File( @@ -1563,16 +1519,12 @@ class NwarpApplyInputSpec(CommandLineInputSpec): name_source='in_file') short = traits.Bool( desc='Write output dataset using 16-bit short integers, rather than ' - 'the usual 32-bit floats.', + 'the usual 32-bit floats.', argstr='-short') quiet = traits.Bool( - desc='don\'t be verbose :(', - argstr='-quiet', - xor=['verb']) + desc='don\'t be verbose :(', argstr='-quiet', xor=['verb']) verb = traits.Bool( - desc='be extra verbose :)', - argstr='-verb', - xor=['quiet']) + desc='be extra verbose :)', argstr='-verb', xor=['quiet']) class NwarpApply(AFNICommandBase): @@ -1603,40 +1555,39 @@ class NwarpApply(AFNICommandBase): class NwarpCatInputSpec(AFNICommandInputSpec): in_files = traits.List( - traits.Either( - traits.File(), - traits.Tuple(traits.Enum('IDENT', 'INV', 'SQRT', 'SQRTINV'), - traits.File())), - descr="list of tuples of 3D warps and associated functions", + traits.Either(traits.File(), + traits.Tuple( + traits.Enum('IDENT', 'INV', 'SQRT', 'SQRTINV'), + traits.File())), + desc="list of tuples of 3D warps and associated functions", mandatory=True, argstr="%s", position=-1) space = traits.String( desc='string to attach to the output dataset as its atlas space ' - 'marker.', + 'marker.', argstr='-space %s') inv_warp = traits.Bool( - desc='invert the final warp before output', - argstr='-iwarp') + desc='invert the final warp before output', argstr='-iwarp') interp = traits.Enum( - 'linear', 'quintic', 'wsinc5', + 'linear', + 'quintic', + 'wsinc5', desc='specify a different interpolation method than might ' - 'be used for the warp', + 'be used for the warp', argstr='-interp %s', default='wsinc5') expad = traits.Int( desc='Pad the nonlinear warps by the given number of voxels voxels in ' - 'all directions. The warp displacements are extended by linear ' - 'extrapolation from the faces of the input grid..', + 'all directions. The warp displacements are extended by linear ' + 'extrapolation from the faces of the input grid..', argstr='-expad %d') out_file = File( name_template='%s_NwarpCat', desc='output image file name', argstr='-prefix %s', name_source='in_files') - verb = traits.Bool( - desc='be verbose', - argstr='-verb') + verb = traits.Bool(desc='be verbose', argstr='-verb') class NwarpCat(AFNICommand): @@ -1697,23 +1648,27 @@ class NwarpCat(AFNICommand): def _format_arg(self, name, spec, value): if name == 'in_files': - return spec.argstr % (' '.join(["'" + v[0] + "(" + v[1] + ")'" - if isinstance(v, tuple) else v - for v in value])) + return spec.argstr % (' '.join([ + "'" + v[0] + "(" + v[1] + ")'" if isinstance(v, tuple) else v + for v in value + ])) return super(NwarpCat, self)._format_arg(name, spec, value) def _gen_filename(self, name): if name == 'out_file': - return self._gen_fname(self.inputs.in_files[0][0], - suffix='_NwarpCat') + return self._gen_fname( + self.inputs.in_files[0][0], suffix='_NwarpCat') def _list_outputs(self): outputs = self.output_spec().get() if isdefined(self.inputs.out_file): outputs['out_file'] = os.path.abspath(self.inputs.out_file) else: - outputs['out_file'] = os.path.abspath(self._gen_fname( - self.inputs.in_files[0], suffix='_NwarpCat+tlrc', ext='.HEAD')) + outputs['out_file'] = os.path.abspath( + self._gen_fname( + self.inputs.in_files[0], + suffix='_NwarpCat+tlrc', + ext='.HEAD')) return outputs @@ -1724,32 +1679,38 @@ class OneDToolPyInputSpec(AFNIPythonCommandInputSpec): mandatory=True, exists=True) set_nruns = traits.Int( - desc='treat the input data as if it has nruns', - argstr='-set_nruns %d') + desc='treat the input data as if it has nruns', argstr='-set_nruns %d') derivative = traits.Bool( - desc='take the temporal derivative of each vector (done as first backward difference)', + desc= + 'take the temporal derivative of each vector (done as first backward difference)', argstr='-derivative') demean = traits.Bool( - desc='demean each run (new mean of each run = 0.0)', - argstr='-demean') + desc='demean each run (new mean of each run = 0.0)', argstr='-demean') out_file = File( desc='write the current 1D data to FILE', argstr='-write %s', xor=['show_cormat_warnings']) show_censor_count = traits.Bool( - desc='display the total number of censored TRs Note : if input is a valid xmat.1D dataset,' - 'then the count will come from the header. Otherwise the input is assumed to be a binary censor' - 'file, and zeros are simply counted.', + desc= + 'display the total number of censored TRs Note : if input is a valid xmat.1D dataset, ' + 'then the count will come from the header. Otherwise the input is assumed to be a binary censor' + 'file, and zeros are simply counted.', argstr="-show_censor_count") censor_motion = traits.Tuple( - (traits.Float(),File()), - desc='Tuple of motion limit and outfile prefix. need to also set set_nruns -r set_run_lengths', + (traits.Float(), File()), + desc= + 'Tuple of motion limit and outfile prefix. need to also set set_nruns -r set_run_lengths', argstr="-censor_motion %f %s") censor_prev_TR = traits.Bool( desc='for each censored TR, also censor previous', argstr='-censor_prev_TR') - show_trs_uncensored = traits.Enum('comma','space','encoded','verbose', - desc='display a list of TRs which were not censored in the specified style', + show_trs_uncensored = traits.Enum( + 'comma', + 'space', + 'encoded', + 'verbose', + desc= + 'display a list of TRs which were not censored in the specified style', argstr='-show_trs_uncensored %s') show_cormat_warnings = traits.File( desc='Write cormat warnings to a file', @@ -1765,9 +1726,11 @@ class OneDToolPyInputSpec(AFNIPythonCommandInputSpec): desc="restrict -show_trs_[un]censored to the given 1-based run", argstr="-show_trs_run %d") + class OneDToolPyOutputSpec(AFNICommandOutputSpec): out_file = File(desc='output of 1D_tool.py') + class OneDToolPy(AFNIPythonCommand): """This program is meant to read/manipulate/write/diagnose 1D datasets. Input can be specified using AFNI sub-brick[]/time{} selectors. @@ -1792,13 +1755,17 @@ def _list_outputs(self): outputs = self.output_spec().get() if isdefined(self.inputs.out_file): - outputs['out_file']=os.path.join(os.getcwd(), self.inputs.out_file) + outputs['out_file'] = os.path.join(os.getcwd(), + self.inputs.out_file) if isdefined(self.inputs.show_cormat_warnings): - outputs['out_file']=os.path.join(os.getcwd(), self.inputs.show_cormat_warnings) + outputs['out_file'] = os.path.join( + os.getcwd(), self.inputs.show_cormat_warnings) if isdefined(self.inputs.censor_motion): - outputs['out_file']=os.path.join(os.getcwd(), self.inputs.censor_motion[1]) + outputs['out_file'] = os.path.join(os.getcwd(), + self.inputs.censor_motion[1]) return outputs + class RefitInputSpec(CommandLineInputSpec): in_file = File( desc='input file to 3drefit', @@ -1811,76 +1778,71 @@ class RefitInputSpec(CommandLineInputSpec): desc='replace current transformation matrix with cardinal matrix', argstr='-deoblique') xorigin = Str( - desc='x distance for edge voxel offset', - argstr='-xorigin %s') + desc='x distance for edge voxel offset', argstr='-xorigin %s') yorigin = Str( - desc='y distance for edge voxel offset', - argstr='-yorigin %s') + desc='y distance for edge voxel offset', argstr='-yorigin %s') zorigin = Str( - desc='z distance for edge voxel offset', - argstr='-zorigin %s') + desc='z distance for edge voxel offset', argstr='-zorigin %s') duporigin_file = File( argstr='-duporigin %s', exists=True, desc='Copies the xorigin, yorigin, and zorigin values from the header ' - 'of the given dataset') - xdel = traits.Float( - desc='new x voxel dimension in mm', - argstr='-xdel %f') - ydel = traits.Float( - desc='new y voxel dimension in mm', - argstr='-ydel %f') - zdel = traits.Float( - desc='new z voxel dimension in mm', - argstr='-zdel %f') + 'of the given dataset') + xdel = traits.Float(desc='new x voxel dimension in mm', argstr='-xdel %f') + ydel = traits.Float(desc='new y voxel dimension in mm', argstr='-ydel %f') + zdel = traits.Float(desc='new z voxel dimension in mm', argstr='-zdel %f') xyzscale = traits.Float( desc='Scale the size of the dataset voxels by the given factor', argstr='-xyzscale %f') space = traits.Enum( - 'TLRC', 'MNI', 'ORIG', + 'TLRC', + 'MNI', + 'ORIG', argstr='-space %s', desc='Associates the dataset with a specific template type, e.g. ' - 'TLRC, MNI, ORIG') + 'TLRC, MNI, ORIG') atrcopy = traits.Tuple( - traits.File(exists=True), traits.Str(), + traits.File(exists=True), + traits.Str(), argstr='-atrcopy %s %s', desc='Copy AFNI header attribute from the given file into the header ' - 'of the dataset(s) being modified. For more information on AFNI ' - 'header attributes, see documentation file README.attributes. ' - 'More than one \'-atrcopy\' option can be used. For AFNI ' - 'advanced users only. Do NOT use -atrcopy or -atrstring with ' - 'other modification options. See also -copyaux.') + 'of the dataset(s) being modified. For more information on AFNI ' + 'header attributes, see documentation file README.attributes. ' + 'More than one \'-atrcopy\' option can be used. For AFNI ' + 'advanced users only. Do NOT use -atrcopy or -atrstring with ' + 'other modification options. See also -copyaux.') atrstring = traits.Tuple( - traits.Str(), traits.Str(), + traits.Str(), + traits.Str(), argstr='-atrstring %s %s', desc='Copy the last given string into the dataset(s) being modified, ' - 'giving it the attribute name given by the last string.' - 'To be safe, the last string should be in quotes.') + 'giving it the attribute name given by the last string.' + 'To be safe, the last string should be in quotes.') atrfloat = traits.Tuple( - traits.Str(), traits.Str(), + traits.Str(), + traits.Str(), argstr='-atrfloat %s %s', desc='Create or modify floating point attributes. ' - 'The input values may be specified as a single string in quotes ' - 'or as a 1D filename or string, example ' - '\'1 0.2 0 0 -0.2 1 0 0 0 0 1 0\' or ' - 'flipZ.1D or \'1D:1,0.2,2@0,-0.2,1,2@0,2@0,1,0\'') + 'The input values may be specified as a single string in quotes ' + 'or as a 1D filename or string, example ' + '\'1 0.2 0 0 -0.2 1 0 0 0 0 1 0\' or ' + 'flipZ.1D or \'1D:1,0.2,2@0,-0.2,1,2@0,2@0,1,0\'') atrint = traits.Tuple( - traits.Str(), traits.Str(), + traits.Str(), + traits.Str(), argstr='-atrint %s %s', desc='Create or modify integer attributes. ' - 'The input values may be specified as a single string in quotes ' - 'or as a 1D filename or string, example ' - '\'1 0 0 0 0 1 0 0 0 0 1 0\' or ' - 'flipZ.1D or \'1D:1,0,2@0,-0,1,2@0,2@0,1,0\'') + 'The input values may be specified as a single string in quotes ' + 'or as a 1D filename or string, example ' + '\'1 0 0 0 0 1 0 0 0 0 1 0\' or ' + 'flipZ.1D or \'1D:1,0,2@0,-0,1,2@0,2@0,1,0\'') saveatr = traits.Bool( argstr='-saveatr', desc='(default) Copy the attributes that are known to AFNI into ' - 'the dset->dblk structure thereby forcing changes to known ' - 'attributes to be present in the output. This option only makes ' - 'sense with -atrcopy.') - nosaveatr = traits.Bool( - argstr='-nosaveatr', - desc='Opposite of -saveatr') + 'the dset->dblk structure thereby forcing changes to known ' + 'attributes to be present in the output. This option only makes ' + 'sense with -atrcopy.') + nosaveatr = traits.Bool(argstr='-nosaveatr', desc='Opposite of -saveatr') class Refit(AFNICommandBase): @@ -1931,22 +1893,22 @@ class ResampleInputSpec(AFNICommandInputSpec): desc='output image file name', argstr='-prefix %s', name_source='in_file') - orientation = Str( - desc='new orientation code', - argstr='-orient %s') + orientation = Str(desc='new orientation code', argstr='-orient %s') resample_mode = traits.Enum( - 'NN', 'Li', 'Cu', 'Bk', + 'NN', + 'Li', + 'Cu', + 'Bk', argstr='-rmode %s', desc='resampling method from set {"NN", "Li", "Cu", "Bk"}. These are ' - 'for "Nearest Neighbor", "Linear", "Cubic" and "Blocky"' - 'interpolation, respectively. Default is NN.') + 'for "Nearest Neighbor", "Linear", "Cubic" and "Blocky"' + 'interpolation, respectively. Default is NN.') voxel_size = traits.Tuple( *[traits.Float()] * 3, argstr='-dxyz %f %f %f', desc='resample to new dx, dy and dz') master = traits.File( - argstr='-master %s', - desc='align dataset grid to a reference file') + argstr='-master %s', desc='align dataset grid to a reference file') class Resample(AFNICommand): @@ -1976,8 +1938,7 @@ class Resample(AFNICommand): class TCatInputSpec(AFNICommandInputSpec): in_files = InputMultiPath( - File( - exists=True), + File(exists=True), desc='input file to 3dTcat', argstr=' %s', position=-1, @@ -1989,17 +1950,18 @@ class TCatInputSpec(AFNICommandInputSpec): argstr='-prefix %s', name_source='in_files') rlt = traits.Enum( - '', '+', '++', + '', + '+', + '++', argstr='-rlt%s', desc='Remove linear trends in each voxel time series loaded from each ' - 'input dataset, SEPARATELY. Option -rlt removes the least squares ' - 'fit of \'a+b*t\' to each voxel time series. Option -rlt+ adds ' - 'dataset mean back in. Option -rlt++ adds overall mean of all ' - 'dataset timeseries back in.', + 'input dataset, SEPARATELY. Option -rlt removes the least squares ' + 'fit of \'a+b*t\' to each voxel time series. Option -rlt+ adds ' + 'dataset mean back in. Option -rlt++ adds overall mean of all ' + 'dataset timeseries back in.', position=1) verbose = traits.Bool( - desc='Print out some verbose output as the program', - argstr='-verb') + desc='Print out some verbose output as the program', argstr='-verb') class TCat(AFNICommand): @@ -2029,28 +1991,29 @@ class TCat(AFNICommand): input_spec = TCatInputSpec output_spec = AFNICommandOutputSpec + class TCatSBInputSpec(AFNICommandInputSpec): in_files = traits.List( - traits.Tuple(File(exists=True),Str()), + traits.Tuple(File(exists=True), Str()), desc='List of tuples of file names and subbrick selectors as strings.' - 'Don\'t forget to protect the single quotes in the subbrick selector' - 'so the contents are protected from the command line interpreter.', + 'Don\'t forget to protect the single quotes in the subbrick selector' + 'so the contents are protected from the command line interpreter.', argstr='%s%s ...', position=-1, mandatory=True, copyfile=False) out_file = File( - desc='output image file name', - argstr='-prefix %s', - genfile=True) + desc='output image file name', argstr='-prefix %s', genfile=True) rlt = traits.Enum( - '', '+', '++', + '', + '+', + '++', argstr='-rlt%s', desc='Remove linear trends in each voxel time series loaded from each ' - 'input dataset, SEPARATELY. Option -rlt removes the least squares ' - 'fit of \'a+b*t\' to each voxel time series. Option -rlt+ adds ' - 'dataset mean back in. Option -rlt++ adds overall mean of all ' - 'dataset timeseries back in.', + 'input dataset, SEPARATELY. Option -rlt removes the least squares ' + 'fit of \'a+b*t\' to each voxel time series. Option -rlt+ adds ' + 'dataset mean back in. Option -rlt++ adds overall mean of all ' + 'dataset timeseries back in.', position=1) @@ -2097,13 +2060,8 @@ class TStatInputSpec(AFNICommandInputSpec): desc='output image file name', argstr='-prefix %s', name_source='in_file') - mask = File( - desc='mask file', - argstr='-mask %s', - exists=True) - options = Str( - desc='selected statistical output', - argstr='%s') + mask = File(desc='mask file', argstr='-mask %s', exists=True) + options = Str(desc='selected statistical output', argstr='%s') class TStat(AFNICommand): @@ -2144,27 +2102,46 @@ class To3DInputSpec(AFNICommandInputSpec): mandatory=True, exists=True) filetype = traits.Enum( - 'spgr', 'fse', 'epan', 'anat', 'ct', 'spct', - 'pet', 'mra', 'bmap', 'diff', - 'omri', 'abuc', 'fim', 'fith', 'fico', 'fitt', - 'fift', 'fizt', 'fict', 'fibt', - 'fibn', 'figt', 'fipt', + 'spgr', + 'fse', + 'epan', + 'anat', + 'ct', + 'spct', + 'pet', + 'mra', + 'bmap', + 'diff', + 'omri', + 'abuc', + 'fim', + 'fith', + 'fico', + 'fitt', + 'fift', + 'fizt', + 'fict', + 'fibt', + 'fibn', + 'figt', + 'fipt', 'fbuc', argstr='-%s', desc='type of datafile being converted') skipoutliers = traits.Bool( - desc='skip the outliers check', - argstr='-skip_outliers') + desc='skip the outliers check', argstr='-skip_outliers') assumemosaic = traits.Bool( desc='assume that Siemens image is mosaic', argstr='-assume_dicom_mosaic') datatype = traits.Enum( - 'short', 'float', 'byte', 'complex', + 'short', + 'float', + 'byte', + 'complex', desc='set output file datatype', argstr='-datum %s') funcparams = Str( - desc='parameters for functional data', - argstr='-time:zt %s alt+z2') + desc='parameters for functional data', argstr='-time:zt %s alt+z2') class To3D(AFNICommand): @@ -2196,7 +2173,7 @@ class To3D(AFNICommand): class UndumpInputSpec(AFNICommandInputSpec): in_file = File( desc='input file to 3dUndump, whose geometry will determine' - 'the geometry of the output', + 'the geometry of the output', argstr='-master %s', position=-1, mandatory=True, @@ -2208,46 +2185,51 @@ class UndumpInputSpec(AFNICommandInputSpec): name_source='in_file') mask_file = File( desc='mask image file name. Only voxels that are nonzero in the mask ' - 'can be set.', + 'can be set.', argstr='-mask %s') datatype = traits.Enum( - 'short', 'float', 'byte', + 'short', + 'float', + 'byte', desc='set output file datatype', argstr='-datum %s') default_value = traits.Float( desc='default value stored in each input voxel that does not have ' - 'a value supplied in the input file', + 'a value supplied in the input file', argstr='-dval %f') fill_value = traits.Float( desc='value, used for each voxel in the output dataset that is NOT ' - 'listed in the input file', + 'listed in the input file', argstr='-fval %f') coordinates_specification = traits.Enum( - 'ijk', 'xyz', + 'ijk', + 'xyz', desc='Coordinates in the input file as index triples (i, j, k) ' - 'or spatial coordinates (x, y, z) in mm', + 'or spatial coordinates (x, y, z) in mm', argstr='-%s') srad = traits.Float( desc='radius in mm of the sphere that will be filled about each input ' - '(x,y,z) or (i,j,k) voxel. If the radius is not given, or is 0, ' - 'then each input data line sets the value in only one voxel.', + '(x,y,z) or (i,j,k) voxel. If the radius is not given, or is 0, ' + 'then each input data line sets the value in only one voxel.', argstr='-srad %f') orient = traits.Tuple( - traits.Enum('R', 'L'), traits.Enum('A', 'P'), traits.Enum('I', 'S'), + traits.Enum('R', 'L'), + traits.Enum('A', 'P'), + traits.Enum('I', 'S'), desc='Specifies the coordinate order used by -xyz. ' - 'The code must be 3 letters, one each from the pairs ' - '{R,L} {A,P} {I,S}. The first letter gives the ' - 'orientation of the x-axis, the second the orientation ' - 'of the y-axis, the third the z-axis: ' - 'R = right-to-left L = left-to-right ' - 'A = anterior-to-posterior P = posterior-to-anterior ' - 'I = inferior-to-superior S = superior-to-inferior ' - 'If -orient isn\'t used, then the coordinate order of the ' - '-master (in_file) dataset is used to interpret (x,y,z) inputs.', + 'The code must be 3 letters, one each from the pairs ' + '{R,L} {A,P} {I,S}. The first letter gives the ' + 'orientation of the x-axis, the second the orientation ' + 'of the y-axis, the third the z-axis: ' + 'R = right-to-left L = left-to-right ' + 'A = anterior-to-posterior P = posterior-to-anterior ' + 'I = inferior-to-superior S = superior-to-inferior ' + 'If -orient isn\'t used, then the coordinate order of the ' + '-master (in_file) dataset is used to interpret (x,y,z) inputs.', argstr='-orient %s') head_only = traits.Bool( desc='create only the .HEAD file which gets exploited by ' - 'the AFNI matlab library function New_HEAD.m', + 'the AFNI matlab library function New_HEAD.m', argstr='-head_only') @@ -2312,63 +2294,64 @@ class UnifizeInputSpec(AFNICommandInputSpec): name_source='in_file') t2 = traits.Bool( desc='Treat the input as if it were T2-weighted, rather than ' - 'T1-weighted. This processing is done simply by inverting ' - 'the image contrast, processing it as if that result were ' - 'T1-weighted, and then re-inverting the results ' - 'counts of voxel overlap, i.e., each voxel will contain the ' - 'number of masks that it is set in.', + 'T1-weighted. This processing is done simply by inverting ' + 'the image contrast, processing it as if that result were ' + 'T1-weighted, and then re-inverting the results ' + 'counts of voxel overlap, i.e., each voxel will contain the ' + 'number of masks that it is set in.', argstr='-T2') gm = traits.Bool( desc='Also scale to unifize \'gray matter\' = lower intensity voxels ' - '(to aid in registering images from different scanners).', + '(to aid in registering images from different scanners).', argstr='-GM') urad = traits.Float( desc='Sets the radius (in voxels) of the ball used for the sneaky ' - 'trick. Default value is 18.3, and should be changed ' - 'proportionally if the dataset voxel size differs significantly ' - 'from 1 mm.', + 'trick. Default value is 18.3, and should be changed ' + 'proportionally if the dataset voxel size differs significantly ' + 'from 1 mm.', argstr='-Urad %s') scale_file = File( desc='output file name to save the scale factor used at each voxel ', argstr='-ssave %s') no_duplo = traits.Bool( desc='Do NOT use the \'duplo down\' step; this can be useful for ' - 'lower resolution datasets.', + 'lower resolution datasets.', argstr='-noduplo') epi = traits.Bool( desc='Assume the input dataset is a T2 (or T2*) weighted EPI time ' - 'series. After computing the scaling, apply it to ALL volumes ' - '(TRs) in the input dataset. That is, a given voxel will be ' - 'scaled by the same factor at each TR. ' - 'This option also implies \'-noduplo\' and \'-T2\'.' - 'This option turns off \'-GM\' if you turned it on.', + 'series. After computing the scaling, apply it to ALL volumes ' + '(TRs) in the input dataset. That is, a given voxel will be ' + 'scaled by the same factor at each TR. ' + 'This option also implies \'-noduplo\' and \'-T2\'.' + 'This option turns off \'-GM\' if you turned it on.', argstr='-EPI', requires=['no_duplo', 't2'], xor=['gm']) rbt = traits.Tuple( - traits.Float(), traits.Float(), traits.Float(), + traits.Float(), + traits.Float(), + traits.Float(), desc='Option for AFNI experts only.' - 'Specify the 3 parameters for the algorithm:\n' - 'R = radius; same as given by option \'-Urad\', [default=18.3]\n' - 'b = bottom percentile of normalizing data range, [default=70.0]\n' - 'r = top percentile of normalizing data range, [default=80.0]\n', + 'Specify the 3 parameters for the algorithm:\n' + 'R = radius; same as given by option \'-Urad\', [default=18.3]\n' + 'b = bottom percentile of normalizing data range, [default=70.0]\n' + 'r = top percentile of normalizing data range, [default=80.0]\n', argstr='-rbt %f %f %f') t2_up = traits.Float( desc='Option for AFNI experts only.' - 'Set the upper percentile point used for T2-T1 inversion. ' - 'Allowed to be anything between 90 and 100 (inclusive), with ' - 'default to 98.5 (for no good reason).', + 'Set the upper percentile point used for T2-T1 inversion. ' + 'Allowed to be anything between 90 and 100 (inclusive), with ' + 'default to 98.5 (for no good reason).', argstr='-T2up %f') cl_frac = traits.Float( desc='Option for AFNI experts only.' - 'Set the automask \'clip level fraction\'. Must be between ' - '0.1 and 0.9. A small fraction means to make the initial ' - 'threshold for clipping (a la 3dClipLevel) smaller, which ' - 'will tend to make the mask larger. [default=0.1]', + 'Set the automask \'clip level fraction\'. Must be between ' + '0.1 and 0.9. A small fraction means to make the initial ' + 'threshold for clipping (a la 3dClipLevel) smaller, which ' + 'will tend to make the mask larger. [default=0.1]', argstr='-clfrac %f') quiet = traits.Bool( - desc='Don\'t print the progress messages.', - argstr='-quiet') + desc='Don\'t print the progress messages.', argstr='-quiet') class UnifizeOutputSpec(TraitedSpec): @@ -2438,9 +2421,7 @@ class ZCutUpInputSpec(AFNICommandInputSpec): desc='output image file name', argstr='-prefix %s', name_source='in_file') - keep = Str( - desc='slice range to keep in output', - argstr='-keep %s') + keep = Str(desc='slice range to keep in output', argstr='-keep %s') class ZCutUp(AFNICommand): @@ -2483,10 +2464,12 @@ class GCORInputSpec(CommandLineInputSpec): exists=True, copyfile=False) - nfirst = traits.Int(0, argstr='-nfirst %d', - desc='specify number of initial TRs to ignore') - no_demean = traits.Bool(False, argstr='-no_demean', - desc='do not (need to) demean as first step') + nfirst = traits.Int( + 0, argstr='-nfirst %d', desc='specify number of initial TRs to ignore') + no_demean = traits.Bool( + False, + argstr='-no_demean', + desc='do not (need to) demean as first step') class GCOROutputSpec(TraitedSpec): @@ -2522,14 +2505,17 @@ class GCOR(CommandLine): def _run_interface(self, runtime): runtime = super(GCOR, self)._run_interface(runtime) - gcor_line = [line.strip() for line in runtime.stdout.split('\n') - if line.strip().startswith('GCOR = ')][-1] + gcor_line = [ + line.strip() for line in runtime.stdout.split('\n') + if line.strip().startswith('GCOR = ') + ][-1] setattr(self, '_gcor', float(gcor_line[len('GCOR = '):])) return runtime def _list_outputs(self): return {'out': getattr(self, '_gcor')} + class AxializeInputSpec(AFNICommandInputSpec): in_file = File( desc='input file to 3daxialize', @@ -2543,9 +2529,7 @@ class AxializeInputSpec(AFNICommandInputSpec): desc='output image file name', argstr='-prefix %s', name_source='in_file') - verb = traits.Bool( - desc='Print out a progerss report', - argstr='-verb') + verb = traits.Bool(desc='Print out a progerss report', argstr='-verb') sagittal = traits.Bool( desc='Do sagittal slice order [-orient ASL]', argstr='-sagittal', @@ -2556,16 +2540,14 @@ class AxializeInputSpec(AFNICommandInputSpec): xor=['sagittal', 'axial']) axial = traits.Bool( desc='Do axial slice order [-orient RAI]' - 'This is the default AFNI axial order, and' - 'is the one currently required by the' - 'volume rendering plugin; this is also' - 'the default orientation output by this' - "program (hence the program's name).", + 'This is the default AFNI axial order, and' + 'is the one currently required by the' + 'volume rendering plugin; this is also' + 'the default orientation output by this' + "program (hence the program's name).", argstr='-axial', xor=['coronal', 'sagittal']) - orientation = Str( - desc='new orientation code', - argstr='-orient %s') + orientation = Str(desc='new orientation code', argstr='-orient %s') class Axialize(AFNICommand): @@ -2594,9 +2576,7 @@ class Axialize(AFNICommand): class ZcatInputSpec(AFNICommandInputSpec): in_files = InputMultiPath( - File( - desc='input files to 3dZcat', - exists=True), + File(desc='input files to 3dZcat', exists=True), argstr='%s', position=-1, mandatory=True, @@ -2606,29 +2586,32 @@ class ZcatInputSpec(AFNICommandInputSpec): desc='output dataset prefix name (default \'zcat\')', argstr='-prefix %s') datum = traits.Enum( - 'byte','short','float', + 'byte', + 'short', + 'float', argstr='-datum %s', desc='specify data type for output. Valid types are \'byte\', ' - '\'short\' and \'float\'.') + '\'short\' and \'float\'.') verb = traits.Bool( desc='print out some verbositiness as the program proceeds.', argstr='-verb') fscale = traits.Bool( desc='Force scaling of the output to the maximum integer ' - 'range. This only has effect if the output datum is ' - 'byte or short (either forced or defaulted). This ' - 'option is sometimes necessary to eliminate ' - 'unpleasant truncation artifacts.', + 'range. This only has effect if the output datum is ' + 'byte or short (either forced or defaulted). This ' + 'option is sometimes necessary to eliminate ' + 'unpleasant truncation artifacts.', argstr='-fscale', xor=['nscale']) nscale = traits.Bool( desc='Don\'t do any scaling on output to byte or short ' - 'datasets. This may be especially useful when ' - 'operating on mask datasets whose output values ' - 'are only 0\'s and 1\'s.', + 'datasets. This may be especially useful when ' + 'operating on mask datasets whose output values ' + 'are only 0\'s and 1\'s.', argstr='-nscale', xor=['fscale']) + class Zcat(AFNICommand): """Copies an image of one type to an image of the same or different type using 3dZcat command @@ -2652,6 +2635,7 @@ class Zcat(AFNICommand): input_spec = ZcatInputSpec output_spec = AFNICommandOutputSpec + class ZeropadInputSpec(AFNICommandInputSpec): in_files = File( desc='input dataset', @@ -2690,41 +2674,46 @@ class ZeropadInputSpec(AFNICommandInputSpec): xor=['master']) z = traits.Int( desc='adds \'n\' planes of zero on EACH of the ' - 'dataset z-axis (slice-direction) faces', + 'dataset z-axis (slice-direction) faces', argstr='-z %i', xor=['master']) - RL = traits.Int(desc='specify that planes should be added or cut ' - 'symmetrically to make the resulting volume have' - 'N slices in the right-left direction', - argstr='-RL %i', - xor=['master']) - AP = traits.Int(desc='specify that planes should be added or cut ' - 'symmetrically to make the resulting volume have' - 'N slices in the anterior-posterior direction', - argstr='-AP %i', - xor=['master']) - IS = traits.Int(desc='specify that planes should be added or cut ' - 'symmetrically to make the resulting volume have' - 'N slices in the inferior-superior direction', - argstr='-IS %i', - xor=['master']) - mm = traits.Bool(desc='pad counts \'n\' are in mm instead of slices, ' - 'where each \'n\' is an integer and at least \'n\' ' - 'mm of slices will be added/removed; e.g., n = 3 ' - 'and slice thickness = 2.5 mm ==> 2 slices added', - argstr='-mm', - xor=['master']) - master = traits.File(desc='match the volume described in dataset ' - '\'mset\', where mset must have the same ' - 'orientation and grid spacing as dataset to be ' - 'padded. the goal of -master is to make the ' - 'output dataset from 3dZeropad match the ' - 'spatial \'extents\' of mset by adding or ' - 'subtracting slices as needed. You can\'t use ' - '-I,-S,..., or -mm with -master', - argstr='-master %s', - xor=['I', 'S', 'A', 'P', 'L', 'R', 'z', - 'RL', 'AP', 'IS', 'mm']) + RL = traits.Int( + desc='specify that planes should be added or cut ' + 'symmetrically to make the resulting volume have' + 'N slices in the right-left direction', + argstr='-RL %i', + xor=['master']) + AP = traits.Int( + desc='specify that planes should be added or cut ' + 'symmetrically to make the resulting volume have' + 'N slices in the anterior-posterior direction', + argstr='-AP %i', + xor=['master']) + IS = traits.Int( + desc='specify that planes should be added or cut ' + 'symmetrically to make the resulting volume have' + 'N slices in the inferior-superior direction', + argstr='-IS %i', + xor=['master']) + mm = traits.Bool( + desc='pad counts \'n\' are in mm instead of slices, ' + 'where each \'n\' is an integer and at least \'n\' ' + 'mm of slices will be added/removed; e.g., n = 3 ' + 'and slice thickness = 2.5 mm ==> 2 slices added', + argstr='-mm', + xor=['master']) + master = traits.File( + desc='match the volume described in dataset ' + '\'mset\', where mset must have the same ' + 'orientation and grid spacing as dataset to be ' + 'padded. the goal of -master is to make the ' + 'output dataset from 3dZeropad match the ' + 'spatial \'extents\' of mset by adding or ' + 'subtracting slices as needed. You can\'t use ' + '-I,-S,..., or -mm with -master', + argstr='-master %s', + xor=['I', 'S', 'A', 'P', 'L', 'R', 'z', 'RL', 'AP', 'IS', 'mm']) + class Zeropad(AFNICommand): """Adds planes of zeros to a dataset (i.e., pads it out). diff --git a/nipype/interfaces/ants/__init__.py b/nipype/interfaces/ants/__init__.py index e8096cc8e0..0de5c1646f 100644 --- a/nipype/interfaces/ants/__init__.py +++ b/nipype/interfaces/ants/__init__.py @@ -1,19 +1,20 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """Top-level namespace for ants.""" # Registraiton programs from .registration import ANTS, Registration, MeasureImageSimilarity # Resampling Programs -from .resampling import (ApplyTransforms, ApplyTransformsToPoints, WarpImageMultiTransform, +from .resampling import (ApplyTransforms, ApplyTransformsToPoints, + WarpImageMultiTransform, WarpTimeSeriesImageMultiTransform) # Segmentation Programs -from .segmentation import (Atropos, LaplacianThickness, N4BiasFieldCorrection, JointFusion, CorticalThickness, - BrainExtraction, DenoiseImage, AntsJointFusion) +from .segmentation import (Atropos, LaplacianThickness, N4BiasFieldCorrection, + JointFusion, CorticalThickness, BrainExtraction, + DenoiseImage, AntsJointFusion) # Visualization Programs from .visualization import ConvertScalarImageToRGB, CreateTiledMosaic diff --git a/nipype/interfaces/ants/base.py b/nipype/interfaces/ants/base.py index 00553fd977..7316c2a733 100644 --- a/nipype/interfaces/ants/base.py +++ b/nipype/interfaces/ants/base.py @@ -2,7 +2,8 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The ants module provides basic functions for interfacing with ANTS tools.""" -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str import os @@ -46,7 +47,8 @@ def parse_version(raw_info): v_string = v_string.split('-')[0] # 2.2.0-equivalent version string - if 'post' in v_string and LooseVersion(v_string) >= LooseVersion('2.1.0.post789'): + if 'post' in v_string and \ + LooseVersion(v_string) >= LooseVersion('2.1.0.post789'): return '2.2.0' else: return '.'.join(v_string.split('.')[:3]) @@ -56,8 +58,11 @@ class ANTSCommandInputSpec(CommandLineInputSpec): """Base Input Specification for all ANTS Commands """ - num_threads = traits.Int(LOCAL_DEFAULT_NUMBER_OF_THREADS, usedefault=True, - nohash=True, desc="Number of ITK threads to use") + num_threads = traits.Int( + LOCAL_DEFAULT_NUMBER_OF_THREADS, + usedefault=True, + nohash=True, + desc="Number of ITK threads to use") class ANTSCommand(CommandLine): @@ -93,12 +98,15 @@ def _num_threads_update(self): if (PREFERED_ITKv4_THREAD_LIMIT_VARIABLE in self.inputs.environ): del self.inputs.environ[PREFERED_ITKv4_THREAD_LIMIT_VARIABLE] else: - self.inputs.environ.update({PREFERED_ITKv4_THREAD_LIMIT_VARIABLE: - '%s' % self.inputs.num_threads}) + self.inputs.environ.update({ + PREFERED_ITKv4_THREAD_LIMIT_VARIABLE: + '%s' % self.inputs.num_threads + }) @staticmethod def _format_xarray(val): - """ Convenience method for converting input arrays [1,2,3] to commandline format '1x2x3' """ + """ Convenience method for converting input arrays [1,2,3] to + commandline format '1x2x3' """ return 'x'.join([str(x) for x in val]) @classmethod diff --git a/nipype/interfaces/ants/legacy.py b/nipype/interfaces/ants/legacy.py index 7df1731fa1..9ca5844426 100644 --- a/nipype/interfaces/ants/legacy.py +++ b/nipype/interfaces/ants/legacy.py @@ -23,54 +23,89 @@ class antsIntroductionInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='-d %d', usedefault=True, - desc='image dimension (2 or 3)', position=1) - reference_image = File(exists=True, - argstr='-r %s', desc='template file to warp to', - mandatory=True, copyfile=True) - input_image = File(exists=True, - argstr='-i %s', desc='input image to warp to template', - mandatory=True, copyfile=False) - force_proceed = traits.Bool(argstr='-f 1', - desc=('force script to proceed even if headers ' - 'may be incompatible')) - inverse_warp_template_labels = traits.Bool(argstr='-l', - desc=('Applies inverse warp to the template labels ' - 'to estimate label positions in target space (use ' - 'for template-based segmentation)')) - max_iterations = traits.List(traits.Int, argstr='-m %s', sep='x', - desc=('maximum number of iterations (must be ' - 'list of integers in the form [J,K,L...]: ' - 'J = coarsest resolution iterations, K = ' - 'middle resolution interations, L = fine ' - 'resolution iterations')) - bias_field_correction = traits.Bool(argstr='-n 1', - desc=('Applies bias field correction to moving ' - 'image')) - similarity_metric = traits.Enum('PR', 'CC', 'MI', 'MSQ', argstr='-s %s', - desc=('Type of similartiy metric used for registration ' - '(CC = cross correlation, MI = mutual information, ' - 'PR = probability mapping, MSQ = mean square difference)')) - transformation_model = traits.Enum('GR', 'EL', 'SY', 'S2', 'EX', 'DD', 'RI', - 'RA', argstr='-t %s', usedefault=True, - desc=('Type of transofmration model used for registration ' - '(EL = elastic transformation model, SY = SyN with time, ' - 'arbitrary number of time points, S2 = SyN with time ' - 'optimized for 2 time points, GR = greedy SyN, EX = ' - 'exponential, DD = diffeomorphic demons style exponential ' - 'mapping, RI = purely rigid, RA = affine rigid')) - out_prefix = traits.Str('ants_', argstr='-o %s', usedefault=True, - desc=('Prefix that is prepended to all output ' - 'files (default = ants_)')) - quality_check = traits.Bool(argstr='-q 1', - desc='Perform a quality check of the result') + dimension = traits.Enum( + 3, + 2, + argstr='-d %d', + usedefault=True, + desc='image dimension (2 or 3)', + position=1) + reference_image = File( + exists=True, + argstr='-r %s', + desc='template file to warp to', + mandatory=True, + copyfile=True) + input_image = File( + exists=True, + argstr='-i %s', + desc='input image to warp to template', + mandatory=True, + copyfile=False) + force_proceed = traits.Bool( + argstr='-f 1', + desc=('force script to proceed even if headers ' + 'may be incompatible')) + inverse_warp_template_labels = traits.Bool( + argstr='-l', + desc=('Applies inverse warp to the template labels ' + 'to estimate label positions in target space (use ' + 'for template-based segmentation)')) + max_iterations = traits.List( + traits.Int, + argstr='-m %s', + sep='x', + desc=('maximum number of iterations (must be ' + 'list of integers in the form [J,K,L...]: ' + 'J = coarsest resolution iterations, K = ' + 'middle resolution interations, L = fine ' + 'resolution iterations')) + bias_field_correction = traits.Bool( + argstr='-n 1', + desc=('Applies bias field correction to moving ' + 'image')) + similarity_metric = traits.Enum( + 'PR', + 'CC', + 'MI', + 'MSQ', + argstr='-s %s', + desc=('Type of similartiy metric used for registration ' + '(CC = cross correlation, MI = mutual information, ' + 'PR = probability mapping, MSQ = mean square difference)')) + transformation_model = traits.Enum( + 'GR', + 'EL', + 'SY', + 'S2', + 'EX', + 'DD', + 'RI', + 'RA', + argstr='-t %s', + usedefault=True, + desc=('Type of transofmration model used for registration ' + '(EL = elastic transformation model, SY = SyN with time, ' + 'arbitrary number of time points, S2 = SyN with time ' + 'optimized for 2 time points, GR = greedy SyN, EX = ' + 'exponential, DD = diffeomorphic demons style exponential ' + 'mapping, RI = purely rigid, RA = affine rigid')) + out_prefix = traits.Str( + 'ants_', + argstr='-o %s', + usedefault=True, + desc=('Prefix that is prepended to all output ' + 'files (default = ants_)')) + quality_check = traits.Bool( + argstr='-q 1', desc='Perform a quality check of the result') class antsIntroductionOutputSpec(TraitedSpec): - affine_transformation = File(exists=True, desc='affine (prefix_Affine.txt)') + affine_transformation = File( + exists=True, desc='affine (prefix_Affine.txt)') warp_field = File(exists=True, desc='warp field (prefix_Warp.nii)') - inverse_warp_field = File(exists=True, - desc='inverse warp field (prefix_InverseWarp.nii)') + inverse_warp_field = File( + exists=True, desc='inverse warp field (prefix_InverseWarp.nii)') input_file = File(exists=True, desc='input image (prefix_repaired.nii)') output_file = File(exists=True, desc='output image (prefix_deformed.nii)') @@ -101,26 +136,23 @@ def _list_outputs(self): # When transform is set as 'RI'/'RA', wrap fields should not be expected # The default transformation is GR, which outputs the wrap fields - if not isdefined(transmodel) or (isdefined(transmodel) and transmodel not in ['RI', 'RA']): - outputs['warp_field'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'Warp.nii.gz') - outputs['inverse_warp_field'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'InverseWarp.nii.gz') - - outputs['affine_transformation'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'Affine.txt') - outputs['input_file'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'repaired.nii.gz') - outputs['output_file'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'deformed.nii.gz') + if not isdefined(transmodel) or (isdefined(transmodel) + and transmodel not in ['RI', 'RA']): + outputs['warp_field'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'Warp.nii.gz') + outputs['inverse_warp_field'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'InverseWarp.nii.gz') + + outputs['affine_transformation'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'Affine.txt') + outputs['input_file'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'repaired.nii.gz') + outputs['output_file'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'deformed.nii.gz') return outputs + # How do we make a pass through so that GenWarpFields is just an alias for antsIntroduction ? @@ -129,65 +161,107 @@ class GenWarpFields(antsIntroduction): class buildtemplateparallelInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, 4, argstr='-d %d', usedefault=True, - desc='image dimension (2, 3 or 4)', position=1) - out_prefix = traits.Str('antsTMPL_', argstr='-o %s', usedefault=True, - desc=('Prefix that is prepended to all output ' - 'files (default = antsTMPL_)')) - in_files = traits.List(File(exists=True), mandatory=True, - desc='list of images to generate template from', - argstr='%s', position=-1) - parallelization = traits.Enum(0, 1, 2, argstr='-c %d', usedefault=True, - desc=('control for parallel processing (0 = ' - 'serial, 1 = use PBS, 2 = use PEXEC, 3 = ' - 'use Apple XGrid')) - gradient_step_size = traits.Float(argstr='-g %f', - desc=('smaller magnitude results in ' - 'more cautious steps (default = ' - '.25)')) - iteration_limit = traits.Int(4, argstr='-i %d', usedefault=True, - desc='iterations of template construction') - num_cores = traits.Int(argstr='-j %d', requires=['parallelization'], - desc=('Requires parallelization = 2 (PEXEC). ' - 'Sets number of cpu cores to use')) - max_iterations = traits.List(traits.Int, argstr='-m %s', sep='x', - desc=('maximum number of iterations (must be ' - 'list of integers in the form [J,K,L...]: ' - 'J = coarsest resolution iterations, K = ' - 'middle resolution interations, L = fine ' - 'resolution iterations')) - bias_field_correction = traits.Bool(argstr='-n 1', - desc=('Applies bias field correction to moving ' - 'image')) - rigid_body_registration = traits.Bool(argstr='-r 1', - desc=('registers inputs before creating template ' - '(useful if no initial template available)')) - similarity_metric = traits.Enum('PR', 'CC', 'MI', 'MSQ', argstr='-s %s', - desc=('Type of similartiy metric used for registration ' - '(CC = cross correlation, MI = mutual information, ' - 'PR = probability mapping, MSQ = mean square difference)')) - transformation_model = traits.Enum('GR', 'EL', 'SY', 'S2', 'EX', 'DD', - argstr='-t %s', usedefault=True, - desc=('Type of transofmration model used for registration ' - '(EL = elastic transformation model, SY = SyN with time, ' - 'arbitrary number of time points, S2 = SyN with time ' - 'optimized for 2 time points, GR = greedy SyN, EX = ' - 'exponential, DD = diffeomorphic demons style exponential ' - 'mapping')) - use_first_as_target = traits.Bool(desc=('uses first volume as target of ' - 'all inputs. When not used, an ' - 'unbiased average image is used ' - 'to start.')) + dimension = traits.Enum( + 3, + 2, + 4, + argstr='-d %d', + usedefault=True, + desc='image dimension (2, 3 or 4)', + position=1) + out_prefix = traits.Str( + 'antsTMPL_', + argstr='-o %s', + usedefault=True, + desc=('Prefix that is prepended to all output ' + 'files (default = antsTMPL_)')) + in_files = traits.List( + File(exists=True), + mandatory=True, + desc='list of images to generate template from', + argstr='%s', + position=-1) + parallelization = traits.Enum( + 0, + 1, + 2, + argstr='-c %d', + usedefault=True, + desc=('control for parallel processing (0 = ' + 'serial, 1 = use PBS, 2 = use PEXEC, 3 = ' + 'use Apple XGrid')) + gradient_step_size = traits.Float( + argstr='-g %f', + desc=('smaller magnitude results in ' + 'more cautious steps (default = ' + '.25)')) + iteration_limit = traits.Int( + 4, + argstr='-i %d', + usedefault=True, + desc='iterations of template construction') + num_cores = traits.Int( + argstr='-j %d', + requires=['parallelization'], + desc=('Requires parallelization = 2 (PEXEC). ' + 'Sets number of cpu cores to use')) + max_iterations = traits.List( + traits.Int, + argstr='-m %s', + sep='x', + desc=('maximum number of iterations (must be ' + 'list of integers in the form [J,K,L...]: ' + 'J = coarsest resolution iterations, K = ' + 'middle resolution interations, L = fine ' + 'resolution iterations')) + bias_field_correction = traits.Bool( + argstr='-n 1', + desc=('Applies bias field correction to moving ' + 'image')) + rigid_body_registration = traits.Bool( + argstr='-r 1', + desc=('registers inputs before creating template ' + '(useful if no initial template available)')) + similarity_metric = traits.Enum( + 'PR', + 'CC', + 'MI', + 'MSQ', + argstr='-s %s', + desc=('Type of similartiy metric used for registration ' + '(CC = cross correlation, MI = mutual information, ' + 'PR = probability mapping, MSQ = mean square difference)')) + transformation_model = traits.Enum( + 'GR', + 'EL', + 'SY', + 'S2', + 'EX', + 'DD', + argstr='-t %s', + usedefault=True, + desc=('Type of transofmration model used for registration ' + '(EL = elastic transformation model, SY = SyN with time, ' + 'arbitrary number of time points, S2 = SyN with time ' + 'optimized for 2 time points, GR = greedy SyN, EX = ' + 'exponential, DD = diffeomorphic demons style exponential ' + 'mapping')) + use_first_as_target = traits.Bool( + desc=('uses first volume as target of ' + 'all inputs. When not used, an ' + 'unbiased average image is used ' + 'to start.')) class buildtemplateparallelOutputSpec(TraitedSpec): final_template_file = File(exists=True, desc='final ANTS template') - template_files = OutputMultiPath(File(exists=True), - desc='Templates from different stages of iteration') - subject_outfiles = OutputMultiPath(File(exists=True), - desc=('Outputs for each input image. Includes warp ' - 'field, inverse warp, Affine, original image ' - '(repaired) and warped image (deformed)')) + template_files = OutputMultiPath( + File(exists=True), desc='Templates from different stages of iteration') + subject_outfiles = OutputMultiPath( + File(exists=True), + desc=('Outputs for each input image. Includes warp ' + 'field, inverse warp, Affine, original image ' + '(repaired) and warped image (deformed)')) class buildtemplateparallel(ANTSCommand): @@ -232,20 +306,16 @@ def _list_outputs(self): outputs['template_files'] = [] for i in range(len(glob(os.path.realpath('*iteration*')))): temp = os.path.realpath('%s_iteration_%d/%stemplate.nii.gz' % - (self.inputs.transformation_model, - i, + (self.inputs.transformation_model, i, self.inputs.out_prefix)) - os.rename(temp, - os.path.realpath('%s_iteration_%d/%stemplate_i%d.nii.gz' % - (self.inputs.transformation_model, - i, - self.inputs.out_prefix, - i))) + os.rename( + temp, + os.path.realpath('%s_iteration_%d/%stemplate_i%d.nii.gz' % + (self.inputs.transformation_model, i, + self.inputs.out_prefix, i))) file_ = ('%s_iteration_%d/%stemplate_i%d.nii.gz' % - (self.inputs.transformation_model, - i, - self.inputs.out_prefix, - i)) + (self.inputs.transformation_model, i, + self.inputs.out_prefix, i)) outputs['template_files'].append(os.path.realpath(file_)) outputs['final_template_file'] = \ @@ -254,8 +324,8 @@ def _list_outputs(self): outputs['subject_outfiles'] = [] for filename in self.inputs.in_files: _, base, _ = split_filename(filename) - temp = glob(os.path.realpath('%s%s*' % (self.inputs.out_prefix, - base))) + temp = glob( + os.path.realpath('%s%s*' % (self.inputs.out_prefix, base))) for file_ in temp: outputs['subject_outfiles'].append(file_) return outputs diff --git a/nipype/interfaces/ants/registration.py b/nipype/interfaces/ants/registration.py index a5fd0e63da..843e9b3043 100644 --- a/nipype/interfaces/ants/registration.py +++ b/nipype/interfaces/ants/registration.py @@ -19,56 +19,83 @@ class ANTSInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='%d', usedefault=False, - position=1, desc='image dimension (2 or 3)') - fixed_image = InputMultiPath(File(exists=True), mandatory=True, - desc=('image to which the moving image is ' - 'warped')) - moving_image = InputMultiPath(File(exists=True), argstr='%s', - mandatory=True, - desc=('image to apply transformation to ' - '(generally a coregistered' - 'functional)')) - -# Not all metrics are appropriate for all modalities. Also, not all metrics -# are efficeint or appropriate at all resolution levels, Some metrics -# perform well for gross global registraiton, but do poorly for small -# changes (i.e. Mattes), and some metrics do well for small changes but -# don't work well for gross level changes (i.e. 'CC'). -# -# This is a two stage registration. in the first stage -# [ 'Mattes', .................] -# ^^^^^^ <- First stage -# Do a unimodal registration of the first elements of the fixed/moving input -# list use the"CC" as the metric. -# -# In the second stage -# [ ....., ['Mattes','CC'] ] -# ^^^^^^^^^^^^^^^ <- Second stage -# Do a multi-modal registration where the first elements of fixed/moving -# input list use 'CC' metric and that is added to 'Mattes' metric result of -# the second elements of the fixed/moving input. -# -# Cost = Sum_i ( metricweight[i] Metric_i ( fixedimage[i], movingimage[i]) ) - metric = traits.List(traits.Enum('CC', 'MI', 'SMI', 'PR', 'SSD', - 'MSQ', 'PSE'), mandatory=True, desc='') - - metric_weight = traits.List(traits.Float(), value=[1.0], usedefault=True, - requires=['metric'], mandatory=True, - desc='the metric weight(s) for each stage. ' - 'The weights must sum to 1 per stage.') - - radius = traits.List(traits.Int(), requires=['metric'], mandatory=True, - desc='radius of the region (i.e. number of layers' - ' around a voxel point)' - ' that is used for computing cross correlation') - - output_transform_prefix = Str('out', usedefault=True, - argstr='--output-naming %s', - mandatory=True, desc='') - transformation_model = traits.Enum('Diff', 'Elast', 'Exp', 'Greedy Exp', - 'SyN', argstr='%s', mandatory=True, - desc='') + dimension = traits.Enum( + 3, + 2, + argstr='%d', + usedefault=False, + position=1, + desc='image dimension (2 or 3)') + fixed_image = InputMultiPath( + File(exists=True), + mandatory=True, + desc=('image to which the moving image is ' + 'warped')) + moving_image = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + desc=('image to apply transformation to ' + '(generally a coregistered' + 'functional)')) + + # Not all metrics are appropriate for all modalities. Also, not all metrics + # are efficeint or appropriate at all resolution levels, Some metrics + # perform well for gross global registraiton, but do poorly for small + # changes (i.e. Mattes), and some metrics do well for small changes but + # don't work well for gross level changes (i.e. 'CC'). + # + # This is a two stage registration. in the first stage + # [ 'Mattes', .................] + # ^^^^^^ <- First stage + # Do a unimodal registration of the first elements of the fixed/moving input + # list use the"CC" as the metric. + # + # In the second stage + # [ ....., ['Mattes','CC'] ] + # ^^^^^^^^^^^^^^^ <- Second stage + # Do a multi-modal registration where the first elements of fixed/moving + # input list use 'CC' metric and that is added to 'Mattes' metric result of + # the second elements of the fixed/moving input. + # + # Cost = Sum_i ( metricweight[i] Metric_i ( fixedimage[i], movingimage[i]) ) + metric = traits.List( + traits.Enum('CC', 'MI', 'SMI', 'PR', 'SSD', 'MSQ', 'PSE'), + mandatory=True, + desc='') + + metric_weight = traits.List( + traits.Float(), + value=[1.0], + usedefault=True, + requires=['metric'], + mandatory=True, + desc='the metric weight(s) for each stage. ' + 'The weights must sum to 1 per stage.') + + radius = traits.List( + traits.Int(), + requires=['metric'], + mandatory=True, + desc='radius of the region (i.e. number of layers' + ' around a voxel point)' + ' that is used for computing cross correlation') + + output_transform_prefix = Str( + 'out', + usedefault=True, + argstr='--output-naming %s', + mandatory=True, + desc='') + transformation_model = traits.Enum( + 'Diff', + 'Elast', + 'Exp', + 'Greedy Exp', + 'SyN', + argstr='%s', + mandatory=True, + desc='') gradient_step_length = traits.Float( requires=['transformation_model'], desc='') number_of_time_steps = traits.Float( @@ -106,7 +133,6 @@ class ANTSOutputSpec(TraitedSpec): class ANTS(ANTSCommand): - """ @@ -147,14 +173,10 @@ def _image_metric_constructor(self): for ii in range(len(self.inputs.moving_image)): if self.inputs.metric[ii] in intensity_based: retval.append( - '--image-metric %s[ %s, %s, %g, %d ]' % (self.inputs.metric[ii], - self.inputs.fixed_image[ - ii], - self.inputs.moving_image[ - ii], - self.inputs.metric_weight[ - ii], - self.inputs.radius[ii])) + '--image-metric %s[ %s, %s, %g, %d ]' % + (self.inputs.metric[ii], self.inputs.fixed_image[ii], + self.inputs.moving_image[ii], + self.inputs.metric_weight[ii], self.inputs.radius[ii])) elif self.inputs.metric[ii] == point_set_based: pass # retval.append('--image-metric %s[%s, %s, ...'.format(self.inputs.metric[ii], @@ -181,9 +203,10 @@ def _transformation_constructor(self): return ''.join(retval) def _regularization_constructor(self): - return '--regularization {0}[{1},{2}]'.format(self.inputs.regularization, - self.inputs.regularization_gradient_field_sigma, - self.inputs.regularization_deformation_field_sigma) + return '--regularization {0}[{1},{2}]'.format( + self.inputs.regularization, + self.inputs.regularization_gradient_field_sigma, + self.inputs.regularization_deformation_field_sigma) def _affine_gradient_descent_option_constructor(self): values = self.inputs.affine_gradient_descent_option @@ -228,171 +251,237 @@ def _list_outputs(self): class RegistrationInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='--dimensionality %d', - usedefault=True, desc='image dimension (2 or 3)') - fixed_image = InputMultiPath(File(exists=True), mandatory=True, - desc='Image to which the moving_image should be transformed' - '(usually a structural image)') + dimension = traits.Enum( + 3, + 2, + argstr='--dimensionality %d', + usedefault=True, + desc='image dimension (2 or 3)') + fixed_image = InputMultiPath( + File(exists=True), + mandatory=True, + desc='Image to which the moving_image should be transformed' + '(usually a structural image)') fixed_image_mask = File( - exists=True, argstr='%s', max_ver='2.1.0', xor=['fixed_image_masks'], + exists=True, + argstr='%s', + max_ver='2.1.0', + xor=['fixed_image_masks'], desc='Mask used to limit metric sampling region of the fixed image' 'in all stages') fixed_image_masks = InputMultiPath( - traits.Either('NULL', File(exists=True)), min_ver='2.2.0', xor=['fixed_image_mask'], - desc='Masks used to limit metric sampling region of the fixed image, defined per registration stage' + traits.Either('NULL', File(exists=True)), + min_ver='2.2.0', + xor=['fixed_image_mask'], + desc= + 'Masks used to limit metric sampling region of the fixed image, defined per registration stage' '(Use "NULL" to omit a mask at a given stage)') - moving_image = InputMultiPath(File(exists=True), mandatory=True, - desc='Image that will be registered to the space of fixed_image. This is the' - 'image on which the transformations will be applied to') + moving_image = InputMultiPath( + File(exists=True), + mandatory=True, + desc= + 'Image that will be registered to the space of fixed_image. This is the' + 'image on which the transformations will be applied to') moving_image_mask = File( - exists=True, requires=['fixed_image_mask'], max_ver='2.1.0', xor=['moving_image_masks'], + exists=True, + requires=['fixed_image_mask'], + max_ver='2.1.0', + xor=['moving_image_masks'], desc='mask used to limit metric sampling region of the moving image' 'in all stages') moving_image_masks = InputMultiPath( - traits.Either('NULL', File(exists=True)), min_ver='2.2.0', xor=['moving_image_mask'], - desc='Masks used to limit metric sampling region of the moving image, defined per registration stage' + traits.Either('NULL', File(exists=True)), + min_ver='2.2.0', + xor=['moving_image_mask'], + desc= + 'Masks used to limit metric sampling region of the moving image, defined per registration stage' '(Use "NULL" to omit a mask at a given stage)') - save_state = File(argstr='--save-state %s', exists=False, - desc='Filename for saving the internal restorable state of the registration') - restore_state = File(argstr='--restore-state %s', exists=True, - desc='Filename for restoring the internal restorable state of the registration') - - initial_moving_transform = InputMultiPath(argstr='%s', - exists=True, - desc='A transform or a list of transforms that should be applied' - 'before the registration begins. Note that, when a list is given,' - 'the transformations are applied in reverse order.', - xor=['initial_moving_transform_com']) - invert_initial_moving_transform = InputMultiPath(traits.Bool(), - requires=[ - "initial_moving_transform"], + save_state = File( + argstr='--save-state %s', + exists=False, + desc= + 'Filename for saving the internal restorable state of the registration' + ) + restore_state = File( + argstr='--restore-state %s', + exists=True, + desc= + 'Filename for restoring the internal restorable state of the registration' + ) + + initial_moving_transform = InputMultiPath( + File(exists=True), + argstr='%s', + desc='A transform or a list of transforms that should be applied' + 'before the registration begins. Note that, when a list is given,' + 'the transformations are applied in reverse order.', + xor=['initial_moving_transform_com']) + invert_initial_moving_transform = InputMultiPath( + traits.Bool(), + requires=["initial_moving_transform"], desc='One boolean or a list of booleans that indicate' 'whether the inverse(s) of the transform(s) defined' 'in initial_moving_transform should be used.', xor=['initial_moving_transform_com']) - initial_moving_transform_com = traits.Enum(0, 1, 2, argstr='%s', - default=0, xor=['initial_moving_transform'], - desc="Align the moving_image nad fixed_image befor registration using" - "the geometric center of the images (=0), the image intensities (=1)," - "or the origin of the images (=2)") + initial_moving_transform_com = traits.Enum( + 0, + 1, + 2, + argstr='%s', + default=0, + xor=['initial_moving_transform'], + desc="Align the moving_image nad fixed_image befor registration using" + "the geometric center of the images (=0), the image intensities (=1)," + "or the origin of the images (=2)") metric_item_trait = traits.Enum("CC", "MeanSquares", "Demons", "GC", "MI", "Mattes") - metric_stage_trait = traits.Either( - metric_item_trait, traits.List(metric_item_trait)) - metric = traits.List(metric_stage_trait, mandatory=True, - desc='the metric(s) to use for each stage. ' - 'Note that multiple metrics per stage are not supported ' - 'in ANTS 1.9.1 and earlier.') + metric_stage_trait = traits.Either(metric_item_trait, + traits.List(metric_item_trait)) + metric = traits.List( + metric_stage_trait, + mandatory=True, + desc='the metric(s) to use for each stage. ' + 'Note that multiple metrics per stage are not supported ' + 'in ANTS 1.9.1 and earlier.') metric_weight_item_trait = traits.Float(1.0) metric_weight_stage_trait = traits.Either( metric_weight_item_trait, traits.List(metric_weight_item_trait)) metric_weight = traits.List( - metric_weight_stage_trait, value=[1.0], usedefault=True, - requires=['metric'], mandatory=True, + metric_weight_stage_trait, + value=[1.0], + usedefault=True, + requires=['metric'], + mandatory=True, desc='the metric weight(s) for each stage. ' 'The weights must sum to 1 per stage.') radius_bins_item_trait = traits.Int(5) radius_bins_stage_trait = traits.Either( radius_bins_item_trait, traits.List(radius_bins_item_trait)) radius_or_number_of_bins = traits.List( - radius_bins_stage_trait, value=[5], usedefault=True, + radius_bins_stage_trait, + value=[5], + usedefault=True, requires=['metric_weight'], desc='the number of bins in each stage for the MI and Mattes metric, ' 'the radius for other metrics') - sampling_strategy_item_trait = traits.Enum( - "None", "Regular", "Random", None) + sampling_strategy_item_trait = traits.Enum("None", "Regular", "Random", + None) sampling_strategy_stage_trait = traits.Either( - sampling_strategy_item_trait, traits.List(sampling_strategy_item_trait)) + sampling_strategy_item_trait, + traits.List(sampling_strategy_item_trait)) sampling_strategy = traits.List( - trait=sampling_strategy_stage_trait, requires=['metric_weight'], + trait=sampling_strategy_stage_trait, + requires=['metric_weight'], desc='the metric sampling strategy (strategies) for each stage') sampling_percentage_item_trait = traits.Either( traits.Range(low=0.0, high=1.0), None) sampling_percentage_stage_trait = traits.Either( - sampling_percentage_item_trait, traits.List(sampling_percentage_item_trait)) + sampling_percentage_item_trait, + traits.List(sampling_percentage_item_trait)) sampling_percentage = traits.List( - trait=sampling_percentage_stage_trait, requires=['sampling_strategy'], + trait=sampling_percentage_stage_trait, + requires=['sampling_strategy'], desc="the metric sampling percentage(s) to use for each stage") use_estimate_learning_rate_once = traits.List(traits.Bool(), desc='') use_histogram_matching = traits.Either( - traits.Bool, traits.List(traits.Bool(argstr='%s')), - default=True, usedefault=True, + traits.Bool, + traits.List(traits.Bool(argstr='%s')), + default=True, + usedefault=True, desc='Histogram match the images before registration.') interpolation = traits.Enum( - 'Linear', 'NearestNeighbor', 'CosineWindowedSinc', 'WelchWindowedSinc', - 'HammingWindowedSinc', 'LanczosWindowedSinc', 'BSpline', 'MultiLabel', 'Gaussian', - argstr='%s', usedefault=True) - interpolation_parameters = traits.Either(traits.Tuple(traits.Int()), # BSpline (order) - traits.Tuple(traits.Float(), # Gaussian/MultiLabel (sigma, alpha) - traits.Float()) - ) + 'Linear', + 'NearestNeighbor', + 'CosineWindowedSinc', + 'WelchWindowedSinc', + 'HammingWindowedSinc', + 'LanczosWindowedSinc', + 'BSpline', + 'MultiLabel', + 'Gaussian', + argstr='%s', + usedefault=True) + interpolation_parameters = traits.Either( + traits.Tuple(traits.Int()), # BSpline (order) + traits.Tuple( + traits.Float(), # Gaussian/MultiLabel (sigma, alpha) + traits.Float())) write_composite_transform = traits.Bool( argstr='--write-composite-transform %d', - default=False, usedefault=True, desc='') + default=False, + usedefault=True, + desc='') collapse_output_transforms = traits.Bool( - argstr='--collapse-output-transforms %d', default=True, + argstr='--collapse-output-transforms %d', + default=True, usedefault=True, # This should be true for explicit completeness desc=('Collapse output transforms. Specifically, enabling this option ' 'combines all adjacent linear transforms and composes all ' 'adjacent displacement field transforms before writing the ' 'results to disk.')) initialize_transforms_per_stage = traits.Bool( - argstr='--initialize-transforms-per-stage %d', default=False, + argstr='--initialize-transforms-per-stage %d', + default=False, usedefault=True, # This should be true for explicit completeness - desc=('Initialize linear transforms from the previous stage. By enabling this option, ' - 'the current linear stage transform is directly intialized from the previous ' - 'stages linear transform; this allows multiple linear stages to be run where ' - 'each stage directly updates the estimated linear transform from the previous ' - 'stage. (e.g. Translation -> Rigid -> Affine). ' - )) + desc= + ('Initialize linear transforms from the previous stage. By enabling this option, ' + 'the current linear stage transform is directly intialized from the previous ' + 'stages linear transform; this allows multiple linear stages to be run where ' + 'each stage directly updates the estimated linear transform from the previous ' + 'stage. (e.g. Translation -> Rigid -> Affine). ')) # NOTE: Even though only 0=False and 1=True are allowed, ants uses integer # values instead of booleans float = traits.Bool( - argstr='--float %d', default=False, + argstr='--float %d', + default=False, desc='Use float instead of double for computations.') - transforms = traits.List(traits.Enum('Rigid', 'Affine', 'CompositeAffine', - 'Similarity', 'Translation', 'BSpline', - 'GaussianDisplacementField', 'TimeVaryingVelocityField', - 'TimeVaryingBSplineVelocityField', 'SyN', 'BSplineSyN', - 'Exponential', 'BSplineExponential'), argstr='%s', mandatory=True) + transforms = traits.List( + traits.Enum('Rigid', 'Affine', 'CompositeAffine', 'Similarity', + 'Translation', 'BSpline', 'GaussianDisplacementField', + 'TimeVaryingVelocityField', + 'TimeVaryingBSplineVelocityField', 'SyN', 'BSplineSyN', + 'Exponential', 'BSplineExponential'), + argstr='%s', + mandatory=True) # TODO: input checking and allow defaults # All parameters must be specified for BSplineDisplacementField, TimeVaryingBSplineVelocityField, BSplineSyN, # Exponential, and BSplineExponential. EVEN DEFAULTS! - transform_parameters = traits.List(traits.Either(traits.Tuple(traits.Float()), # Translation, Rigid, Affine, - # CompositeAffine, Similarity - traits.Tuple(traits.Float(), # GaussianDisplacementField, SyN - traits.Float(), - traits.Float() - ), - traits.Tuple(traits.Float(), # BSplineSyn, - traits.Int(), # BSplineDisplacementField, - traits.Int(), # TimeVaryingBSplineVelocityField - traits.Int() - ), - traits.Tuple(traits.Float(), # TimeVaryingVelocityField - traits.Int(), - traits.Float(), - traits.Float(), - traits.Float(), - traits.Float() - ), - traits.Tuple(traits.Float(), # Exponential - traits.Float(), - traits.Float(), - traits.Int() - ), - traits.Tuple(traits.Float(), # BSplineExponential - traits.Int(), - traits.Int(), - traits.Int(), - traits.Int() - ), - ) - ) + transform_parameters = traits.List( + traits.Either( + traits.Tuple(traits.Float()), # Translation, Rigid, Affine, + # CompositeAffine, Similarity + traits.Tuple( + traits.Float(), # GaussianDisplacementField, SyN + traits.Float(), + traits.Float()), + traits.Tuple( + traits.Float(), # BSplineSyn, + traits.Int(), # BSplineDisplacementField, + traits.Int(), # TimeVaryingBSplineVelocityField + traits.Int()), + traits.Tuple( + traits.Float(), # TimeVaryingVelocityField + traits.Int(), + traits.Float(), + traits.Float(), + traits.Float(), + traits.Float()), + traits.Tuple( + traits.Float(), # Exponential + traits.Float(), + traits.Float(), + traits.Int()), + traits.Tuple( + traits.Float(), # BSplineExponential + traits.Int(), + traits.Int(), + traits.Int(), + traits.Int()), + )) restrict_deformation = traits.List( traits.List(traits.Enum(0, 1)), desc=("This option allows the user to restrict the optimization of " @@ -406,50 +495,76 @@ class RegistrationInputSpec(ANTSCommandInputSpec): # Convergence flags number_of_iterations = traits.List(traits.List(traits.Int())) smoothing_sigmas = traits.List(traits.List(traits.Float()), mandatory=True) - sigma_units = traits.List(traits.Enum('mm', 'vox'), - requires=['smoothing_sigmas'], - desc="units for smoothing sigmas") + sigma_units = traits.List( + traits.Enum('mm', 'vox'), + requires=['smoothing_sigmas'], + desc="units for smoothing sigmas") shrink_factors = traits.List(traits.List(traits.Int()), mandatory=True) - convergence_threshold = traits.List(trait=traits.Float(), value=[ - 1e-6], minlen=1, requires=['number_of_iterations'], usedefault=True) - convergence_window_size = traits.List(trait=traits.Int(), value=[ - 10], minlen=1, requires=['convergence_threshold'], usedefault=True) + convergence_threshold = traits.List( + trait=traits.Float(), + value=[1e-6], + minlen=1, + requires=['number_of_iterations'], + usedefault=True) + convergence_window_size = traits.List( + trait=traits.Int(), + value=[10], + minlen=1, + requires=['convergence_threshold'], + usedefault=True) # Output flags output_transform_prefix = Str( "transform", usedefault=True, argstr="%s", desc="") output_warped_image = traits.Either( traits.Bool, File(), hash_files=False, desc="") - output_inverse_warped_image = traits.Either(traits.Bool, File(), - hash_files=False, - requires=['output_warped_image'], desc="") + output_inverse_warped_image = traits.Either( + traits.Bool, + File(), + hash_files=False, + requires=['output_warped_image'], + desc="") winsorize_upper_quantile = traits.Range( - low=0.0, high=1.0, value=1.0, argstr='%s', usedefault=True, desc="The Upper quantile to clip image ranges") + low=0.0, + high=1.0, + value=1.0, + argstr='%s', + usedefault=True, + desc="The Upper quantile to clip image ranges") winsorize_lower_quantile = traits.Range( - low=0.0, high=1.0, value=0.0, argstr='%s', usedefault=True, desc="The Lower quantile to clip image ranges") + low=0.0, + high=1.0, + value=0.0, + argstr='%s', + usedefault=True, + desc="The Lower quantile to clip image ranges") verbose = traits.Bool(argstr='-v', default=False) class RegistrationOutputSpec(TraitedSpec): forward_transforms = traits.List( - File(exists=True), desc='List of output transforms for forward registration') + File(exists=True), + desc='List of output transforms for forward registration') reverse_transforms = traits.List( - File(exists=True), desc='List of output transforms for reverse registration') - forward_invert_flags = traits.List(traits.Bool( - ), desc='List of flags corresponding to the forward transforms') - reverse_invert_flags = traits.List(traits.Bool( - ), desc='List of flags corresponding to the reverse transforms') + File(exists=True), + desc='List of output transforms for reverse registration') + forward_invert_flags = traits.List( + traits.Bool(), + desc='List of flags corresponding to the forward transforms') + reverse_invert_flags = traits.List( + traits.Bool(), + desc='List of flags corresponding to the reverse transforms') composite_transform = File(exists=True, desc='Composite transform file') inverse_composite_transform = File(desc='Inverse composite transform file') warped_image = File(desc="Outputs warped image") inverse_warped_image = File(desc="Outputs the inverse of the warped image") save_state = File(desc="The saved registration state to be restored") metric_value = traits.Float(desc='the final value of metric') - elapsed_time = traits.Float(desc='the total elapsed time as reported by ANTs') + elapsed_time = traits.Float( + desc='the total elapsed time as reported by ANTs') class Registration(ANTSCommand): - """ `antsRegistration `_ registers a ``moving_image`` to a ``fixed_image``, using a predefined (sequence of) cost function(s) and transformation operations. @@ -820,15 +935,16 @@ class Registration(ANTSCommand): input_spec = RegistrationInputSpec output_spec = RegistrationOutputSpec _quantilesDone = False - _linear_transform_names = ['Rigid', 'Affine', - 'Translation', 'CompositeAffine', 'Similarity'] + _linear_transform_names = [ + 'Rigid', 'Affine', 'Translation', 'CompositeAffine', 'Similarity' + ] def __init__(self, **inputs): super(Registration, self).__init__(**inputs) self._elapsed_time = None self._metric_value = None - def _run_interface(self, runtime, correct_return_codes=(0,)): + def _run_interface(self, runtime, correct_return_codes=(0, )): runtime = super(Registration, self)._run_interface(runtime) # Parse some profiling info @@ -863,14 +979,15 @@ def _format_metric(self, index): metric=name_input, weight=self.inputs.metric_weight[index], radius_or_bins=self.inputs.radius_or_number_of_bins[index], - optional=self.inputs.radius_or_number_of_bins[index] - ) + optional=self.inputs.radius_or_number_of_bins[index]) # The optional sampling strategy and percentage. - if isdefined(self.inputs.sampling_strategy) and self.inputs.sampling_strategy: + if isdefined(self.inputs.sampling_strategy + ) and self.inputs.sampling_strategy: sampling_strategy = self.inputs.sampling_strategy[index] if sampling_strategy: stage_inputs['sampling_strategy'] = sampling_strategy - if isdefined(self.inputs.sampling_percentage) and self.inputs.sampling_percentage: + if isdefined(self.inputs.sampling_percentage + ) and self.inputs.sampling_percentage: sampling_percentage = self.inputs.sampling_percentage[index] if sampling_percentage: stage_inputs['sampling_percentage'] = sampling_percentage @@ -935,8 +1052,9 @@ def _format_metric_argument(**kwargs): def _format_transform(self, index): retval = [] retval.append('%s[ ' % self.inputs.transforms[index]) - parameters = ', '.join([str( - element) for element in self.inputs.transform_parameters[index]]) + parameters = ', '.join([ + str(element) for element in self.inputs.transform_parameters[index] + ]) retval.append('%s' % parameters) retval.append(' ]') return "".join(retval) @@ -949,14 +1067,15 @@ def _format_registration(self): retval.append('--metric %s' % metric) retval.append('--convergence %s' % self._format_convergence(ii)) if isdefined(self.inputs.sigma_units): - retval.append('--smoothing-sigmas %s%s' % - (self._format_xarray(self.inputs.smoothing_sigmas[ii]), - self.inputs.sigma_units[ii])) + retval.append( + '--smoothing-sigmas %s%s' % + (self._format_xarray(self.inputs.smoothing_sigmas[ii]), + self.inputs.sigma_units[ii])) else: - retval.append('--smoothing-sigmas %s' % - self._format_xarray(self.inputs.smoothing_sigmas[ii])) - retval.append('--shrink-factors %s' % - self._format_xarray(self.inputs.shrink_factors[ii])) + retval.append('--smoothing-sigmas %s' % self._format_xarray( + self.inputs.smoothing_sigmas[ii])) + retval.append('--shrink-factors %s' % self._format_xarray( + self.inputs.shrink_factors[ii])) if isdefined(self.inputs.use_estimate_learning_rate_once): retval.append('--use-estimate-learning-rate-once %d' % self.inputs.use_estimate_learning_rate_once[ii]) @@ -969,8 +1088,9 @@ def _format_registration(self): histval = self.inputs.use_histogram_matching[ii] retval.append('--use-histogram-matching %d' % histval) if isdefined(self.inputs.restrict_deformation): - retval.append('--restrict-deformation %s' % - self._format_xarray(self.inputs.restrict_deformation[ii])) + retval.append( + '--restrict-deformation %s' % self._format_xarray( + self.inputs.restrict_deformation[ii])) if any((isdefined(self.inputs.fixed_image_masks), isdefined(self.inputs.moving_image_masks))): if isdefined(self.inputs.fixed_image_masks): @@ -983,8 +1103,8 @@ def _format_registration(self): if isdefined(self.inputs.moving_image_masks): moving_masks = filename_to_list( self.inputs.moving_image_masks) - moving_mask = moving_masks[ii if len( - moving_masks) > 1 else 0] + moving_mask = moving_masks[ii + if len(moving_masks) > 1 else 0] else: moving_mask = 'NULL' retval.append('--masks [ %s, %s ]' % (fixed_mask, moving_mask)) @@ -1022,15 +1142,20 @@ def _format_convergence(self, ii): convergence_ws = self.inputs.convergence_window_size[ii] else: convergence_ws = self.inputs.convergence_window_size[0] - return '[ %s, %g, %d ]' % (convergence_iter, convergence_value, convergence_ws) + return '[ %s, %g, %d ]' % (convergence_iter, convergence_value, + convergence_ws) def _format_winsorize_image_intensities(self): if not self.inputs.winsorize_upper_quantile > self.inputs.winsorize_lower_quantile: - raise RuntimeError("Upper bound MUST be more than lower bound: %g > %g" - % (self.inputs.winsorize_upper_quantile, self.inputs.winsorize_lower_quantile)) + raise RuntimeError( + "Upper bound MUST be more than lower bound: %g > %g" % + (self.inputs.winsorize_upper_quantile, + self.inputs.winsorize_lower_quantile)) self._quantilesDone = True - return '--winsorize-image-intensities [ %s, %s ]' % (self.inputs.winsorize_lower_quantile, - self.inputs.winsorize_upper_quantile) + return '--winsorize-image-intensities [ %s, %s ]' % ( + self.inputs.winsorize_lower_quantile, + self.inputs.winsorize_upper_quantile) + def _get_initial_transform_filenames(self): n_transforms = len(self.inputs.initial_moving_transform) @@ -1043,8 +1168,10 @@ def _get_initial_transform_filenames(self): 'should have the same length.') invert_flags = self.inputs.invert_initial_moving_transform - retval = ["[ %s, %d ]" % (xfm, int(flag)) for xfm, flag in zip( - self.inputs.initial_moving_transform, invert_flags)] + retval = [ + "[ %s, %d ]" % (xfm, int(flag)) for xfm, flag in zip( + self.inputs.initial_moving_transform, invert_flags) + ] return " ".join(['--initial-moving-transform'] + retval) def _format_arg(self, opt, spec, val): @@ -1061,27 +1188,29 @@ def _format_arg(self, opt, spec, val): elif opt == 'initial_moving_transform_com': do_center_of_mass_init = self.inputs.initial_moving_transform_com \ if isdefined(self.inputs.initial_moving_transform_com) else 0 # Just do the default behavior - return '--initial-moving-transform [ %s, %s, %d ]' % (self.inputs.fixed_image[0], - self.inputs.moving_image[0], - do_center_of_mass_init) + return '--initial-moving-transform [ %s, %s, %d ]' % ( + self.inputs.fixed_image[0], self.inputs.moving_image[0], + do_center_of_mass_init) elif opt == 'interpolation': if self.inputs.interpolation in ['BSpline', 'MultiLabel', 'Gaussian'] and \ isdefined(self.inputs.interpolation_parameters): - return '--interpolation %s[ %s ]' % (self.inputs.interpolation, - ', '.join([str(param) - for param in self.inputs.interpolation_parameters])) + return '--interpolation %s[ %s ]' % ( + self.inputs.interpolation, ', '.join([ + str(param) + for param in self.inputs.interpolation_parameters + ])) else: return '--interpolation %s' % self.inputs.interpolation elif opt == 'output_transform_prefix': out_filename = self._get_outputfilenames(inverse=False) inv_out_filename = self._get_outputfilenames(inverse=True) if out_filename and inv_out_filename: - return '--output [ %s, %s, %s ]' % (self.inputs.output_transform_prefix, - out_filename, - inv_out_filename) + return '--output [ %s, %s, %s ]' % ( + self.inputs.output_transform_prefix, out_filename, + inv_out_filename) elif out_filename: - return '--output [ %s, %s ]' % (self.inputs.output_transform_prefix, - out_filename) + return '--output [ %s, %s ]' % ( + self.inputs.output_transform_prefix, out_filename) else: return '--output %s' % self.inputs.output_transform_prefix elif opt == 'winsorize_upper_quantile' or opt == 'winsorize_lower_quantile': @@ -1096,14 +1225,16 @@ def _format_arg(self, opt, spec, val): return super(Registration, self)._format_arg(opt, spec, val) def _output_filenames(self, prefix, count, transform, inverse=False): - self.low_dimensional_transform_map = {'Rigid': 'Rigid.mat', - 'Affine': 'Affine.mat', - 'GenericAffine': 'GenericAffine.mat', - 'CompositeAffine': 'Affine.mat', - 'Similarity': 'Similarity.mat', - 'Translation': 'Translation.mat', - 'BSpline': 'BSpline.txt', - 'Initial': 'DerivedInitialMovingTranslation.mat'} + self.low_dimensional_transform_map = { + 'Rigid': 'Rigid.mat', + 'Affine': 'Affine.mat', + 'GenericAffine': 'GenericAffine.mat', + 'CompositeAffine': 'Affine.mat', + 'Similarity': 'Similarity.mat', + 'Translation': 'Translation.mat', + 'BSpline': 'BSpline.txt', + 'Initial': 'DerivedInitialMovingTranslation.mat' + } if transform in list(self.low_dimensional_transform_map.keys()): suffix = self.low_dimensional_transform_map[transform] inverse_mode = inverse @@ -1124,8 +1255,8 @@ def _list_outputs(self): # invert_initial_moving_transform should be always defined, even if # there's no initial transform - invert_initial_moving_transform = [ - False] * len(self.inputs.initial_moving_transform) + invert_initial_moving_transform = [False] * len( + self.inputs.initial_moving_transform) if isdefined(self.inputs.invert_initial_moving_transform): invert_initial_moving_transform = self.inputs.invert_initial_moving_transform @@ -1140,28 +1271,29 @@ def _list_outputs(self): if not self.inputs.collapse_output_transforms: transform_count = 0 if isdefined(self.inputs.initial_moving_transform): - outputs['forward_transforms'] += self.inputs.initial_moving_transform - outputs['forward_invert_flags'] += invert_initial_moving_transform + outputs[ + 'forward_transforms'] += self.inputs.initial_moving_transform + outputs[ + 'forward_invert_flags'] += invert_initial_moving_transform outputs['reverse_transforms'] = self.inputs.initial_moving_transform + \ outputs['reverse_transforms'] outputs['reverse_invert_flags'] = [ - not e for e in invert_initial_moving_transform] + outputs['reverse_invert_flags'] # Prepend - transform_count += len(self.inputs.initial_moving_transform) + not e for e in invert_initial_moving_transform + ] + outputs['reverse_invert_flags'] # Prepend + transform_count += len( + self.inputs.initial_moving_transform) elif isdefined(self.inputs.initial_moving_transform_com): forward_filename, forward_inversemode = self._output_filenames( - self.inputs.output_transform_prefix, - transform_count, + self.inputs.output_transform_prefix, transform_count, 'Initial') reverse_filename, reverse_inversemode = self._output_filenames( - self.inputs.output_transform_prefix, - transform_count, - 'Initial', - True) + self.inputs.output_transform_prefix, transform_count, + 'Initial', True) outputs['forward_transforms'].append( os.path.abspath(forward_filename)) outputs['forward_invert_flags'].append(False) - outputs['reverse_transforms'].insert(0, - os.path.abspath(reverse_filename)) + outputs['reverse_transforms'].insert( + 0, os.path.abspath(reverse_filename)) outputs['reverse_invert_flags'].insert(0, True) transform_count += 1 @@ -1183,7 +1315,9 @@ def _list_outputs(self): else: transform_count = 0 is_linear = [ - t in self._linear_transform_names for t in self.inputs.transforms] + t in self._linear_transform_names + for t in self.inputs.transforms + ] collapse_list = [] if isdefined(self.inputs.initial_moving_transform) or \ @@ -1232,49 +1366,70 @@ def _list_outputs(self): class MeasureImageSimilarityInputSpec(ANTSCommandInputSpec): dimension = traits.Enum( - 2, 3, 4, - argstr='--dimensionality %d', position=1, + 2, + 3, + 4, + argstr='--dimensionality %d', + position=1, desc='Dimensionality of the fixed/moving image pair', ) fixed_image = File( - exists=True, mandatory=True, + exists=True, + mandatory=True, desc='Image to which the moving image is warped', ) moving_image = File( - exists=True, mandatory=True, - desc='Image to apply transformation to (generally a coregistered functional)', + exists=True, + mandatory=True, + desc= + 'Image to apply transformation to (generally a coregistered functional)', ) metric = traits.Enum( - "CC", "MI", "Mattes", "MeanSquares", "Demons", "GC", - argstr="%s", mandatory=True, + "CC", + "MI", + "Mattes", + "MeanSquares", + "Demons", + "GC", + argstr="%s", + mandatory=True, ) metric_weight = traits.Float( - requires=['metric'], default=1.0, usedefault=True, + requires=['metric'], + default=1.0, + usedefault=True, desc='The "metricWeight" variable is not used.', ) radius_or_number_of_bins = traits.Int( - requires=['metric'], mandatory=True, + requires=['metric'], + mandatory=True, desc='The number of bins in each stage for the MI and Mattes metric, ' 'or the radius for other metrics', ) sampling_strategy = traits.Enum( - "None", "Regular", "Random", - requires=['metric'], default="None", usedefault=True, + "None", + "Regular", + "Random", + requires=['metric'], + default="None", + usedefault=True, desc='Manner of choosing point set over which to optimize the metric. ' - 'Defaults to "None" (i.e. a dense sampling of one sample per voxel).' - ) + 'Defaults to "None" (i.e. a dense sampling of one sample per voxel).') sampling_percentage = traits.Either( traits.Range(low=0.0, high=1.0), - requires=['metric'], mandatory=True, - desc='Percentage of points accessible to the sampling strategy over which ' - 'to optimize the metric.' - ) + requires=['metric'], + mandatory=True, + desc= + 'Percentage of points accessible to the sampling strategy over which ' + 'to optimize the metric.') fixed_image_mask = File( - exists=True, argstr='%s', + exists=True, + argstr='%s', desc='mask used to limit metric sampling region of the fixed image', ) moving_image_mask = File( - exists=True, requires=['fixed_image_mask'], + exists=True, + requires=['fixed_image_mask'], desc='mask used to limit metric sampling region of the moving image', ) diff --git a/nipype/interfaces/ants/resampling.py b/nipype/interfaces/ants/resampling.py index 3ed60a51b1..a3f5723ba8 100644 --- a/nipype/interfaces/ants/resampling.py +++ b/nipype/interfaces/ants/resampling.py @@ -7,7 +7,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, str import os @@ -17,38 +18,59 @@ class WarpTimeSeriesImageMultiTransformInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(4, 3, argstr='%d', usedefault=True, - desc='image dimension (3 or 4)', position=1) - input_image = File(argstr='%s', mandatory=True, copyfile=True, - desc=('image to apply transformation to (generally a ' - 'coregistered functional)')) - out_postfix = traits.Str('_wtsimt', argstr='%s', usedefault=True, - desc=('Postfix that is prepended to all output ' - 'files (default = _wtsimt)')) - reference_image = File(argstr='-R %s', xor=['tightest_box'], - desc='reference image space that you wish to warp INTO') - tightest_box = traits.Bool(argstr='--tightest-bounding-box', - desc=('computes tightest bounding box (overrided by ' - 'reference_image if given)'), - xor=['reference_image']) - reslice_by_header = traits.Bool(argstr='--reslice-by-header', - desc=('Uses orientation matrix and origin encoded in ' - 'reference image file header. Not typically used ' - 'with additional transforms')) - use_nearest = traits.Bool(argstr='--use-NN', - desc='Use nearest neighbor interpolation') - use_bspline = traits.Bool(argstr='--use-Bspline', - desc='Use 3rd order B-Spline interpolation') - transformation_series = InputMultiPath(File(exists=True), argstr='%s', - desc='transformation file(s) to be applied', - mandatory=True, copyfile=False) - invert_affine = traits.List(traits.Int, - desc=('List of Affine transformations to invert.' - 'E.g.: [1,4,5] inverts the 1st, 4th, and 5th Affines ' - 'found in transformation_series. Note that indexing ' - 'starts with 1 and does not include warp fields. Affine ' - 'transformations are distinguished ' - 'from warp fields by the word "affine" included in their filenames.')) + dimension = traits.Enum( + 4, + 3, + argstr='%d', + usedefault=True, + desc='image dimension (3 or 4)', + position=1) + input_image = File( + argstr='%s', + mandatory=True, + copyfile=True, + desc=('image to apply transformation to (generally a ' + 'coregistered functional)')) + out_postfix = traits.Str( + '_wtsimt', + argstr='%s', + usedefault=True, + desc=('Postfix that is prepended to all output ' + 'files (default = _wtsimt)')) + reference_image = File( + argstr='-R %s', + xor=['tightest_box'], + desc='reference image space that you wish to warp INTO') + tightest_box = traits.Bool( + argstr='--tightest-bounding-box', + desc=('computes tightest bounding box (overrided by ' + 'reference_image if given)'), + xor=['reference_image']) + reslice_by_header = traits.Bool( + argstr='--reslice-by-header', + desc=('Uses orientation matrix and origin encoded in ' + 'reference image file header. Not typically used ' + 'with additional transforms')) + use_nearest = traits.Bool( + argstr='--use-NN', desc='Use nearest neighbor interpolation') + use_bspline = traits.Bool( + argstr='--use-Bspline', desc='Use 3rd order B-Spline interpolation') + transformation_series = InputMultiPath( + File(exists=True), + argstr='%s', + desc='transformation file(s) to be applied', + mandatory=True, + copyfile=False) + invert_affine = traits.List( + traits.Int, + desc=( + 'List of Affine transformations to invert.' + 'E.g.: [1,4,5] inverts the 1st, 4th, and 5th Affines ' + 'found in transformation_series. Note that indexing ' + 'starts with 1 and does not include warp fields. Affine ' + 'transformations are distinguished ' + 'from warp fields by the word "affine" included in their filenames.' + )) class WarpTimeSeriesImageMultiTransformOutputSpec(TraitedSpec): @@ -105,63 +127,92 @@ def _format_arg(self, opt, spec, val): if isdefined(self.inputs.invert_affine): diff_inv = set(self.inputs.invert_affine) - set(affine_invert) if diff_inv: - raise Exceptions("Review invert_affine, not all indexes from invert_affine were used, " - "check the description for the full definition") + raise Exceptions( + "Review invert_affine, not all indexes from invert_affine were used, " + "check the description for the full definition") return ' '.join(series) - return super(WarpTimeSeriesImageMultiTransform, self)._format_arg(opt, spec, val) + return super(WarpTimeSeriesImageMultiTransform, self)._format_arg( + opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() _, name, ext = split_filename(os.path.abspath(self.inputs.input_image)) - outputs['output_image'] = os.path.join(os.getcwd(), - ''.join((name, - self.inputs.out_postfix, - ext))) + outputs['output_image'] = os.path.join(os.getcwd(), ''.join( + (name, self.inputs.out_postfix, ext))) return outputs def _run_interface(self, runtime, correct_return_codes=[0]): - runtime = super(WarpTimeSeriesImageMultiTransform, self)._run_interface(runtime, correct_return_codes=[0, 1]) + runtime = super(WarpTimeSeriesImageMultiTransform, + self)._run_interface( + runtime, correct_return_codes=[0, 1]) if "100 % complete" not in runtime.stdout: self.raise_exception(runtime) return runtime class WarpImageMultiTransformInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='%d', usedefault=True, - desc='image dimension (2 or 3)', position=1) - input_image = File(argstr='%s', mandatory=True, - desc=('image to apply transformation to (generally a ' - 'coregistered functional)'), position=2) - output_image = File(genfile=True, hash_files=False, argstr='%s', - desc='name of the output warped image', position=3, xor=['out_postfix']) - out_postfix = File("_wimt", usedefault=True, hash_files=False, - desc=('Postfix that is prepended to all output ' - 'files (default = _wimt)'), xor=['output_image']) - reference_image = File(argstr='-R %s', xor=['tightest_box'], - desc='reference image space that you wish to warp INTO') - tightest_box = traits.Bool(argstr='--tightest-bounding-box', - desc=('computes tightest bounding box (overrided by ' - 'reference_image if given)'), - xor=['reference_image']) - reslice_by_header = traits.Bool(argstr='--reslice-by-header', - desc=('Uses orientation matrix and origin encoded in ' - 'reference image file header. Not typically used ' - 'with additional transforms')) - use_nearest = traits.Bool(argstr='--use-NN', - desc='Use nearest neighbor interpolation') - use_bspline = traits.Bool(argstr='--use-BSpline', - desc='Use 3rd order B-Spline interpolation') - transformation_series = InputMultiPath(File(exists=True), argstr='%s', - desc='transformation file(s) to be applied', - mandatory=True, position=-1) - invert_affine = traits.List(traits.Int, - desc=('List of Affine transformations to invert.' - 'E.g.: [1,4,5] inverts the 1st, 4th, and 5th Affines ' - 'found in transformation_series. Note that indexing ' - 'starts with 1 and does not include warp fields. Affine ' - 'transformations are distinguished ' - 'from warp fields by the word "affine" included in their filenames.')) + dimension = traits.Enum( + 3, + 2, + argstr='%d', + usedefault=True, + desc='image dimension (2 or 3)', + position=1) + input_image = File( + argstr='%s', + mandatory=True, + desc=('image to apply transformation to (generally a ' + 'coregistered functional)'), + position=2) + output_image = File( + genfile=True, + hash_files=False, + argstr='%s', + desc='name of the output warped image', + position=3, + xor=['out_postfix']) + out_postfix = File( + "_wimt", + usedefault=True, + hash_files=False, + desc=('Postfix that is prepended to all output ' + 'files (default = _wimt)'), + xor=['output_image']) + reference_image = File( + argstr='-R %s', + xor=['tightest_box'], + desc='reference image space that you wish to warp INTO') + tightest_box = traits.Bool( + argstr='--tightest-bounding-box', + desc=('computes tightest bounding box (overrided by ' + 'reference_image if given)'), + xor=['reference_image']) + reslice_by_header = traits.Bool( + argstr='--reslice-by-header', + desc=('Uses orientation matrix and origin encoded in ' + 'reference image file header. Not typically used ' + 'with additional transforms')) + use_nearest = traits.Bool( + argstr='--use-NN', desc='Use nearest neighbor interpolation') + use_bspline = traits.Bool( + argstr='--use-BSpline', desc='Use 3rd order B-Spline interpolation') + transformation_series = InputMultiPath( + File(exists=True), + argstr='%s', + desc='transformation file(s) to be applied', + mandatory=True, + position=-1) + invert_affine = traits.List( + traits.Int, + desc=( + 'List of Affine transformations to invert.' + 'E.g.: [1,4,5] inverts the 1st, 4th, and 5th Affines ' + 'found in transformation_series. Note that indexing ' + 'starts with 1 and does not include warp fields. Affine ' + 'transformations are distinguished ' + 'from warp fields by the word "affine" included in their filenames.' + )) class WarpImageMultiTransformOutputSpec(TraitedSpec): @@ -223,8 +274,9 @@ def _format_arg(self, opt, spec, val): if isdefined(self.inputs.invert_affine): diff_inv = set(self.inputs.invert_affine) - set(affine_invert) if diff_inv: - raise Exceptions("Review invert_affine, not all indexes from invert_affine were used, " - "check the description for the full definition") + raise Exceptions( + "Review invert_affine, not all indexes from invert_affine were used, " + "check the description for the full definition") return ' '.join(series) @@ -241,52 +293,80 @@ def _list_outputs(self): class ApplyTransformsInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(2, 3, 4, argstr='--dimensionality %d', - desc=('This option forces the image to be treated ' - 'as a specified-dimensional image. If not ' - 'specified, antsWarp tries to infer the ' - 'dimensionality from the input image.')) - input_image_type = traits.Enum(0, 1, 2, 3, - argstr='--input-image-type %d', - desc=('Option specifying the input image ' - 'type of scalar (default), vector, ' - 'tensor, or time series.')) - input_image = File(argstr='--input %s', mandatory=True, - desc=('image to apply transformation to (generally a ' - 'coregistered functional)'), - exists=True) - output_image = traits.Str(argstr='--output %s', desc='output file name', - genfile=True, hash_files=False) - out_postfix = traits.Str("_trans", usedefault=True, - desc=('Postfix that is appended to all output ' - 'files (default = _trans)')) - reference_image = File(argstr='--reference-image %s', mandatory=True, - desc='reference image space that you wish to warp INTO', - exists=True) - interpolation = traits.Enum('Linear', - 'NearestNeighbor', - 'CosineWindowedSinc', - 'WelchWindowedSinc', - 'HammingWindowedSinc', - 'LanczosWindowedSinc', - 'MultiLabel', - 'Gaussian', - 'BSpline', - argstr='%s', usedefault=True) + dimension = traits.Enum( + 2, + 3, + 4, + argstr='--dimensionality %d', + desc=('This option forces the image to be treated ' + 'as a specified-dimensional image. If not ' + 'specified, antsWarp tries to infer the ' + 'dimensionality from the input image.')) + input_image_type = traits.Enum( + 0, + 1, + 2, + 3, + argstr='--input-image-type %d', + desc=('Option specifying the input image ' + 'type of scalar (default), vector, ' + 'tensor, or time series.')) + input_image = File( + argstr='--input %s', + mandatory=True, + desc=('image to apply transformation to (generally a ' + 'coregistered functional)'), + exists=True) + output_image = traits.Str( + argstr='--output %s', + desc='output file name', + genfile=True, + hash_files=False) + out_postfix = traits.Str( + "_trans", + usedefault=True, + desc=('Postfix that is appended to all output ' + 'files (default = _trans)')) + reference_image = File( + argstr='--reference-image %s', + mandatory=True, + desc='reference image space that you wish to warp INTO', + exists=True) + interpolation = traits.Enum( + 'Linear', + 'NearestNeighbor', + 'CosineWindowedSinc', + 'WelchWindowedSinc', + 'HammingWindowedSinc', + 'LanczosWindowedSinc', + 'MultiLabel', + 'Gaussian', + 'BSpline', + argstr='%s', + usedefault=True) interpolation_parameters = traits.Either( traits.Tuple(traits.Int()), # BSpline (order) - traits.Tuple(traits.Float(), # Gaussian/MultiLabel (sigma, alpha) - traits.Float()) - ) + traits.Tuple( + traits.Float(), # Gaussian/MultiLabel (sigma, alpha) + traits.Float())) transforms = traits.Either( - InputMultiPath(File(exists=True)), 'identity', argstr='%s', mandatory=True, + InputMultiPath(File(exists=True)), + 'identity', + argstr='%s', + mandatory=True, desc='transform files: will be applied in reverse order. For ' - 'example, the last specified transform will be applied first.') + 'example, the last specified transform will be applied first.') invert_transform_flags = InputMultiPath(traits.Bool()) - default_value = traits.Float(0.0, argstr='--default-value %g', usedefault=True) - print_out_composite_warp_file = traits.Bool(False, requires=["output_image"], - desc='output a composite warp file instead of a transformed image') - float = traits.Bool(argstr='--float %d', default=False, desc='Use float instead of double for computations.') + default_value = traits.Float( + 0.0, argstr='--default-value %g', usedefault=True) + print_out_composite_warp_file = traits.Bool( + False, + requires=["output_image"], + desc='output a composite warp file instead of a transformed image') + float = traits.Bool( + argstr='--float %d', + default=False, + desc='Use float instead of double for computations.') class ApplyTransformsOutputSpec(TraitedSpec): @@ -356,22 +436,25 @@ def _get_transform_filenames(self): retval = [] for ii in range(len(self.inputs.transforms)): if isdefined(self.inputs.invert_transform_flags): - if len(self.inputs.transforms) == len(self.inputs.invert_transform_flags): + if len(self.inputs.transforms) == len( + self.inputs.invert_transform_flags): invert_code = 1 if self.inputs.invert_transform_flags[ ii] else 0 retval.append("--transform [ %s, %d ]" % (self.inputs.transforms[ii], invert_code)) else: - raise Exception(("ERROR: The useInverse list must have the same number " - "of entries as the transformsFileName list.")) + raise Exception(( + "ERROR: The useInverse list must have the same number " + "of entries as the transformsFileName list.")) else: retval.append("--transform %s" % self.inputs.transforms[ii]) return " ".join(retval) def _get_output_warped_filename(self): if isdefined(self.inputs.print_out_composite_warp_file): - return "--output [ %s, %d ]" % (self._gen_filename("output_image"), - int(self.inputs.print_out_composite_warp_file)) + return "--output [ %s, %d ]" % ( + self._gen_filename("output_image"), + int(self.inputs.print_out_composite_warp_file)) else: return "--output %s" % (self._gen_filename("output_image")) @@ -385,9 +468,11 @@ def _format_arg(self, opt, spec, val): elif opt == 'interpolation': if self.inputs.interpolation in ['BSpline', 'MultiLabel', 'Gaussian'] and \ isdefined(self.inputs.interpolation_parameters): - return '--interpolation %s[ %s ]' % (self.inputs.interpolation, - ', '.join([str(param) - for param in self.inputs.interpolation_parameters])) + return '--interpolation %s[ %s ]' % ( + self.inputs.interpolation, ', '.join([ + str(param) + for param in self.inputs.interpolation_parameters + ])) else: return '--interpolation %s' % self.inputs.interpolation return super(ApplyTransforms, self)._format_arg(opt, spec, val) @@ -400,33 +485,48 @@ def _list_outputs(self): class ApplyTransformsToPointsInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(2, 3, 4, argstr='--dimensionality %d', - desc=('This option forces the image to be treated ' - 'as a specified-dimensional image. If not ' - 'specified, antsWarp tries to infer the ' - 'dimensionality from the input image.')) - input_file = File(argstr='--input %s', mandatory=True, - desc=("Currently, the only input supported is a csv file with " - "columns including x,y (2D), x,y,z (3D) or x,y,z,t,label (4D) column headers." - "The points should be defined in physical space." - "If in doubt how to convert coordinates from your files to the space" - "required by antsApplyTransformsToPoints try creating/drawing a simple" - "label volume with only one voxel set to 1 and all others set to 0." - "Write down the voxel coordinates. Then use ImageMaths LabelStats to find" - "out what coordinates for this voxel antsApplyTransformsToPoints is" - "expecting."), - exists=True) - output_file = traits.Str(argstr='--output %s', - desc='Name of the output CSV file', name_source=['input_file'], - hash_files=False, name_template='%s_transformed.csv') - transforms = traits.List(File(exists=True), argstr='%s', mandatory=True, - desc='transforms that will be applied to the points') - invert_transform_flags = traits.List(traits.Bool(), - desc='list indicating if a transform should be reversed') + dimension = traits.Enum( + 2, + 3, + 4, + argstr='--dimensionality %d', + desc=('This option forces the image to be treated ' + 'as a specified-dimensional image. If not ' + 'specified, antsWarp tries to infer the ' + 'dimensionality from the input image.')) + input_file = File( + argstr='--input %s', + mandatory=True, + desc= + ("Currently, the only input supported is a csv file with " + "columns including x,y (2D), x,y,z (3D) or x,y,z,t,label (4D) column headers." + "The points should be defined in physical space." + "If in doubt how to convert coordinates from your files to the space" + "required by antsApplyTransformsToPoints try creating/drawing a simple" + "label volume with only one voxel set to 1 and all others set to 0." + "Write down the voxel coordinates. Then use ImageMaths LabelStats to find" + "out what coordinates for this voxel antsApplyTransformsToPoints is" + "expecting."), + exists=True) + output_file = traits.Str( + argstr='--output %s', + desc='Name of the output CSV file', + name_source=['input_file'], + hash_files=False, + name_template='%s_transformed.csv') + transforms = traits.List( + File(exists=True), + argstr='%s', + mandatory=True, + desc='transforms that will be applied to the points') + invert_transform_flags = traits.List( + traits.Bool(), + desc='list indicating if a transform should be reversed') class ApplyTransformsToPointsOutputSpec(TraitedSpec): - output_file = File(exists=True, desc='csv file with transformed coordinates') + output_file = File( + exists=True, desc='csv file with transformed coordinates') class ApplyTransformsToPoints(ANTSCommand): @@ -456,14 +556,16 @@ def _get_transform_filenames(self): retval = [] for ii in range(len(self.inputs.transforms)): if isdefined(self.inputs.invert_transform_flags): - if len(self.inputs.transforms) == len(self.inputs.invert_transform_flags): + if len(self.inputs.transforms) == len( + self.inputs.invert_transform_flags): invert_code = 1 if self.inputs.invert_transform_flags[ ii] else 0 retval.append("--transform [ %s, %d ]" % (self.inputs.transforms[ii], invert_code)) else: - raise Exception(("ERROR: The useInverse list must have the same number " - "of entries as the transformsFileName list.")) + raise Exception(( + "ERROR: The useInverse list must have the same number " + "of entries as the transformsFileName list.")) else: retval.append("--transform %s" % self.inputs.transforms[ii]) return " ".join(retval) diff --git a/nipype/interfaces/ants/segmentation.py b/nipype/interfaces/ants/segmentation.py index 6c594b5e24..b82db2e401 100644 --- a/nipype/interfaces/ants/segmentation.py +++ b/nipype/interfaces/ants/segmentation.py @@ -8,7 +8,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, str import os @@ -19,18 +20,25 @@ class AtroposInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, 4, argstr='--image-dimensionality %d', - usedefault=True, - desc='image dimension (2, 3, or 4)') - intensity_images = InputMultiPath(File(exists=True), - argstr="--intensity-image %s...", - mandatory=True) + dimension = traits.Enum( + 3, + 2, + 4, + argstr='--image-dimensionality %d', + usedefault=True, + desc='image dimension (2, 3, or 4)') + intensity_images = InputMultiPath( + File(exists=True), argstr="--intensity-image %s...", mandatory=True) mask_image = File(exists=True, argstr='--mask-image %s', mandatory=True) - initialization = traits.Enum('Random', 'Otsu', 'KMeans', - 'PriorProbabilityImages', 'PriorLabelImage', - argstr="%s", - requires=['number_of_tissue_classes'], - mandatory=True) + initialization = traits.Enum( + 'Random', + 'Otsu', + 'KMeans', + 'PriorProbabilityImages', + 'PriorLabelImage', + argstr="%s", + requires=['number_of_tissue_classes'], + mandatory=True) prior_probability_images = InputMultiPath(File(exists=True)) number_of_tissue_classes = traits.Int(mandatory=True) prior_weighting = traits.Float() @@ -44,15 +52,18 @@ class AtroposInputSpec(ANTSCommandInputSpec): n_iterations = traits.Int(argstr="%s") convergence_threshold = traits.Float(requires=['n_iterations']) posterior_formulation = traits.Str(argstr="%s") - use_random_seed = traits.Bool(True, argstr='--use-random-seed %d', desc='use random seed value over constant', - usedefault=True) + use_random_seed = traits.Bool( + True, + argstr='--use-random-seed %d', + desc='use random seed value over constant', + usedefault=True) use_mixture_model_proportions = traits.Bool( requires=['posterior_formulation']) - out_classified_image_name = File(argstr="%s", genfile=True, - hash_files=False) + out_classified_image_name = File( + argstr="%s", genfile=True, hash_files=False) save_posteriors = traits.Bool() - output_posteriors_name_template = traits.Str('POSTERIOR_%02d.nii.gz', - usedefault=True) + output_posteriors_name_template = traits.Str( + 'POSTERIOR_%02d.nii.gz', usedefault=True) class AtroposOutputSpec(TraitedSpec): @@ -103,8 +114,8 @@ class Atropos(ANTSCommand): def _format_arg(self, opt, spec, val): if opt == 'initialization': - retval = "--initialization %s[%d" % (val, - self.inputs.number_of_tissue_classes) + retval = "--initialization %s[%d" % ( + val, self.inputs.number_of_tissue_classes) if val == "PriorProbabilityImages": _, _, ext = split_filename( self.inputs.prior_probability_images[0]) @@ -116,7 +127,8 @@ def _format_arg(self, opt, spec, val): if opt == 'mrf_smoothing_factor': retval = "--mrf [%g" % val if isdefined(self.inputs.mrf_radius): - retval += ",%s" % self._format_xarray([str(s) for s in self.inputs.mrf_radius]) + retval += ",%s" % self._format_xarray( + [str(s) for s in self.inputs.mrf_radius]) return retval + "]" if opt == "icm_use_synchronous_update": retval = "--icm [%d" % val @@ -149,9 +161,12 @@ def _run_interface(self, runtime, correct_return_codes=[0]): for i, f in enumerate(self.inputs.prior_probability_images): target = os.path.join(priors_directory, 'priorProbImages%02d' % (i + 1) + ext) - if not (os.path.exists(target) and os.path.realpath(target) == os.path.abspath(f)): - copyfile(os.path.abspath(f), os.path.join(priors_directory, - 'priorProbImages%02d' % (i + 1) + ext)) + if not (os.path.exists(target) + and os.path.realpath(target) == os.path.abspath(f)): + copyfile( + os.path.abspath(f), + os.path.join(priors_directory, + 'priorProbImages%02d' % (i + 1) + ext)) runtime = super(Atropos, self)._run_interface(runtime) return runtime @@ -168,29 +183,42 @@ def _list_outputs(self): outputs = self._outputs().get() outputs['classified_image'] = os.path.abspath( self._gen_filename('out_classified_image_name')) - if isdefined(self.inputs.save_posteriors) and self.inputs.save_posteriors: + if isdefined( + self.inputs.save_posteriors) and self.inputs.save_posteriors: outputs['posteriors'] = [] for i in range(self.inputs.number_of_tissue_classes): - outputs['posteriors'].append(os.path.abspath(self.inputs.output_posteriors_name_template % (i + 1))) + outputs['posteriors'].append( + os.path.abspath( + self.inputs.output_posteriors_name_template % (i + 1))) return outputs class LaplacianThicknessInputSpec(ANTSCommandInputSpec): - input_wm = File(argstr='%s', mandatory=True, copyfile=True, - desc='white matter segmentation image', - position=1) - input_gm = File(argstr='%s', mandatory=True, copyfile=True, - desc='gray matter segmentation image', - position=2) - output_image = File(desc='name of output file', argstr='%s', position=3, - genfile=True, hash_files=False) + input_wm = File( + argstr='%s', + mandatory=True, + copyfile=True, + desc='white matter segmentation image', + position=1) + input_gm = File( + argstr='%s', + mandatory=True, + copyfile=True, + desc='gray matter segmentation image', + position=2) + output_image = File( + desc='name of output file', + argstr='%s', + position=3, + genfile=True, + hash_files=False) smooth_param = traits.Float(argstr='smoothparam=%d', desc='', position=4) - prior_thickness = traits.Float(argstr='priorthickval=%d', desc='', - position=5) + prior_thickness = traits.Float( + argstr='priorthickval=%d', desc='', position=5) dT = traits.Float(argstr='dT=%d', desc='', position=6) sulcus_prior = traits.Bool(argstr='use-sulcus-prior', desc='', position=7) - opt_tolerance = traits.Float(argstr='optional-laplacian-tolerance=%d', - desc='', position=8) + opt_tolerance = traits.Float( + argstr='optional-laplacian-tolerance=%d', desc='', position=8) class LaplacianThicknessOutputSpec(TraitedSpec): @@ -229,38 +257,51 @@ def _gen_filename(self, name): def _list_outputs(self): outputs = self._outputs().get() _, name, ext = split_filename(os.path.abspath(self.inputs.input_wm)) - outputs['output_image'] = os.path.join(os.getcwd(), - ''.join((name, - self.inputs.output_image, - ext))) + outputs['output_image'] = os.path.join(os.getcwd(), ''.join( + (name, self.inputs.output_image, ext))) return outputs class N4BiasFieldCorrectionInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, 4, argstr='-d %d', - usedefault=True, - desc='image dimension (2, 3 or 4)') - input_image = File(argstr='--input-image %s', mandatory=True, - desc=('image to apply transformation to (generally a ' - 'coregistered functional)')) + dimension = traits.Enum( + 3, + 2, + 4, + argstr='-d %d', + usedefault=True, + desc='image dimension (2, 3 or 4)') + input_image = File( + argstr='--input-image %s', + mandatory=True, + desc=('image to apply transformation to (generally a ' + 'coregistered functional)')) mask_image = File(argstr='--mask-image %s') weight_image = File(argstr='--weight-image %s') - output_image = traits.Str(argstr='--output %s', - desc='output file name', genfile=True, - hash_files=False) + output_image = traits.Str( + argstr='--output %s', + desc='output file name', + genfile=True, + hash_files=False) bspline_fitting_distance = traits.Float(argstr="--bspline-fitting %s") bspline_order = traits.Int(requires=['bspline_fitting_distance']) shrink_factor = traits.Int(argstr="--shrink-factor %d") n_iterations = traits.List(traits.Int(), argstr="--convergence %s") convergence_threshold = traits.Float(requires=['n_iterations']) - save_bias = traits.Bool(False, mandatory=True, usedefault=True, - desc=('True if the estimated bias should be saved' - ' to file.'), xor=['bias_image']) - bias_image = File(desc='Filename for the estimated bias.', - hash_files=False) - copy_header = traits.Bool(False, mandatory=True, usedefault=True, - desc='copy headers of the original image into the ' - 'output (corrected) file') + save_bias = traits.Bool( + False, + mandatory=True, + usedefault=True, + desc=('True if the estimated bias should be saved' + ' to file.'), + xor=['bias_image']) + bias_image = File( + desc='Filename for the estimated bias.', hash_files=False) + copy_header = traits.Bool( + False, + mandatory=True, + usedefault=True, + desc='copy headers of the original image into the ' + 'output (corrected) file') class N4BiasFieldCorrectionOutputSpec(TraitedSpec): @@ -346,7 +387,7 @@ def _gen_filename(self, name): def _format_arg(self, name, trait_spec, value): if ((name == 'output_image') and - (self.inputs.save_bias or isdefined(self.inputs.bias_image))): + (self.inputs.save_bias or isdefined(self.inputs.bias_image))): bias_image = self._gen_filename('bias_image') output = self._gen_filename('output_image') newval = '[ %s, %s ]' % (output, bias_image) @@ -361,14 +402,16 @@ def _format_arg(self, name, trait_spec, value): if name == 'n_iterations': if isdefined(self.inputs.convergence_threshold): - newval = '[ %s, %g ]' % (self._format_xarray([str(elt) for elt in value]), - self.inputs.convergence_threshold) + newval = '[ %s, %g ]' % ( + self._format_xarray([str(elt) for elt in value]), + self.inputs.convergence_threshold) else: - newval = '[ %s ]' % self._format_xarray([str(elt) for elt in value]) + newval = '[ %s ]' % self._format_xarray( + [str(elt) for elt in value]) return trait_spec.argstr % newval - return super(N4BiasFieldCorrection, - self)._format_arg(name, trait_spec, value) + return super(N4BiasFieldCorrection, self)._format_arg( + name, trait_spec, value) def _parse_inputs(self, skip=None): if skip is None: @@ -386,7 +429,7 @@ def _list_outputs(self): self._gen_filename('bias_image')) return outputs - def _run_interface(self, runtime, correct_return_codes=(0,)): + def _run_interface(self, runtime, correct_return_codes=(0, )): runtime = super(N4BiasFieldCorrection, self)._run_interface( runtime, correct_return_codes) @@ -409,96 +452,134 @@ def _copy_header(self, fname): class CorticalThicknessInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='-d %d', usedefault=True, - desc='image dimension (2 or 3)') - anatomical_image = File(exists=True, argstr='-a %s', - desc=('Structural *intensity* image, typically T1.' - 'If more than one anatomical image is specified,' - 'subsequently specified images are used during the' - 'segmentation process. However, only the first' - 'image is used in the registration of priors.' - 'Our suggestion would be to specify the T1' - 'as the first image.'), - mandatory=True) - brain_template = File(exists=True, argstr='-e %s', - desc=('Anatomical *intensity* template (possibly created using a' - 'population data set with buildtemplateparallel.sh in ANTs).' - 'This template is *not* skull-stripped.'), - mandatory=True) - brain_probability_mask = File(exists=True, argstr='-m %s', - desc='brain probability mask in template space', copyfile=False, mandatory=True) + dimension = traits.Enum( + 3, 2, argstr='-d %d', usedefault=True, desc='image dimension (2 or 3)') + anatomical_image = File( + exists=True, + argstr='-a %s', + desc=('Structural *intensity* image, typically T1.' + 'If more than one anatomical image is specified,' + 'subsequently specified images are used during the' + 'segmentation process. However, only the first' + 'image is used in the registration of priors.' + 'Our suggestion would be to specify the T1' + 'as the first image.'), + mandatory=True) + brain_template = File( + exists=True, + argstr='-e %s', + desc=('Anatomical *intensity* template (possibly created using a' + 'population data set with buildtemplateparallel.sh in ANTs).' + 'This template is *not* skull-stripped.'), + mandatory=True) + brain_probability_mask = File( + exists=True, + argstr='-m %s', + desc='brain probability mask in template space', + copyfile=False, + mandatory=True) segmentation_priors = InputMultiPath( File(exists=True), argstr='-p %s', mandatory=True) - out_prefix = traits.Str('antsCT_', argstr='-o %s', usedefault=True, - desc=('Prefix that is prepended to all output' - ' files (default = antsCT_)')) - image_suffix = traits.Str('nii.gz', desc=('any of standard ITK formats,' - ' nii.gz is default'), - argstr='-s %s', usedefault=True) - t1_registration_template = File(exists=True, - desc=('Anatomical *intensity* template' - '(assumed to be skull-stripped). A common' - 'case would be where this would be the same' - 'template as specified in the -e option which' - 'is not skull stripped.'), - argstr='-t %s', mandatory=True) - extraction_registration_mask = File(exists=True, argstr='-f %s', - desc=('Mask (defined in the template space) used during' - ' registration for brain extraction.')) - keep_temporary_files = traits.Int(argstr='-k %d', - desc='Keep brain extraction/segmentation warps, etc (default = 0).') - max_iterations = traits.Int(argstr='-i %d', desc=('ANTS registration max iterations' - '(default = 100x100x70x20)')) - prior_segmentation_weight = traits.Float(argstr='-w %f', - desc=('Atropos spatial prior *probability* weight for' - 'the segmentation')) - segmentation_iterations = traits.Int(argstr='-n %d', - desc=('N4 -> Atropos -> N4 iterations during segmentation' - '(default = 3)')) - posterior_formulation = traits.Str(argstr='-b %s', - desc=('Atropos posterior formulation and whether or not' - 'to use mixture model proportions.' - '''e.g 'Socrates[1]' (default) or 'Aristotle[1]'.''' - 'Choose the latter if you' - 'want use the distance priors (see also the -l option' - 'for label propagation control).')) - use_floatingpoint_precision = traits.Enum(0, 1, argstr='-j %d', - desc=('Use floating point precision ' - 'in registrations (default = 0)')) - use_random_seeding = traits.Enum(0, 1, argstr='-u %d', - desc=('Use random number generated from system clock in Atropos' - '(default = 1)')) - b_spline_smoothing = traits.Bool(argstr='-v', - desc=('Use B-spline SyN for registrations and B-spline' - 'exponential mapping in DiReCT.')) - cortical_label_image = File(exists=True, - desc='Cortical ROI labels to use as a prior for ATITH.') - label_propagation = traits.Str(argstr='-l %s', - desc=('Incorporate a distance prior one the posterior formulation. Should be' - '''of the form 'label[lambda,boundaryProbability]' where label''' - 'is a value of 1,2,3,... denoting label ID. The label' - 'probability for anything outside the current label' - ' = boundaryProbability * exp( -lambda * distanceFromBoundary )' - 'Intuitively, smaller lambda values will increase the spatial capture' - 'range of the distance prior. To apply to all label values, simply omit' - 'specifying the label, i.e. -l [lambda,boundaryProbability].')) - quick_registration = traits.Bool(argstr='-q 1', - desc=('If = 1, use antsRegistrationSyNQuick.sh as the basis for registration' - 'during brain extraction, brain segmentation, and' - '(optional) normalization to a template.' - 'Otherwise use antsRegistrationSyN.sh (default = 0).')) - debug = traits.Bool(argstr='-z 1', - desc=('If > 0, runs a faster version of the script.' - 'Only for testing. Implies -u 0.' - 'Requires single thread computation for complete reproducibility.')) + out_prefix = traits.Str( + 'antsCT_', + argstr='-o %s', + usedefault=True, + desc=('Prefix that is prepended to all output' + ' files (default = antsCT_)')) + image_suffix = traits.Str( + 'nii.gz', + desc=('any of standard ITK formats,' + ' nii.gz is default'), + argstr='-s %s', + usedefault=True) + t1_registration_template = File( + exists=True, + desc=('Anatomical *intensity* template' + '(assumed to be skull-stripped). A common' + 'case would be where this would be the same' + 'template as specified in the -e option which' + 'is not skull stripped.'), + argstr='-t %s', + mandatory=True) + extraction_registration_mask = File( + exists=True, + argstr='-f %s', + desc=('Mask (defined in the template space) used during' + ' registration for brain extraction.')) + keep_temporary_files = traits.Int( + argstr='-k %d', + desc='Keep brain extraction/segmentation warps, etc (default = 0).') + max_iterations = traits.Int( + argstr='-i %d', + desc=('ANTS registration max iterations' + '(default = 100x100x70x20)')) + prior_segmentation_weight = traits.Float( + argstr='-w %f', + desc=('Atropos spatial prior *probability* weight for' + 'the segmentation')) + segmentation_iterations = traits.Int( + argstr='-n %d', + desc=('N4 -> Atropos -> N4 iterations during segmentation' + '(default = 3)')) + posterior_formulation = traits.Str( + argstr='-b %s', + desc=('Atropos posterior formulation and whether or not' + 'to use mixture model proportions.' + '''e.g 'Socrates[1]' (default) or 'Aristotle[1]'.''' + 'Choose the latter if you' + 'want use the distance priors (see also the -l option' + 'for label propagation control).')) + use_floatingpoint_precision = traits.Enum( + 0, + 1, + argstr='-j %d', + desc=('Use floating point precision ' + 'in registrations (default = 0)')) + use_random_seeding = traits.Enum( + 0, + 1, + argstr='-u %d', + desc=('Use random number generated from system clock in Atropos' + '(default = 1)')) + b_spline_smoothing = traits.Bool( + argstr='-v', + desc=('Use B-spline SyN for registrations and B-spline' + 'exponential mapping in DiReCT.')) + cortical_label_image = File( + exists=True, desc='Cortical ROI labels to use as a prior for ATITH.') + label_propagation = traits.Str( + argstr='-l %s', + desc= + ('Incorporate a distance prior one the posterior formulation. Should be' + '''of the form 'label[lambda,boundaryProbability]' where label''' + 'is a value of 1,2,3,... denoting label ID. The label' + 'probability for anything outside the current label' + ' = boundaryProbability * exp( -lambda * distanceFromBoundary )' + 'Intuitively, smaller lambda values will increase the spatial capture' + 'range of the distance prior. To apply to all label values, simply omit' + 'specifying the label, i.e. -l [lambda,boundaryProbability].')) + quick_registration = traits.Bool( + argstr='-q 1', + desc= + ('If = 1, use antsRegistrationSyNQuick.sh as the basis for registration' + 'during brain extraction, brain segmentation, and' + '(optional) normalization to a template.' + 'Otherwise use antsRegistrationSyN.sh (default = 0).')) + debug = traits.Bool( + argstr='-z 1', + desc=( + 'If > 0, runs a faster version of the script.' + 'Only for testing. Implies -u 0.' + 'Requires single thread computation for complete reproducibility.' + )) class CorticalThicknessOutputSpec(TraitedSpec): BrainExtractionMask = File(exists=True, desc='brain extraction mask') BrainSegmentation = File(exists=True, desc='brain segmentaion image') BrainSegmentationN4 = File(exists=True, desc='N4 corrected image') - BrainSegmentationPosteriors = OutputMultiPath(File(exists=True), - desc='Posterior probability images') + BrainSegmentationPosteriors = OutputMultiPath( + File(exists=True), desc='Posterior probability images') CorticalThickness = File(exists=True, desc='cortical thickness file') TemplateToSubject1GenericAffine = File( exists=True, desc='Template to subject affine') @@ -509,8 +590,8 @@ class CorticalThicknessOutputSpec(TraitedSpec): exists=True, desc='Template to subject inverse affine') SubjectToTemplateLogJacobian = File( exists=True, desc='Template to subject log jacobian') - CorticalThicknessNormedToTemplate = File(exists=True, - desc='Normalized cortical thickness') + CorticalThicknessNormedToTemplate = File( + exists=True, desc='Normalized cortical thickness') BrainVolumes = File(exists=True, desc='Brain volumes as text') @@ -567,121 +648,142 @@ def _run_interface(self, runtime, correct_return_codes=[0]): os.makedirs(priors_directory) _, _, ext = split_filename(self.inputs.segmentation_priors[0]) for i, f in enumerate(self.inputs.segmentation_priors): - target = os.path.join( - priors_directory, 'BrainSegmentationPrior%02d' % (i + 1) + ext) - if not (os.path.exists(target) and os.path.realpath(target) == os.path.abspath(f)): + target = os.path.join(priors_directory, + 'BrainSegmentationPrior%02d' % (i + 1) + ext) + if not (os.path.exists(target) + and os.path.realpath(target) == os.path.abspath(f)): copyfile(os.path.abspath(f), target) runtime = super(CorticalThickness, self)._run_interface(runtime) return runtime def _list_outputs(self): outputs = self._outputs().get() - outputs['BrainExtractionMask'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'BrainExtractionMask.' + - self.inputs.image_suffix) - outputs['BrainSegmentation'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'BrainSegmentation.' + - self.inputs.image_suffix) - outputs['BrainSegmentationN4'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'BrainSegmentation0N4.' + - self.inputs.image_suffix) + outputs['BrainExtractionMask'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'BrainExtractionMask.' + + self.inputs.image_suffix) + outputs['BrainSegmentation'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'BrainSegmentation.' + + self.inputs.image_suffix) + outputs['BrainSegmentationN4'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'BrainSegmentation0N4.' + + self.inputs.image_suffix) posteriors = [] for i in range(len(self.inputs.segmentation_priors)): - posteriors.append(os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'BrainSegmentationPosteriors%02d.' % (i + 1) + - self.inputs.image_suffix)) + posteriors.append( + os.path.join(os.getcwd(), self.inputs.out_prefix + + 'BrainSegmentationPosteriors%02d.' % + (i + 1) + self.inputs.image_suffix)) outputs['BrainSegmentationPosteriors'] = posteriors - outputs['CorticalThickness'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'CorticalThickness.' + - self.inputs.image_suffix) - outputs['TemplateToSubject1GenericAffine'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'TemplateToSubject1GenericAffine.mat') - outputs['TemplateToSubject0Warp'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'TemplateToSubject0Warp.' + - self.inputs.image_suffix) - outputs['SubjectToTemplate1Warp'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'SubjectToTemplate1Warp.' + - self.inputs.image_suffix) - outputs['SubjectToTemplate0GenericAffine'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'SubjectToTemplate0GenericAffine.mat') - outputs['SubjectToTemplateLogJacobian'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'SubjectToTemplateLogJacobian.' + - self.inputs.image_suffix) - outputs['CorticalThicknessNormedToTemplate'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'CorticalThickness.' + - self.inputs.image_suffix) - outputs['BrainVolumes'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'brainvols.csv') + outputs['CorticalThickness'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'CorticalThickness.' + + self.inputs.image_suffix) + outputs['TemplateToSubject1GenericAffine'] = os.path.join( + os.getcwd(), + self.inputs.out_prefix + 'TemplateToSubject1GenericAffine.mat') + outputs['TemplateToSubject0Warp'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'TemplateToSubject0Warp.' + + self.inputs.image_suffix) + outputs['SubjectToTemplate1Warp'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'SubjectToTemplate1Warp.' + + self.inputs.image_suffix) + outputs['SubjectToTemplate0GenericAffine'] = os.path.join( + os.getcwd(), + self.inputs.out_prefix + 'SubjectToTemplate0GenericAffine.mat') + outputs['SubjectToTemplateLogJacobian'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + + 'SubjectToTemplateLogJacobian.' + self.inputs.image_suffix) + outputs['CorticalThicknessNormedToTemplate'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'CorticalThickness.' + + self.inputs.image_suffix) + outputs['BrainVolumes'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'brainvols.csv') return outputs class antsCorticalThickness(CorticalThickness): - DeprecationWarning('This class has been replaced by CorticalThickness and will be removed in version 0.13') + DeprecationWarning( + 'This class has been replaced by CorticalThickness and will be removed in version 0.13' + ) class BrainExtractionInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='-d %d', usedefault=True, - desc='image dimension (2 or 3)') - anatomical_image = File(exists=True, argstr='-a %s', - desc=('Structural image, typically T1. If more than one' - 'anatomical image is specified, subsequently specified' - 'images are used during the segmentation process. However,' - 'only the first image is used in the registration of priors.' - 'Our suggestion would be to specify the T1 as the first image.' - 'Anatomical template created using e.g. LPBA40 data set with' - 'buildtemplateparallel.sh in ANTs.'), - mandatory=True) - brain_template = File(exists=True, argstr='-e %s', - desc=('Anatomical template created using e.g. LPBA40 data set with' - 'buildtemplateparallel.sh in ANTs.'), - mandatory=True) - brain_probability_mask = File(exists=True, argstr='-m %s', - desc=('Brain probability mask created using e.g. LPBA40 data set which' - 'have brain masks defined, and warped to anatomical template and' - 'averaged resulting in a probability image.'), - copyfile=False, mandatory=True) - out_prefix = traits.Str('highres001_', argstr='-o %s', usedefault=True, - desc=('Prefix that is prepended to all output' - ' files (default = highress001_)')) - - extraction_registration_mask = File(exists=True, argstr='-f %s', - desc=('Mask (defined in the template space) used during' - ' registration for brain extraction.' - 'To limit the metric computation to a specific region.')) - image_suffix = traits.Str('nii.gz', desc=('any of standard ITK formats,' - ' nii.gz is default'), - argstr='-s %s', usedefault=True) - use_random_seeding = traits.Enum(0, 1, argstr='-u %d', - desc=('Use random number generated from system clock in Atropos' - '(default = 1)')) - keep_temporary_files = traits.Int(argstr='-k %d', - desc='Keep brain extraction/segmentation warps, etc (default = 0).') - use_floatingpoint_precision = traits.Enum(0, 1, argstr='-q %d', - desc=('Use floating point precision ' - 'in registrations (default = 0)')) - debug = traits.Bool(argstr='-z 1', - desc=('If > 0, runs a faster version of the script.' - 'Only for testing. Implies -u 0.' - 'Requires single thread computation for complete reproducibility.')) + dimension = traits.Enum( + 3, 2, argstr='-d %d', usedefault=True, desc='image dimension (2 or 3)') + anatomical_image = File( + exists=True, + argstr='-a %s', + desc=('Structural image, typically T1. If more than one' + 'anatomical image is specified, subsequently specified' + 'images are used during the segmentation process. However,' + 'only the first image is used in the registration of priors.' + 'Our suggestion would be to specify the T1 as the first image.' + 'Anatomical template created using e.g. LPBA40 data set with' + 'buildtemplateparallel.sh in ANTs.'), + mandatory=True) + brain_template = File( + exists=True, + argstr='-e %s', + desc=('Anatomical template created using e.g. LPBA40 data set with' + 'buildtemplateparallel.sh in ANTs.'), + mandatory=True) + brain_probability_mask = File( + exists=True, + argstr='-m %s', + desc=('Brain probability mask created using e.g. LPBA40 data set which' + 'have brain masks defined, and warped to anatomical template and' + 'averaged resulting in a probability image.'), + copyfile=False, + mandatory=True) + out_prefix = traits.Str( + 'highres001_', + argstr='-o %s', + usedefault=True, + desc=('Prefix that is prepended to all output' + ' files (default = highress001_)')) + + extraction_registration_mask = File( + exists=True, + argstr='-f %s', + desc=('Mask (defined in the template space) used during' + ' registration for brain extraction.' + 'To limit the metric computation to a specific region.')) + image_suffix = traits.Str( + 'nii.gz', + desc=('any of standard ITK formats,' + ' nii.gz is default'), + argstr='-s %s', + usedefault=True) + use_random_seeding = traits.Enum( + 0, + 1, + argstr='-u %d', + desc=('Use random number generated from system clock in Atropos' + '(default = 1)')) + keep_temporary_files = traits.Int( + argstr='-k %d', + desc='Keep brain extraction/segmentation warps, etc (default = 0).') + use_floatingpoint_precision = traits.Enum( + 0, + 1, + argstr='-q %d', + desc=('Use floating point precision ' + 'in registrations (default = 0)')) + debug = traits.Bool( + argstr='-z 1', + desc=( + 'If > 0, runs a faster version of the script.' + 'Only for testing. Implies -u 0.' + 'Requires single thread computation for complete reproducibility.' + )) class BrainExtractionOutputSpec(TraitedSpec): BrainExtractionMask = File(exists=True, desc='brain extraction mask') BrainExtractionBrain = File(exists=True, desc='brain extraction image') - BrainExtractionCSF = File(exists=True, desc='segmentation mask with only CSF') - BrainExtractionGM = File(exists=True, desc='segmentation mask with only grey matter') + BrainExtractionCSF = File( + exists=True, desc='segmentation mask with only CSF') + BrainExtractionGM = File( + exists=True, desc='segmentation mask with only grey matter') BrainExtractionInitialAffine = File(exists=True, desc='') BrainExtractionInitialAffineFixed = File(exists=True, desc='') BrainExtractionInitialAffineMoving = File(exists=True, desc='') @@ -690,10 +792,12 @@ class BrainExtractionOutputSpec(TraitedSpec): BrainExtractionPrior1InverseWarp = File(exists=True, desc='') BrainExtractionPrior1Warp = File(exists=True, desc='') BrainExtractionPriorWarped = File(exists=True, desc='') - BrainExtractionSegmentation = File(exists=True, desc='segmentation mask with CSF, GM, and WM') + BrainExtractionSegmentation = File( + exists=True, desc='segmentation mask with CSF, GM, and WM') BrainExtractionTemplateLaplacian = File(exists=True, desc='') BrainExtractionTmp = File(exists=True, desc='') - BrainExtractionWM = File(exists=True, desc='segmenration mask with only white matter') + BrainExtractionWM = File( + exists=True, desc='segmenration mask with only white matter') N4Corrected0 = File(exists=True, desc='N4 bias field corrected image') N4Truncated0 = File(exists=True, desc='') @@ -716,10 +820,11 @@ class BrainExtraction(ANTSCommand): output_spec = BrainExtractionOutputSpec _cmd = 'antsBrainExtraction.sh' - def _run_interface(self, runtime, correct_return_codes=(0,)): + def _run_interface(self, runtime, correct_return_codes=(0, )): # antsBrainExtraction.sh requires ANTSPATH to be defined out_environ = self._get_environ() - ants_path = out_environ.get('ANTSPATH', None) or os.getenv('ANTSPATH', None) + ants_path = out_environ.get('ANTSPATH', None) or os.getenv( + 'ANTSPATH', None) if ants_path is None: # Check for antsRegistration, which is under bin/ (the $ANTSPATH) instead of # checking for antsBrainExtraction.sh which is under script/ @@ -727,7 +832,8 @@ def _run_interface(self, runtime, correct_return_codes=(0,)): if not cmd_path: raise RuntimeError( 'The environment variable $ANTSPATH is not defined in host "%s", ' - 'and Nipype could not determine it automatically.' % runtime.hostname) + 'and Nipype could not determine it automatically.' % + runtime.hostname) ants_path = os.path.dirname(cmd_path) self.inputs.environ.update({'ANTSPATH': ants_path}) @@ -738,11 +844,13 @@ def _run_interface(self, runtime, correct_return_codes=(0,)): if 'we cant find' in runtime.stdout: for line in runtime.stdout.split('\n'): if line.strip().startswith('we cant find'): - tool = line.strip().replace('we cant find the', '').split(' ')[0] + tool = line.strip().replace('we cant find the', + '').split(' ')[0] break - errmsg = ('antsBrainExtraction.sh requires "%s" to be found in $ANTSPATH ' - '($ANTSPATH="%s").') % (tool, ants_path) + errmsg = ( + 'antsBrainExtraction.sh requires "%s" to be found in $ANTSPATH ' + '($ANTSPATH="%s").') % (tool, ants_path) if runtime.stderr is None: runtime.stderr = errmsg else: @@ -754,128 +862,152 @@ def _run_interface(self, runtime, correct_return_codes=(0,)): def _list_outputs(self): outputs = self._outputs().get() - outputs['BrainExtractionMask'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'BrainExtractionMask.' + - self.inputs.image_suffix) - outputs['BrainExtractionBrain'] = os.path.join(os.getcwd(), - self.inputs.out_prefix + - 'BrainExtractionBrain.' + - self.inputs.image_suffix) - if isdefined(self.inputs.keep_temporary_files) and self.inputs.keep_temporary_files != 0: + outputs['BrainExtractionMask'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'BrainExtractionMask.' + + self.inputs.image_suffix) + outputs['BrainExtractionBrain'] = os.path.join( + os.getcwd(), self.inputs.out_prefix + 'BrainExtractionBrain.' + + self.inputs.image_suffix) + if isdefined(self.inputs.keep_temporary_files + ) and self.inputs.keep_temporary_files != 0: outputs['BrainExtractionCSF'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionCSF.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + 'BrainExtractionCSF.' + + self.inputs.image_suffix) outputs['BrainExtractionGM'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionGM.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + 'BrainExtractionGM.' + + self.inputs.image_suffix) outputs['BrainExtractionInitialAffine'] = os.path.join( os.getcwd(), - self.inputs.out_prefix +'BrainExtractionInitialAffine.mat' - ) + self.inputs.out_prefix + 'BrainExtractionInitialAffine.mat') outputs['BrainExtractionInitialAffineFixed'] = os.path.join( os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionInitialAffineFixed.' + self.inputs.image_suffix - ) + self.inputs.out_prefix + 'BrainExtractionInitialAffineFixed.' + + self.inputs.image_suffix) outputs['BrainExtractionInitialAffineMoving'] = os.path.join( os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionInitialAffineMoving.' + self.inputs.image_suffix - ) + self.inputs.out_prefix + 'BrainExtractionInitialAffineMoving.' + + self.inputs.image_suffix) outputs['BrainExtractionLaplacian'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionLaplacian.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + + 'BrainExtractionLaplacian.' + self.inputs.image_suffix) outputs['BrainExtractionPrior0GenericAffine'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionPrior0GenericAffine.mat' - ) + os.getcwd(), self.inputs.out_prefix + + 'BrainExtractionPrior0GenericAffine.mat') outputs['BrainExtractionPrior1InverseWarp'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionPrior1InverseWarp.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + + 'BrainExtractionPrior1InverseWarp.' + self.inputs.image_suffix) outputs['BrainExtractionPrior1Warp'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionPrior1Warp.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + + 'BrainExtractionPrior1Warp.' + self.inputs.image_suffix) outputs['BrainExtractionPriorWarped'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionPriorWarped.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + + 'BrainExtractionPriorWarped.' + self.inputs.image_suffix) outputs['BrainExtractionSegmentation'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionSegmentation.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + + 'BrainExtractionSegmentation.' + self.inputs.image_suffix) outputs['BrainExtractionTemplateLaplacian'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionTemplateLaplacian.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + + 'BrainExtractionTemplateLaplacian.' + self.inputs.image_suffix) outputs['BrainExtractionTmp'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionTmp.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + 'BrainExtractionTmp.' + + self.inputs.image_suffix) outputs['BrainExtractionWM'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'BrainExtractionWM.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + 'BrainExtractionWM.' + + self.inputs.image_suffix) outputs['N4Corrected0'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'N4Corrected0.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + 'N4Corrected0.' + + self.inputs.image_suffix) outputs['N4Truncated0'] = os.path.join( - os.getcwd(), - self.inputs.out_prefix + 'N4Truncated0.' + self.inputs.image_suffix - ) + os.getcwd(), self.inputs.out_prefix + 'N4Truncated0.' + + self.inputs.image_suffix) return outputs class antsBrainExtraction(BrainExtraction): - DeprecationWarning('This class has been replaced by BrainExtraction and will be removed in version 0.13') + DeprecationWarning( + 'This class has been replaced by BrainExtraction and will be removed in version 0.13' + ) class JointFusionInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, 4, argstr='%d', position=0, usedefault=True, - mandatory=True, - desc='image dimension (2, 3, or 4)') - modalities = traits.Int(argstr='%d', position=1, mandatory=True, - desc='Number of modalities or features') - warped_intensity_images = InputMultiPath(File(exists=True), - argstr="-g %s...", mandatory=True, - desc='Warped atlas images') - target_image = InputMultiPath(File(exists=True), argstr='-tg %s...', - mandatory=True, desc='Target image(s)') - warped_label_images = InputMultiPath(File(exists=True), argstr="-l %s...", - mandatory=True, - desc='Warped atlas segmentations') - method = traits.Str(default='Joint', argstr='-m %s', usedefault=True, - desc=('Select voting method. Options: Joint (Joint ' - 'Label Fusion). May be followed by optional ' - 'parameters in brackets, e.g., -m Joint[0.1,2]')) - alpha = traits.Float(default=0.1, usedefault=True, requires=['method'], - desc=('Regularization term added to matrix Mx for ' - 'inverse')) - beta = traits.Int(default=2, usedefault=True, requires=['method'], - desc=('Exponent for mapping intensity difference to joint' - ' error')) - output_label_image = File(argstr='%s', mandatory=True, position=-1, - name_template='%s', - output_name='output_label_image', - desc='Output fusion label map image') - patch_radius = traits.ListInt(minlen=3, maxlen=3, argstr='-rp %s', - desc=('Patch radius for similarity measures, ' - 'scalar or vector. Default: 2x2x2')) - search_radius = traits.ListInt(minlen=3, maxlen=3, argstr='-rs %s', - desc='Local search radius. Default: 3x3x3') - exclusion_region = File(exists=True, argstr='-x %s', - desc=('Specify an exclusion region for the given ' - 'label.')) - atlas_group_id = traits.ListInt(argstr='-gp %d...', - desc='Assign a group ID for each atlas') - atlas_group_weights = traits.ListInt(argstr='-gpw %d...', - desc=('Assign the voting weights to ' - 'each atlas group')) + dimension = traits.Enum( + 3, + 2, + 4, + argstr='%d', + position=0, + usedefault=True, + mandatory=True, + desc='image dimension (2, 3, or 4)') + modalities = traits.Int( + argstr='%d', + position=1, + mandatory=True, + desc='Number of modalities or features') + warped_intensity_images = InputMultiPath( + File(exists=True), + argstr="-g %s...", + mandatory=True, + desc='Warped atlas images') + target_image = InputMultiPath( + File(exists=True), + argstr='-tg %s...', + mandatory=True, + desc='Target image(s)') + warped_label_images = InputMultiPath( + File(exists=True), + argstr="-l %s...", + mandatory=True, + desc='Warped atlas segmentations') + method = traits.Str( + default='Joint', + argstr='-m %s', + usedefault=True, + desc=('Select voting method. Options: Joint (Joint ' + 'Label Fusion). May be followed by optional ' + 'parameters in brackets, e.g., -m Joint[0.1,2]')) + alpha = traits.Float( + default=0.1, + usedefault=True, + requires=['method'], + desc=('Regularization term added to matrix Mx for ' + 'inverse')) + beta = traits.Int( + default=2, + usedefault=True, + requires=['method'], + desc=('Exponent for mapping intensity difference to joint' + ' error')) + output_label_image = File( + argstr='%s', + mandatory=True, + position=-1, + name_template='%s', + output_name='output_label_image', + desc='Output fusion label map image') + patch_radius = traits.ListInt( + minlen=3, + maxlen=3, + argstr='-rp %s', + desc=('Patch radius for similarity measures, ' + 'scalar or vector. Default: 2x2x2')) + search_radius = traits.ListInt( + minlen=3, + maxlen=3, + argstr='-rs %s', + desc='Local search radius. Default: 3x3x3') + exclusion_region = File( + exists=True, + argstr='-x %s', + desc=('Specify an exclusion region for the given ' + 'label.')) + atlas_group_id = traits.ListInt( + argstr='-gp %d...', desc='Assign a group ID for each atlas') + atlas_group_weights = traits.ListInt( + argstr='-gpw %d...', + desc=('Assign the voting weights to ' + 'each atlas group')) class JointFusionOutputSpec(TraitedSpec): @@ -945,31 +1077,57 @@ def _list_outputs(self): class DenoiseImageInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(2, 3, 4, argstr='-d %d', usedefault=False, - desc='This option forces the image to be treated ' - 'as a specified-dimensional image. If not ' - 'specified, the program tries to infer the ' - 'dimensionality from the input image.') - input_image = File(exists=True, argstr="-i %s", mandatory=True, - desc='A scalar image is expected as input for noise correction.') - noise_model = traits.Enum('Gaussian', 'Rician', argstr='-n %s', usedefault=True, - desc=('Employ a Rician or Gaussian noise model.')) - shrink_factor = traits.Int(default_value=1, usedefault=True, argstr='-s %s', - desc=('Running noise correction on large images can ' - 'be time consuming. To lessen computation time, ' - 'the input image can be resampled. The shrink ' - 'factor, specified as a single integer, describes ' - 'this resampling. Shrink factor = 1 is the default.')) - output_image = File(argstr="-o %s", name_source=['input_image'], hash_files=False, - keep_extension=True, name_template='%s_noise_corrected', - desc='The output consists of the noise corrected ' - 'version of the input image.') - save_noise = traits.Bool(False, mandatory=True, usedefault=True, - desc=('True if the estimated noise should be saved ' - 'to file.'), xor=['noise_image']) - noise_image = File(name_source=['input_image'], hash_files=False, - keep_extension=True, name_template='%s_noise', - desc='Filename for the estimated noise.') + dimension = traits.Enum( + 2, + 3, + 4, + argstr='-d %d', + usedefault=False, + desc='This option forces the image to be treated ' + 'as a specified-dimensional image. If not ' + 'specified, the program tries to infer the ' + 'dimensionality from the input image.') + input_image = File( + exists=True, + argstr="-i %s", + mandatory=True, + desc='A scalar image is expected as input for noise correction.') + noise_model = traits.Enum( + 'Gaussian', + 'Rician', + argstr='-n %s', + usedefault=True, + desc=('Employ a Rician or Gaussian noise model.')) + shrink_factor = traits.Int( + default_value=1, + usedefault=True, + argstr='-s %s', + desc=('Running noise correction on large images can ' + 'be time consuming. To lessen computation time, ' + 'the input image can be resampled. The shrink ' + 'factor, specified as a single integer, describes ' + 'this resampling. Shrink factor = 1 is the default.')) + output_image = File( + argstr="-o %s", + name_source=['input_image'], + hash_files=False, + keep_extension=True, + name_template='%s_noise_corrected', + desc='The output consists of the noise corrected ' + 'version of the input image.') + save_noise = traits.Bool( + False, + mandatory=True, + usedefault=True, + desc=('True if the estimated noise should be saved ' + 'to file.'), + xor=['noise_image']) + noise_image = File( + name_source=['input_image'], + hash_files=False, + keep_extension=True, + name_template='%s_noise', + desc='Filename for the estimated noise.') verbose = traits.Bool(False, argstr="-v", desc=('Verbose output.')) @@ -1009,80 +1167,136 @@ class DenoiseImage(ANTSCommand): def _format_arg(self, name, trait_spec, value): if ((name == 'output_image') and - (self.inputs.save_noise or isdefined(self.inputs.noise_image))): - newval = '[ %s, %s ]' % (self._filename_from_source('output_image'), - self._filename_from_source('noise_image')) + (self.inputs.save_noise or isdefined(self.inputs.noise_image))): + newval = '[ %s, %s ]' % ( + self._filename_from_source('output_image'), + self._filename_from_source('noise_image')) return trait_spec.argstr % newval - return super(DenoiseImage, - self)._format_arg(name, trait_spec, value) + return super(DenoiseImage, self)._format_arg(name, trait_spec, value) class AntsJointFusionInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, 4, argstr='-d %d', usedefault=False, - desc='This option forces the image to be treated ' - 'as a specified-dimensional image. If not ' - 'specified, the program tries to infer the ' - 'dimensionality from the input image.') - target_image = traits.List(InputMultiPath(File(exists=True)), argstr='-t %s', - mandatory=True, desc='The target image (or ' - 'multimodal target images) assumed to be ' - 'aligned to a common image domain.') - atlas_image = traits.List(InputMultiPath(File(exists=True)), argstr="-g %s...", - mandatory=True, desc='The atlas image (or ' - 'multimodal atlas images) assumed to be ' - 'aligned to a common image domain.') - atlas_segmentation_image = InputMultiPath(File(exists=True), argstr="-l %s...", - mandatory=True, desc='The atlas segmentation ' - 'images. For performing label fusion the number ' - 'of specified segmentations should be identical ' - 'to the number of atlas image sets.') - alpha = traits.Float(default_value=0.1, usedefault=True, argstr='-a %s', desc=('Regularization ' - 'term added to matrix Mx for calculating the inverse. Default = 0.1')) - beta = traits.Float(default_value=2.0, usedefault=True, argstr='-b %s', desc=('Exponent for mapping ' - 'intensity difference to the joint error. Default = 2.0')) - retain_label_posterior_images = traits.Bool(False, argstr='-r', usedefault=True, - requires=['atlas_segmentation_image'], - desc=('Retain label posterior probability images. Requires ' - 'atlas segmentations to be specified. Default = false')) - retain_atlas_voting_images = traits.Bool(False, argstr='-f', usedefault=True, - desc=('Retain atlas voting images. Default = false')) - constrain_nonnegative = traits.Bool(False, argstr='-c', usedefault=True, - desc=('Constrain solution to non-negative weights.')) - patch_radius = traits.ListInt(minlen=3, maxlen=3, argstr='-p %s', - desc=('Patch radius for similarity measures.' - 'Default: 2x2x2')) - patch_metric = traits.Enum('PC', 'MSQ', argstr='-m %s', usedefault=False, - desc=('Metric to be used in determining the most similar ' - 'neighborhood patch. Options include Pearson\'s ' - 'correlation (PC) and mean squares (MSQ). Default = ' - 'PC (Pearson correlation).')) - search_radius = traits.List([3,3,3], minlen=1, maxlen=3, argstr='-s %s', usedefault=True, - desc=('Search radius for similarity measures. Default = 3x3x3. ' - 'One can also specify an image where the value at the ' - 'voxel specifies the isotropic search radius at that voxel.')) - exclusion_image_label = traits.List(traits.Str(), argstr='-e %s', requires=['exclusion_image'], - desc=('Specify a label for the exclusion region.')) - exclusion_image = traits.List(File(exists=True), - desc=('Specify an exclusion region for the given label.')) - mask_image = File(argstr='-x %s', exists=True, desc='If a mask image ' - 'is specified, fusion is only performed in the mask region.') - out_label_fusion = File(argstr="%s", hash_files=False, - desc='The output label fusion image.') - out_intensity_fusion_name_format = traits.Str('antsJointFusionIntensity_%d.nii.gz', - argstr="", desc='Optional intensity fusion ' - 'image file name format.') - out_label_post_prob_name_format = traits.Str('antsJointFusionPosterior_%d.nii.gz', - requires=['out_label_fusion', - 'out_intensity_fusion_name_format'], - desc='Optional label posterior probability ' - 'image file name format.') - out_atlas_voting_weight_name_format = traits.Str('antsJointFusionVotingWeight_%d.nii.gz', - requires=['out_label_fusion', - 'out_intensity_fusion_name_format', - 'out_label_post_prob_name_format'], - desc='Optional atlas voting weight image ' - 'file name format.') + dimension = traits.Enum( + 3, + 2, + 4, + argstr='-d %d', + usedefault=False, + desc='This option forces the image to be treated ' + 'as a specified-dimensional image. If not ' + 'specified, the program tries to infer the ' + 'dimensionality from the input image.') + target_image = traits.List( + InputMultiPath(File(exists=True)), + argstr='-t %s', + mandatory=True, + desc='The target image (or ' + 'multimodal target images) assumed to be ' + 'aligned to a common image domain.') + atlas_image = traits.List( + InputMultiPath(File(exists=True)), + argstr="-g %s...", + mandatory=True, + desc='The atlas image (or ' + 'multimodal atlas images) assumed to be ' + 'aligned to a common image domain.') + atlas_segmentation_image = InputMultiPath( + File(exists=True), + argstr="-l %s...", + mandatory=True, + desc='The atlas segmentation ' + 'images. For performing label fusion the number ' + 'of specified segmentations should be identical ' + 'to the number of atlas image sets.') + alpha = traits.Float( + default_value=0.1, + usedefault=True, + argstr='-a %s', + desc=( + 'Regularization ' + 'term added to matrix Mx for calculating the inverse. Default = 0.1' + )) + beta = traits.Float( + default_value=2.0, + usedefault=True, + argstr='-b %s', + desc=('Exponent for mapping ' + 'intensity difference to the joint error. Default = 2.0')) + retain_label_posterior_images = traits.Bool( + False, + argstr='-r', + usedefault=True, + requires=['atlas_segmentation_image'], + desc=('Retain label posterior probability images. Requires ' + 'atlas segmentations to be specified. Default = false')) + retain_atlas_voting_images = traits.Bool( + False, + argstr='-f', + usedefault=True, + desc=('Retain atlas voting images. Default = false')) + constrain_nonnegative = traits.Bool( + False, + argstr='-c', + usedefault=True, + desc=('Constrain solution to non-negative weights.')) + patch_radius = traits.ListInt( + minlen=3, + maxlen=3, + argstr='-p %s', + desc=('Patch radius for similarity measures.' + 'Default: 2x2x2')) + patch_metric = traits.Enum( + 'PC', + 'MSQ', + argstr='-m %s', + usedefault=False, + desc=('Metric to be used in determining the most similar ' + 'neighborhood patch. Options include Pearson\'s ' + 'correlation (PC) and mean squares (MSQ). Default = ' + 'PC (Pearson correlation).')) + search_radius = traits.List( + [3, 3, 3], + minlen=1, + maxlen=3, + argstr='-s %s', + usedefault=True, + desc=('Search radius for similarity measures. Default = 3x3x3. ' + 'One can also specify an image where the value at the ' + 'voxel specifies the isotropic search radius at that voxel.')) + exclusion_image_label = traits.List( + traits.Str(), + argstr='-e %s', + requires=['exclusion_image'], + desc=('Specify a label for the exclusion region.')) + exclusion_image = traits.List( + File(exists=True), + desc=('Specify an exclusion region for the given label.')) + mask_image = File( + argstr='-x %s', + exists=True, + desc='If a mask image ' + 'is specified, fusion is only performed in the mask region.') + out_label_fusion = File( + argstr="%s", hash_files=False, desc='The output label fusion image.') + out_intensity_fusion_name_format = traits.Str( + 'antsJointFusionIntensity_%d.nii.gz', + argstr="", + desc='Optional intensity fusion ' + 'image file name format.') + out_label_post_prob_name_format = traits.Str( + 'antsJointFusionPosterior_%d.nii.gz', + requires=['out_label_fusion', 'out_intensity_fusion_name_format'], + desc='Optional label posterior probability ' + 'image file name format.') + out_atlas_voting_weight_name_format = traits.Str( + 'antsJointFusionVotingWeight_%d.nii.gz', + requires=[ + 'out_label_fusion', 'out_intensity_fusion_name_format', + 'out_label_post_prob_name_format' + ], + desc='Optional atlas voting weight image ' + 'file name format.') verbose = traits.Bool(False, argstr="-v", desc=('Verbose output.')) @@ -1161,9 +1375,9 @@ def _format_arg(self, opt, spec, val): if opt == 'exclusion_image_label': retval = [] for ii in range(len(self.inputs.exclusion_image_label)): - retval.append('-e {0}[{1}]'.format( - self.inputs.exclusion_image_label[ii], - self.inputs.exclusion_image[ii])) + retval.append( + '-e {0}[{1}]'.format(self.inputs.exclusion_image_label[ii], + self.inputs.exclusion_image[ii])) retval = ' '.join(retval) elif opt == 'patch_radius': retval = '-p {0}'.format(self._format_xarray(val)) @@ -1172,44 +1386,50 @@ def _format_arg(self, opt, spec, val): elif opt == 'out_label_fusion': if isdefined(self.inputs.out_intensity_fusion_name_format): if isdefined(self.inputs.out_label_post_prob_name_format): - if isdefined(self.inputs.out_atlas_voting_weight_name_format): - retval = '-o [{0}, {1}, {2}, {3}]'.format(self.inputs.out_label_fusion, - self.inputs.out_intensity_fusion_name_format, - self.inputs.out_label_post_prob_name_format, - self.inputs.out_atlas_voting_weight_name_format) + if isdefined( + self.inputs.out_atlas_voting_weight_name_format): + retval = '-o [{0}, {1}, {2}, {3}]'.format( + self.inputs.out_label_fusion, + self.inputs.out_intensity_fusion_name_format, + self.inputs.out_label_post_prob_name_format, + self.inputs.out_atlas_voting_weight_name_format) else: - retval = '-o [{0}, {1}, {2}]'.format(self.inputs.out_label_fusion, - self.inputs.out_intensity_fusion_name_format, - self.inputs.out_label_post_prob_name_format) + retval = '-o [{0}, {1}, {2}]'.format( + self.inputs.out_label_fusion, + self.inputs.out_intensity_fusion_name_format, + self.inputs.out_label_post_prob_name_format) else: - retval = '-o [{0}, {1}]'.format(self.inputs.out_label_fusion, - self.inputs.out_intensity_fusion_name_format) + retval = '-o [{0}, {1}]'.format( + self.inputs.out_label_fusion, + self.inputs.out_intensity_fusion_name_format) else: retval = '-o {0}'.format(self.inputs.out_label_fusion) elif opt == 'out_intensity_fusion_name_format': retval = '' if not isdefined(self.inputs.out_label_fusion): - retval = '-o {0}'.format(self.inputs.out_intensity_fusion_name_format) + retval = '-o {0}'.format( + self.inputs.out_intensity_fusion_name_format) elif opt == 'atlas_image': - atlas_image_cmd = " ".join( - ['-g [{0}]'.format(", ".join("'%s'" % fn for fn in ai)) - for ai in self.inputs.atlas_image] - ) + atlas_image_cmd = " ".join([ + '-g [{0}]'.format(", ".join("'%s'" % fn for fn in ai)) + for ai in self.inputs.atlas_image + ]) retval = atlas_image_cmd elif opt == 'target_image': - target_image_cmd = " ".join( - ['-t [{0}]'.format(", ".join("'%s'" % fn for fn in ai)) - for ai in self.inputs.target_image] - ) + target_image_cmd = " ".join([ + '-t [{0}]'.format(", ".join("'%s'" % fn for fn in ai)) + for ai in self.inputs.target_image + ]) retval = target_image_cmd elif opt == 'atlas_segmentation_image': assert len(val) == len(self.inputs.atlas_image), "Number of specified " \ "segmentations should be identical to the number of atlas image " \ "sets {0}!={1}".format(len(val), len(self.inputs.atlas_image)) - atlas_segmentation_image_cmd = " ".join( - ['-l {0}'.format(fn) for fn in self.inputs.atlas_segmentation_image] - ) + atlas_segmentation_image_cmd = " ".join([ + '-l {0}'.format(fn) + for fn in self.inputs.atlas_segmentation_image + ]) retval = atlas_segmentation_image_cmd else: @@ -1235,72 +1455,127 @@ def _list_outputs(self): class KellyKapowskiInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='--image-dimensionality %d', usedefault=True, - desc='image dimension (2 or 3)') - - segmentation_image = File(exists=True, argstr='--segmentation-image "%s"', mandatory=True, - desc="A segmentation image must be supplied labeling the gray and white matters.\n" - "Default values = 2 and 3, respectively.",) - - gray_matter_label = traits.Int(2, usedefault=True, - desc="The label value for the gray matter label in the segmentation_image.") - - white_matter_label = traits.Int(3, usedefault=True, - desc="The label value for the white matter label in the segmentation_image.") - - gray_matter_prob_image = File(exists=True, argstr='--gray-matter-probability-image "%s"', - desc="In addition to the segmentation image, a gray matter probability image can be\n" - "used. If no such image is supplied, one is created using the segmentation image\n" - "and a variance of 1.0 mm.") - - white_matter_prob_image = File(exists=True, argstr='--white-matter-probability-image "%s"', - desc="In addition to the segmentation image, a white matter probability image can be\n" - "used. If no such image is supplied, one is created using the segmentation image\n" - "and a variance of 1.0 mm.") - - convergence = traits.Str(default="[50,0.001,10]", argstr='--convergence "%s"', usedefault=True, - desc="Convergence is determined by fitting a line to the normalized energy profile of\n" - "the last N iterations (where N is specified by the window size) and determining\n" - "the slope which is then compared with the convergence threshold.",) - - thickness_prior_estimate = traits.Float(10, usedefault=True, argstr="--thickness-prior-estimate %f", - desc="Provides a prior constraint on the final thickness measurement in mm.") - - thickness_prior_image = File(exists=True, argstr='--thickness-prior-image "%s"', - desc="An image containing spatially varying prior thickness values.") - - gradient_step = traits.Float(0.025, usedefault=True, argstr="--gradient-step %f", - desc="Gradient step size for the optimization.") - - smoothing_variance = traits.Float(1.0, argstr="--smoothing-variance %f", - desc="Defines the Gaussian smoothing of the hit and total images.") - - smoothing_velocity_field = traits.Float(1.5, argstr="--smoothing-velocity-field-parameter %f", - desc="Defines the Gaussian smoothing of the velocity field (default = 1.5).\n" - "If the b-spline smoothing option is chosen, then this defines the \n" - "isotropic mesh spacing for the smoothing spline (default = 15).") - - use_bspline_smoothing = traits.Bool(argstr="--use-bspline-smoothing 1", - desc="Sets the option for B-spline smoothing of the velocity field.") - - number_integration_points = traits.Int(10, argstr="--number-of-integration-points %d", - desc="Number of compositions of the diffeomorphism per iteration.") - - max_invert_displacement_field_iters = traits.Int(20, argstr="--maximum-number-of-invert-displacement-field-iterations %d", - desc="Maximum number of iterations for estimating the invert \n" - "displacement field.") - - cortical_thickness = File(argstr='--output "%s"', keep_extension=True, - name_source=["segmentation_image"], name_template='%s_cortical_thickness', - desc='Filename for the cortical thickness.', hash_files=False) - - warped_white_matter = File(name_source=["segmentation_image"], keep_extension=True, - name_template='%s_warped_white_matter', - desc='Filename for the warped white matter file.', hash_files=False) + dimension = traits.Enum( + 3, + 2, + argstr='--image-dimensionality %d', + usedefault=True, + desc='image dimension (2 or 3)') + + segmentation_image = File( + exists=True, + argstr='--segmentation-image "%s"', + mandatory=True, + desc= + "A segmentation image must be supplied labeling the gray and white matters.\n" + "Default values = 2 and 3, respectively.", + ) + + gray_matter_label = traits.Int( + 2, + usedefault=True, + desc= + "The label value for the gray matter label in the segmentation_image.") + + white_matter_label = traits.Int( + 3, + usedefault=True, + desc= + "The label value for the white matter label in the segmentation_image." + ) + + gray_matter_prob_image = File( + exists=True, + argstr='--gray-matter-probability-image "%s"', + desc= + "In addition to the segmentation image, a gray matter probability image can be\n" + "used. If no such image is supplied, one is created using the segmentation image\n" + "and a variance of 1.0 mm.") + + white_matter_prob_image = File( + exists=True, + argstr='--white-matter-probability-image "%s"', + desc= + "In addition to the segmentation image, a white matter probability image can be\n" + "used. If no such image is supplied, one is created using the segmentation image\n" + "and a variance of 1.0 mm.") + + convergence = traits.Str( + default="[50,0.001,10]", + argstr='--convergence "%s"', + usedefault=True, + desc= + "Convergence is determined by fitting a line to the normalized energy profile of\n" + "the last N iterations (where N is specified by the window size) and determining\n" + "the slope which is then compared with the convergence threshold.", + ) + + thickness_prior_estimate = traits.Float( + 10, + usedefault=True, + argstr="--thickness-prior-estimate %f", + desc= + "Provides a prior constraint on the final thickness measurement in mm." + ) + + thickness_prior_image = File( + exists=True, + argstr='--thickness-prior-image "%s"', + desc="An image containing spatially varying prior thickness values.") + + gradient_step = traits.Float( + 0.025, + usedefault=True, + argstr="--gradient-step %f", + desc="Gradient step size for the optimization.") + + smoothing_variance = traits.Float( + 1.0, + argstr="--smoothing-variance %f", + desc="Defines the Gaussian smoothing of the hit and total images.") + + smoothing_velocity_field = traits.Float( + 1.5, + argstr="--smoothing-velocity-field-parameter %f", + desc= + "Defines the Gaussian smoothing of the velocity field (default = 1.5).\n" + "If the b-spline smoothing option is chosen, then this defines the \n" + "isotropic mesh spacing for the smoothing spline (default = 15).") + + use_bspline_smoothing = traits.Bool( + argstr="--use-bspline-smoothing 1", + desc="Sets the option for B-spline smoothing of the velocity field.") + + number_integration_points = traits.Int( + 10, + argstr="--number-of-integration-points %d", + desc="Number of compositions of the diffeomorphism per iteration.") + + max_invert_displacement_field_iters = traits.Int( + 20, + argstr="--maximum-number-of-invert-displacement-field-iterations %d", + desc="Maximum number of iterations for estimating the invert \n" + "displacement field.") + + cortical_thickness = File( + argstr='--output "%s"', + keep_extension=True, + name_source=["segmentation_image"], + name_template='%s_cortical_thickness', + desc='Filename for the cortical thickness.', + hash_files=False) + + warped_white_matter = File( + name_source=["segmentation_image"], + keep_extension=True, + name_template='%s_warped_white_matter', + desc='Filename for the warped white matter file.', + hash_files=False) class KellyKapowskiOutputSpec(TraitedSpec): - cortical_thickness = File(desc="A thickness map defined in the segmented gray matter.") + cortical_thickness = File( + desc="A thickness map defined in the segmented gray matter.") warped_white_matter = File(desc="A warped white matter image.") @@ -1336,26 +1611,32 @@ class KellyKapowski(ANTSCommand): input_spec = KellyKapowskiInputSpec output_spec = KellyKapowskiOutputSpec - references_ = [{'entry': BibTeX("@book{Das2009867," - "author={Sandhitsu R. Das and Brian B. Avants and Murray Grossman and James C. Gee}," - "title={Registration based cortical thickness measurement.}," - "journal={NeuroImage}," - "volume={45}," - "number={37}," - "pages={867--879}," - "year={2009}," - "issn={1053-8119}," - "url={http://www.sciencedirect.com/science/article/pii/S1053811908012780}," - "doi={http://dx.doi.org/10.1016/j.neuroimage.2008.12.016}" - "}"), - 'description': 'The details on the implementation of DiReCT.', - 'tags': ['implementation'], - }] + references_ = [{ + 'entry': + BibTeX( + "@book{Das2009867," + "author={Sandhitsu R. Das and Brian B. Avants and Murray Grossman and James C. Gee}," + "title={Registration based cortical thickness measurement.}," + "journal={NeuroImage}," + "volume={45}," + "number={37}," + "pages={867--879}," + "year={2009}," + "issn={1053-8119}," + "url={http://www.sciencedirect.com/science/article/pii/S1053811908012780}," + "doi={http://dx.doi.org/10.1016/j.neuroimage.2008.12.016}" + "}"), + 'description': + 'The details on the implementation of DiReCT.', + 'tags': ['implementation'], + }] def _parse_inputs(self, skip=None): if skip is None: skip = [] - skip += ['warped_white_matter', 'gray_matter_label', 'white_matter_label'] + skip += [ + 'warped_white_matter', 'gray_matter_label', 'white_matter_label' + ] return super(KellyKapowski, self)._parse_inputs(skip=skip) def _gen_filename(self, name): diff --git a/nipype/interfaces/ants/tests/test_auto_ANTS.py b/nipype/interfaces/ants/tests/test_auto_ANTS.py index 682d070ee2..b066461ba5 100644 --- a/nipype/interfaces/ants/tests/test_auto_ANTS.py +++ b/nipype/interfaces/ants/tests/test_auto_ANTS.py @@ -4,94 +4,101 @@ def test_ANTS_inputs(): - input_map = dict(affine_gradient_descent_option=dict(argstr='%s', - ), - args=dict(argstr='%s', - ), - delta_time=dict(requires=['number_of_time_steps'], - ), - dimension=dict(argstr='%d', - position=1, - usedefault=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_image=dict(mandatory=True, - ), - gradient_step_length=dict(requires=['transformation_model'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - metric=dict(mandatory=True, - ), - metric_weight=dict(mandatory=True, - requires=['metric'], - usedefault=True, - ), - mi_option=dict(argstr='--MI-option %s', - sep='x', - ), - moving_image=dict(argstr='%s', - mandatory=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - number_of_affine_iterations=dict(argstr='--number-of-affine-iterations %s', - sep='x', - ), - number_of_iterations=dict(argstr='--number-of-iterations %s', - sep='x', - ), - number_of_time_steps=dict(requires=['gradient_step_length'], - ), - output_transform_prefix=dict(argstr='--output-naming %s', - mandatory=True, - usedefault=True, - ), - radius=dict(mandatory=True, - requires=['metric'], - ), - regularization=dict(argstr='%s', - ), - regularization_deformation_field_sigma=dict(requires=['regularization'], - ), - regularization_gradient_field_sigma=dict(requires=['regularization'], - ), - smoothing_sigmas=dict(argstr='--gaussian-smoothing-sigmas %s', - sep='x', - ), - subsampling_factors=dict(argstr='--subsampling-factors %s', - sep='x', - ), - symmetry_type=dict(requires=['delta_time'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformation_model=dict(argstr='%s', - mandatory=True, - ), - use_histogram_matching=dict(argstr='%s', - usedefault=True, - ), + input_map = dict( + affine_gradient_descent_option=dict(argstr='%s', ), + args=dict(argstr='%s', ), + delta_time=dict(requires=['number_of_time_steps'], ), + dimension=dict( + argstr='%d', + position=1, + usedefault=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict(mandatory=True, ), + gradient_step_length=dict(requires=['transformation_model'], ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + metric=dict(mandatory=True, ), + metric_weight=dict( + mandatory=True, + requires=['metric'], + usedefault=True, + ), + mi_option=dict( + argstr='--MI-option %s', + sep='x', + ), + moving_image=dict( + argstr='%s', + mandatory=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + number_of_affine_iterations=dict( + argstr='--number-of-affine-iterations %s', + sep='x', + ), + number_of_iterations=dict( + argstr='--number-of-iterations %s', + sep='x', + ), + number_of_time_steps=dict(requires=['gradient_step_length'], ), + output_transform_prefix=dict( + argstr='--output-naming %s', + mandatory=True, + usedefault=True, + ), + radius=dict( + mandatory=True, + requires=['metric'], + ), + regularization=dict(argstr='%s', ), + regularization_deformation_field_sigma=dict( + requires=['regularization'], ), + regularization_gradient_field_sigma=dict( + requires=['regularization'], ), + smoothing_sigmas=dict( + argstr='--gaussian-smoothing-sigmas %s', + sep='x', + ), + subsampling_factors=dict( + argstr='--subsampling-factors %s', + sep='x', + ), + symmetry_type=dict(requires=['delta_time'], ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformation_model=dict( + argstr='%s', + mandatory=True, + ), + use_histogram_matching=dict( + argstr='%s', + usedefault=True, + ), ) inputs = ANTS.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ANTS_outputs(): - output_map = dict(affine_transform=dict(), - inverse_warp_transform=dict(), - metaheader=dict(), - metaheader_raw=dict(), - warp_transform=dict(), + output_map = dict( + affine_transform=dict(), + inverse_warp_transform=dict(), + metaheader=dict(), + metaheader_raw=dict(), + warp_transform=dict(), ) outputs = ANTS.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py b/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py index c58eeefc67..b92f7bc916 100644 --- a/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py +++ b/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py @@ -4,25 +4,28 @@ def test_ANTSCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ANTSCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py b/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py index fcdc519aad..8a0346aa81 100644 --- a/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py +++ b/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py @@ -4,64 +4,73 @@ def test_AffineInitializer_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='%s', - position=0, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_image=dict(argstr='%s', - mandatory=True, - position=1, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - local_search=dict(argstr='%d', - position=7, - usedefault=True, - ), - moving_image=dict(argstr='%s', - mandatory=True, - position=2, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_file=dict(argstr='%s', - position=3, - usedefault=True, - ), - principal_axes=dict(argstr='%d', - position=6, - usedefault=True, - ), - radian_fraction=dict(argstr='%f', - position=5, - usedefault=True, - ), - search_factor=dict(argstr='%f', - position=4, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='%s', + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + argstr='%s', + mandatory=True, + position=1, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + local_search=dict( + argstr='%d', + position=7, + usedefault=True, + ), + moving_image=dict( + argstr='%s', + mandatory=True, + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='%s', + position=3, + usedefault=True, + ), + principal_axes=dict( + argstr='%d', + position=6, + usedefault=True, + ), + radian_fraction=dict( + argstr='%f', + position=5, + usedefault=True, + ), + search_factor=dict( + argstr='%f', + position=4, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AffineInitializer.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AffineInitializer_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = AffineInitializer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_AntsJointFusion.py b/nipype/interfaces/ants/tests/test_auto_AntsJointFusion.py index 09d95a4205..2302344e7b 100644 --- a/nipype/interfaces/ants/tests/test_auto_AntsJointFusion.py +++ b/nipype/interfaces/ants/tests/test_auto_AntsJointFusion.py @@ -4,89 +4,107 @@ def test_AntsJointFusion_inputs(): - input_map = dict(alpha=dict(argstr='-a %s', - usedefault=True, - ), - args=dict(argstr='%s', - ), - atlas_image=dict(argstr='-g %s...', - mandatory=True, - ), - atlas_segmentation_image=dict(argstr='-l %s...', - mandatory=True, - ), - beta=dict(argstr='-b %s', - usedefault=True, - ), - constrain_nonnegative=dict(argstr='-c', - usedefault=True, - ), - dimension=dict(argstr='-d %d', - usedefault=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclusion_image=dict(), - exclusion_image_label=dict(argstr='-e %s', - requires=['exclusion_image'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask_image=dict(argstr='-x %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_atlas_voting_weight_name_format=dict(requires=['out_label_fusion', 'out_intensity_fusion_name_format', 'out_label_post_prob_name_format'], - ), - out_intensity_fusion_name_format=dict(argstr='', - ), - out_label_fusion=dict(argstr='%s', - hash_files=False, - ), - out_label_post_prob_name_format=dict(requires=['out_label_fusion', 'out_intensity_fusion_name_format'], - ), - patch_metric=dict(argstr='-m %s', - usedefault=False, - ), - patch_radius=dict(argstr='-p %s', - maxlen=3, - minlen=3, - ), - retain_atlas_voting_images=dict(argstr='-f', - usedefault=True, - ), - retain_label_posterior_images=dict(argstr='-r', - requires=['atlas_segmentation_image'], - usedefault=True, - ), - search_radius=dict(argstr='-s %s', - usedefault=True, - ), - target_image=dict(argstr='-t %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-v', - ), + input_map = dict( + alpha=dict( + argstr='-a %s', + usedefault=True, + ), + args=dict(argstr='%s', ), + atlas_image=dict( + argstr='-g %s...', + mandatory=True, + ), + atlas_segmentation_image=dict( + argstr='-l %s...', + mandatory=True, + ), + beta=dict( + argstr='-b %s', + usedefault=True, + ), + constrain_nonnegative=dict( + argstr='-c', + usedefault=True, + ), + dimension=dict( + argstr='-d %d', + usedefault=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclusion_image=dict(), + exclusion_image_label=dict( + argstr='-e %s', + requires=['exclusion_image'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask_image=dict(argstr='-x %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_atlas_voting_weight_name_format=dict( + requires=[ + 'out_label_fusion', 'out_intensity_fusion_name_format', + 'out_label_post_prob_name_format' + ], ), + out_intensity_fusion_name_format=dict(argstr='', ), + out_label_fusion=dict( + argstr='%s', + hash_files=False, + ), + out_label_post_prob_name_format=dict( + requires=['out_label_fusion', 'out_intensity_fusion_name_format'], + ), + patch_metric=dict( + argstr='-m %s', + usedefault=False, + ), + patch_radius=dict( + argstr='-p %s', + maxlen=3, + minlen=3, + ), + retain_atlas_voting_images=dict( + argstr='-f', + usedefault=True, + ), + retain_label_posterior_images=dict( + argstr='-r', + requires=['atlas_segmentation_image'], + usedefault=True, + ), + search_radius=dict( + argstr='-s %s', + usedefault=True, + ), + target_image=dict( + argstr='-t %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-v', ), ) inputs = AntsJointFusion.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AntsJointFusion_outputs(): - output_map = dict(out_atlas_voting_weight_name_format=dict(), - out_intensity_fusion_name_format=dict(), - out_label_fusion=dict(), - out_label_post_prob_name_format=dict(), + output_map = dict( + out_atlas_voting_weight_name_format=dict(), + out_intensity_fusion_name_format=dict(), + out_label_fusion=dict(), + out_label_post_prob_name_format=dict(), ) outputs = AntsJointFusion.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py b/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py index b159e6ee1d..32d04bace8 100644 --- a/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py +++ b/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py @@ -4,63 +4,65 @@ def test_ApplyTransforms_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - default_value=dict(argstr='--default-value %g', - usedefault=True, - ), - dimension=dict(argstr='--dimensionality %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - float=dict(argstr='--float %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='--input %s', - mandatory=True, - ), - input_image_type=dict(argstr='--input-image-type %d', - ), - interpolation=dict(argstr='%s', - usedefault=True, - ), - interpolation_parameters=dict(), - invert_transform_flags=dict(), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_postfix=dict(usedefault=True, - ), - output_image=dict(argstr='--output %s', - genfile=True, - hash_files=False, - ), - print_out_composite_warp_file=dict(requires=['output_image'], - ), - reference_image=dict(argstr='--reference-image %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transforms=dict(argstr='%s', - mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + default_value=dict( + argstr='--default-value %g', + usedefault=True, + ), + dimension=dict(argstr='--dimensionality %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + float=dict(argstr='--float %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='--input %s', + mandatory=True, + ), + input_image_type=dict(argstr='--input-image-type %d', ), + interpolation=dict( + argstr='%s', + usedefault=True, + ), + interpolation_parameters=dict(), + invert_transform_flags=dict(), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_postfix=dict(usedefault=True, ), + output_image=dict( + argstr='--output %s', + genfile=True, + hash_files=False, + ), + print_out_composite_warp_file=dict(requires=['output_image'], ), + reference_image=dict( + argstr='--reference-image %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transforms=dict( + argstr='%s', + mandatory=True, + ), ) inputs = ApplyTransforms.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyTransforms_outputs(): - output_map = dict(output_image=dict(), - ) + output_map = dict(output_image=dict(), ) outputs = ApplyTransforms.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py b/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py index b9f3f63d54..115265d2ce 100644 --- a/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py +++ b/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py @@ -4,46 +4,49 @@ def test_ApplyTransformsToPoints_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='--dimensionality %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='--input %s', - mandatory=True, - ), - invert_transform_flags=dict(), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_file=dict(argstr='--output %s', - hash_files=False, - name_source=['input_file'], - name_template='%s_transformed.csv', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transforms=dict(argstr='%s', - mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict(argstr='--dimensionality %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='--input %s', + mandatory=True, + ), + invert_transform_flags=dict(), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_file=dict( + argstr='--output %s', + hash_files=False, + name_source=['input_file'], + name_template='%s_transformed.csv', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transforms=dict( + argstr='%s', + mandatory=True, + ), ) inputs = ApplyTransformsToPoints.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyTransformsToPoints_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = ApplyTransformsToPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_Atropos.py b/nipype/interfaces/ants/tests/test_auto_Atropos.py index 9cb7d36844..11a3a06c16 100644 --- a/nipype/interfaces/ants/tests/test_auto_Atropos.py +++ b/nipype/interfaces/ants/tests/test_auto_Atropos.py @@ -4,79 +4,78 @@ def test_Atropos_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - convergence_threshold=dict(requires=['n_iterations'], - ), - dimension=dict(argstr='--image-dimensionality %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - icm_use_synchronous_update=dict(argstr='%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialization=dict(argstr='%s', - mandatory=True, - requires=['number_of_tissue_classes'], - ), - intensity_images=dict(argstr='--intensity-image %s...', - mandatory=True, - ), - likelihood_model=dict(argstr='--likelihood-model %s', - ), - mask_image=dict(argstr='--mask-image %s', - mandatory=True, - ), - maximum_number_of_icm_terations=dict(requires=['icm_use_synchronous_update'], - ), - mrf_radius=dict(requires=['mrf_smoothing_factor'], - ), - mrf_smoothing_factor=dict(argstr='%s', - ), - n_iterations=dict(argstr='%s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - number_of_tissue_classes=dict(mandatory=True, - ), - out_classified_image_name=dict(argstr='%s', - genfile=True, - hash_files=False, - ), - output_posteriors_name_template=dict(usedefault=True, - ), - posterior_formulation=dict(argstr='%s', - ), - prior_probability_images=dict(), - prior_probability_threshold=dict(requires=['prior_weighting'], - ), - prior_weighting=dict(), - save_posteriors=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_mixture_model_proportions=dict(requires=['posterior_formulation'], - ), - use_random_seed=dict(argstr='--use-random-seed %d', - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + convergence_threshold=dict(requires=['n_iterations'], ), + dimension=dict( + argstr='--image-dimensionality %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + icm_use_synchronous_update=dict(argstr='%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialization=dict( + argstr='%s', + mandatory=True, + requires=['number_of_tissue_classes'], + ), + intensity_images=dict( + argstr='--intensity-image %s...', + mandatory=True, + ), + likelihood_model=dict(argstr='--likelihood-model %s', ), + mask_image=dict( + argstr='--mask-image %s', + mandatory=True, + ), + maximum_number_of_icm_terations=dict( + requires=['icm_use_synchronous_update'], ), + mrf_radius=dict(requires=['mrf_smoothing_factor'], ), + mrf_smoothing_factor=dict(argstr='%s', ), + n_iterations=dict(argstr='%s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + number_of_tissue_classes=dict(mandatory=True, ), + out_classified_image_name=dict( + argstr='%s', + genfile=True, + hash_files=False, + ), + output_posteriors_name_template=dict(usedefault=True, ), + posterior_formulation=dict(argstr='%s', ), + prior_probability_images=dict(), + prior_probability_threshold=dict(requires=['prior_weighting'], ), + prior_weighting=dict(), + save_posteriors=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_mixture_model_proportions=dict( + requires=['posterior_formulation'], ), + use_random_seed=dict( + argstr='--use-random-seed %d', + usedefault=True, + ), ) inputs = Atropos.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Atropos_outputs(): - output_map = dict(classified_image=dict(), - posteriors=dict(), + output_map = dict( + classified_image=dict(), + posteriors=dict(), ) outputs = Atropos.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py b/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py index 52ff9679ee..e322852428 100644 --- a/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py @@ -4,45 +4,49 @@ def test_AverageAffineTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='%d', - mandatory=True, - position=0, - usedefault=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_affine_transform=dict(argstr='%s', - mandatory=True, - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transforms=dict(argstr='%s', - mandatory=True, - position=3, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='%d', + mandatory=True, + position=0, + usedefault=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_affine_transform=dict( + argstr='%s', + mandatory=True, + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transforms=dict( + argstr='%s', + mandatory=True, + position=3, + ), ) inputs = AverageAffineTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AverageAffineTransform_outputs(): - output_map = dict(affine_transform=dict(), - ) + output_map = dict(affine_transform=dict(), ) outputs = AverageAffineTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_AverageImages.py b/nipype/interfaces/ants/tests/test_auto_AverageImages.py index 4c49eb27c0..bb2e58b508 100644 --- a/nipype/interfaces/ants/tests/test_auto_AverageImages.py +++ b/nipype/interfaces/ants/tests/test_auto_AverageImages.py @@ -4,49 +4,54 @@ def test_AverageImages_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='%d', - mandatory=True, - position=0, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - images=dict(argstr='%s', - mandatory=True, - position=3, - ), - normalize=dict(argstr='%d', - mandatory=True, - position=2, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_average_image=dict(argstr='%s', - hash_files=False, - position=1, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='%d', + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + images=dict( + argstr='%s', + mandatory=True, + position=3, + ), + normalize=dict( + argstr='%d', + mandatory=True, + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_average_image=dict( + argstr='%s', + hash_files=False, + position=1, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AverageImages.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AverageImages_outputs(): - output_map = dict(output_average_image=dict(), - ) + output_map = dict(output_average_image=dict(), ) outputs = AverageImages.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py b/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py index 3f1ade4bc3..f174c99019 100644 --- a/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py +++ b/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py @@ -4,77 +4,81 @@ def test_BrainExtraction_inputs(): - input_map = dict(anatomical_image=dict(argstr='-a %s', - mandatory=True, - ), - args=dict(argstr='%s', - ), - brain_probability_mask=dict(argstr='-m %s', - copyfile=False, - mandatory=True, - ), - brain_template=dict(argstr='-e %s', - mandatory=True, - ), - debug=dict(argstr='-z 1', - ), - dimension=dict(argstr='-d %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - extraction_registration_mask=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_suffix=dict(argstr='-s %s', - usedefault=True, - ), - keep_temporary_files=dict(argstr='-k %d', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_prefix=dict(argstr='-o %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_floatingpoint_precision=dict(argstr='-q %d', - ), - use_random_seeding=dict(argstr='-u %d', - ), + input_map = dict( + anatomical_image=dict( + argstr='-a %s', + mandatory=True, + ), + args=dict(argstr='%s', ), + brain_probability_mask=dict( + argstr='-m %s', + copyfile=False, + mandatory=True, + ), + brain_template=dict( + argstr='-e %s', + mandatory=True, + ), + debug=dict(argstr='-z 1', ), + dimension=dict( + argstr='-d %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extraction_registration_mask=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_suffix=dict( + argstr='-s %s', + usedefault=True, + ), + keep_temporary_files=dict(argstr='-k %d', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr='-o %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_floatingpoint_precision=dict(argstr='-q %d', ), + use_random_seeding=dict(argstr='-u %d', ), ) inputs = BrainExtraction.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BrainExtraction_outputs(): - output_map = dict(BrainExtractionBrain=dict(), - BrainExtractionCSF=dict(), - BrainExtractionGM=dict(), - BrainExtractionInitialAffine=dict(), - BrainExtractionInitialAffineFixed=dict(), - BrainExtractionInitialAffineMoving=dict(), - BrainExtractionLaplacian=dict(), - BrainExtractionMask=dict(), - BrainExtractionPrior0GenericAffine=dict(), - BrainExtractionPrior1InverseWarp=dict(), - BrainExtractionPrior1Warp=dict(), - BrainExtractionPriorWarped=dict(), - BrainExtractionSegmentation=dict(), - BrainExtractionTemplateLaplacian=dict(), - BrainExtractionTmp=dict(), - BrainExtractionWM=dict(), - N4Corrected0=dict(), - N4Truncated0=dict(), + output_map = dict( + BrainExtractionBrain=dict(), + BrainExtractionCSF=dict(), + BrainExtractionGM=dict(), + BrainExtractionInitialAffine=dict(), + BrainExtractionInitialAffineFixed=dict(), + BrainExtractionInitialAffineMoving=dict(), + BrainExtractionLaplacian=dict(), + BrainExtractionMask=dict(), + BrainExtractionPrior0GenericAffine=dict(), + BrainExtractionPrior1InverseWarp=dict(), + BrainExtractionPrior1Warp=dict(), + BrainExtractionPriorWarped=dict(), + BrainExtractionSegmentation=dict(), + BrainExtractionTemplateLaplacian=dict(), + BrainExtractionTmp=dict(), + BrainExtractionWM=dict(), + N4Corrected0=dict(), + N4Truncated0=dict(), ) outputs = BrainExtraction.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py b/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py index c9465f6a8e..b164aa0709 100644 --- a/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py @@ -4,49 +4,54 @@ def test_ComposeMultiTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='%d', - position=0, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_transform=dict(argstr='%s', - keep_ext=True, - name_source=['transforms'], - name_template='%s_composed', - position=1, - ), - reference_image=dict(argstr='%s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transforms=dict(argstr='%s', - mandatory=True, - position=3, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='%d', + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_transform=dict( + argstr='%s', + keep_extension=True, + name_source=['transforms'], + name_template='%s_composed', + position=1, + ), + reference_image=dict( + argstr='%s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transforms=dict( + argstr='%s', + mandatory=True, + position=3, + ), ) inputs = ComposeMultiTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComposeMultiTransform_outputs(): - output_map = dict(output_transform=dict(), - ) + output_map = dict(output_transform=dict(), ) outputs = ComposeMultiTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py b/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py index 2afe734522..aedd316c75 100644 --- a/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py +++ b/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py @@ -4,74 +4,85 @@ def test_ConvertScalarImageToRGB_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - colormap=dict(argstr='%s', - mandatory=True, - position=4, - usedefault=True, - ), - custom_color_map_file=dict(argstr='%s', - position=5, - usedefault=True, - ), - dimension=dict(argstr='%d', - mandatory=True, - position=0, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='%s', - mandatory=True, - position=1, - ), - mask_image=dict(argstr='%s', - position=3, - usedefault=True, - ), - maximum_RGB_output=dict(argstr='%d', - position=9, - usedefault=True, - ), - maximum_input=dict(argstr='%d', - mandatory=True, - position=7, - ), - minimum_RGB_output=dict(argstr='%d', - position=8, - usedefault=True, - ), - minimum_input=dict(argstr='%d', - mandatory=True, - position=6, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_image=dict(argstr='%s', - position=2, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + colormap=dict( + argstr='%s', + mandatory=True, + position=4, + usedefault=True, + ), + custom_color_map_file=dict( + argstr='%s', + position=5, + usedefault=True, + ), + dimension=dict( + argstr='%d', + mandatory=True, + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='%s', + mandatory=True, + position=1, + ), + mask_image=dict( + argstr='%s', + position=3, + usedefault=True, + ), + maximum_RGB_output=dict( + argstr='%d', + position=9, + usedefault=True, + ), + maximum_input=dict( + argstr='%d', + mandatory=True, + position=7, + ), + minimum_RGB_output=dict( + argstr='%d', + position=8, + usedefault=True, + ), + minimum_input=dict( + argstr='%d', + mandatory=True, + position=6, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_image=dict( + argstr='%s', + position=2, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ConvertScalarImageToRGB.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ConvertScalarImageToRGB_outputs(): - output_map = dict(output_image=dict(), - ) + output_map = dict(output_image=dict(), ) outputs = ConvertScalarImageToRGB.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py b/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py index 8ad0203370..6855368a7a 100644 --- a/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py +++ b/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py @@ -4,92 +4,91 @@ def test_CorticalThickness_inputs(): - input_map = dict(anatomical_image=dict(argstr='-a %s', - mandatory=True, - ), - args=dict(argstr='%s', - ), - b_spline_smoothing=dict(argstr='-v', - ), - brain_probability_mask=dict(argstr='-m %s', - copyfile=False, - mandatory=True, - ), - brain_template=dict(argstr='-e %s', - mandatory=True, - ), - cortical_label_image=dict(), - debug=dict(argstr='-z 1', - ), - dimension=dict(argstr='-d %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - extraction_registration_mask=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_suffix=dict(argstr='-s %s', - usedefault=True, - ), - keep_temporary_files=dict(argstr='-k %d', - ), - label_propagation=dict(argstr='-l %s', - ), - max_iterations=dict(argstr='-i %d', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_prefix=dict(argstr='-o %s', - usedefault=True, - ), - posterior_formulation=dict(argstr='-b %s', - ), - prior_segmentation_weight=dict(argstr='-w %f', - ), - quick_registration=dict(argstr='-q 1', - ), - segmentation_iterations=dict(argstr='-n %d', - ), - segmentation_priors=dict(argstr='-p %s', - mandatory=True, - ), - t1_registration_template=dict(argstr='-t %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_floatingpoint_precision=dict(argstr='-j %d', - ), - use_random_seeding=dict(argstr='-u %d', - ), + input_map = dict( + anatomical_image=dict( + argstr='-a %s', + mandatory=True, + ), + args=dict(argstr='%s', ), + b_spline_smoothing=dict(argstr='-v', ), + brain_probability_mask=dict( + argstr='-m %s', + copyfile=False, + mandatory=True, + ), + brain_template=dict( + argstr='-e %s', + mandatory=True, + ), + cortical_label_image=dict(), + debug=dict(argstr='-z 1', ), + dimension=dict( + argstr='-d %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extraction_registration_mask=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_suffix=dict( + argstr='-s %s', + usedefault=True, + ), + keep_temporary_files=dict(argstr='-k %d', ), + label_propagation=dict(argstr='-l %s', ), + max_iterations=dict(argstr='-i %d', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr='-o %s', + usedefault=True, + ), + posterior_formulation=dict(argstr='-b %s', ), + prior_segmentation_weight=dict(argstr='-w %f', ), + quick_registration=dict(argstr='-q 1', ), + segmentation_iterations=dict(argstr='-n %d', ), + segmentation_priors=dict( + argstr='-p %s', + mandatory=True, + ), + t1_registration_template=dict( + argstr='-t %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_floatingpoint_precision=dict(argstr='-j %d', ), + use_random_seeding=dict(argstr='-u %d', ), ) inputs = CorticalThickness.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CorticalThickness_outputs(): - output_map = dict(BrainExtractionMask=dict(), - BrainSegmentation=dict(), - BrainSegmentationN4=dict(), - BrainSegmentationPosteriors=dict(), - BrainVolumes=dict(), - CorticalThickness=dict(), - CorticalThicknessNormedToTemplate=dict(), - SubjectToTemplate0GenericAffine=dict(), - SubjectToTemplate1Warp=dict(), - SubjectToTemplateLogJacobian=dict(), - TemplateToSubject0Warp=dict(), - TemplateToSubject1GenericAffine=dict(), + output_map = dict( + BrainExtractionMask=dict(), + BrainSegmentation=dict(), + BrainSegmentationN4=dict(), + BrainSegmentationPosteriors=dict(), + BrainVolumes=dict(), + CorticalThickness=dict(), + CorticalThicknessNormedToTemplate=dict(), + SubjectToTemplate0GenericAffine=dict(), + SubjectToTemplate1Warp=dict(), + SubjectToTemplateLogJacobian=dict(), + TemplateToSubject0Warp=dict(), + TemplateToSubject1GenericAffine=dict(), ) outputs = CorticalThickness.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py b/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py index 561853e79b..b789de0633 100644 --- a/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py +++ b/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py @@ -4,51 +4,57 @@ def test_CreateJacobianDeterminantImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - deformationField=dict(argstr='%s', - mandatory=True, - position=1, - ), - doLogJacobian=dict(argstr='%d', - position=3, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - imageDimension=dict(argstr='%d', - mandatory=True, - position=0, - usedefault=False, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - outputImage=dict(argstr='%s', - mandatory=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - useGeometric=dict(argstr='%d', - position=4, - ), + input_map = dict( + args=dict(argstr='%s', ), + deformationField=dict( + argstr='%s', + mandatory=True, + position=1, + ), + doLogJacobian=dict( + argstr='%d', + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + imageDimension=dict( + argstr='%d', + mandatory=True, + position=0, + usedefault=False, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + outputImage=dict( + argstr='%s', + mandatory=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + useGeometric=dict( + argstr='%d', + position=4, + ), ) inputs = CreateJacobianDeterminantImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CreateJacobianDeterminantImage_outputs(): - output_map = dict(jacobian_image=dict(), - ) + output_map = dict(jacobian_image=dict(), ) outputs = CreateJacobianDeterminantImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py b/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py index 38f24644a9..1d6871baa3 100644 --- a/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py +++ b/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py @@ -4,57 +4,53 @@ def test_CreateTiledMosaic_inputs(): - input_map = dict(alpha_value=dict(argstr='-a %.2f', - ), - args=dict(argstr='%s', - ), - direction=dict(argstr='-d %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - flip_slice=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='-i %s', - mandatory=True, - ), - mask_image=dict(argstr='-x %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_image=dict(argstr='-o %s', - usedefault=True, - ), - pad_or_crop=dict(argstr='-p %s', - ), - permute_axes=dict(argstr='-g', - ), - rgb_image=dict(argstr='-r %s', - mandatory=True, - ), - slices=dict(argstr='-s %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tile_geometry=dict(argstr='-t %s', - ), + input_map = dict( + alpha_value=dict(argstr='-a %.2f', ), + args=dict(argstr='%s', ), + direction=dict(argstr='-d %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip_slice=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='-i %s', + mandatory=True, + ), + mask_image=dict(argstr='-x %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_image=dict( + argstr='-o %s', + usedefault=True, + ), + pad_or_crop=dict(argstr='-p %s', ), + permute_axes=dict(argstr='-g', ), + rgb_image=dict( + argstr='-r %s', + mandatory=True, + ), + slices=dict(argstr='-s %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tile_geometry=dict(argstr='-t %s', ), ) inputs = CreateTiledMosaic.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CreateTiledMosaic_outputs(): - output_map = dict(output_image=dict(), - ) + output_map = dict(output_image=dict(), ) outputs = CreateTiledMosaic.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py b/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py index 7d120a2f2e..5bbf4f2d51 100644 --- a/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py +++ b/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py @@ -4,61 +4,70 @@ def test_DenoiseImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-d %d', - usedefault=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='-i %s', - mandatory=True, - ), - noise_image=dict(hash_files=False, - keep_extension=True, - name_source=['input_image'], - name_template='%s_noise', - ), - noise_model=dict(argstr='-n %s', - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_image=dict(argstr='-o %s', - hash_files=False, - keep_extension=True, - name_source=['input_image'], - name_template='%s_noise_corrected', - ), - save_noise=dict(mandatory=True, - usedefault=True, - xor=['noise_image'], - ), - shrink_factor=dict(argstr='-s %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-v', - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-d %d', + usedefault=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='-i %s', + mandatory=True, + ), + noise_image=dict( + hash_files=False, + keep_extension=True, + name_source=['input_image'], + name_template='%s_noise', + ), + noise_model=dict( + argstr='-n %s', + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_image=dict( + argstr='-o %s', + hash_files=False, + keep_extension=True, + name_source=['input_image'], + name_template='%s_noise_corrected', + ), + save_noise=dict( + mandatory=True, + usedefault=True, + xor=['noise_image'], + ), + shrink_factor=dict( + argstr='-s %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-v', ), ) inputs = DenoiseImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DenoiseImage_outputs(): - output_map = dict(noise_image=dict(), - output_image=dict(), + output_map = dict( + noise_image=dict(), + output_image=dict(), ) outputs = DenoiseImage.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_GenWarpFields.py b/nipype/interfaces/ants/tests/test_auto_GenWarpFields.py index c58c8abf20..c1669f38e5 100644 --- a/nipype/interfaces/ants/tests/test_auto_GenWarpFields.py +++ b/nipype/interfaces/ants/tests/test_auto_GenWarpFields.py @@ -4,66 +4,70 @@ def test_GenWarpFields_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bias_field_correction=dict(argstr='-n 1', - ), - dimension=dict(argstr='-d %d', - position=1, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - force_proceed=dict(argstr='-f 1', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='-i %s', - copyfile=False, - mandatory=True, - ), - inverse_warp_template_labels=dict(argstr='-l', - ), - max_iterations=dict(argstr='-m %s', - sep='x', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_prefix=dict(argstr='-o %s', - usedefault=True, - ), - quality_check=dict(argstr='-q 1', - ), - reference_image=dict(argstr='-r %s', - copyfile=True, - mandatory=True, - ), - similarity_metric=dict(argstr='-s %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformation_model=dict(argstr='-t %s', - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bias_field_correction=dict(argstr='-n 1', ), + dimension=dict( + argstr='-d %d', + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_proceed=dict(argstr='-f 1', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='-i %s', + copyfile=False, + mandatory=True, + ), + inverse_warp_template_labels=dict(argstr='-l', ), + max_iterations=dict( + argstr='-m %s', + sep='x', + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr='-o %s', + usedefault=True, + ), + quality_check=dict(argstr='-q 1', ), + reference_image=dict( + argstr='-r %s', + copyfile=True, + mandatory=True, + ), + similarity_metric=dict(argstr='-s %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformation_model=dict( + argstr='-t %s', + usedefault=True, + ), ) inputs = GenWarpFields.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenWarpFields_outputs(): - output_map = dict(affine_transformation=dict(), - input_file=dict(), - inverse_warp_field=dict(), - output_file=dict(), - warp_field=dict(), + output_map = dict( + affine_transformation=dict(), + input_file=dict(), + inverse_warp_field=dict(), + output_file=dict(), + warp_field=dict(), ) outputs = GenWarpFields.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_JointFusion.py b/nipype/interfaces/ants/tests/test_auto_JointFusion.py index 796c7a7e13..3dcd63dfdc 100644 --- a/nipype/interfaces/ants/tests/test_auto_JointFusion.py +++ b/nipype/interfaces/ants/tests/test_auto_JointFusion.py @@ -4,79 +4,88 @@ def test_JointFusion_inputs(): - input_map = dict(alpha=dict(requires=['method'], - usedefault=True, - ), - args=dict(argstr='%s', - ), - atlas_group_id=dict(argstr='-gp %d...', - ), - atlas_group_weights=dict(argstr='-gpw %d...', - ), - beta=dict(requires=['method'], - usedefault=True, - ), - dimension=dict(argstr='%d', - mandatory=True, - position=0, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclusion_region=dict(argstr='-x %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - method=dict(argstr='-m %s', - usedefault=True, - ), - modalities=dict(argstr='%d', - mandatory=True, - position=1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_label_image=dict(argstr='%s', - mandatory=True, - name_template='%s', - output_name='output_label_image', - position=-1, - ), - patch_radius=dict(argstr='-rp %s', - maxlen=3, - minlen=3, - ), - search_radius=dict(argstr='-rs %s', - maxlen=3, - minlen=3, - ), - target_image=dict(argstr='-tg %s...', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warped_intensity_images=dict(argstr='-g %s...', - mandatory=True, - ), - warped_label_images=dict(argstr='-l %s...', - mandatory=True, - ), + input_map = dict( + alpha=dict( + requires=['method'], + usedefault=True, + ), + args=dict(argstr='%s', ), + atlas_group_id=dict(argstr='-gp %d...', ), + atlas_group_weights=dict(argstr='-gpw %d...', ), + beta=dict( + requires=['method'], + usedefault=True, + ), + dimension=dict( + argstr='%d', + mandatory=True, + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclusion_region=dict(argstr='-x %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + method=dict( + argstr='-m %s', + usedefault=True, + ), + modalities=dict( + argstr='%d', + mandatory=True, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_label_image=dict( + argstr='%s', + mandatory=True, + name_template='%s', + output_name='output_label_image', + position=-1, + ), + patch_radius=dict( + argstr='-rp %s', + maxlen=3, + minlen=3, + ), + search_radius=dict( + argstr='-rs %s', + maxlen=3, + minlen=3, + ), + target_image=dict( + argstr='-tg %s...', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warped_intensity_images=dict( + argstr='-g %s...', + mandatory=True, + ), + warped_label_images=dict( + argstr='-l %s...', + mandatory=True, + ), ) inputs = JointFusion.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JointFusion_outputs(): - output_map = dict(output_label_image=dict(), - ) + output_map = dict(output_label_image=dict(), ) outputs = JointFusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py b/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py index e94cd44b1d..ec61845fe5 100644 --- a/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py +++ b/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py @@ -4,78 +4,84 @@ def test_KellyKapowski_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - convergence=dict(argstr='--convergence "%s"', - usedefault=True, - ), - cortical_thickness=dict(argstr='--output "%s"', - hash_files=False, - keep_extension=True, - name_source=['segmentation_image'], - name_template='%s_cortical_thickness', - ), - dimension=dict(argstr='--image-dimensionality %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - gradient_step=dict(argstr='--gradient-step %f', - usedefault=True, - ), - gray_matter_label=dict(usedefault=True, - ), - gray_matter_prob_image=dict(argstr='--gray-matter-probability-image "%s"', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - max_invert_displacement_field_iters=dict(argstr='--maximum-number-of-invert-displacement-field-iterations %d', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - number_integration_points=dict(argstr='--number-of-integration-points %d', - ), - segmentation_image=dict(argstr='--segmentation-image "%s"', - mandatory=True, - ), - smoothing_variance=dict(argstr='--smoothing-variance %f', - ), - smoothing_velocity_field=dict(argstr='--smoothing-velocity-field-parameter %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thickness_prior_estimate=dict(argstr='--thickness-prior-estimate %f', - usedefault=True, - ), - thickness_prior_image=dict(argstr='--thickness-prior-image "%s"', - ), - use_bspline_smoothing=dict(argstr='--use-bspline-smoothing 1', - ), - warped_white_matter=dict(hash_files=False, - keep_extension=True, - name_source=['segmentation_image'], - name_template='%s_warped_white_matter', - ), - white_matter_label=dict(usedefault=True, - ), - white_matter_prob_image=dict(argstr='--white-matter-probability-image "%s"', - ), + input_map = dict( + args=dict(argstr='%s', ), + convergence=dict( + argstr='--convergence "%s"', + usedefault=True, + ), + cortical_thickness=dict( + argstr='--output "%s"', + hash_files=False, + keep_extension=True, + name_source=['segmentation_image'], + name_template='%s_cortical_thickness', + ), + dimension=dict( + argstr='--image-dimensionality %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradient_step=dict( + argstr='--gradient-step %f', + usedefault=True, + ), + gray_matter_label=dict(usedefault=True, ), + gray_matter_prob_image=dict( + argstr='--gray-matter-probability-image "%s"', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + max_invert_displacement_field_iters=dict( + argstr= + '--maximum-number-of-invert-displacement-field-iterations %d', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + number_integration_points=dict( + argstr='--number-of-integration-points %d', ), + segmentation_image=dict( + argstr='--segmentation-image "%s"', + mandatory=True, + ), + smoothing_variance=dict(argstr='--smoothing-variance %f', ), + smoothing_velocity_field=dict( + argstr='--smoothing-velocity-field-parameter %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thickness_prior_estimate=dict( + argstr='--thickness-prior-estimate %f', + usedefault=True, + ), + thickness_prior_image=dict(argstr='--thickness-prior-image "%s"', ), + use_bspline_smoothing=dict(argstr='--use-bspline-smoothing 1', ), + warped_white_matter=dict( + hash_files=False, + keep_extension=True, + name_source=['segmentation_image'], + name_template='%s_warped_white_matter', + ), + white_matter_label=dict(usedefault=True, ), + white_matter_prob_image=dict( + argstr='--white-matter-probability-image "%s"', ), ) inputs = KellyKapowski.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_KellyKapowski_outputs(): - output_map = dict(cortical_thickness=dict(), - warped_white_matter=dict(), + output_map = dict( + cortical_thickness=dict(), + warped_white_matter=dict(), ) outputs = KellyKapowski.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py b/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py index 83b6b37d83..c1d496f4c6 100644 --- a/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py +++ b/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py @@ -4,62 +4,71 @@ def test_LaplacianThickness_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dT=dict(argstr='dT=%d', - position=6, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_gm=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=2, - ), - input_wm=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=1, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - opt_tolerance=dict(argstr='optional-laplacian-tolerance=%d', - position=8, - ), - output_image=dict(argstr='%s', - genfile=True, - hash_files=False, - position=3, - ), - prior_thickness=dict(argstr='priorthickval=%d', - position=5, - ), - smooth_param=dict(argstr='smoothparam=%d', - position=4, - ), - sulcus_prior=dict(argstr='use-sulcus-prior', - position=7, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dT=dict( + argstr='dT=%d', + position=6, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_gm=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=2, + ), + input_wm=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + opt_tolerance=dict( + argstr='optional-laplacian-tolerance=%d', + position=8, + ), + output_image=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=3, + ), + prior_thickness=dict( + argstr='priorthickval=%d', + position=5, + ), + smooth_param=dict( + argstr='smoothparam=%d', + position=4, + ), + sulcus_prior=dict( + argstr='use-sulcus-prior', + position=7, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = LaplacianThickness.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LaplacianThickness_outputs(): - output_map = dict(output_image=dict(), - ) + output_map = dict(output_image=dict(), ) outputs = LaplacianThickness.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py b/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py index fbed924b24..cd03ec4b05 100644 --- a/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py +++ b/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py @@ -4,58 +4,61 @@ def test_MeasureImageSimilarity_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='--dimensionality %d', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_image=dict(mandatory=True, - ), - fixed_image_mask=dict(argstr='%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - metric=dict(argstr='%s', - mandatory=True, - ), - metric_weight=dict(requires=['metric'], - usedefault=True, - ), - moving_image=dict(mandatory=True, - ), - moving_image_mask=dict(requires=['fixed_image_mask'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - radius_or_number_of_bins=dict(mandatory=True, - requires=['metric'], - ), - sampling_percentage=dict(mandatory=True, - requires=['metric'], - ), - sampling_strategy=dict(requires=['metric'], - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='--dimensionality %d', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict(mandatory=True, ), + fixed_image_mask=dict(argstr='%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + metric=dict( + argstr='%s', + mandatory=True, + ), + metric_weight=dict( + requires=['metric'], + usedefault=True, + ), + moving_image=dict(mandatory=True, ), + moving_image_mask=dict(requires=['fixed_image_mask'], ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + radius_or_number_of_bins=dict( + mandatory=True, + requires=['metric'], + ), + sampling_percentage=dict( + mandatory=True, + requires=['metric'], + ), + sampling_strategy=dict( + requires=['metric'], + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MeasureImageSimilarity.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MeasureImageSimilarity_outputs(): - output_map = dict(similarity=dict(), - ) + output_map = dict(similarity=dict(), ) outputs = MeasureImageSimilarity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py b/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py index 5057cb4ddf..5ed884cf0a 100644 --- a/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py +++ b/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py @@ -4,49 +4,54 @@ def test_MultiplyImages_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='%d', - mandatory=True, - position=0, - usedefault=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - first_input=dict(argstr='%s', - mandatory=True, - position=1, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_product_image=dict(argstr='%s', - mandatory=True, - position=3, - ), - second_input=dict(argstr='%s', - mandatory=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='%d', + mandatory=True, + position=0, + usedefault=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + first_input=dict( + argstr='%s', + mandatory=True, + position=1, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_product_image=dict( + argstr='%s', + mandatory=True, + position=3, + ), + second_input=dict( + argstr='%s', + mandatory=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MultiplyImages.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MultiplyImages_outputs(): - output_map = dict(output_product_image=dict(), - ) + output_map = dict(output_product_image=dict(), ) outputs = MultiplyImages.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py b/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py index 044b16ce50..cc76720ec7 100644 --- a/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py +++ b/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py @@ -4,65 +4,65 @@ def test_N4BiasFieldCorrection_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bias_image=dict(hash_files=False, - ), - bspline_fitting_distance=dict(argstr='--bspline-fitting %s', - ), - bspline_order=dict(requires=['bspline_fitting_distance'], - ), - convergence_threshold=dict(requires=['n_iterations'], - ), - copy_header=dict(mandatory=True, - usedefault=True, - ), - dimension=dict(argstr='-d %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='--input-image %s', - mandatory=True, - ), - mask_image=dict(argstr='--mask-image %s', - ), - n_iterations=dict(argstr='--convergence %s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - output_image=dict(argstr='--output %s', - genfile=True, - hash_files=False, - ), - save_bias=dict(mandatory=True, - usedefault=True, - xor=['bias_image'], - ), - shrink_factor=dict(argstr='--shrink-factor %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - weight_image=dict(argstr='--weight-image %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + bias_image=dict(hash_files=False, ), + bspline_fitting_distance=dict(argstr='--bspline-fitting %s', ), + bspline_order=dict(requires=['bspline_fitting_distance'], ), + convergence_threshold=dict(requires=['n_iterations'], ), + copy_header=dict( + mandatory=True, + usedefault=True, + ), + dimension=dict( + argstr='-d %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='--input-image %s', + mandatory=True, + ), + mask_image=dict(argstr='--mask-image %s', ), + n_iterations=dict(argstr='--convergence %s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_image=dict( + argstr='--output %s', + genfile=True, + hash_files=False, + ), + save_bias=dict( + mandatory=True, + usedefault=True, + xor=['bias_image'], + ), + shrink_factor=dict(argstr='--shrink-factor %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + weight_image=dict(argstr='--weight-image %s', ), ) inputs = N4BiasFieldCorrection.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_N4BiasFieldCorrection_outputs(): - output_map = dict(bias_image=dict(), - output_image=dict(), + output_map = dict( + bias_image=dict(), + output_image=dict(), ) outputs = N4BiasFieldCorrection.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_Registration.py b/nipype/interfaces/ants/tests/test_auto_Registration.py deleted file mode 100644 index ea9bc02e79..0000000000 --- a/nipype/interfaces/ants/tests/test_auto_Registration.py +++ /dev/null @@ -1,157 +0,0 @@ -# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT -from __future__ import unicode_literals -from ..registration import Registration - - -def test_Registration_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - collapse_output_transforms=dict(argstr='--collapse-output-transforms %d', - usedefault=True, - ), - convergence_threshold=dict(requires=['number_of_iterations'], - usedefault=True, - ), - convergence_window_size=dict(requires=['convergence_threshold'], - usedefault=True, - ), - dimension=dict(argstr='--dimensionality %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_image=dict(mandatory=True, - ), - fixed_image_mask=dict(argstr='%s', - max_ver='2.1.0', - xor=['fixed_image_masks'], - ), - fixed_image_masks=dict(min_ver='2.2.0', - xor=['fixed_image_mask'], - ), - float=dict(argstr='--float %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initial_moving_transform=dict(argstr='%s', - exists=True, - xor=['initial_moving_transform_com'], - ), - initial_moving_transform_com=dict(argstr='%s', - xor=['initial_moving_transform'], - ), - initialize_transforms_per_stage=dict(argstr='--initialize-transforms-per-stage %d', - usedefault=True, - ), - interpolation=dict(argstr='%s', - usedefault=True, - ), - interpolation_parameters=dict(), - invert_initial_moving_transform=dict(requires=['initial_moving_transform'], - xor=['initial_moving_transform_com'], - ), - metric=dict(mandatory=True, - ), - metric_item_trait=dict(), - metric_stage_trait=dict(), - metric_weight=dict(mandatory=True, - requires=['metric'], - usedefault=True, - ), - metric_weight_item_trait=dict(), - metric_weight_stage_trait=dict(), - moving_image=dict(mandatory=True, - ), - moving_image_mask=dict(max_ver='2.1.0', - requires=['fixed_image_mask'], - xor=['moving_image_masks'], - ), - moving_image_masks=dict(min_ver='2.2.0', - xor=['moving_image_mask'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - number_of_iterations=dict(), - output_inverse_warped_image=dict(hash_files=False, - requires=['output_warped_image'], - ), - output_transform_prefix=dict(argstr='%s', - usedefault=True, - ), - output_warped_image=dict(hash_files=False, - ), - radius_bins_item_trait=dict(), - radius_bins_stage_trait=dict(), - radius_or_number_of_bins=dict(requires=['metric_weight'], - usedefault=True, - ), - restore_state=dict(argstr='--restore-state %s', - ), - restrict_deformation=dict(), - sampling_percentage=dict(requires=['sampling_strategy'], - ), - sampling_percentage_item_trait=dict(), - sampling_percentage_stage_trait=dict(), - sampling_strategy=dict(requires=['metric_weight'], - ), - sampling_strategy_item_trait=dict(), - sampling_strategy_stage_trait=dict(), - save_state=dict(argstr='--save-state %s', - ), - shrink_factors=dict(mandatory=True, - ), - sigma_units=dict(requires=['smoothing_sigmas'], - ), - smoothing_sigmas=dict(mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform_parameters=dict(), - transforms=dict(argstr='%s', - mandatory=True, - ), - use_estimate_learning_rate_once=dict(), - use_histogram_matching=dict(usedefault=True, - ), - verbose=dict(argstr='-v', - ), - winsorize_lower_quantile=dict(argstr='%s', - usedefault=True, - ), - winsorize_upper_quantile=dict(argstr='%s', - usedefault=True, - ), - write_composite_transform=dict(argstr='--write-composite-transform %d', - usedefault=True, - ), - ) - inputs = Registration.input_spec() - - for key, metadata in list(input_map.items()): - for metakey, value in list(metadata.items()): - assert getattr(inputs.traits()[key], metakey) == value - - -def test_Registration_outputs(): - output_map = dict(composite_transform=dict(), - elapsed_time=dict(), - forward_invert_flags=dict(), - forward_transforms=dict(), - inverse_composite_transform=dict(), - inverse_warped_image=dict(), - metric_value=dict(), - reverse_invert_flags=dict(), - reverse_transforms=dict(), - save_state=dict(), - warped_image=dict(), - ) - outputs = Registration.output_spec() - - for key, metadata in list(output_map.items()): - for metakey, value in list(metadata.items()): - assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py b/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py index 9678152ba4..16d2e47a04 100644 --- a/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py @@ -4,67 +4,72 @@ def test_WarpImageMultiTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='%d', - position=1, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='%s', - mandatory=True, - position=2, - ), - invert_affine=dict(), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_postfix=dict(hash_files=False, - usedefault=True, - xor=['output_image'], - ), - output_image=dict(argstr='%s', - genfile=True, - hash_files=False, - position=3, - xor=['out_postfix'], - ), - reference_image=dict(argstr='-R %s', - xor=['tightest_box'], - ), - reslice_by_header=dict(argstr='--reslice-by-header', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tightest_box=dict(argstr='--tightest-bounding-box', - xor=['reference_image'], - ), - transformation_series=dict(argstr='%s', - mandatory=True, - position=-1, - ), - use_bspline=dict(argstr='--use-BSpline', - ), - use_nearest=dict(argstr='--use-NN', - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='%d', + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='%s', + mandatory=True, + position=2, + ), + invert_affine=dict(), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_postfix=dict( + hash_files=False, + usedefault=True, + xor=['output_image'], + ), + output_image=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=3, + xor=['out_postfix'], + ), + reference_image=dict( + argstr='-R %s', + xor=['tightest_box'], + ), + reslice_by_header=dict(argstr='--reslice-by-header', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tightest_box=dict( + argstr='--tightest-bounding-box', + xor=['reference_image'], + ), + transformation_series=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + use_bspline=dict(argstr='--use-BSpline', ), + use_nearest=dict(argstr='--use-NN', ), ) inputs = WarpImageMultiTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WarpImageMultiTransform_outputs(): - output_map = dict(output_image=dict(), - ) + output_map = dict(output_image=dict(), ) outputs = WarpImageMultiTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py b/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py index f7f310b5f8..4715bcf156 100644 --- a/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py @@ -4,60 +4,64 @@ def test_WarpTimeSeriesImageMultiTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='%d', - position=1, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='%s', - copyfile=True, - mandatory=True, - ), - invert_affine=dict(), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_postfix=dict(argstr='%s', - usedefault=True, - ), - reference_image=dict(argstr='-R %s', - xor=['tightest_box'], - ), - reslice_by_header=dict(argstr='--reslice-by-header', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tightest_box=dict(argstr='--tightest-bounding-box', - xor=['reference_image'], - ), - transformation_series=dict(argstr='%s', - copyfile=False, - mandatory=True, - ), - use_bspline=dict(argstr='--use-Bspline', - ), - use_nearest=dict(argstr='--use-NN', - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='%d', + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='%s', + copyfile=True, + mandatory=True, + ), + invert_affine=dict(), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_postfix=dict( + argstr='%s', + usedefault=True, + ), + reference_image=dict( + argstr='-R %s', + xor=['tightest_box'], + ), + reslice_by_header=dict(argstr='--reslice-by-header', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tightest_box=dict( + argstr='--tightest-bounding-box', + xor=['reference_image'], + ), + transformation_series=dict( + argstr='%s', + copyfile=False, + mandatory=True, + ), + use_bspline=dict(argstr='--use-Bspline', ), + use_nearest=dict(argstr='--use-NN', ), ) inputs = WarpTimeSeriesImageMultiTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WarpTimeSeriesImageMultiTransform_outputs(): - output_map = dict(output_image=dict(), - ) + output_map = dict(output_image=dict(), ) outputs = WarpTimeSeriesImageMultiTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_antsBrainExtraction.py b/nipype/interfaces/ants/tests/test_auto_antsBrainExtraction.py index 05e12b9a00..19f42b7c2d 100644 --- a/nipype/interfaces/ants/tests/test_auto_antsBrainExtraction.py +++ b/nipype/interfaces/ants/tests/test_auto_antsBrainExtraction.py @@ -4,77 +4,81 @@ def test_antsBrainExtraction_inputs(): - input_map = dict(anatomical_image=dict(argstr='-a %s', - mandatory=True, - ), - args=dict(argstr='%s', - ), - brain_probability_mask=dict(argstr='-m %s', - copyfile=False, - mandatory=True, - ), - brain_template=dict(argstr='-e %s', - mandatory=True, - ), - debug=dict(argstr='-z 1', - ), - dimension=dict(argstr='-d %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - extraction_registration_mask=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_suffix=dict(argstr='-s %s', - usedefault=True, - ), - keep_temporary_files=dict(argstr='-k %d', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_prefix=dict(argstr='-o %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_floatingpoint_precision=dict(argstr='-q %d', - ), - use_random_seeding=dict(argstr='-u %d', - ), + input_map = dict( + anatomical_image=dict( + argstr='-a %s', + mandatory=True, + ), + args=dict(argstr='%s', ), + brain_probability_mask=dict( + argstr='-m %s', + copyfile=False, + mandatory=True, + ), + brain_template=dict( + argstr='-e %s', + mandatory=True, + ), + debug=dict(argstr='-z 1', ), + dimension=dict( + argstr='-d %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extraction_registration_mask=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_suffix=dict( + argstr='-s %s', + usedefault=True, + ), + keep_temporary_files=dict(argstr='-k %d', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr='-o %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_floatingpoint_precision=dict(argstr='-q %d', ), + use_random_seeding=dict(argstr='-u %d', ), ) inputs = antsBrainExtraction.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_antsBrainExtraction_outputs(): - output_map = dict(BrainExtractionBrain=dict(), - BrainExtractionCSF=dict(), - BrainExtractionGM=dict(), - BrainExtractionInitialAffine=dict(), - BrainExtractionInitialAffineFixed=dict(), - BrainExtractionInitialAffineMoving=dict(), - BrainExtractionLaplacian=dict(), - BrainExtractionMask=dict(), - BrainExtractionPrior0GenericAffine=dict(), - BrainExtractionPrior1InverseWarp=dict(), - BrainExtractionPrior1Warp=dict(), - BrainExtractionPriorWarped=dict(), - BrainExtractionSegmentation=dict(), - BrainExtractionTemplateLaplacian=dict(), - BrainExtractionTmp=dict(), - BrainExtractionWM=dict(), - N4Corrected0=dict(), - N4Truncated0=dict(), + output_map = dict( + BrainExtractionBrain=dict(), + BrainExtractionCSF=dict(), + BrainExtractionGM=dict(), + BrainExtractionInitialAffine=dict(), + BrainExtractionInitialAffineFixed=dict(), + BrainExtractionInitialAffineMoving=dict(), + BrainExtractionLaplacian=dict(), + BrainExtractionMask=dict(), + BrainExtractionPrior0GenericAffine=dict(), + BrainExtractionPrior1InverseWarp=dict(), + BrainExtractionPrior1Warp=dict(), + BrainExtractionPriorWarped=dict(), + BrainExtractionSegmentation=dict(), + BrainExtractionTemplateLaplacian=dict(), + BrainExtractionTmp=dict(), + BrainExtractionWM=dict(), + N4Corrected0=dict(), + N4Truncated0=dict(), ) outputs = antsBrainExtraction.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_antsCorticalThickness.py b/nipype/interfaces/ants/tests/test_auto_antsCorticalThickness.py index 0e7a7ca4ba..4fccadacce 100644 --- a/nipype/interfaces/ants/tests/test_auto_antsCorticalThickness.py +++ b/nipype/interfaces/ants/tests/test_auto_antsCorticalThickness.py @@ -4,92 +4,91 @@ def test_antsCorticalThickness_inputs(): - input_map = dict(anatomical_image=dict(argstr='-a %s', - mandatory=True, - ), - args=dict(argstr='%s', - ), - b_spline_smoothing=dict(argstr='-v', - ), - brain_probability_mask=dict(argstr='-m %s', - copyfile=False, - mandatory=True, - ), - brain_template=dict(argstr='-e %s', - mandatory=True, - ), - cortical_label_image=dict(), - debug=dict(argstr='-z 1', - ), - dimension=dict(argstr='-d %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - extraction_registration_mask=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_suffix=dict(argstr='-s %s', - usedefault=True, - ), - keep_temporary_files=dict(argstr='-k %d', - ), - label_propagation=dict(argstr='-l %s', - ), - max_iterations=dict(argstr='-i %d', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_prefix=dict(argstr='-o %s', - usedefault=True, - ), - posterior_formulation=dict(argstr='-b %s', - ), - prior_segmentation_weight=dict(argstr='-w %f', - ), - quick_registration=dict(argstr='-q 1', - ), - segmentation_iterations=dict(argstr='-n %d', - ), - segmentation_priors=dict(argstr='-p %s', - mandatory=True, - ), - t1_registration_template=dict(argstr='-t %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_floatingpoint_precision=dict(argstr='-j %d', - ), - use_random_seeding=dict(argstr='-u %d', - ), + input_map = dict( + anatomical_image=dict( + argstr='-a %s', + mandatory=True, + ), + args=dict(argstr='%s', ), + b_spline_smoothing=dict(argstr='-v', ), + brain_probability_mask=dict( + argstr='-m %s', + copyfile=False, + mandatory=True, + ), + brain_template=dict( + argstr='-e %s', + mandatory=True, + ), + cortical_label_image=dict(), + debug=dict(argstr='-z 1', ), + dimension=dict( + argstr='-d %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extraction_registration_mask=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_suffix=dict( + argstr='-s %s', + usedefault=True, + ), + keep_temporary_files=dict(argstr='-k %d', ), + label_propagation=dict(argstr='-l %s', ), + max_iterations=dict(argstr='-i %d', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr='-o %s', + usedefault=True, + ), + posterior_formulation=dict(argstr='-b %s', ), + prior_segmentation_weight=dict(argstr='-w %f', ), + quick_registration=dict(argstr='-q 1', ), + segmentation_iterations=dict(argstr='-n %d', ), + segmentation_priors=dict( + argstr='-p %s', + mandatory=True, + ), + t1_registration_template=dict( + argstr='-t %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_floatingpoint_precision=dict(argstr='-j %d', ), + use_random_seeding=dict(argstr='-u %d', ), ) inputs = antsCorticalThickness.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_antsCorticalThickness_outputs(): - output_map = dict(BrainExtractionMask=dict(), - BrainSegmentation=dict(), - BrainSegmentationN4=dict(), - BrainSegmentationPosteriors=dict(), - BrainVolumes=dict(), - CorticalThickness=dict(), - CorticalThicknessNormedToTemplate=dict(), - SubjectToTemplate0GenericAffine=dict(), - SubjectToTemplate1Warp=dict(), - SubjectToTemplateLogJacobian=dict(), - TemplateToSubject0Warp=dict(), - TemplateToSubject1GenericAffine=dict(), + output_map = dict( + BrainExtractionMask=dict(), + BrainSegmentation=dict(), + BrainSegmentationN4=dict(), + BrainSegmentationPosteriors=dict(), + BrainVolumes=dict(), + CorticalThickness=dict(), + CorticalThicknessNormedToTemplate=dict(), + SubjectToTemplate0GenericAffine=dict(), + SubjectToTemplate1Warp=dict(), + SubjectToTemplateLogJacobian=dict(), + TemplateToSubject0Warp=dict(), + TemplateToSubject1GenericAffine=dict(), ) outputs = antsCorticalThickness.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_antsIntroduction.py b/nipype/interfaces/ants/tests/test_auto_antsIntroduction.py index 7dfd0f6539..bb5fd19e73 100644 --- a/nipype/interfaces/ants/tests/test_auto_antsIntroduction.py +++ b/nipype/interfaces/ants/tests/test_auto_antsIntroduction.py @@ -4,66 +4,70 @@ def test_antsIntroduction_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bias_field_correction=dict(argstr='-n 1', - ), - dimension=dict(argstr='-d %d', - position=1, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - force_proceed=dict(argstr='-f 1', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='-i %s', - copyfile=False, - mandatory=True, - ), - inverse_warp_template_labels=dict(argstr='-l', - ), - max_iterations=dict(argstr='-m %s', - sep='x', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_prefix=dict(argstr='-o %s', - usedefault=True, - ), - quality_check=dict(argstr='-q 1', - ), - reference_image=dict(argstr='-r %s', - copyfile=True, - mandatory=True, - ), - similarity_metric=dict(argstr='-s %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformation_model=dict(argstr='-t %s', - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bias_field_correction=dict(argstr='-n 1', ), + dimension=dict( + argstr='-d %d', + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_proceed=dict(argstr='-f 1', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr='-i %s', + copyfile=False, + mandatory=True, + ), + inverse_warp_template_labels=dict(argstr='-l', ), + max_iterations=dict( + argstr='-m %s', + sep='x', + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr='-o %s', + usedefault=True, + ), + quality_check=dict(argstr='-q 1', ), + reference_image=dict( + argstr='-r %s', + copyfile=True, + mandatory=True, + ), + similarity_metric=dict(argstr='-s %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformation_model=dict( + argstr='-t %s', + usedefault=True, + ), ) inputs = antsIntroduction.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_antsIntroduction_outputs(): - output_map = dict(affine_transformation=dict(), - input_file=dict(), - inverse_warp_field=dict(), - output_file=dict(), - warp_field=dict(), + output_map = dict( + affine_transformation=dict(), + input_file=dict(), + inverse_warp_field=dict(), + output_file=dict(), + warp_field=dict(), ) outputs = antsIntroduction.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_buildtemplateparallel.py b/nipype/interfaces/ants/tests/test_auto_buildtemplateparallel.py index 9b5005e840..5e732f6bb9 100644 --- a/nipype/interfaces/ants/tests/test_auto_buildtemplateparallel.py +++ b/nipype/interfaces/ants/tests/test_auto_buildtemplateparallel.py @@ -4,68 +4,75 @@ def test_buildtemplateparallel_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bias_field_correction=dict(argstr='-n 1', - ), - dimension=dict(argstr='-d %d', - position=1, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - gradient_step_size=dict(argstr='-g %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=-1, - ), - iteration_limit=dict(argstr='-i %d', - usedefault=True, - ), - max_iterations=dict(argstr='-m %s', - sep='x', - ), - num_cores=dict(argstr='-j %d', - requires=['parallelization'], - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - out_prefix=dict(argstr='-o %s', - usedefault=True, - ), - parallelization=dict(argstr='-c %d', - usedefault=True, - ), - rigid_body_registration=dict(argstr='-r 1', - ), - similarity_metric=dict(argstr='-s %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformation_model=dict(argstr='-t %s', - usedefault=True, - ), - use_first_as_target=dict(), + input_map = dict( + args=dict(argstr='%s', ), + bias_field_correction=dict(argstr='-n 1', ), + dimension=dict( + argstr='-d %d', + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradient_step_size=dict(argstr='-g %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + iteration_limit=dict( + argstr='-i %d', + usedefault=True, + ), + max_iterations=dict( + argstr='-m %s', + sep='x', + ), + num_cores=dict( + argstr='-j %d', + requires=['parallelization'], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr='-o %s', + usedefault=True, + ), + parallelization=dict( + argstr='-c %d', + usedefault=True, + ), + rigid_body_registration=dict(argstr='-r 1', ), + similarity_metric=dict(argstr='-s %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformation_model=dict( + argstr='-t %s', + usedefault=True, + ), + use_first_as_target=dict(), ) inputs = buildtemplateparallel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_buildtemplateparallel_outputs(): - output_map = dict(final_template_file=dict(), - subject_outfiles=dict(), - template_files=dict(), + output_map = dict( + final_template_file=dict(), + subject_outfiles=dict(), + template_files=dict(), ) outputs = buildtemplateparallel.output_spec() diff --git a/nipype/interfaces/ants/tests/test_resampling.py b/nipype/interfaces/ants/tests/test_resampling.py index 509ebfe844..14903f0137 100644 --- a/nipype/interfaces/ants/tests/test_resampling.py +++ b/nipype/interfaces/ants/tests/test_resampling.py @@ -8,76 +8,83 @@ @pytest.fixture() def change_dir(request): - orig_dir = os.getcwd() - filepath = os.path.dirname( os.path.realpath( __file__ ) ) - datadir = os.path.realpath(os.path.join(filepath, '../../../testing/data')) - os.chdir(datadir) + orig_dir = os.getcwd() + filepath = os.path.dirname(os.path.realpath(__file__)) + datadir = os.path.realpath(os.path.join(filepath, '../../../testing/data')) + os.chdir(datadir) - def move2orig(): - os.chdir(orig_dir) + def move2orig(): + os.chdir(orig_dir) - request.addfinalizer(move2orig) + request.addfinalizer(move2orig) @pytest.fixture() def create_wimt(): - wimt = WarpImageMultiTransform() - wimt.inputs.input_image = 'diffusion_weighted.nii' - wimt.inputs.reference_image = 'functional.nii' - wimt.inputs.transformation_series = ['func2anat_coreg_Affine.txt','func2anat_InverseWarp.nii.gz', \ - 'dwi2anat_Warp.nii.gz','dwi2anat_coreg_Affine.txt'] - return wimt + wimt = WarpImageMultiTransform() + wimt.inputs.input_image = 'diffusion_weighted.nii' + wimt.inputs.reference_image = 'functional.nii' + wimt.inputs.transformation_series = [ + 'func2anat_coreg_Affine.txt', 'func2anat_InverseWarp.nii.gz', + 'dwi2anat_Warp.nii.gz', 'dwi2anat_coreg_Affine.txt' + ] + return wimt + def test_WarpImageMultiTransform(change_dir, create_wimt): - wimt = create_wimt - assert wimt.cmdline == 'WarpImageMultiTransform 3 diffusion_weighted.nii diffusion_weighted_wimt.nii -R functional.nii \ + wimt = create_wimt + assert wimt.cmdline == 'WarpImageMultiTransform 3 diffusion_weighted.nii diffusion_weighted_wimt.nii -R functional.nii \ func2anat_coreg_Affine.txt func2anat_InverseWarp.nii.gz dwi2anat_Warp.nii.gz dwi2anat_coreg_Affine.txt' def test_WarpImageMultiTransform_invaffine_1(change_dir, create_wimt): - wimt = create_wimt - wimt.inputs.invert_affine = [1] - assert wimt.cmdline == 'WarpImageMultiTransform 3 diffusion_weighted.nii diffusion_weighted_wimt.nii -R functional.nii \ + wimt = create_wimt + wimt.inputs.invert_affine = [1] + assert wimt.cmdline == 'WarpImageMultiTransform 3 diffusion_weighted.nii diffusion_weighted_wimt.nii -R functional.nii \ -i func2anat_coreg_Affine.txt func2anat_InverseWarp.nii.gz dwi2anat_Warp.nii.gz dwi2anat_coreg_Affine.txt' def test_WarpImageMultiTransform_invaffine_2(change_dir, create_wimt): - wimt = create_wimt - wimt.inputs.invert_affine = [2] - assert wimt.cmdline == 'WarpImageMultiTransform 3 diffusion_weighted.nii diffusion_weighted_wimt.nii -R functional.nii func2anat_coreg_Affine.txt func2anat_InverseWarp.nii.gz dwi2anat_Warp.nii.gz -i dwi2anat_coreg_Affine.txt' + wimt = create_wimt + wimt.inputs.invert_affine = [2] + assert wimt.cmdline == 'WarpImageMultiTransform 3 diffusion_weighted.nii diffusion_weighted_wimt.nii -R functional.nii func2anat_coreg_Affine.txt func2anat_InverseWarp.nii.gz dwi2anat_Warp.nii.gz -i dwi2anat_coreg_Affine.txt' def test_WarpImageMultiTransform_invaffine_wrong(change_dir, create_wimt): - wimt = create_wimt - wimt.inputs.invert_affine = [3] - with pytest.raises(Exception): - assert wimt.cmdline + wimt = create_wimt + wimt.inputs.invert_affine = [3] + with pytest.raises(Exception): + assert wimt.cmdline @pytest.fixture() def create_wtsimt(): - wtsimt = WarpTimeSeriesImageMultiTransform() - wtsimt.inputs.input_image = 'resting.nii' - wtsimt.inputs.reference_image = 'ants_deformed.nii.gz' - wtsimt.inputs.transformation_series = ['ants_Warp.nii.gz','ants_Affine.txt'] - return wtsimt + wtsimt = WarpTimeSeriesImageMultiTransform() + wtsimt.inputs.input_image = 'resting.nii' + wtsimt.inputs.reference_image = 'ants_deformed.nii.gz' + wtsimt.inputs.transformation_series = [ + 'ants_Warp.nii.gz', 'ants_Affine.txt' + ] + return wtsimt def test_WarpTimeSeriesImageMultiTransform(change_dir, create_wtsimt): - wtsimt = create_wtsimt - assert wtsimt.cmdline == 'WarpTimeSeriesImageMultiTransform 4 resting.nii resting_wtsimt.nii \ + wtsimt = create_wtsimt + assert wtsimt.cmdline == 'WarpTimeSeriesImageMultiTransform 4 resting.nii resting_wtsimt.nii \ -R ants_deformed.nii.gz ants_Warp.nii.gz ants_Affine.txt' -def test_WarpTimeSeriesImageMultiTransform_invaffine(change_dir, create_wtsimt): - wtsimt = create_wtsimt - wtsimt.inputs.invert_affine = [1] - assert wtsimt.cmdline == 'WarpTimeSeriesImageMultiTransform 4 resting.nii resting_wtsimt.nii \ +def test_WarpTimeSeriesImageMultiTransform_invaffine(change_dir, + create_wtsimt): + wtsimt = create_wtsimt + wtsimt.inputs.invert_affine = [1] + assert wtsimt.cmdline == 'WarpTimeSeriesImageMultiTransform 4 resting.nii resting_wtsimt.nii \ -R ants_deformed.nii.gz ants_Warp.nii.gz -i ants_Affine.txt' -def test_WarpTimeSeriesImageMultiTransform_invaffine_wrong(change_dir, create_wtsimt): - wtsimt = create_wtsimt - wtsimt.inputs.invert_affine = [0] - with pytest.raises(Exception): - wtsimt.cmdline +def test_WarpTimeSeriesImageMultiTransform_invaffine_wrong( + change_dir, create_wtsimt): + wtsimt = create_wtsimt + wtsimt.inputs.invert_affine = [0] + with pytest.raises(Exception): + wtsimt.cmdline diff --git a/nipype/interfaces/ants/tests/test_spec_JointFusion.py b/nipype/interfaces/ants/tests/test_spec_JointFusion.py index 676631f08e..b2ca69926a 100644 --- a/nipype/interfaces/ants/tests/test_spec_JointFusion.py +++ b/nipype/interfaces/ants/tests/test_spec_JointFusion.py @@ -7,6 +7,7 @@ from nipype.interfaces.ants import JointFusion import pytest + def test_JointFusion_dimension(): at = JointFusion() set_dimension = lambda d: setattr(at.inputs, 'dimension', int(d)) @@ -17,13 +18,16 @@ def test_JointFusion_dimension(): with pytest.raises(TraitError): set_dimension(d) + @pytest.mark.parametrize("m", range(1, 5)) def test_JointFusion_modalities(m): at = JointFusion() setattr(at.inputs, 'modalities', int(m)) assert at.inputs.modalities == int(m) -@pytest.mark.parametrize("a, b", [(a,b) for a in range(10) for b in range(10)]) + +@pytest.mark.parametrize("a, b", + [(a, b) for a in range(10) for b in range(10)]) def test_JointFusion_method(a, b): at = JointFusion() set_method = lambda a, b: setattr(at.inputs, 'method', 'Joint[%.1f,%d]'.format(a, b)) @@ -38,11 +42,16 @@ def test_JointFusion_method(a, b): # set with alpha/beta assert at.inputs.method == 'Joint[%.1f,%d]'.format(aprime, bprime) -@pytest.mark.parametrize("attr, x", [(attr, x) for attr in ['patch_radius', 'search_radius'] for x in range(5)]) + +@pytest.mark.parametrize("attr, x", + [(attr, x) + for attr in ['patch_radius', 'search_radius'] + for x in range(5)]) def test_JointFusion_radius(attr, x): at = JointFusion() - setattr(at.inputs, attr, [x, x+1, x**x]) - assert at._format_arg(attr, None, getattr(at.inputs, attr))[4:] == '{0}x{1}x{2}'.format(x, x + 1, x**x) + setattr(at.inputs, attr, [x, x + 1, x**x]) + assert at._format_arg(attr, None, getattr( + at.inputs, attr))[4:] == '{0}x{1}x{2}'.format(x, x + 1, x**x) def test_JointFusion_cmd(): @@ -51,11 +60,15 @@ def test_JointFusion_cmd(): at.inputs.modalities = 1 at.inputs.method = 'Joint[0.1,2]' at.inputs.output_label_image = 'fusion_labelimage_output.nii' - warped_intensity_images = [example_data('im1.nii'), - example_data('im2.nii')] + warped_intensity_images = [ + example_data('im1.nii'), + example_data('im2.nii') + ] at.inputs.warped_intensity_images = warped_intensity_images - segmentation_images = [example_data('segmentation0.nii.gz'), - example_data('segmentation1.nii.gz')] + segmentation_images = [ + example_data('segmentation0.nii.gz'), + example_data('segmentation1.nii.gz') + ] at.inputs.warped_label_images = segmentation_images T1_image = example_data('T1.nii') at.inputs.target_image = T1_image @@ -63,12 +76,12 @@ def test_JointFusion_cmd(): at.inputs.search_radius = [1, 2, 3] expected_command = ('jointfusion 3 1 -m Joint[0.1,2] -rp 3x2x1 -rs 1x2x3' ' -tg %s -g %s -g %s -l %s -l %s' - ' fusion_labelimage_output.nii') % (T1_image, - warped_intensity_images[0], - warped_intensity_images[1], - segmentation_images[0], - segmentation_images[1]) + ' fusion_labelimage_output.nii') % ( + T1_image, warped_intensity_images[0], + warped_intensity_images[1], segmentation_images[0], + segmentation_images[1]) assert at.cmdline == expected_command # setting intensity or labels with unequal lengths raises error with pytest.raises(AssertionError): - at._format_arg('warped_intensity_images', InputMultiPath, warped_intensity_images + [example_data('im3.nii')]) + at._format_arg('warped_intensity_images', InputMultiPath, + warped_intensity_images + [example_data('im3.nii')]) diff --git a/nipype/interfaces/ants/utils.py b/nipype/interfaces/ants/utils.py index 0ba918ee27..43a3b4b98c 100644 --- a/nipype/interfaces/ants/utils.py +++ b/nipype/interfaces/ants/utils.py @@ -7,7 +7,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os @@ -16,12 +17,25 @@ class AverageAffineTransformInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='%d', usedefault=False, mandatory=True, - position=0, desc='image dimension (2 or 3)') - output_affine_transform = File(argstr='%s', mandatory=True, position=1, - desc='Outputfname.txt: the name of the resulting transform.') - transforms = InputMultiPath(File(exists=True), argstr='%s', mandatory=True, - position=3, desc='transforms to average') + dimension = traits.Enum( + 3, + 2, + argstr='%d', + usedefault=False, + mandatory=True, + position=0, + desc='image dimension (2 or 3)') + output_affine_transform = File( + argstr='%s', + mandatory=True, + position=1, + desc='Outputfname.txt: the name of the resulting transform.') + transforms = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + position=3, + desc='transforms to average') class AverageAffineTransformOutputSpec(TraitedSpec): @@ -55,18 +69,34 @@ def _list_outputs(self): class AverageImagesInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='%d', mandatory=True, - position=0, desc='image dimension (2 or 3)') + dimension = traits.Enum( + 3, + 2, + argstr='%d', + mandatory=True, + position=0, + desc='image dimension (2 or 3)') output_average_image = File( - "average.nii", argstr='%s', position=1, usedefault=True, hash_files=False, + "average.nii", + argstr='%s', + position=1, + usedefault=True, + hash_files=False, desc='the name of the resulting image.') normalize = traits.Bool( - argstr="%d", mandatory=True, position=2, + argstr="%d", + mandatory=True, + position=2, desc='Normalize: if true, the 2nd image is divided by its mean. ' - 'This will select the largest image to average into.') + 'This will select the largest image to average into.') images = InputMultiPath( - File(exists=True), argstr='%s', mandatory=True, position=3, - desc='image to apply transformation to (generally a coregistered functional)') + File(exists=True), + argstr='%s', + mandatory=True, + position=3, + desc= + 'image to apply transformation to (generally a coregistered functional)' + ) class AverageImagesOutputSpec(TraitedSpec): @@ -101,15 +131,28 @@ def _list_outputs(self): class MultiplyImagesInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='%d', usedefault=False, mandatory=True, position=0, - desc='image dimension (2 or 3)') - first_input = File(argstr='%s', exists=True, - mandatory=True, position=1, desc='image 1') + dimension = traits.Enum( + 3, + 2, + argstr='%d', + usedefault=False, + mandatory=True, + position=0, + desc='image dimension (2 or 3)') + first_input = File( + argstr='%s', exists=True, mandatory=True, position=1, desc='image 1') second_input = traits.Either( - File(exists=True), traits.Float, argstr='%s', mandatory=True, position=2, + File(exists=True), + traits.Float, + argstr='%s', + mandatory=True, + position=2, desc='image 2 or multiplication weight') - output_product_image = File(argstr='%s', mandatory=True, position=3, - desc='Outputfname.nii.gz: the name of the resulting image.') + output_product_image = File( + argstr='%s', + mandatory=True, + position=3, + desc='Outputfname.nii.gz: the name of the resulting image.') class MultiplyImagesOutputSpec(TraitedSpec): @@ -144,17 +187,26 @@ def _list_outputs(self): class CreateJacobianDeterminantImageInputSpec(ANTSCommandInputSpec): - imageDimension = traits.Enum(3, 2, argstr='%d', usedefault=False, mandatory=True, - position=0, desc='image dimension (2 or 3)') - deformationField = File(argstr='%s', exists=True, mandatory=True, - position=1, desc='deformation transformation file') - outputImage = File(argstr='%s', mandatory=True, - position=2, - desc='output filename') - doLogJacobian = traits.Enum(0, 1, argstr='%d', position=3, - desc='return the log jacobian') - useGeometric = traits.Enum(0, 1, argstr='%d', position=4, - desc='return the geometric jacobian') + imageDimension = traits.Enum( + 3, + 2, + argstr='%d', + usedefault=False, + mandatory=True, + position=0, + desc='image dimension (2 or 3)') + deformationField = File( + argstr='%s', + exists=True, + mandatory=True, + position=1, + desc='deformation transformation file') + outputImage = File( + argstr='%s', mandatory=True, position=2, desc='output filename') + doLogJacobian = traits.Enum( + 0, 1, argstr='%d', position=3, desc='return the log jacobian') + useGeometric = traits.Enum( + 0, 1, argstr='%d', position=4, desc='return the geometric jacobian') class CreateJacobianDeterminantImageOutputSpec(TraitedSpec): @@ -179,36 +231,67 @@ class CreateJacobianDeterminantImage(ANTSCommand): output_spec = CreateJacobianDeterminantImageOutputSpec def _format_arg(self, opt, spec, val): - return super(CreateJacobianDeterminantImage, self)._format_arg(opt, spec, val) + return super(CreateJacobianDeterminantImage, self)._format_arg( + opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() - outputs['jacobian_image'] = os.path.abspath( - self.inputs.outputImage) + outputs['jacobian_image'] = os.path.abspath(self.inputs.outputImage) return outputs class AffineInitializerInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, usedefault=True, position=0, argstr='%s', - desc='dimension') - fixed_image = File(exists=True, mandatory=True, position=1, argstr='%s', - desc='reference image') - moving_image = File(exists=True, mandatory=True, position=2, argstr='%s', - desc='moving image') - out_file = File('transform.mat', usedefault=True, position=3, argstr='%s', - desc='output transform file') + dimension = traits.Enum( + 3, 2, usedefault=True, position=0, argstr='%s', desc='dimension') + fixed_image = File( + exists=True, + mandatory=True, + position=1, + argstr='%s', + desc='reference image') + moving_image = File( + exists=True, + mandatory=True, + position=2, + argstr='%s', + desc='moving image') + out_file = File( + 'transform.mat', + usedefault=True, + position=3, + argstr='%s', + desc='output transform file') # Defaults in antsBrainExtraction.sh -> 15 0.1 0 10 - search_factor = traits.Float(15.0, usedefault=True, position=4, argstr='%f', - desc='increments (degrees) for affine search') - radian_fraction = traits.Range(0.0, 1.0, value=0.1, usedefault=True, position=5, - argstr='%f', desc='search this arc +/- principal axes') + search_factor = traits.Float( + 15.0, + usedefault=True, + position=4, + argstr='%f', + desc='increments (degrees) for affine search') + radian_fraction = traits.Range( + 0.0, + 1.0, + value=0.1, + usedefault=True, + position=5, + argstr='%f', + desc='search this arc +/- principal axes') principal_axes = traits.Bool( - False, usedefault=True, position=6, argstr='%d', - desc='whether the rotation is searched around an initial principal axis alignment.') + False, + usedefault=True, + position=6, + argstr='%d', + desc= + 'whether the rotation is searched around an initial principal axis alignment.' + ) local_search = traits.Int( - 10, usedefault=True, position=7, argstr='%d', - desc=' determines if a local optimization is run at each search point for the set ' - 'number of iterations') + 10, + usedefault=True, + position=7, + argstr='%d', + desc= + ' determines if a local optimization is run at each search point for the set ' + 'number of iterations') class AffineInitializerOutputSpec(TraitedSpec): @@ -236,15 +319,30 @@ def _list_outputs(self): class ComposeMultiTransformInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='%d', usedefault=True, position=0, - desc='image dimension (2 or 3)') - output_transform = File(argstr='%s', position=1, name_source=['transforms'], - name_template='%s_composed', keep_ext=True, - desc='the name of the resulting transform.') - reference_image = File(argstr='%s', position=2, - desc='Reference image (only necessary when output is warpfield)') - transforms = InputMultiPath(File(exists=True), argstr='%s', mandatory=True, - position=3, desc='transforms to average') + dimension = traits.Enum( + 3, + 2, + argstr='%d', + usedefault=True, + position=0, + desc='image dimension (2 or 3)') + output_transform = File( + argstr='%s', + position=1, + name_source=['transforms'], + name_template='%s_composed', + keep_extension=True, + desc='the name of the resulting transform.') + reference_image = File( + argstr='%s', + position=2, + desc='Reference image (only necessary when output is warpfield)') + transforms = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + position=3, + desc='transforms to average') class ComposeMultiTransformOutputSpec(TraitedSpec): @@ -262,7 +360,7 @@ class ComposeMultiTransform(ANTSCommand): >>> compose_transform.inputs.dimension = 3 >>> compose_transform.inputs.transforms = ['struct_to_template.mat', 'func_to_struct.mat'] >>> compose_transform.cmdline - 'ComposeMultiTransform 3 struct_to_template_composed struct_to_template.mat func_to_struct.mat' + 'ComposeMultiTransform 3 struct_to_template_composed.mat struct_to_template.mat func_to_struct.mat' """ _cmd = 'ComposeMultiTransform' diff --git a/nipype/interfaces/ants/visualization.py b/nipype/interfaces/ants/visualization.py index 07cf8af086..02e91b9321 100644 --- a/nipype/interfaces/ants/visualization.py +++ b/nipype/interfaces/ants/visualization.py @@ -6,7 +6,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os @@ -15,31 +16,55 @@ class ConvertScalarImageToRGBInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum(3, 2, argstr='%d', usedefault=True, - desc='image dimension (2 or 3)', mandatory=True, - position=0) - input_image = File(argstr='%s', exists=True, - desc='Main input is a 3-D grayscale image.', mandatory=True, - position=1) - output_image = traits.Str('rgb.nii.gz', argstr='%s', usedefault=True, - desc='rgb output image', position=2) - mask_image = File('none', argstr='%s', exists=True, - desc='mask image', position=3, usedefault=True) - colormap = traits.Str(argstr='%s', usedefault=True, - desc=('Possible colormaps: grey, red, green, ' - 'blue, copper, jet, hsv, spring, summer, ' - 'autumn, winter, hot, cool, overunder, custom ' - ), mandatory=True, position=4) - custom_color_map_file = traits.Str('none', argstr='%s', usedefault=True, - desc='custom color map file', position=5) - minimum_input = traits.Int(argstr='%d', desc='minimum input', - mandatory=True, position=6) - maximum_input = traits.Int(argstr='%d', desc='maximum input', - mandatory=True, position=7) - minimum_RGB_output = traits.Int(0, usedefault=True, - argstr='%d', desc='', position=8) - maximum_RGB_output = traits.Int(255, usedefault=True, - argstr='%d', desc='', position=9) + dimension = traits.Enum( + 3, + 2, + argstr='%d', + usedefault=True, + desc='image dimension (2 or 3)', + mandatory=True, + position=0) + input_image = File( + argstr='%s', + exists=True, + desc='Main input is a 3-D grayscale image.', + mandatory=True, + position=1) + output_image = traits.Str( + 'rgb.nii.gz', + argstr='%s', + usedefault=True, + desc='rgb output image', + position=2) + mask_image = File( + 'none', + argstr='%s', + exists=True, + desc='mask image', + position=3, + usedefault=True) + colormap = traits.Str( + argstr='%s', + usedefault=True, + desc=('Possible colormaps: grey, red, green, ' + 'blue, copper, jet, hsv, spring, summer, ' + 'autumn, winter, hot, cool, overunder, custom '), + mandatory=True, + position=4) + custom_color_map_file = traits.Str( + 'none', + argstr='%s', + usedefault=True, + desc='custom color map file', + position=5) + minimum_input = traits.Int( + argstr='%d', desc='minimum input', mandatory=True, position=6) + maximum_input = traits.Int( + argstr='%d', desc='maximum input', mandatory=True, position=7) + minimum_RGB_output = traits.Int( + 0, usedefault=True, argstr='%d', desc='', position=8) + maximum_RGB_output = traits.Int( + 255, usedefault=True, argstr='%d', desc='', position=9) class ConvertScalarImageToRGBOutputSpec(TraitedSpec): @@ -75,47 +100,61 @@ def _list_outputs(self): class CreateTiledMosaicInputSpec(ANTSCommandInputSpec): - input_image = File(argstr='-i %s', exists=True, - desc='Main input is a 3-D grayscale image.', - mandatory=True) - rgb_image = File(argstr='-r %s', exists=True, - desc=('An optional Rgb image can be added as an overlay.' - 'It must have the same image' - 'geometry as the input grayscale image.'), - mandatory=True) - mask_image = File(argstr='-x %s', exists=True, - desc='Specifies the ROI of the RGB voxels used.') - alpha_value = traits.Float(argstr='-a %.2f', - desc=('If an Rgb image is provided, render the overlay ' - 'using the specified alpha parameter.')) - output_image = traits.Str('output.png', argstr='-o %s', - desc='The output consists of the tiled mosaic image.', - usedefault=True) - tile_geometry = traits.Str(argstr='-t %s', desc=( - 'The tile geometry specifies the number of rows and columns' - 'in the output image. For example, if the user specifies "5x10", ' - 'then 5 rows by 10 columns of slices are rendered. If R < 0 and C > ' - '0 (or vice versa), the negative value is selected' - 'based on direction.')) - direction = traits.Int(argstr='-d %d', desc=('Specifies the direction of ' - 'the slices. If no direction is specified, the ' - 'direction with the coarsest spacing is chosen.')) - pad_or_crop = traits.Str(argstr='-p %s', - desc='argument passed to -p flag:' - '[padVoxelWidth,]' - '[lowerPadding[0]xlowerPadding[1],upperPadding[0]xupperPadding[1],' - 'constantValue]' - 'The user can specify whether to pad or crop a specified ' - 'voxel-width boundary of each individual slice. For this ' - 'program, cropping is simply padding with negative voxel-widths.' - 'If one pads (+), the user can also specify a constant pad ' - 'value (default = 0). If a mask is specified, the user can use ' - 'the mask to define the region, by using the keyword "mask"' - ' plus an offset, e.g. "-p mask+3".' - ) - slices = traits.Str(argstr='-s %s', - desc=('Number of slices to increment Slice1xSlice2xSlice3' - '[numberOfSlicesToIncrement,,]')) + input_image = File( + argstr='-i %s', + exists=True, + desc='Main input is a 3-D grayscale image.', + mandatory=True) + rgb_image = File( + argstr='-r %s', + exists=True, + desc=('An optional Rgb image can be added as an overlay.' + 'It must have the same image' + 'geometry as the input grayscale image.'), + mandatory=True) + mask_image = File( + argstr='-x %s', + exists=True, + desc='Specifies the ROI of the RGB voxels used.') + alpha_value = traits.Float( + argstr='-a %.2f', + desc=('If an Rgb image is provided, render the overlay ' + 'using the specified alpha parameter.')) + output_image = traits.Str( + 'output.png', + argstr='-o %s', + desc='The output consists of the tiled mosaic image.', + usedefault=True) + tile_geometry = traits.Str( + argstr='-t %s', + desc=( + 'The tile geometry specifies the number of rows and columns' + 'in the output image. For example, if the user specifies "5x10", ' + 'then 5 rows by 10 columns of slices are rendered. If R < 0 and C > ' + '0 (or vice versa), the negative value is selected' + 'based on direction.')) + direction = traits.Int( + argstr='-d %d', + desc=('Specifies the direction of ' + 'the slices. If no direction is specified, the ' + 'direction with the coarsest spacing is chosen.')) + pad_or_crop = traits.Str( + argstr='-p %s', + desc='argument passed to -p flag:' + '[padVoxelWidth,]' + '[lowerPadding[0]xlowerPadding[1],upperPadding[0]xupperPadding[1],' + 'constantValue]' + 'The user can specify whether to pad or crop a specified ' + 'voxel-width boundary of each individual slice. For this ' + 'program, cropping is simply padding with negative voxel-widths.' + 'If one pads (+), the user can also specify a constant pad ' + 'value (default = 0). If a mask is specified, the user can use ' + 'the mask to define the region, by using the keyword "mask"' + ' plus an offset, e.g. "-p mask+3".') + slices = traits.Str( + argstr='-s %s', + desc=('Number of slices to increment Slice1xSlice2xSlice3' + '[numberOfSlicesToIncrement,,]')) flip_slice = traits.Str(argstr='-f %s', desc='flipXxflipY') permute_axes = traits.Bool(argstr='-g', desc='doPermute') diff --git a/nipype/interfaces/base/__init__.py b/nipype/interfaces/base/__init__.py index ee0f10fd7a..cb24ea50a9 100644 --- a/nipype/interfaces/base/__init__.py +++ b/nipype/interfaces/base/__init__.py @@ -8,24 +8,18 @@ This module defines the API of all nipype interfaces. """ -from .core import ( - Interface, BaseInterface, SimpleInterface, - CommandLine, StdOutCommandLine, - MpiCommandLine, SEMLikeCommandLine, PackageInfo -) +from .core import (Interface, BaseInterface, SimpleInterface, CommandLine, + StdOutCommandLine, MpiCommandLine, SEMLikeCommandLine, + PackageInfo) -from .specs import ( - BaseTraitedSpec, TraitedSpec, DynamicTraitedSpec, - BaseInterfaceInputSpec, CommandLineInputSpec, - StdOutCommandLineInputSpec -) +from .specs import (BaseTraitedSpec, TraitedSpec, DynamicTraitedSpec, + BaseInterfaceInputSpec, CommandLineInputSpec, + StdOutCommandLineInputSpec) from .traits_extension import ( traits, Undefined, TraitDictObject, TraitListObject, TraitError, isdefined, - File, Directory, Str, DictStrStr, has_metadata, ImageFile, - MultiPath, OutputMultiPath, InputMultiPath) + File, Directory, Str, DictStrStr, has_metadata, ImageFile, MultiPath, + OutputMultiPath, InputMultiPath) -from .support import ( - Bunch, InterfaceResult, load_template, - NipypeInterfaceError -) +from .support import (Bunch, InterfaceResult, load_template, + NipypeInterfaceError) diff --git a/nipype/interfaces/base/core.py b/nipype/interfaces/base/core.py index bcf2656620..34f650cde2 100644 --- a/nipype/interfaces/base/core.py +++ b/nipype/interfaces/base/core.py @@ -12,7 +12,8 @@ interfaces are found in the ``specs`` module. """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object, open, str, bytes @@ -33,31 +34,28 @@ from ... import config, logging, LooseVersion from ...utils.provenance import write_provenance from ...utils.misc import trim, str2bool -from ...utils.filemanip import ( - FileNotFoundError, split_filename, read_stream, which, - get_dependencies, canonicalize_env as _canonicalize_env) +from ...utils.filemanip import (FileNotFoundError, split_filename, read_stream, + which, get_dependencies, canonicalize_env as + _canonicalize_env) from ...external.due import due from .traits_extension import traits, isdefined, TraitError -from .specs import ( - BaseInterfaceInputSpec, CommandLineInputSpec, - StdOutCommandLineInputSpec, MpiCommandLineInputSpec -) -from .support import ( - Bunch, Stream, InterfaceResult, NipypeInterfaceError -) +from .specs import (BaseInterfaceInputSpec, CommandLineInputSpec, + StdOutCommandLineInputSpec, MpiCommandLineInputSpec) +from .support import (Bunch, Stream, InterfaceResult, NipypeInterfaceError) from future import standard_library standard_library.install_aliases() - iflogger = logging.getLogger('interface') PY35 = sys.version_info >= (3, 5) PY3 = sys.version_info[0] > 2 -VALID_TERMINAL_OUTPUT = ['stream', 'allatonce', 'file', 'file_split', - 'file_stdout', 'file_stderr', 'none'] +VALID_TERMINAL_OUTPUT = [ + 'stream', 'allatonce', 'file', 'file_split', 'file_stdout', 'file_stderr', + 'none' +] __docformat__ = 'restructuredtext' @@ -173,8 +171,8 @@ class BaseInterface(Interface): def __init__(self, from_file=None, resource_monitor=None, **inputs): if not self.input_spec: - raise Exception('No input_spec in class: %s' % - self.__class__.__name__) + raise Exception( + 'No input_spec in class: %s' % self.__class__.__name__) self.inputs = self.input_spec(**inputs) @@ -199,9 +197,8 @@ def help(cls, returnhelp=False): else: docstring = [''] - allhelp = '\n'.join(docstring + cls._inputs_help() + [''] + - cls._outputs_help() + [''] + - cls._refs_help() + ['']) + allhelp = '\n'.join(docstring + cls._inputs_help( + ) + [''] + cls._outputs_help() + [''] + cls._refs_help() + ['']) if returnhelp: return allhelp else: @@ -234,43 +231,53 @@ def _get_trait_desc(self, inputs, name, spec): default = '' if spec.usedefault: - default = ', nipype default value: %s' % str(spec.default_value()[1]) + default = ', nipype default value: %s' % str( + spec.default_value()[1]) line = "(%s%s)" % (type_info, default) - manhelpstr = wrap(line, 70, - initial_indent=manhelpstr[0] + ': ', - subsequent_indent='\t\t ') + manhelpstr = wrap( + line, + 70, + initial_indent=manhelpstr[0] + ': ', + subsequent_indent='\t\t ') if desc: for line in desc.split('\n'): line = re.sub("\s+", " ", line) - manhelpstr += wrap(line, 70, - initial_indent='\t\t', - subsequent_indent='\t\t') + manhelpstr += wrap( + line, 70, initial_indent='\t\t', subsequent_indent='\t\t') if argstr: pos = spec.position if pos is not None: - manhelpstr += wrap('flag: %s, position: %s' % (argstr, pos), 70, - initial_indent='\t\t', - subsequent_indent='\t\t') + manhelpstr += wrap( + 'flag: %s, position: %s' % (argstr, pos), + 70, + initial_indent='\t\t', + subsequent_indent='\t\t') else: - manhelpstr += wrap('flag: %s' % argstr, 70, - initial_indent='\t\t', - subsequent_indent='\t\t') + manhelpstr += wrap( + 'flag: %s' % argstr, + 70, + initial_indent='\t\t', + subsequent_indent='\t\t') if xor: line = '%s' % ', '.join(xor) - manhelpstr += wrap(line, 70, - initial_indent='\t\tmutually_exclusive: ', - subsequent_indent='\t\t ') + manhelpstr += wrap( + line, + 70, + initial_indent='\t\tmutually_exclusive: ', + subsequent_indent='\t\t ') if requires: others = [field for field in requires if field != name] line = '%s' % ', '.join(others) - manhelpstr += wrap(line, 70, - initial_indent='\t\trequires: ', - subsequent_indent='\t\t ') + manhelpstr += wrap( + line, + 70, + initial_indent='\t\trequires: ', + subsequent_indent='\t\t ') return manhelpstr @classmethod @@ -307,7 +314,7 @@ def _outputs_help(cls): """ helpstr = ['Outputs::', ''] if cls.output_spec: - outputs = cls.output_spec() # pylint: disable=E1102 + outputs = cls.output_spec() for name, spec in sorted(outputs.traits(transient=None).items()): helpstr += cls._get_trait_desc(outputs, name, spec) if len(helpstr) == 2: @@ -319,7 +326,7 @@ def _outputs(self): """ outputs = None if self.output_spec: - outputs = self.output_spec() # pylint: disable=E1102 + outputs = self.output_spec() return outputs @@ -333,16 +340,17 @@ def _get_filecopy_info(cls): return info metadata = dict(copyfile=lambda t: t is not None) for name, spec in sorted(cls.input_spec().traits(**metadata).items()): - info.append(dict(key=name, - copy=spec.copyfile)) + info.append(dict(key=name, copy=spec.copyfile)) return info def _check_requires(self, spec, name, value): """ check if required inputs are satisfied """ if spec.requires: - values = [not isdefined(getattr(self.inputs, field)) - for field in spec.requires] + values = [ + not isdefined(getattr(self.inputs, field)) + for field in spec.requires + ] if any(values) and isdefined(value): msg = ("%s requires a value for input '%s' because one of %s " "is set. For a list of required inputs, see %s.help()" % @@ -354,8 +362,9 @@ def _check_xor(self, spec, name, value): """ check if mutually exclusive inputs are satisfied """ if spec.xor: - values = [isdefined(getattr(self.inputs, field)) - for field in spec.xor] + values = [ + isdefined(getattr(self.inputs, field)) for field in spec.xor + ] if not any(values) and not isdefined(value): msg = ("%s requires a value for one of the inputs '%s'. " "For a list of required inputs, see %s.help()" % @@ -372,12 +381,13 @@ def _check_mandatory_inputs(self): if not isdefined(value) and spec.xor is None: msg = ("%s requires a value for input '%s'. " "For a list of required inputs, see %s.help()" % - (self.__class__.__name__, name, self.__class__.__name__)) + (self.__class__.__name__, name, + self.__class__.__name__)) raise ValueError(msg) if isdefined(value): self._check_requires(spec, name, value) - for name, spec in list(self.inputs.traits(mandatory=None, - transient=None).items()): + for name, spec in list( + self.inputs.traits(mandatory=None, transient=None).items()): self._check_requires(spec, name, getattr(self.inputs, name)) def _check_version_requirements(self, trait_object, raise_exception=True): @@ -391,27 +401,29 @@ def _check_version_requirements(self, trait_object, raise_exception=True): if names and self.version: version = LooseVersion(str(self.version)) for name in names: - min_ver = LooseVersion(str(trait_object.traits()[name].min_ver)) + min_ver = LooseVersion( + str(trait_object.traits()[name].min_ver)) if min_ver > version: unavailable_traits.append(name) if not isdefined(getattr(trait_object, name)): continue if raise_exception: - raise Exception('Trait %s (%s) (version %s < required %s)' % - (name, self.__class__.__name__, - version, min_ver)) + raise Exception( + 'Trait %s (%s) (version %s < required %s)' % + (name, self.__class__.__name__, version, min_ver)) check = dict(max_ver=lambda t: t is not None) names = trait_object.trait_names(**check) for name in names: - max_ver = LooseVersion(str(trait_object.traits()[name].max_ver)) + max_ver = LooseVersion( + str(trait_object.traits()[name].max_ver)) if max_ver < version: unavailable_traits.append(name) if not isdefined(getattr(trait_object, name)): continue if raise_exception: - raise Exception('Trait %s (%s) (version %s > required %s)' % - (name, self.__class__.__name__, - version, max_ver)) + raise Exception( + 'Trait %s (%s) (version %s > required %s)' % + (name, self.__class__.__name__, version, max_ver)) return unavailable_traits def _run_interface(self, runtime): @@ -452,28 +464,31 @@ def run(self, **inputs): self._duecredit_cite() # initialize provenance tracking - store_provenance = str2bool(config.get( - 'execution', 'write_provenance', 'false')) + store_provenance = str2bool( + config.get('execution', 'write_provenance', 'false')) env = deepcopy(dict(os.environ)) if self._redirect_x: env['DISPLAY'] = config.get_display() - runtime = Bunch(cwd=os.getcwd(), - returncode=None, - duration=None, - environ=env, - startTime=dt.isoformat(dt.utcnow()), - endTime=None, - platform=platform.platform(), - hostname=platform.node(), - version=self.version) + runtime = Bunch( + cwd=os.getcwd(), + returncode=None, + duration=None, + environ=env, + startTime=dt.isoformat(dt.utcnow()), + endTime=None, + platform=platform.platform(), + hostname=platform.node(), + version=self.version) mon_sp = None if enable_rm: - mon_freq = float(config.get('execution', 'resource_monitor_frequency', 1)) + mon_freq = float( + config.get('execution', 'resource_monitor_frequency', 1)) proc_pid = os.getpid() - iflogger.debug('Creating a ResourceMonitor on a %s interface, PID=%d.', - self.__class__.__name__, proc_pid) + iflogger.debug( + 'Creating a ResourceMonitor on a %s interface, PID=%d.', + self.__class__.__name__, proc_pid) mon_sp = ResourceMonitor(proc_pid, freq=mon_freq) mon_sp.start() @@ -490,12 +505,15 @@ def run(self, **inputs): runtime.traceback = traceback.format_exc() # Gather up the exception arguments and append nipype info. exc_args = e.args if getattr(e, 'args') else tuple() - exc_args += ('An exception of type %s occurred while running interface %s.' % - (type(e).__name__, self.__class__.__name__), ) - if config.get('logging', 'interface_level', 'info').lower() == 'debug': - exc_args += ('Inputs: %s' % str(self.inputs),) + exc_args += ( + 'An exception of type %s occurred while running interface %s.' + % (type(e).__name__, self.__class__.__name__), ) + if config.get('logging', 'interface_level', + 'info').lower() == 'debug': + exc_args += ('Inputs: %s' % str(self.inputs), ) - runtime.traceback_args = ('\n'.join(['%s' % arg for arg in exc_args]),) + runtime.traceback_args = ('\n'.join( + ['%s' % arg for arg in exc_args]), ) if force_raise: raise @@ -505,8 +523,12 @@ def run(self, **inputs): timediff = parseutc(runtime.endTime) - parseutc(runtime.startTime) runtime.duration = (timediff.days * 86400 + timediff.seconds + timediff.microseconds / 1e6) - results = InterfaceResult(interface, runtime, inputs=inputs, outputs=outputs, - provenance=None) + results = InterfaceResult( + interface, + runtime, + inputs=inputs, + outputs=outputs, + provenance=None) # Add provenance (if required) if store_provenance: @@ -567,7 +589,8 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): try: setattr(outputs, key, val) except TraitError as error: - if getattr(error, 'info', 'default').startswith('an existing'): + if getattr(error, 'info', + 'default').startswith('an existing'): msg = ("File/Directory '%s' not found for %s output " "'%s'." % (val, self.__class__.__name__, key)) raise FileNotFoundError(msg) @@ -700,14 +723,15 @@ def run_command(runtime, output=None, timeout=0.01): errfile = os.path.join(runtime.cwd, 'stderr.nipype') stderr = open(errfile, 'wb') - proc = sp.Popen(cmdline, - stdout=stdout, - stderr=stderr, - shell=True, - cwd=runtime.cwd, - env=env, - close_fds=True, - ) + proc = sp.Popen( + cmdline, + stdout=stdout, + stderr=stderr, + shell=True, + cwd=runtime.cwd, + env=env, + close_fds=True, + ) result = { 'stdout': [], @@ -716,7 +740,10 @@ def run_command(runtime, output=None, timeout=0.01): } if output == 'stream': - streams = [Stream('stdout', proc.stdout), Stream('stderr', proc.stderr)] + streams = [ + Stream('stdout', proc.stdout), + Stream('stderr', proc.stderr) + ] def _process(drain=0): try: @@ -847,8 +874,8 @@ def set_default_terminal_output(cls, output_type): if output_type in VALID_TERMINAL_OUTPUT: cls._terminal_output = output_type else: - raise AttributeError('Invalid terminal output_type: %s' % - output_type) + raise AttributeError( + 'Invalid terminal output_type: %s' % output_type) @classmethod def help(cls, returnhelp=False): @@ -865,7 +892,8 @@ def __init__(self, command=None, terminal_output=None, **inputs): self._cmd = command or getattr(self, '_cmd', None) # Store dependencies in runtime object - self._ldd = str2bool(config.get('execution', 'get_linked_libs', 'true')) + self._ldd = str2bool( + config.get('execution', 'get_linked_libs', 'true')) if self._cmd is None: raise Exception("Missing command") @@ -899,7 +927,9 @@ def terminal_output(self, value): if value not in VALID_TERMINAL_OUTPUT: raise RuntimeError( 'Setting invalid value "%s" for terminal_output. Valid values are ' - '%s.' % (value, ', '.join(['"%s"' % v for v in VALID_TERMINAL_OUTPUT]))) + '%s.' % (value, + ', '.join(['"%s"' % v + for v in VALID_TERMINAL_OUTPUT]))) self._terminal_output = value def _terminal_output_update(self): @@ -908,8 +938,8 @@ def _terminal_output_update(self): def raise_exception(self, runtime): raise RuntimeError( ('Command:\n{cmdline}\nStandard output:\n{stdout}\n' - 'Standard error:\n{stderr}\nReturn code: {returncode}').format( - **runtime.dictcopy())) + 'Standard error:\n{stderr}\nReturn code: {returncode}' + ).format(**runtime.dictcopy())) def _get_environ(self): return getattr(self.inputs, 'environ', {}) @@ -924,16 +954,17 @@ def version_from_command(self, flag='-v', cmd=None): if which(cmd, env=env): out_environ = self._get_environ() env.update(out_environ) - proc = sp.Popen(' '.join((cmd, flag)), - shell=True, - env=env, - stdout=sp.PIPE, - stderr=sp.PIPE, - ) + proc = sp.Popen( + ' '.join((cmd, flag)), + shell=True, + env=env, + stdout=sp.PIPE, + stderr=sp.PIPE, + ) o, e = proc.communicate() return o - def _run_interface(self, runtime, correct_return_codes=(0,)): + def _run_interface(self, runtime, correct_return_codes=(0, )): """Execute command via subprocess Parameters @@ -961,11 +992,12 @@ def _run_interface(self, runtime, correct_return_codes=(0,)): if cmd_path is None: raise IOError( 'No command "%s" found on host %s. Please check that the ' - 'corresponding package is installed.' % ( - executable_name, runtime.hostname)) + 'corresponding package is installed.' % (executable_name, + runtime.hostname)) runtime.command_path = cmd_path - runtime.dependencies = (get_dependencies(executable_name, runtime.environ) + runtime.dependencies = (get_dependencies(executable_name, + runtime.environ) if self._ldd else '') runtime = run_command(runtime, output=self.terminal_output) if runtime.returncode is None or \ @@ -1032,13 +1064,15 @@ def _filename_from_source(self, name, chain=None): ns = trait_spec.name_source while isinstance(ns, (list, tuple)): if len(ns) > 1: - iflogger.warning('Only one name_source per trait is allowed') + iflogger.warning( + 'Only one name_source per trait is allowed') ns = ns[0] if not isinstance(ns, (str, bytes)): raise ValueError( 'name_source of \'{}\' trait should be an input trait ' - 'name, but a type {} object was found'.format(name, type(ns))) + 'name, but a type {} object was found'.format( + name, type(ns))) if isdefined(getattr(self.inputs, ns)): name_source = ns @@ -1053,7 +1087,8 @@ def _filename_from_source(self, name, chain=None): base = source else: if name in chain: - raise NipypeInterfaceError('Mutually pointing name_sources') + raise NipypeInterfaceError( + 'Mutually pointing name_sources') chain.append(name) base = self._filename_from_source(ns, chain) @@ -1080,7 +1115,7 @@ def _list_outputs(self): metadata = dict(name_source=lambda t: t is not None) traits = self.inputs.traits(**metadata) if traits: - outputs = self.output_spec().get() # pylint: disable=E1102 + outputs = self.output_spec().get() for name, trait_spec in list(traits.items()): out_name = name if trait_spec.output_name is not None: @@ -1184,21 +1219,22 @@ class SEMLikeCommandLine(CommandLine): """ def _list_outputs(self): - outputs = self.output_spec().get() # pylint: disable=E1102 + outputs = self.output_spec().get() return self._outputs_from_inputs(outputs) def _outputs_from_inputs(self, outputs): for name in list(outputs.keys()): corresponding_input = getattr(self.inputs, name) if isdefined(corresponding_input): - if (isinstance(corresponding_input, bool) and - corresponding_input): + if (isinstance(corresponding_input, bool) + and corresponding_input): outputs[name] = \ os.path.abspath(self._outputs_filenames[name]) else: if isinstance(corresponding_input, list): - outputs[name] = [os.path.abspath(inp) - for inp in corresponding_input] + outputs[name] = [ + os.path.abspath(inp) for inp in corresponding_input + ] else: outputs[name] = os.path.abspath(corresponding_input) return outputs @@ -1223,9 +1259,10 @@ def version(klass): if klass._version is None: if klass.version_cmd is not None: try: - clout = CommandLine(command=klass.version_cmd, - resource_monitor=False, - terminal_output='allatonce').run() + clout = CommandLine( + command=klass.version_cmd, + resource_monitor=False, + terminal_output='allatonce').run() except IOError: return None diff --git a/nipype/interfaces/base/specs.py b/nipype/interfaces/base/specs.py index f0d1184d85..0bc0544b9a 100644 --- a/nipype/interfaces/base/specs.py +++ b/nipype/interfaces/base/specs.py @@ -9,7 +9,8 @@ Define the API for the I/O of interfaces """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from copy import deepcopy @@ -20,7 +21,12 @@ from ...utils.misc import is_container from ...utils.filemanip import md5, hash_infile, hash_timestamp, to_str from .traits_extension import ( - traits, Undefined, isdefined, TraitError, TraitDictObject, TraitListObject, + traits, + Undefined, + isdefined, + TraitError, + TraitDictObject, + TraitListObject, has_metadata, ) @@ -105,8 +111,10 @@ def _xor_warn(self, obj, name, old, new): # skip ourself continue if isdefined(getattr(self, trait_name)): - self.trait_set(trait_change_notify=False, - **{'%s' % name: Undefined}) + self.trait_set( + trait_change_notify=False, **{ + '%s' % name: Undefined + }) msg = ('Input "%s" is mutually exclusive with input "%s", ' 'which is already set') % (name, trait_name) raise IOError(msg) @@ -131,10 +139,9 @@ def _deprecated_warn(self, obj, name, old, new): if isdefined(new): trait_spec = self.traits()[name] msg1 = ('Input %s in interface %s is deprecated.' % - (name, - self.__class__.__name__.split('InputSpec')[0])) - msg2 = ('Will be removed or raise an error as of release %s' - % trait_spec.deprecated) + (name, self.__class__.__name__.split('InputSpec')[0])) + msg2 = ('Will be removed or raise an error as of release %s' % + trait_spec.deprecated) if trait_spec.new_name: if trait_spec.new_name not in self.copyable_trait_names(): raise TraitError(msg1 + ' Replacement trait %s not found' % @@ -151,9 +158,12 @@ def _deprecated_warn(self, obj, name, old, new): name, trait_spec.new_name) warn(msg) if trait_spec.new_name: - self.trait_set(trait_change_notify=False, - **{'%s' % name: Undefined, - '%s' % trait_spec.new_name: new}) + self.trait_set( + trait_change_notify=False, + **{ + '%s' % name: Undefined, + '%s' % trait_spec.new_name: new + }) def _hash_infile(self, adict, key): """ Inject file hashes into adict[key]""" @@ -173,8 +183,8 @@ def _hash_infile(self, adict, key): 'hash_method').lower() == 'content': hash = hash_infile(afile) else: - raise Exception("Unknown hash method: %s" % - config.get('execution', 'hash_method')) + raise Exception("Unknown hash method: %s" % config.get( + 'execution', 'hash_method')) file_list.append((afile, hash)) return file_list @@ -210,8 +220,8 @@ def _clean_container(self, objekt, undefinedval=None, skipundefined=False): else: if not skipundefined: out[key] = undefinedval - elif (isinstance(objekt, TraitListObject) or - isinstance(objekt, list) or isinstance(objekt, tuple)): + elif (isinstance(objekt, TraitListObject) or isinstance(objekt, list) + or isinstance(objekt, tuple)): out = [] for val in objekt: if isdefined(val): @@ -236,8 +246,8 @@ def has_metadata(self, name, metadata, value=None, recursive=True): Return has_metadata for the requested trait name in this interface """ - return has_metadata(self.trait(name).trait_type, metadata, value, - recursive) + return has_metadata( + self.trait(name).trait_type, metadata, value, recursive) def get_hashval(self, hash_method=None): """Return a dictionary of our items with hashes for each file. @@ -267,39 +277,52 @@ def get_hashval(self, hash_method=None): # skip undefined traits and traits with nohash=True continue - hash_files = (not self.has_metadata(name, "hash_files", False) and not - self.has_metadata(name, "name_source")) + hash_files = (not self.has_metadata(name, "hash_files", False) + and not self.has_metadata(name, "name_source")) list_nofilename.append((name, - self._get_sorteddict(val, hash_method=hash_method, - hash_files=hash_files))) + self._get_sorteddict( + val, + hash_method=hash_method, + hash_files=hash_files))) list_withhash.append((name, - self._get_sorteddict(val, True, hash_method=hash_method, - hash_files=hash_files))) + self._get_sorteddict( + val, + True, + hash_method=hash_method, + hash_files=hash_files))) return list_withhash, md5(to_str(list_nofilename).encode()).hexdigest() - def _get_sorteddict(self, objekt, dictwithhash=False, hash_method=None, + def _get_sorteddict(self, + objekt, + dictwithhash=False, + hash_method=None, hash_files=True): if isinstance(objekt, dict): out = [] for key, val in sorted(objekt.items()): if isdefined(val): out.append((key, - self._get_sorteddict(val, dictwithhash, - hash_method=hash_method, - hash_files=hash_files))) + self._get_sorteddict( + val, + dictwithhash, + hash_method=hash_method, + hash_files=hash_files))) elif isinstance(objekt, (list, tuple)): out = [] for val in objekt: if isdefined(val): - out.append(self._get_sorteddict(val, dictwithhash, - hash_method=hash_method, - hash_files=hash_files)) + out.append( + self._get_sorteddict( + val, + dictwithhash, + hash_method=hash_method, + hash_files=hash_files)) if isinstance(objekt, tuple): out = tuple(out) else: if isdefined(objekt): - if (hash_files and isinstance(objekt, (str, bytes)) and - os.path.isfile(objekt)): + if (hash_files and isinstance(objekt, (str, bytes)) + and os.path.isfile(objekt)): if hash_method is None: hash_method = config.get('execution', 'hash_method') @@ -308,7 +331,8 @@ def _get_sorteddict(self, objekt, dictwithhash=False, hash_method=None, elif hash_method.lower() == 'content': hash = hash_infile(objekt) else: - raise Exception("Unknown hash method: %s" % hash_method) + raise Exception( + "Unknown hash method: %s" % hash_method) if dictwithhash: out = (objekt, hash) else: @@ -329,9 +353,13 @@ class TraitedSpec(BaseTraitedSpec): class BaseInterfaceInputSpec(TraitedSpec): - ignore_exception = traits.Bool(False, usedefault=True, nohash=True, deprecated='1.0.0', - desc='Print an error message instead of throwing an exception ' - 'in case the interface fails to run') + ignore_exception = traits.Bool( + False, + usedefault=True, + nohash=True, + deprecated='1.0.0', + desc='Print an error message instead of throwing an exception ' + 'in case the interface fails to run') class DynamicTraitedSpec(BaseTraitedSpec): @@ -368,19 +396,23 @@ def __deepcopy__(self, memo): class CommandLineInputSpec(BaseInterfaceInputSpec): args = traits.Str(argstr='%s', desc='Additional parameters to the command') - environ = traits.DictStrStr(desc='Environment variables', usedefault=True, - nohash=True) + environ = traits.DictStrStr( + desc='Environment variables', usedefault=True, nohash=True) # This input does not have a "usedefault=True" so the set_default_terminal_output() # method would work - terminal_output = traits.Enum('stream', 'allatonce', 'file', 'none', - deprecated='1.0.0', - desc=('Control terminal output: `stream` - ' - 'displays to terminal immediately (default), ' - '`allatonce` - waits till command is ' - 'finished to display output, `file` - ' - 'writes output to file, `none` - output' - ' is ignored'), - nohash=True) + terminal_output = traits.Enum( + 'stream', + 'allatonce', + 'file', + 'none', + deprecated='1.0.0', + desc=('Control terminal output: `stream` - ' + 'displays to terminal immediately (default), ' + '`allatonce` - waits till command is ' + 'finished to display output, `file` - ' + 'writes output to file, `none` - output' + ' is ignored'), + nohash=True) class StdOutCommandLineInputSpec(CommandLineInputSpec): @@ -388,9 +420,10 @@ class StdOutCommandLineInputSpec(CommandLineInputSpec): class MpiCommandLineInputSpec(CommandLineInputSpec): - use_mpi = traits.Bool(False, - desc="Whether or not to run the command with mpiexec", - usedefault=True) + use_mpi = traits.Bool( + False, + desc="Whether or not to run the command with mpiexec", + usedefault=True) n_procs = traits.Int(desc="Num processors to specify to mpiexec. Do not " "specify if this is managed externally (e.g. through " "SGE)") diff --git a/nipype/interfaces/base/support.py b/nipype/interfaces/base/support.py index f047cd120f..88fdf761a5 100644 --- a/nipype/interfaces/base/support.py +++ b/nipype/interfaces/base/support.py @@ -7,7 +7,8 @@ ...................................................... """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, object, str import os @@ -191,8 +192,7 @@ def _hash_bunch_dict(adict, key): stuff = adict[key] if not is_container(stuff): stuff = [stuff] - return [(afile, hash_infile(afile)) - for afile in stuff] + return [(afile, hash_infile(afile)) for afile in stuff] class InterfaceResult(object): @@ -222,7 +222,11 @@ class InterfaceResult(object): """ - def __init__(self, interface, runtime, inputs=None, outputs=None, + def __init__(self, + interface, + runtime, + inputs=None, + outputs=None, provenance=None): self._version = 2.0 self.interface = interface @@ -297,6 +301,5 @@ def load_template(name): from ..fsl.model import load_template iflogger.warning( 'Deprecated in 1.0.0, and will be removed in 1.1.0, ' - 'please use nipype.interfaces.fsl.model.load_template instead.' - ) + 'please use nipype.interfaces.fsl.model.load_template instead.') return load_template(name) diff --git a/nipype/interfaces/base/tests/test_auto_BaseInterface.py b/nipype/interfaces/base/tests/test_auto_BaseInterface.py index 33652036c7..562fc9dd52 100644 --- a/nipype/interfaces/base/tests/test_auto_BaseInterface.py +++ b/nipype/interfaces/base/tests/test_auto_BaseInterface.py @@ -4,14 +4,14 @@ def test_BaseInterface_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ) + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = BaseInterface.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/base/tests/test_auto_CommandLine.py b/nipype/interfaces/base/tests/test_auto_CommandLine.py index 8154f73a3d..6a247000d5 100644 --- a/nipype/interfaces/base/tests/test_auto_CommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_CommandLine.py @@ -4,22 +4,24 @@ def test_CommandLine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = CommandLine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py b/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py index 644de736ba..7a8fc298db 100644 --- a/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py @@ -4,25 +4,26 @@ def test_MpiCommandLine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - n_procs=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_mpi=dict(usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + n_procs=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_mpi=dict(usedefault=True, ), ) inputs = MpiCommandLine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py b/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py index 98ee386ee4..b86153fc75 100644 --- a/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py @@ -4,22 +4,24 @@ def test_SEMLikeCommandLine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SEMLikeCommandLine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/base/tests/test_auto_SimpleInterface.py b/nipype/interfaces/base/tests/test_auto_SimpleInterface.py index 6c19b125f2..94a2858f88 100644 --- a/nipype/interfaces/base/tests/test_auto_SimpleInterface.py +++ b/nipype/interfaces/base/tests/test_auto_SimpleInterface.py @@ -4,14 +4,14 @@ def test_SimpleInterface_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ) + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = SimpleInterface.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py b/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py index a876e1b61e..69e324be86 100644 --- a/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py @@ -4,26 +4,29 @@ def test_StdOutCommandLine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = StdOutCommandLine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/base/tests/test_core.py b/nipype/interfaces/base/tests/test_core.py index 1eb2cf4b42..05a9f02b47 100644 --- a/nipype/interfaces/base/tests/test_core.py +++ b/nipype/interfaces/base/tests/test_core.py @@ -18,6 +18,7 @@ def check_dict(ref_dict, tst_dict): """Compare dictionaries of inputs and and those loaded from json files""" + def to_list(x): if isinstance(x, tuple): x = list(x) @@ -135,8 +136,7 @@ class DerivedInterface(nib.BaseInterface): def __init__(self, **inputs): super(DerivedInterface, self).__init__(**inputs) - inputs_dict = {'input1': 12, 'input3': True, - 'input4': 'some string'} + inputs_dict = {'input1': 12, 'input3': True, 'input4': 'some string'} bif = DerivedInterface(**inputs_dict) bif.save_inputs_to_json(tmp_json) bif2 = DerivedInterface() @@ -161,7 +161,8 @@ def __init__(self, **inputs): # test get hashval in a complex interface from nipype.interfaces.ants import Registration - settings = example_data(example_data('smri_ants_registration_settings.json')) + settings = example_data( + example_data('smri_ants_registration_settings.json')) with open(settings) as setf: data_dict = json.load(setf) @@ -182,6 +183,7 @@ class InputSpec(nib.TraitedSpec): class DerivedInterface1(nib.BaseInterface): input_spec = InputSpec + obj = DerivedInterface1() obj._check_version_requirements(obj.inputs) @@ -198,6 +200,7 @@ class InputSpec(nib.TraitedSpec): class DerivedInterface1(nib.BaseInterface): input_spec = InputSpec _version = '0.8' + obj = DerivedInterface1() obj.inputs.foo = 1 with pytest.raises(Exception): @@ -209,6 +212,7 @@ class InputSpec(nib.TraitedSpec): class DerivedInterface1(nib.BaseInterface): input_spec = InputSpec _version = '0.10' + obj = DerivedInterface1() obj._check_version_requirements(obj.inputs) @@ -218,6 +222,7 @@ class InputSpec(nib.TraitedSpec): class DerivedInterface1(nib.BaseInterface): input_spec = InputSpec _version = '0.9' + obj = DerivedInterface1() obj.inputs.foo = 1 obj._check_version_requirements(obj.inputs) @@ -228,6 +233,7 @@ class InputSpec(nib.TraitedSpec): class DerivedInterface2(nib.BaseInterface): input_spec = InputSpec _version = '0.8' + obj = DerivedInterface2() obj.inputs.foo = 1 with pytest.raises(Exception): @@ -239,6 +245,7 @@ class InputSpec(nib.TraitedSpec): class DerivedInterface1(nib.BaseInterface): input_spec = InputSpec _version = '0.9' + obj = DerivedInterface1() obj.inputs.foo = 1 obj._check_version_requirements(obj.inputs) @@ -292,6 +299,7 @@ def _run_interface(self, runtime): def _list_outputs(self): return {'foo': 1} + obj = DerivedInterface1() with pytest.raises(KeyError): obj.run() @@ -316,8 +324,8 @@ class CommandLineInputSpec1(nib.CommandLineInputSpec): foo = nib.Str(argstr='%s', desc='a str') goo = nib.traits.Bool(argstr='-g', desc='a bool', position=0) hoo = nib.traits.List(argstr='-l %s', desc='a list') - moo = nib.traits.List(argstr='-i %d...', desc='a repeated list', - position=-1) + moo = nib.traits.List( + argstr='-i %d...', desc='a repeated list', position=-1) noo = nib.traits.Int(argstr='-x %d', desc='an int') roo = nib.traits.Str(desc='not on command line') soo = nib.traits.Bool(argstr="-soo") @@ -342,6 +350,7 @@ class CommandLineInputSpec1(nib.CommandLineInputSpec): class CommandLineInputSpec2(nib.CommandLineInputSpec): foo = nib.File(argstr='%s', desc='a str', genfile=True) + nib.CommandLine.input_spec = CommandLineInputSpec2 ci5 = nib.CommandLine(command='cmd') with pytest.raises(NotImplementedError): diff --git a/nipype/interfaces/base/tests/test_resource_monitor.py b/nipype/interfaces/base/tests/test_resource_monitor.py index 88e71921c4..f82a82661d 100644 --- a/nipype/interfaces/base/tests/test_resource_monitor.py +++ b/nipype/interfaces/base/tests/test_resource_monitor.py @@ -6,7 +6,8 @@ Module to unit test the resource_monitor in nipype """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import pytest @@ -22,10 +23,10 @@ class UseResourcesInputSpec(CommandLineInputSpec): - mem_gb = traits.Float(desc='Number of GB of RAM to use', - argstr='-g %f', mandatory=True) - n_procs = traits.Int(desc='Number of threads to use', - argstr='-p %d', mandatory=True) + mem_gb = traits.Float( + desc='Number of GB of RAM to use', argstr='-g %f', mandatory=True) + n_procs = traits.Int( + desc='Number of threads to use', argstr='-p %d', mandatory=True) class UseResources(CommandLine): @@ -46,8 +47,10 @@ class UseResources(CommandLine): @pytest.mark.skip(reason="inconsistent readings") -@pytest.mark.skipif(os.getenv('CI_SKIP_TEST', False), reason='disabled in CI tests') -@pytest.mark.parametrize("mem_gb,n_procs", [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)]) +@pytest.mark.skipif( + os.getenv('CI_SKIP_TEST', False), reason='disabled in CI tests') +@pytest.mark.parametrize("mem_gb,n_procs", [(0.5, 3), (2.2, 8), (0.8, 4), + (1.5, 1)]) def test_cmdline_profiling(tmpdir, mem_gb, n_procs): """ Test runtime profiler correctly records workflow RAM/CPUs consumption @@ -60,12 +63,16 @@ def test_cmdline_profiling(tmpdir, mem_gb, n_procs): iface = UseResources(mem_gb=mem_gb, n_procs=n_procs) result = iface.run() - assert abs(mem_gb - result.runtime.mem_peak_gb) < 0.3, 'estimated memory error above .3GB' - assert int(result.runtime.cpu_percent / 100 + 0.2) == n_procs, 'wrong number of threads estimated' + assert abs(mem_gb - result.runtime.mem_peak_gb + ) < 0.3, 'estimated memory error above .3GB' + assert int(result.runtime.cpu_percent / 100 + 0.2 + ) == n_procs, 'wrong number of threads estimated' -@pytest.mark.skipif(True, reason='test disabled temporarily, until funcion profiling works') -@pytest.mark.parametrize("mem_gb,n_procs", [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)]) +@pytest.mark.skipif( + True, reason='test disabled temporarily, until funcion profiling works') +@pytest.mark.parametrize("mem_gb,n_procs", [(0.5, 3), (2.2, 8), (0.8, 4), + (1.5, 1)]) def test_function_profiling(tmpdir, mem_gb, n_procs): """ Test runtime profiler correctly records workflow RAM/CPUs consumption @@ -80,5 +87,6 @@ def test_function_profiling(tmpdir, mem_gb, n_procs): iface.inputs.n_procs = n_procs result = iface.run() - assert abs(mem_gb - result.runtime.mem_peak_gb) < 0.3, 'estimated memory error above .3GB' + assert abs(mem_gb - result.runtime.mem_peak_gb + ) < 0.3, 'estimated memory error above .3GB' assert int(result.runtime.cpu_percent / 100 + 0.2) >= n_procs diff --git a/nipype/interfaces/base/tests/test_specs.py b/nipype/interfaces/base/tests/test_specs.py index 168e021339..86b70f40dc 100644 --- a/nipype/interfaces/base/tests/test_specs.py +++ b/nipype/interfaces/base/tests/test_specs.py @@ -41,7 +41,8 @@ class spec(nib.TraitedSpec): with pytest.raises(nib.traits.TraitError): specfunc(1) infields = spec(foo=1) - hashval = ([('foo', 1), ('goo', '0.0000000000')], 'e89433b8c9141aa0fda2f8f4d662c047') + hashval = ([('foo', 1), ('goo', '0.0000000000')], + 'e89433b8c9141aa0fda2f8f4d662c047') assert infields.get_hashval() == hashval assert infields.__repr__() == '\nfoo = 1\ngoo = 0.0\n' @@ -66,13 +67,10 @@ def test_TraitedSpec_logic(): class spec3(nib.TraitedSpec): _xor_inputs = ('foo', 'bar') - foo = nib.traits.Int(xor=_xor_inputs, - desc='foo or bar, not both') - bar = nib.traits.Int(xor=_xor_inputs, - desc='bar or foo, not both') - kung = nib.traits.Float(requires=('foo',), - position=0, - desc='kung foo') + foo = nib.traits.Int(xor=_xor_inputs, desc='foo or bar, not both') + bar = nib.traits.Int(xor=_xor_inputs, desc='bar or foo, not both') + kung = nib.traits.Float( + requires=('foo', ), position=0, desc='kung foo') class out3(nib.TraitedSpec): output = nib.traits.Int @@ -101,6 +99,7 @@ def test_deprecation(): class DeprecationSpec1(nib.TraitedSpec): foo = nib.traits.Int(deprecated='0.1') + spec_instance = DeprecationSpec1() set_foo = lambda: setattr(spec_instance, 'foo', 1) with pytest.raises(nib.TraitError): @@ -112,6 +111,7 @@ class DeprecationSpec1(nib.TraitedSpec): class DeprecationSpec2(nib.TraitedSpec): foo = nib.traits.Int(deprecated='100', new_name='bar') + spec_instance = DeprecationSpec2() set_foo = lambda: setattr(spec_instance, 'foo', 1) with pytest.raises(nib.TraitError): @@ -124,6 +124,7 @@ class DeprecationSpec2(nib.TraitedSpec): class DeprecationSpec3(nib.TraitedSpec): foo = nib.traits.Int(deprecated='1000', new_name='bar') bar = nib.traits.Int() + spec_instance = DeprecationSpec3() not_raised = True try: @@ -131,7 +132,8 @@ class DeprecationSpec3(nib.TraitedSpec): except nib.TraitError: not_raised = False assert not_raised - assert len(w) == 1, 'deprecated warning 1 %s' % [w1.message for w1 in w] + assert len( + w) == 1, 'deprecated warning 1 %s' % [w1.message for w1 in w] with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', UserWarning) @@ -139,6 +141,7 @@ class DeprecationSpec3(nib.TraitedSpec): class DeprecationSpec3(nib.TraitedSpec): foo = nib.traits.Int(deprecated='1000', new_name='bar') bar = nib.traits.Int() + spec_instance = DeprecationSpec3() not_raised = True try: @@ -148,7 +151,8 @@ class DeprecationSpec3(nib.TraitedSpec): assert not_raised assert spec_instance.foo == Undefined assert spec_instance.bar == 1 - assert len(w) == 1, 'deprecated warning 2 %s' % [w1.message for w1 in w] + assert len( + w) == 1, 'deprecated warning 2 %s' % [w1.message for w1 in w] def test_namesource(setup_file): @@ -156,16 +160,17 @@ def test_namesource(setup_file): tmpd, nme, ext = split_filename(tmp_infile) class spec2(nib.CommandLineInputSpec): - moo = nib.File(name_source=['doo'], hash_files=False, argstr="%s", - position=2) + moo = nib.File( + name_source=['doo'], hash_files=False, argstr="%s", position=2) doo = nib.File(exists=True, argstr="%s", position=1) goo = traits.Int(argstr="%d", position=4) - poo = nib.File(name_source=['goo'], hash_files=False, argstr="%s", - position=3) + poo = nib.File( + name_source=['goo'], hash_files=False, argstr="%s", position=3) class TestName(nib.CommandLine): _cmd = "mycommand" input_spec = spec2 + testobj = TestName() testobj.inputs.doo = tmp_infile testobj.inputs.goo = 99 @@ -181,10 +186,14 @@ def test_chained_namesource(setup_file): class spec2(nib.CommandLineInputSpec): doo = nib.File(exists=True, argstr="%s", position=1) - moo = nib.File(name_source=['doo'], hash_files=False, argstr="%s", - position=2, name_template='%s_mootpl') - poo = nib.File(name_source=['moo'], hash_files=False, - argstr="%s", position=3) + moo = nib.File( + name_source=['doo'], + hash_files=False, + argstr="%s", + position=2, + name_template='%s_mootpl') + poo = nib.File( + name_source=['moo'], hash_files=False, argstr="%s", position=3) class TestName(nib.CommandLine): _cmd = "mycommand" @@ -203,12 +212,16 @@ def test_cycle_namesource1(setup_file): tmpd, nme, ext = split_filename(tmp_infile) class spec3(nib.CommandLineInputSpec): - moo = nib.File(name_source=['doo'], hash_files=False, argstr="%s", - position=1, name_template='%s_mootpl') - poo = nib.File(name_source=['moo'], hash_files=False, - argstr="%s", position=2) - doo = nib.File(name_source=['poo'], hash_files=False, - argstr="%s", position=3) + moo = nib.File( + name_source=['doo'], + hash_files=False, + argstr="%s", + position=1, + name_template='%s_mootpl') + poo = nib.File( + name_source=['moo'], hash_files=False, argstr="%s", position=2) + doo = nib.File( + name_source=['poo'], hash_files=False, argstr="%s", position=3) class TestCycle(nib.CommandLine): _cmd = "mycommand" @@ -229,12 +242,16 @@ def test_cycle_namesource2(setup_file): tmpd, nme, ext = split_filename(tmp_infile) class spec3(nib.CommandLineInputSpec): - moo = nib.File(name_source=['doo'], hash_files=False, argstr="%s", - position=1, name_template='%s_mootpl') - poo = nib.File(name_source=['moo'], hash_files=False, - argstr="%s", position=2) - doo = nib.File(name_source=['poo'], hash_files=False, - argstr="%s", position=3) + moo = nib.File( + name_source=['doo'], + hash_files=False, + argstr="%s", + position=1, + name_template='%s_mootpl') + poo = nib.File( + name_source=['moo'], hash_files=False, argstr="%s", position=2) + doo = nib.File( + name_source=['poo'], hash_files=False, argstr="%s", position=3) class TestCycle(nib.CommandLine): _cmd = "mycommand" @@ -265,6 +282,7 @@ def test_TraitedSpec_withFile(setup_file): class spec2(nib.TraitedSpec): moo = nib.File(exists=True) doo = nib.traits.List(nib.File(exists=True)) + infields = spec2(moo=tmp_infile, doo=[tmp_infile]) hashval = infields.get_hashval(hash_method='content') assert hashval[1] == 'a00e9ee24f5bfa9545a515b7a759886b' @@ -278,6 +296,7 @@ def test_TraitedSpec_withNoFileHashing(setup_file): class spec2(nib.TraitedSpec): moo = nib.File(exists=True, hash_files=False) doo = nib.traits.List(nib.File(exists=True)) + infields = spec2(moo=nme, doo=[tmp_infile]) hashval = infields.get_hashval(hash_method='content') assert hashval[1] == '8da4669ff5d72f670a46ea3e7a203215' @@ -285,12 +304,14 @@ class spec2(nib.TraitedSpec): class spec3(nib.TraitedSpec): moo = nib.File(exists=True, name_source="doo") doo = nib.traits.List(nib.File(exists=True)) + infields = spec3(moo=nme, doo=[tmp_infile]) hashval1 = infields.get_hashval(hash_method='content') class spec4(nib.TraitedSpec): moo = nib.File(exists=True) doo = nib.traits.List(nib.File(exists=True)) + infields = spec4(moo=nme, doo=[tmp_infile]) hashval2 = infields.get_hashval(hash_method='content') assert hashval1[1] != hashval2[1] @@ -303,8 +324,8 @@ def test_ImageFile(): x.add_trait('nifti', nib.ImageFile(types=['nifti1', 'dicom'])) x.add_trait('anytype', nib.ImageFile()) x.add_trait('newtype', nib.ImageFile(types=['nifti10'])) - x.add_trait('nocompress', nib.ImageFile(types=['mgh'], - allow_compressed=False)) + x.add_trait('nocompress', + nib.ImageFile(types=['mgh'], allow_compressed=False)) with pytest.raises(nib.TraitError): x.nifti = 'test.mgz' diff --git a/nipype/interfaces/base/tests/test_support.py b/nipype/interfaces/base/tests/test_support.py index 260a5eb882..e6db69a458 100644 --- a/nipype/interfaces/base/tests/test_support.py +++ b/nipype/interfaces/base/tests/test_support.py @@ -14,10 +14,7 @@ standard_library.install_aliases() -@pytest.mark.parametrize("args", [ - {}, - {'a': 1, 'b': [2, 3]} -]) +@pytest.mark.parametrize("args", [{}, {'a': 1, 'b': [2, 3]}]) def test_bunch(args): b = nib.Bunch(**args) assert b.__dict__ == args @@ -50,12 +47,10 @@ def test_bunch_methods(): def test_bunch_hash(): # NOTE: Since the path to the json file is included in the Bunch, # the hash will be unique to each machine. - json_pth = pkgrf( - 'nipype', os.path.join('testing', 'data', 'realign_json.json')) + json_pth = pkgrf('nipype', + os.path.join('testing', 'data', 'realign_json.json')) - b = nib.Bunch(infile=json_pth, - otherthing='blue', - yat=True) + b = nib.Bunch(infile=json_pth, otherthing='blue', yat=True) newbdict, bhash = b._get_bunch_hash() assert bhash == 'd1f46750044c3de102efc847720fc35f' # Make sure the hash stored in the json file for `infile` is correct. diff --git a/nipype/interfaces/base/traits_extension.py b/nipype/interfaces/base/traits_extension.py index 18bdd003c2..78b68a5601 100644 --- a/nipype/interfaces/base/traits_extension.py +++ b/nipype/interfaces/base/traits_extension.py @@ -20,7 +20,8 @@ (usually by Robert Kern). """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, bytes import os @@ -60,8 +61,13 @@ class BaseFile(BaseUnicode): # A description of the type of value this trait accepts: info_text = 'a file name' - def __init__(self, value='', filter=None, auto_set=False, - entries=0, exists=False, **metadata): + def __init__(self, + value='', + filter=None, + auto_set=False, + entries=0, + exists=False, + **metadata): """ Creates a File trait. Parameters @@ -105,20 +111,25 @@ def validate(self, object, name, value): else: raise TraitError( args='The trait \'{}\' of {} instance is {}, but the path ' - ' \'{}\' does not exist.'.format(name, class_of(object), - self.info_text, value)) + ' \'{}\' does not exist.'.format(name, class_of(object), + self.info_text, value)) self.error(object, name, value) -class File (BaseFile): +class File(BaseFile): """ Defines a trait whose value must be the name of a file. Disables the default C-level fast validator. """ - def __init__(self, value='', filter=None, auto_set=False, - entries=0, exists=False, **metadata): + def __init__(self, + value='', + filter=None, + auto_set=False, + entries=0, + exists=False, + **metadata): """ Creates a File trait. Parameters @@ -146,12 +157,13 @@ def __init__(self, value='', filter=None, auto_set=False, super(File, self).__init__(value, filter, auto_set, entries, exists, **metadata) + # ------------------------------------------------------------------------------- # 'BaseDirectory' and 'Directory' traits: # ------------------------------------------------------------------------------- -class BaseDirectory (BaseUnicode): +class BaseDirectory(BaseUnicode): """ Defines a trait whose value must be the name of a directory. """ @@ -159,8 +171,12 @@ class BaseDirectory (BaseUnicode): # A description of the type of value this trait accepts: info_text = 'a directory name' - def __init__(self, value='', auto_set=False, entries=0, - exists=False, **metadata): + def __init__(self, + value='', + auto_set=False, + entries=0, + exists=False, + **metadata): """ Creates a BaseDirectory trait. Parameters @@ -200,20 +216,24 @@ def validate(self, object, name, value): else: raise TraitError( args='The trait \'{}\' of {} instance is {}, but the path ' - ' \'{}\' does not exist.'.format(name, - class_of(object), self.info_text, value)) + ' \'{}\' does not exist.'.format(name, class_of(object), + self.info_text, value)) self.error(object, name, value) -class Directory (BaseDirectory): +class Directory(BaseDirectory): """ Defines a trait whose value must be the name of a directory. Disables the default C-level fast validator. """ - def __init__(self, value='', auto_set=False, entries=0, - exists=False, **metadata): + def __init__(self, + value='', + auto_set=False, + entries=0, + exists=False, + **metadata): """ Creates a Directory trait. Parameters @@ -239,13 +259,13 @@ def __init__(self, value='', auto_set=False, entries=0, super(Directory, self).__init__(value, auto_set, entries, exists, **metadata) + # lists of tuples # each element consists of : # - uncompressed (tuple[0]) extension # - compressed (tuple[1]) extension img_fmt_types = { - 'nifti1': [('.nii', '.nii.gz'), - (('.hdr', '.img'), ('.hdr', '.img.gz'))], + 'nifti1': [('.nii', '.nii.gz'), (('.hdr', '.img'), ('.hdr', '.img.gz'))], 'mgh': [('.mgh', '.mgz'), ('.mgh', '.mgh.gz')], 'nifti2': [('.nii', '.nii.gz')], 'cifti2': [('.nii', '.nii.gz')], @@ -259,8 +279,15 @@ def __init__(self, value='', auto_set=False, entries=0, class ImageFile(File): """ Defines a trait of specific neuroimaging files """ - def __init__(self, value='', filter=None, auto_set=False, entries=0, - exists=False, types=[], allow_compressed=True, **metadata): + def __init__(self, + value='', + filter=None, + auto_set=False, + entries=0, + exists=False, + types=[], + allow_compressed=True, + **metadata): """ Trait handles neuroimaging files. Parameters @@ -280,16 +307,20 @@ def grab_exts(self): exts = [] for fmt in self.types: if fmt in img_fmt_types: - exts.extend(sum([[u for u in y[0]] if isinstance(y[0], tuple) - else [y[0]] for y in img_fmt_types[fmt]], [])) + exts.extend( + sum([[u for u in y[0]] + if isinstance(y[0], tuple) else [y[0]] + for y in img_fmt_types[fmt]], [])) if self.allow_compressed: - exts.extend(sum([[u for u in y[-1]] if isinstance(y[-1], - tuple) else [y[-1]] for y in img_fmt_types[fmt]], [])) + exts.extend( + sum([[u for u in y[-1]] + if isinstance(y[-1], tuple) else [y[-1]] + for y in img_fmt_types[fmt]], [])) else: - raise AttributeError('Information has not been added for format' - ' type {} yet. Supported formats include: ' - '{}'.format(fmt, - ', '.join(img_fmt_types.keys()))) + raise AttributeError( + 'Information has not been added for format' + ' type {} yet. Supported formats include: ' + '{}'.format(fmt, ', '.join(img_fmt_types.keys()))) return list(set(exts)) def validate(self, object, name, value): @@ -304,6 +335,7 @@ def validate(self, object, name, value): validated_value, ', '.join(self._exts))) return validated_value + """ The functions that pop-up the Traits GUIs, edit_traits and configure_traits, were failing because all of our inputs default to @@ -324,6 +356,7 @@ def validate(self, object, name, value): def length(self): return 0 + ########################################################################## # Apply monkeypatch here _Undefined.__len__ = length @@ -341,12 +374,15 @@ def has_metadata(trait, metadata, value=None, recursive=True): Checks if a given trait has a metadata (and optionally if it is set to particular value) ''' count = 0 - if hasattr(trait, "_metadata") and metadata in list(trait._metadata.keys()) and (trait._metadata[metadata] == value or value is None): + if hasattr(trait, "_metadata") and metadata in list( + trait._metadata.keys()) and (trait._metadata[metadata] == value + or value is None): count += 1 if recursive: if hasattr(trait, 'inner_traits'): for inner_trait in trait.inner_traits(): - count += has_metadata(inner_trait.trait_type, metadata, recursive) + count += has_metadata(inner_trait.trait_type, metadata, + recursive) if hasattr(trait, 'handlers') and trait.handlers is not None: for handler in trait.handlers: count += has_metadata(handler, metadata, recursive) @@ -361,7 +397,8 @@ class MultiPath(traits.List): def validate(self, object, name, value): # want to treat range and other sequences (except str) as list - if not isinstance(value, (str, bytes)) and isinstance(value, collections.Sequence): + if not isinstance(value, (str, bytes)) and isinstance( + value, collections.Sequence): value = list(value) if not isdefined(value) or \ diff --git a/nipype/interfaces/bids_utils.py b/nipype/interfaces/bids_utils.py index 0259a80352..0a74410936 100644 --- a/nipype/interfaces/bids_utils.py +++ b/nipype/interfaces/bids_utils.py @@ -16,13 +16,8 @@ from os.path import join, dirname import json from .. import logging -from .base import (traits, - DynamicTraitedSpec, - Directory, - BaseInterface, - isdefined, - Str, - Undefined) +from .base import (traits, DynamicTraitedSpec, Directory, BaseInterface, + isdefined, Str, Undefined) have_pybids = True try: @@ -34,20 +29,21 @@ class BIDSDataGrabberInputSpec(DynamicTraitedSpec): - base_dir = Directory(exists=True, - desc='Path to BIDS Directory.', - mandatory=True) - output_query = traits.Dict(key_trait=Str, - value_trait=traits.Dict, - desc='Queries for outfield outputs') - raise_on_empty = traits.Bool(True, usedefault=True, - desc='Generate exception if list is empty ' - 'for a given field') + base_dir = Directory( + exists=True, desc='Path to BIDS Directory.', mandatory=True) + output_query = traits.Dict( + key_trait=Str, + value_trait=traits.Dict, + desc='Queries for outfield outputs') + raise_on_empty = traits.Bool( + True, + usedefault=True, + desc='Generate exception if list is empty ' + 'for a given field') return_type = traits.Enum('file', 'namedtuple', usedefault=True) class BIDSDataGrabber(BaseInterface): - """ BIDS datagrabber module that wraps around pybids to allow arbitrary querying of BIDS datasets. @@ -94,11 +90,17 @@ def __init__(self, infields=None, **kwargs): super(BIDSDataGrabber, self).__init__(**kwargs) if not isdefined(self.inputs.output_query): - self.inputs.output_query = {"func": {"modality": "func"}, - "anat": {"modality": "anat"}} + self.inputs.output_query = { + "func": { + "modality": "func" + }, + "anat": { + "modality": "anat" + } + } # If infields is empty, use all BIDS entities - if not infields is None and have_pybids: + if infields is not None and have_pybids: bids_config = join(dirname(gb.__file__), 'config', 'bids.json') bids_config = json.load(open(bids_config, 'r')) infields = [i['name'] for i in bids_config['entities']] diff --git a/nipype/interfaces/brainsuite/__init__.py b/nipype/interfaces/brainsuite/__init__.py index fdce17778c..6611aedff4 100644 --- a/nipype/interfaces/brainsuite/__init__.py +++ b/nipype/interfaces/brainsuite/__init__.py @@ -1,4 +1,4 @@ # -*- coding: utf-8 -*- from .brainsuite import (Bse, Bfc, Pvc, Cerebro, Cortex, Scrubmask, Tca, - Dewisp, Dfs, Pialmesh, Skullfinder, Hemisplit, - SVReg, BDP, ThicknessPVC) + Dewisp, Dfs, Pialmesh, Skullfinder, Hemisplit, SVReg, + BDP, ThicknessPVC) diff --git a/nipype/interfaces/brainsuite/brainsuite.py b/nipype/interfaces/brainsuite/brainsuite.py index 60141bcb00..aa75d2bf81 100644 --- a/nipype/interfaces/brainsuite/brainsuite.py +++ b/nipype/interfaces/brainsuite/brainsuite.py @@ -1,28 +1,34 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import re as regex from ..base import TraitedSpec, CommandLineInputSpec, CommandLine, File, traits, isdefined - - """This script provides interfaces for BrainSuite command line tools. Please see brainsuite.org for more information. Author: Jason Wong """ + class BseInputSpec(CommandLineInputSpec): inputMRIFile = File( mandatory=True, argstr='-i %s', desc='input MRI volume') outputMRIVolume = File( - desc='output brain-masked MRI volume. If unspecified, output file name will be auto generated.', - argstr='-o %s', hash_files=False, genfile=True) + desc= + 'output brain-masked MRI volume. If unspecified, output file name will be auto generated.', + argstr='-o %s', + hash_files=False, + genfile=True) outputMaskFile = File( - desc='save smooth brain mask. If unspecified, output file name will be auto generated.', - argstr='--mask %s', hash_files=False, genfile=True) + desc= + 'save smooth brain mask. If unspecified, output file name will be auto generated.', + argstr='--mask %s', + hash_files=False, + genfile=True) diffusionConstant = traits.Float( 25, usedefault=True, desc='diffusion constant', argstr='-d %f') diffusionIterations = traits.Int( @@ -30,7 +36,10 @@ class BseInputSpec(CommandLineInputSpec): edgeDetectionConstant = traits.Float( 0.64, usedefault=True, desc='edge detection constant', argstr='-s %f') radius = traits.Float( - 1, usedefault=True, desc='radius of erosion/dilation filter', argstr='-r %f') + 1, + usedefault=True, + desc='radius of erosion/dilation filter', + argstr='-r %f') dilateFinalMask = traits.Bool( True, usedefault=True, desc='dilate final mask', argstr='-p') trim = traits.Bool( @@ -46,9 +55,10 @@ class BseInputSpec(CommandLineInputSpec): verbosityLevel = traits.Float( 1, usedefault=True, desc=' verbosity level (0=silent)', argstr='-v %f') noRotate = traits.Bool( - desc='retain original orientation(default behavior will auto-rotate input NII files to LPI orientation)', argstr='--norotate') - timer = traits.Bool( - desc='show timing', argstr='--timer') + desc= + 'retain original orientation(default behavior will auto-rotate input NII files to LPI orientation)', + argstr='--norotate') + timer = traits.Bool(desc='show timing', argstr='--timer') class BseOutputSpec(TraitedSpec): @@ -61,7 +71,6 @@ class BseOutputSpec(TraitedSpec): class Bse(CommandLine): - """ brain surface extractor (BSE) This program performs automated skull and scalp removal on T1-weighted MRI volumes. @@ -88,9 +97,10 @@ def _gen_filename(self, name): if isdefined(inputs[name]): return os.path.abspath(inputs[name]) - fileToSuffixMap = {'outputMRIVolume': '.bse.nii.gz', - 'outputMaskFile': '.mask.nii.gz' - } + fileToSuffixMap = { + 'outputMRIVolume': '.bse.nii.gz', + 'outputMaskFile': '.mask.nii.gz' + } if name in fileToSuffixMap: return getFileName(self.inputs.inputMRIFile, fileToSuffixMap[name]) @@ -104,15 +114,19 @@ def _list_outputs(self): class BfcInputSpec(CommandLineInputSpec): inputMRIFile = File( mandatory=True, desc='input skull-stripped MRI volume', argstr='-i %s') - inputMaskFile = File( - desc='mask file', argstr='-m %s', hash_files=False) + inputMaskFile = File(desc='mask file', argstr='-m %s', hash_files=False) outputMRIVolume = File( - desc='output bias-corrected MRI volume.If unspecified, output file name will be auto generated.', - argstr='-o %s', hash_files=False, genfile=True) + desc= + 'output bias-corrected MRI volume.If unspecified, output file name will be auto generated.', + argstr='-o %s', + hash_files=False, + genfile=True) outputBiasField = File( desc='save bias field estimate', argstr='--bias %s', hash_files=False) outputMaskedBiasField = File( - desc='save bias field estimate (masked)', argstr='--maskedbias %s', hash_files=False) + desc='save bias field estimate (masked)', + argstr='--maskedbias %s', + hash_files=False) histogramRadius = traits.Int( desc='histogram radius (voxels)', argstr='-r %d') biasEstimateSpacing = traits.Int( @@ -122,10 +136,14 @@ class BfcInputSpec(CommandLineInputSpec): splineLambda = traits.Float( desc='spline stiffness weighting parameter', argstr='-w %f') histogramType = traits.Enum( - 'ellipse', 'block', desc='Options for type of histogram\nellipse: use ellipsoid for ROI histogram\nblock :use block for ROI histogram', + 'ellipse', + 'block', + desc= + 'Options for type of histogram\nellipse: use ellipsoid for ROI histogram\nblock :use block for ROI histogram', argstr='%s') iterativeMode = traits.Bool( - desc='iterative mode (overrides -r, -s, -c, -w settings)', argstr='--iterate') + desc='iterative mode (overrides -r, -s, -c, -w settings)', + argstr='--iterate') correctionScheduleFile = File( desc='list of parameters ', argstr='--schedule %s') biasFieldEstimatesOutputPrefix = traits.Str( @@ -135,31 +153,40 @@ class BfcInputSpec(CommandLineInputSpec): desc='save iterative corrected images as .n.bfc.nii.gz', argstr='--prefix %s') correctWholeVolume = traits.Bool( - desc='apply correction field to entire volume', - argstr='--extrapolate') + desc='apply correction field to entire volume', argstr='--extrapolate') minBias = traits.Float( - 0.5, usedefault=True, desc='minimum allowed bias value', + 0.5, + usedefault=True, + desc='minimum allowed bias value', argstr='-L %f') maxBias = traits.Float( - 1.5, usedefault=True, desc='maximum allowed bias value', + 1.5, + usedefault=True, + desc='maximum allowed bias value', argstr='-U %f') biasRange = traits.Enum( - "low", "medium", "high", - desc='Preset options for bias_model\n low: small bias model [0.95,1.05]\n' - 'medium: medium bias model [0.90,1.10]\n high: high bias model [0.80,1.20]', + "low", + "medium", + "high", + desc= + 'Preset options for bias_model\n low: small bias model [0.95,1.05]\n' + 'medium: medium bias model [0.90,1.10]\n high: high bias model [0.80,1.20]', argstr='%s') intermediate_file_type = traits.Enum( - "analyze", "nifti", "gzippedAnalyze", "gzippedNifti", + "analyze", + "nifti", + "gzippedAnalyze", + "gzippedNifti", desc='Options for the format in which intermediate files are generated', argstr='%s') convergenceThreshold = traits.Float( desc='convergence threshold', argstr='--eps %f') biasEstimateConvergenceThreshold = traits.Float( - desc='bias estimate convergence threshold (values > 0.1 disable)', argstr='--beps %f') + desc='bias estimate convergence threshold (values > 0.1 disable)', + argstr='--beps %f') verbosityLevel = traits.Int( desc='verbosity level (0=silent)', argstr='-v %d') - timer = traits.Bool( - desc='display timing information', argstr='--timer') + timer = traits.Bool(desc='display timing information', argstr='--timer') class BfcOutputSpec(TraitedSpec): @@ -170,7 +197,6 @@ class BfcOutputSpec(TraitedSpec): class Bfc(CommandLine): - """ bias field corrector (BFC) This program corrects gain variation in T1-weighted MRI. @@ -206,11 +232,23 @@ def _gen_filename(self, name): def _format_arg(self, name, spec, value): if name == 'histogramType': - return spec.argstr % {"ellipse": "--ellipse", "block": "--block"}[value] + return spec.argstr % { + "ellipse": "--ellipse", + "block": "--block" + }[value] if name == 'biasRange': - return spec.argstr % {"low": "--low", "medium": "--medium", "high": "--high"}[value] + return spec.argstr % { + "low": "--low", + "medium": "--medium", + "high": "--high" + }[value] if name == 'intermediate_file_type': - return spec.argstr % {"analyze": "--analyze", "nifti": "--nifti", "gzippedAnalyze": "--analyzegz", "gzippedNifti": "--niftigz"}[value] + return spec.argstr % { + "analyze": "--analyze", + "nifti": "--nifti", + "gzippedAnalyze": "--analyzegz", + "gzippedNifti": "--niftigz" + }[value] return super(Bfc, self)._format_arg(name, spec, value) @@ -222,11 +260,12 @@ class PvcInputSpec(CommandLineInputSpec): inputMRIFile = File(mandatory=True, desc='MRI file', argstr='-i %s') inputMaskFile = File(desc='brain mask file', argstr='-m %s') outputLabelFile = File( - desc='output label file. If unspecified, output file name will be auto generated.', - argstr='-o %s', genfile=True) + desc= + 'output label file. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) outputTissueFractionFile = File( - desc='output tissue fraction file', - argstr='-f %s', genfile=True) + desc='output tissue fraction file', argstr='-f %s', genfile=True) spatialPrior = traits.Float(desc='spatial prior strength', argstr='-l %f') verbosity = traits.Int(desc='verbosity level (0 = silent)', argstr='-v %d') threeClassFlag = traits.Bool( @@ -240,7 +279,6 @@ class PvcOutputSpec(TraitedSpec): class Pvc(CommandLine): - """ partial volume classifier (PVC) tool. This program performs voxel-wise tissue classification T1-weighted MRI. @@ -269,9 +307,10 @@ def _gen_filename(self, name): if isdefined(inputs[name]): return os.path.abspath(inputs[name]) - fileToSuffixMap = {'outputLabelFile': '.pvc.label.nii.gz', - 'outputTissueFractionFile': '.pvc.frac.nii.gz' - } + fileToSuffixMap = { + 'outputLabelFile': '.pvc.label.nii.gz', + 'outputTissueFractionFile': '.pvc.frac.nii.gz' + } if name in fileToSuffixMap: return getFileName(self.inputs.inputMRIFile, fileToSuffixMap[name]) @@ -290,14 +329,19 @@ class CerebroInputSpec(CommandLineInputSpec): mandatory=True, desc='atlas labeling', argstr='--atlaslabels %s') inputBrainMaskFile = File(desc='brain mask file', argstr='-m %s') outputCerebrumMaskFile = File( - desc='output cerebrum mask volume. If unspecified, output file name will be auto generated.', - argstr='-o %s', genfile=True) + desc= + 'output cerebrum mask volume. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) outputLabelVolumeFile = File( - desc='output labeled hemisphere/cerebrum volume. If unspecified, output file name will be auto generated.', - argstr='-l %s', genfile=True) + desc= + 'output labeled hemisphere/cerebrum volume. If unspecified, output file name will be auto generated.', + argstr='-l %s', + genfile=True) costFunction = traits.Int(2, usedefault=True, desc='0,1,2', argstr='-c %d') useCentroids = traits.Bool( - desc='use centroids of data to initialize position', argstr='--centroids') + desc='use centroids of data to initialize position', + argstr='--centroids') outputAffineTransformFile = File( desc='save affine transform to file.', argstr='--air %s', genfile=True) outputWarpTransformFile = File( @@ -312,9 +356,11 @@ class CerebroInputSpec(CommandLineInputSpec): keepTempFiles = traits.Bool( desc="don't remove temporary files", argstr='--keep') tempDirectory = traits.Str( - desc='specify directory to use for temporary files', argstr='--tempdir %s') + desc='specify directory to use for temporary files', + argstr='--tempdir %s') tempDirectoryBase = traits.Str( - desc='create a temporary directory within this directory', argstr='--tempdirbase %s') + desc='create a temporary directory within this directory', + argstr='--tempdirbase %s') class CerebroOutputSpec(TraitedSpec): @@ -325,7 +371,6 @@ class CerebroOutputSpec(TraitedSpec): class Cerebro(CommandLine): - """ Cerebrum/cerebellum labeling tool This program performs automated labeling of cerebellum and cerebrum in T1 MRI. @@ -376,17 +421,28 @@ class CortexInputSpec(CommandLineInputSpec): inputHemisphereLabelFile = File( mandatory=True, desc='hemisphere / lobe label volume', argstr='-h %s') outputCerebrumMask = File( - desc='output structure mask. If unspecified, output file name will be auto generated.', argstr='-o %s', genfile=True) + desc= + 'output structure mask. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) inputTissueFractionFile = File( - mandatory=True, desc='tissue fraction file (32-bit float)', argstr='-f %s') + mandatory=True, + desc='tissue fraction file (32-bit float)', + argstr='-f %s') tissueFractionThreshold = traits.Float( - 50.0, usedefault=True, desc='tissue fraction threshold (percentage)', argstr='-p %f') + 50.0, + usedefault=True, + desc='tissue fraction threshold (percentage)', + argstr='-p %f') computeWGBoundary = traits.Bool( True, usedefault=True, desc='compute WM/GM boundary', argstr='-w') computeGCBoundary = traits.Bool( desc='compute GM/CSF boundary', argstr='-g') includeAllSubcorticalAreas = traits.Bool( - True, usedefault=True, desc='include all subcortical areas in WM mask', argstr='-a') + True, + usedefault=True, + desc='include all subcortical areas in WM mask', + argstr='-a') verbosity = traits.Int(desc='verbosity level', argstr='-v %d') timer = traits.Bool(desc='timing function', argstr='--timer') @@ -396,7 +452,6 @@ class CortexOutputSpec(TraitedSpec): class Cortex(CommandLine): - """ cortex extractor This program produces a cortical mask using tissue fraction estimates @@ -426,7 +481,8 @@ def _gen_filename(self, name): return os.path.abspath(inputs[name]) if name == 'outputCerebrumMask': - return getFileName(self.inputs.inputHemisphereLabelFile, '.init.cortex.mask.nii.gz') + return getFileName(self.inputs.inputHemisphereLabelFile, + '.init.cortex.mask.nii.gz') return None def _list_outputs(self): @@ -437,7 +493,10 @@ class ScrubmaskInputSpec(CommandLineInputSpec): inputMaskFile = File( mandatory=True, desc='input structure mask file', argstr='-i %s') outputMaskFile = File( - desc='output structure mask file. If unspecified, output file name will be auto generated.', argstr='-o %s', genfile=True) + desc= + 'output structure mask file. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) backgroundFillThreshold = traits.Int( 2, usedefault=True, desc='background fill threshold', argstr='-b %d') foregroundTrimThreshold = traits.Int( @@ -452,7 +511,6 @@ class ScrubmaskOutputSpec(TraitedSpec): class Scrubmask(CommandLine): - """ ScrubMask tool scrubmask filters binary masks to trim loosely connected voxels that may @@ -480,7 +538,8 @@ def _gen_filename(self, name): return os.path.abspath(inputs[name]) if name == 'outputMaskFile': - return getFileName(self.inputs.inputMaskFile, '.cortex.scrubbed.mask.nii.gz') + return getFileName(self.inputs.inputMaskFile, + '.cortex.scrubbed.mask.nii.gz') return None @@ -492,7 +551,10 @@ class TcaInputSpec(CommandLineInputSpec): inputMaskFile = File( mandatory=True, desc='input mask volume', argstr='-i %s') outputMaskFile = File( - desc='output mask volume. If unspecified, output file name will be auto generated.', argstr='-o %s', genfile=True) + desc= + 'output mask volume. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) minCorrectionSize = traits.Int( 2500, usedefault=True, desc='maximum correction size', argstr='-m %d') maxCorrectionSize = traits.Int( @@ -508,7 +570,6 @@ class TcaOutputSpec(TraitedSpec): class Tca(CommandLine): - """ topological correction algorithm (TCA) This program removes topological handles from a binary object. @@ -534,7 +595,8 @@ def _gen_filename(self, name): return os.path.abspath(inputs[name]) if name == 'outputMaskFile': - return getFileName(self.inputs.inputMaskFile, '.cortex.tca.mask.nii.gz') + return getFileName(self.inputs.inputMaskFile, + '.cortex.tca.mask.nii.gz') return None @@ -545,7 +607,10 @@ def _list_outputs(self): class DewispInputSpec(CommandLineInputSpec): inputMaskFile = File(mandatory=True, desc='input file', argstr='-i %s') outputMaskFile = File( - desc='output file. If unspecified, output file name will be auto generated.', argstr='-o %s', genfile=True) + desc= + 'output file. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) verbosity = traits.Int(desc='verbosity', argstr='-v %d') sizeThreshold = traits.Int(desc='size threshold', argstr='-t %d') maximumIterations = traits.Int( @@ -558,7 +623,6 @@ class DewispOutputSpec(TraitedSpec): class Dewisp(CommandLine): - """ dewisp removes wispy tendril structures from cortex model binary masks. @@ -591,7 +655,8 @@ def _gen_filename(self, name): return os.path.abspath(inputs[name]) if name == 'outputMaskFile': - return getFileName(self.inputs.inputMaskFile, '.cortex.dewisp.mask.nii.gz') + return getFileName(self.inputs.inputMaskFile, + '.cortex.dewisp.mask.nii.gz') return None @@ -603,22 +668,40 @@ class DfsInputSpec(CommandLineInputSpec): inputVolumeFile = File( mandatory=True, desc='input 3D volume', argstr='-i %s') outputSurfaceFile = File( - desc='output surface mesh file. If unspecified, output file name will be auto generated.', argstr='-o %s', genfile=True) + desc= + 'output surface mesh file. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) inputShadingVolume = File( desc='shade surface model with data from image volume', argstr='-c %s') smoothingIterations = traits.Int( - 10, usedefault=True, desc='number of smoothing iterations', argstr='-n %d') + 10, + usedefault=True, + desc='number of smoothing iterations', + argstr='-n %d') smoothingConstant = traits.Float( 0.5, usedefault=True, desc='smoothing constant', argstr='-a %f') curvatureWeighting = traits.Float( 5.0, usedefault=True, desc='curvature weighting', argstr='-w %f') scalingPercentile = traits.Float(desc='scaling percentile', argstr='-f %f') nonZeroTessellation = traits.Bool( - desc='tessellate non-zero voxels', argstr='-nz', xor=('nonZeroTessellation', 'specialTessellation')) + desc='tessellate non-zero voxels', + argstr='-nz', + xor=('nonZeroTessellation', 'specialTessellation')) tessellationThreshold = traits.Float( - desc='To be used with specialTessellation. Set this value first, then set specialTessellation value.\nUsage: tessellate voxels greater_than, less_than, or equal_to ', argstr='%f') - specialTessellation = traits.Enum('greater_than', 'less_than', 'equal_to', desc='To avoid throwing a UserWarning, set tessellationThreshold first. Then set this attribute.\nUsage: tessellate voxels greater_than, less_than, or equal_to ', argstr='%s', xor=( - 'nonZeroTessellation', 'specialTessellation'), requires=['tessellationThreshold'], position=-1) + desc= + 'To be used with specialTessellation. Set this value first, then set specialTessellation value.\nUsage: tessellate voxels greater_than, less_than, or equal_to ', + argstr='%f') + specialTessellation = traits.Enum( + 'greater_than', + 'less_than', + 'equal_to', + desc= + 'To avoid throwing a UserWarning, set tessellationThreshold first. Then set this attribute.\nUsage: tessellate voxels greater_than, less_than, or equal_to ', + argstr='%s', + xor=('nonZeroTessellation', 'specialTessellation'), + requires=['tessellationThreshold'], + position=-1) zeroPadFlag = traits.Bool( desc='zero-pad volume (avoids clipping at edges)', argstr='-z') noNormalsFlag = traits.Bool( @@ -634,7 +717,6 @@ class DfsOutputSpec(TraitedSpec): class Dfs(CommandLine): - """ Surface Generator Generates mesh surfaces using an isosurface algorithm. @@ -661,7 +743,11 @@ def _format_arg(self, name, spec, value): return '' # blank argstr if name == 'specialTessellation': threshold = self.inputs.tessellationThreshold - return spec.argstr % {"greater_than": ''.join(("-gt %f" % threshold)), "less_than": ''.join(("-lt %f" % threshold)), "equal_to": ''.join(("-eq %f" % threshold))}[value] + return spec.argstr % { + "greater_than": ''.join(("-gt %f" % threshold)), + "less_than": ''.join(("-lt %f" % threshold)), + "equal_to": ''.join(("-eq %f" % threshold)) + }[value] return super(Dfs, self)._format_arg(name, spec, value) def _gen_filename(self, name): @@ -670,7 +756,8 @@ def _gen_filename(self, name): return os.path.abspath(inputs[name]) if name == 'outputSurfaceFile': - return getFileName(self.inputs.inputVolumeFile, '.inner.cortex.dfs') + return getFileName(self.inputs.inputVolumeFile, + '.inner.cortex.dfs') return None @@ -681,35 +768,52 @@ def _list_outputs(self): class PialmeshInputSpec(CommandLineInputSpec): inputSurfaceFile = File(mandatory=True, desc='input file', argstr='-i %s') outputSurfaceFile = File( - desc='output file. If unspecified, output file name will be auto generated.', argstr='-o %s', genfile=True) + desc= + 'output file. If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) verbosity = traits.Int(desc='verbosity', argstr='-v %d') inputTissueFractionFile = File( - mandatory=True, desc='floating point (32) tissue fraction image', argstr='-f %s') + mandatory=True, + desc='floating point (32) tissue fraction image', + argstr='-f %s') numIterations = traits.Int( 100, usedefault=True, desc='number of iterations', argstr='-n %d') searchRadius = traits.Float( 1, usedefault=True, desc='search radius', argstr='-r %f') - stepSize = traits.Float(0.4, usedefault=True, - desc='step size', argstr='-s %f') + stepSize = traits.Float( + 0.4, usedefault=True, desc='step size', argstr='-s %f') inputMaskFile = File( - mandatory=True, desc='restrict growth to mask file region', argstr='-m %s') + mandatory=True, + desc='restrict growth to mask file region', + argstr='-m %s') maxThickness = traits.Float( - 20, usedefault=True, desc='maximum allowed tissue thickness', argstr='--max %f') + 20, + usedefault=True, + desc='maximum allowed tissue thickness', + argstr='--max %f') tissueThreshold = traits.Float( 1.05, usedefault=True, desc='tissue threshold', argstr='-t %f') -# output interval is not an output -- it specifies how frequently the -# output surfaces are generated + # output interval is not an output -- it specifies how frequently the + # output surfaces are generated outputInterval = traits.Int( 10, usedefault=True, desc='output interval', argstr='--interval %d') exportPrefix = traits.Str( - desc='prefix for exporting surfaces if interval is set', argstr='--prefix %s') + desc='prefix for exporting surfaces if interval is set', + argstr='--prefix %s') laplacianSmoothing = traits.Float( - 0.025, usedefault=True, desc='apply Laplacian smoothing', argstr='--smooth %f') + 0.025, + usedefault=True, + desc='apply Laplacian smoothing', + argstr='--smooth %f') timer = traits.Bool(desc='show timing', argstr='--timer') recomputeNormals = traits.Bool( desc='recompute normals at each iteration', argstr='--norm') normalSmoother = traits.Float( - 0.2, usedefault=True, desc='strength of normal smoother.', argstr='--nc %f') + 0.2, + usedefault=True, + desc='strength of normal smoother.', + argstr='--nc %f') tangentSmoother = traits.Float( desc='strength of tangential smoother.', argstr='--tc %f') @@ -719,7 +823,6 @@ class PialmeshOutputSpec(TraitedSpec): class Pialmesh(CommandLine): - """ pialmesh computes a pial surface model using an inner WM/GM mesh and a tissue fraction map. @@ -749,7 +852,8 @@ def _gen_filename(self, name): return os.path.abspath(inputs[name]) if name == 'outputSurfaceFile': - return getFileName(self.inputs.inputSurfaceFile, '.pial.cortex.dfs') + return getFileName(self.inputs.inputSurfaceFile, + '.pial.cortex.dfs') return None @@ -763,15 +867,28 @@ class HemisplitInputSpec(CommandLineInputSpec): inputHemisphereLabelFile = File( mandatory=True, desc='input hemisphere label volume', argstr='-l %s') outputLeftHemisphere = File( - desc='output surface file, left hemisphere. If unspecified, output file name will be auto generated.', argstr='--left %s', genfile=True) + desc= + 'output surface file, left hemisphere. If unspecified, output file name will be auto generated.', + argstr='--left %s', + genfile=True) outputRightHemisphere = File( - desc='output surface file, right hemisphere. If unspecified, output file name will be auto generated.', argstr='--right %s', genfile=True) + desc= + 'output surface file, right hemisphere. If unspecified, output file name will be auto generated.', + argstr='--right %s', + genfile=True) pialSurfaceFile = File( - desc='pial surface file -- must have same geometry as input surface', argstr='-p %s') + desc='pial surface file -- must have same geometry as input surface', + argstr='-p %s') outputLeftPialHemisphere = File( - desc='output pial surface file, left hemisphere. If unspecified, output file name will be auto generated.', argstr='-pl %s', genfile=True) + desc= + 'output pial surface file, left hemisphere. If unspecified, output file name will be auto generated.', + argstr='-pl %s', + genfile=True) outputRightPialHemisphere = File( - desc='output pial surface file, right hemisphere. If unspecified, output file name will be auto generated.', argstr='-pr %s', genfile=True) + desc= + 'output pial surface file, right hemisphere. If unspecified, output file name will be auto generated.', + argstr='-pr %s', + genfile=True) verbosity = traits.Int(desc='verbosity (0 = silent)', argstr='-v %d') timer = traits.Bool(desc='timing function', argstr='--timer') @@ -784,7 +901,6 @@ class HemisplitOutputSpec(TraitedSpec): class Hemisplit(CommandLine): - """ Hemisphere splitter Splits a surface object into two separate surfaces given an input label volume. @@ -820,7 +936,8 @@ def _gen_filename(self, name): 'outputRightPialHemisphere': '.right.pial.cortex.dfs' } if name in fileToSuffixMap: - return getFileName(self.inputs.inputSurfaceFile, fileToSuffixMap[name]) + return getFileName(self.inputs.inputSurfaceFile, + fileToSuffixMap[name]) return None @@ -831,18 +948,23 @@ def _list_outputs(self): class SkullfinderInputSpec(CommandLineInputSpec): inputMRIFile = File(mandatory=True, desc='input file', argstr='-i %s') inputMaskFile = File( - mandatory=True, desc='A brain mask file, 8-bit image (0=non-brain, 255=brain)', argstr='-m %s') + mandatory=True, + desc='A brain mask file, 8-bit image (0=non-brain, 255=brain)', + argstr='-m %s') outputLabelFile = File( - desc='output multi-colored label volume segmenting brain, scalp, inner skull & outer skull ' - 'If unspecified, output file name will be auto generated.', - argstr='-o %s', genfile=True) + desc= + 'output multi-colored label volume segmenting brain, scalp, inner skull & outer skull ' + 'If unspecified, output file name will be auto generated.', + argstr='-o %s', + genfile=True) verbosity = traits.Int(desc='verbosity', argstr='-v %d') lowerThreshold = traits.Int( desc='Lower threshold for segmentation', argstr='-l %d') upperThreshold = traits.Int( desc='Upper threshold for segmentation', argstr='-u %d') surfaceFilePrefix = traits.Str( - desc='if specified, generate surface files for brain, skull, and scalp', argstr='-s %s') + desc='if specified, generate surface files for brain, skull, and scalp', + argstr='-s %s') bgLabelValue = traits.Int( desc='background label value (0-255)', argstr='--bglabel %d') scalpLabelValue = traits.Int( @@ -854,7 +976,8 @@ class SkullfinderInputSpec(CommandLineInputSpec): brainLabelValue = traits.Int( desc='brain label value (0-255)', argstr='--brainlabel %d') performFinalOpening = traits.Bool( - desc='perform a final opening operation on the scalp mask', argstr='--finalOpening') + desc='perform a final opening operation on the scalp mask', + argstr='--finalOpening') class SkullfinderOutputSpec(TraitedSpec): @@ -862,7 +985,6 @@ class SkullfinderOutputSpec(TraitedSpec): class Skullfinder(CommandLine): - """ Skull and scalp segmentation algorithm. @@ -887,7 +1009,8 @@ def _gen_filename(self, name): return os.path.abspath(inputs[name]) if name == 'outputLabelFile': - return getFileName(self.inputs.inputMRIFile, '.skullfinder.label.nii.gz') + return getFileName(self.inputs.inputMRIFile, + '.skullfinder.label.nii.gz') return None @@ -897,123 +1020,119 @@ def _list_outputs(self): class SVRegInputSpec(CommandLineInputSpec): subjectFilePrefix = traits.Str( - argstr='\'%s\'', mandatory=True, position=0, - desc='Absolute path and filename prefix of the subjects output from BrainSuite ' - 'Cortical Surface Extraction Sequence' - ) + argstr='\'%s\'', + mandatory=True, + position=0, + desc= + 'Absolute path and filename prefix of the subjects output from BrainSuite ' + 'Cortical Surface Extraction Sequence') dataSinkDelay = traits.List( - traits.Str, argstr='%s', - desc='Connect datasink out_file to dataSinkDelay to delay execution of SVReg ' - 'until dataSink has finished sinking CSE outputs.' - 'For use with parallel processing workflows including Brainsuites Cortical ' - 'Surface Extraction sequence (SVReg requires certain files from Brainsuite ' - 'CSE, which must all be in the pathway specified by subjectFilePrefix. see ' - 'http://brainsuite.org/processing/svreg/usage/ for list of required inputs ' + traits.Str, + argstr='%s', + desc= + 'Connect datasink out_file to dataSinkDelay to delay execution of SVReg ' + 'until dataSink has finished sinking CSE outputs.' + 'For use with parallel processing workflows including Brainsuites Cortical ' + 'Surface Extraction sequence (SVReg requires certain files from Brainsuite ' + 'CSE, which must all be in the pathway specified by subjectFilePrefix. see ' + 'http://brainsuite.org/processing/svreg/usage/ for list of required inputs ' ) atlasFilePrefix = traits.Str( - position=1, argstr='\'%s\'', - desc='Optional: Absolute Path and filename prefix of atlas files and labels to which ' - 'the subject will be registered. If unspecified, SVReg' - 'will use its own included atlas files' - ) + position=1, + argstr='\'%s\'', + desc= + 'Optional: Absolute Path and filename prefix of atlas files and labels to which ' + 'the subject will be registered. If unspecified, SVReg' + 'will use its own included atlas files') iterations = traits.Int( argstr='\'-H %d\'', desc='Assigns a number of iterations in the intensity registration step.' - 'if unspecified, performs 100 iterations' - ) + 'if unspecified, performs 100 iterations') refineOutputs = traits.Bool( argstr='\'-r\'', - desc='Refine outputs at the expense of more processing time.' - ) + desc='Refine outputs at the expense of more processing time.') skipToVolumeReg = traits.Bool( argstr='\'-s\'', - desc='If surface registration was already performed at an earlier time and the ' - 'user would not like to redo this step, then this flag may be used to skip ' - 'ahead to the volumetric registration. Necessary input files will need to ' - 'be present in the input directory called by the command.' - ) + desc= + 'If surface registration was already performed at an earlier time and the ' + 'user would not like to redo this step, then this flag may be used to skip ' + 'ahead to the volumetric registration. Necessary input files will need to ' + 'be present in the input directory called by the command.') skipToIntensityReg = traits.Bool( argstr='\'-p\'', - desc='If the p-harmonic volumetric registration was already performed at an ' - 'earlier time and the user would not like to redo this step, then this ' - 'flag may be used to skip ahead to the intensity registration and ' - 'label transfer step.' - ) + desc= + 'If the p-harmonic volumetric registration was already performed at an ' + 'earlier time and the user would not like to redo this step, then this ' + 'flag may be used to skip ahead to the intensity registration and ' + 'label transfer step.') useManualMaskFile = traits.Bool( argstr='\'-cbm\'', - desc='Can call a manually edited cerebrum mask to limit boundaries. Will ' - 'use file: subbasename.cerebrum.mask.nii.gz Make sure to correctly ' - 'replace your manually edited mask file in your input folder with the ' - 'correct subbasename.' - ) + desc= + 'Can call a manually edited cerebrum mask to limit boundaries. Will ' + 'use file: subbasename.cerebrum.mask.nii.gz Make sure to correctly ' + 'replace your manually edited mask file in your input folder with the ' + 'correct subbasename.') curveMatchingInstructions = traits.Str( argstr='\'-cur %s\'', - desc='Used to take control of the curve matching process between the atlas ' - 'and subject. One can specify the name of the .dfc file and ' - 'the sulcal numbers <#sul> to be used as constraints. ' - 'example: curveMatchingInstructions = "subbasename.right.dfc 1 2 20"' - ) + desc= + 'Used to take control of the curve matching process between the atlas ' + 'and subject. One can specify the name of the .dfc file and ' + 'the sulcal numbers <#sul> to be used as constraints. ' + 'example: curveMatchingInstructions = "subbasename.right.dfc 1 2 20"') useCerebrumMask = traits.Bool( argstr='\'-C\'', - desc='The cerebrum mask will be used for ' - 'masking the final labels instead of the default pial surface mask. ' - 'Every voxel will be labeled within the cerebrum mask regardless of ' - 'the boundaries of the pial surface.' - ) + desc= + 'The cerebrum mask will be used for ' + 'masking the final labels instead of the default pial surface mask. ' + 'Every voxel will be labeled within the cerebrum mask regardless of ' + 'the boundaries of the pial surface.') pialSurfaceMaskDilation = traits.Int( argstr='\'-D %d\'', - desc='Cortical volume labels found in file output subbasename.svreg.label.nii.gz ' - 'find its boundaries by using the pial surface then dilating by 1 voxel. ' - 'Use this flag in order to control the number of pial surface mask dilation. ' - '(ie. -D 0 will assign no voxel dilation)' - ) + desc= + 'Cortical volume labels found in file output subbasename.svreg.label.nii.gz ' + 'find its boundaries by using the pial surface then dilating by 1 voxel. ' + 'Use this flag in order to control the number of pial surface mask dilation. ' + '(ie. -D 0 will assign no voxel dilation)') keepIntermediates = traits.Bool( argstr='\'-k\'', desc='Keep the intermediate files after the svreg sequence is complete.' ) _XOR_verbosity = ('verbosity0', 'verbosity1', 'verbosity2') verbosity0 = traits.Bool( - argstr='\'-v0\'', xor=_XOR_verbosity, - desc='no messages will be reported' - ) + argstr='\'-v0\'', + xor=_XOR_verbosity, + desc='no messages will be reported') verbosity1 = traits.Bool( - argstr='\'-v1\'', xor=_XOR_verbosity, - desc='messages will be reported but not the iteration-wise detailed messages' + argstr='\'-v1\'', + xor=_XOR_verbosity, + desc= + 'messages will be reported but not the iteration-wise detailed messages' ) verbosity2 = traits.Bool( - argstr='\'v2\'', xor=_XOR_verbosity, - desc='all the messages, including per-iteration, will be displayed' - ) + argstr='\'v2\'', + xor=_XOR_verbosity, + desc='all the messages, including per-iteration, will be displayed') shortMessages = traits.Bool( - argstr='\'-gui\'', - desc='Short messages instead of detailed messages' - ) + argstr='\'-gui\'', desc='Short messages instead of detailed messages') displayModuleName = traits.Bool( - argstr='\'-m\'', - desc='Module name will be displayed in the messages' - ) + argstr='\'-m\'', desc='Module name will be displayed in the messages') displayTimestamps = traits.Bool( - argstr='\'-t\'', - desc='Timestamps will be displayed in the messages' - ) + argstr='\'-t\'', desc='Timestamps will be displayed in the messages') skipVolumetricProcessing = traits.Bool( argstr='\'-S\'', - desc='Only surface registration and labeling will be performed. Volumetric ' - 'processing will be skipped.' - ) + desc= + 'Only surface registration and labeling will be performed. Volumetric ' + 'processing will be skipped.') useMultiThreading = traits.Bool( argstr='\'-P\'', - desc='If multiple CPUs are present on the system, the code will try to use ' - 'multithreading to make the execution fast.' - ) + desc= + 'If multiple CPUs are present on the system, the code will try to use ' + 'multithreading to make the execution fast.') useSingleThreading = traits.Bool( - argstr='\'-U\'', - desc='Use single threaded mode.' - ) + argstr='\'-U\'', desc='Use single threaded mode.') class SVReg(CommandLine): - """ surface and volume registration (svreg) This program registers a subject's BrainSuite-processed volume and surfaces @@ -1052,485 +1171,508 @@ def _format_arg(self, name, spec, value): class BDPInputSpec(CommandLineInputSpec): bfcFile = File( - argstr='%s', mandatory=True, position=0, xor=['noStructuralRegistration'], - desc='Specify absolute path to file produced by bfc. By default, bfc produces the file in ' - 'the format: prefix.bfc.nii.gz' - ) + argstr='%s', + mandatory=True, + position=0, + xor=['noStructuralRegistration'], + desc= + 'Specify absolute path to file produced by bfc. By default, bfc produces the file in ' + 'the format: prefix.bfc.nii.gz') noStructuralRegistration = traits.Bool( - argstr='--no-structural-registration', mandatory=True, position=0, xor=['bfcFile'], - desc='Allows BDP to work without any structural input. This can useful when ' - 'one is only interested in diffusion modelling part of BDP. With this ' - 'flag only fieldmap-based distortion correction is supported. ' - 'outPrefix can be used to specify fileprefix of the output ' - 'filenames. Change dwiMask to define region of interest ' - 'for diffusion modelling.' - ) + argstr='--no-structural-registration', + mandatory=True, + position=0, + xor=['bfcFile'], + desc= + 'Allows BDP to work without any structural input. This can useful when ' + 'one is only interested in diffusion modelling part of BDP. With this ' + 'flag only fieldmap-based distortion correction is supported. ' + 'outPrefix can be used to specify fileprefix of the output ' + 'filenames. Change dwiMask to define region of interest ' + 'for diffusion modelling.') inputDiffusionData = File( - argstr='--nii %s', mandatory=True, position=-2, - desc='Specifies the absolute path and filename of the input diffusion data in 4D NIfTI-1 ' - 'format. The flag must be followed by the filename. Only NIfTI-1 files ' - 'with extension .nii or .nii.gz are supported. Furthermore, either ' - 'bMatrixFile, or a combination of both bValueFile and diffusionGradientFile ' - 'must be used to provide the necessary b-matrices/b-values and gradient vectors. ' + argstr='--nii %s', + mandatory=True, + position=-2, + desc= + 'Specifies the absolute path and filename of the input diffusion data in 4D NIfTI-1 ' + 'format. The flag must be followed by the filename. Only NIfTI-1 files ' + 'with extension .nii or .nii.gz are supported. Furthermore, either ' + 'bMatrixFile, or a combination of both bValueFile and diffusionGradientFile ' + 'must be used to provide the necessary b-matrices/b-values and gradient vectors. ' ) bMatrixFile = File( - argstr='--bmat %s', mandatory=True, xor=['BVecBValPair'], position=-1, - desc='Specifies the absolute path and filename of the file containing b-matrices for ' - 'diffusion-weighted scans. The flag must be followed by the filename. ' - 'This file must be a plain text file containing 3x3 matrices for each ' - 'diffusion encoding direction. It should contain zero matrices ' - 'corresponding to b=0 images. This file usually has ".bmat" as its ' - 'extension, and can be used to provide BDP with the more-accurate ' - 'b-matrices as saved by some proprietary scanners. The b-matrices ' - 'specified by the file must be in the voxel coordinates of the input ' - 'diffusion weighted image (NIfTI file). In case b-matrices are not known/calculated, ' - 'bvec and .bval files can be used instead (see diffusionGradientFile and bValueFile). ' + argstr='--bmat %s', + mandatory=True, + xor=['BVecBValPair'], + position=-1, + desc= + 'Specifies the absolute path and filename of the file containing b-matrices for ' + 'diffusion-weighted scans. The flag must be followed by the filename. ' + 'This file must be a plain text file containing 3x3 matrices for each ' + 'diffusion encoding direction. It should contain zero matrices ' + 'corresponding to b=0 images. This file usually has ".bmat" as its ' + 'extension, and can be used to provide BDP with the more-accurate ' + 'b-matrices as saved by some proprietary scanners. The b-matrices ' + 'specified by the file must be in the voxel coordinates of the input ' + 'diffusion weighted image (NIfTI file). In case b-matrices are not known/calculated, ' + 'bvec and .bval files can be used instead (see diffusionGradientFile and bValueFile). ' ) BVecBValPair = traits.List( - traits.Str, minlen=2, maxlen=2, mandatory=True, position=-1, xor=['bMatrixFile'], + traits.Str, + minlen=2, + maxlen=2, + mandatory=True, + position=-1, + xor=['bMatrixFile'], argstr='--bvec %s --bval %s', - desc='Must input a list containing first the BVector file, then the BValue file (both must be absolute paths)\n' - 'Example: bdp.inputs.BVecBValPair = [\'/directory/subdir/prefix.dwi.bvec\', \'/directory/subdir/prefix.dwi.bval\'] ' - 'The first item in the list specifies the filename of the file containing b-values for the ' - 'diffusion scan. The b-value file must be a plain-text file and usually has an ' - 'extension of .bval\n' - 'The second item in the list specifies the filename of the file containing the diffusion gradient ' - 'directions (specified in the voxel coordinates of the input ' - 'diffusion-weighted image)The b-vectors file must be a plain text file and ' - 'usually has an extension of .bvec ' - ) + desc= + 'Must input a list containing first the BVector file, then the BValue file (both must be absolute paths)\n' + 'Example: bdp.inputs.BVecBValPair = [\'/directory/subdir/prefix.dwi.bvec\', \'/directory/subdir/prefix.dwi.bval\'] ' + 'The first item in the list specifies the filename of the file containing b-values for the ' + 'diffusion scan. The b-value file must be a plain-text file and usually has an ' + 'extension of .bval\n' + 'The second item in the list specifies the filename of the file containing the diffusion gradient ' + 'directions (specified in the voxel coordinates of the input ' + 'diffusion-weighted image)The b-vectors file must be a plain text file and ' + 'usually has an extension of .bvec ') dataSinkDelay = traits.List( - traits.Str, argstr='%s', - desc='For use in parallel processing workflows including Brainsuite Cortical ' - 'Surface Extraction sequence. Connect datasink out_file to dataSinkDelay ' - 'to delay execution of BDP until dataSink has finished sinking outputs. ' - 'In particular, BDP may be run after BFC has finished. For more information ' - 'see http://brainsuite.org/processing/diffusion/pipeline/' - ) + traits.Str, + argstr='%s', + desc= + 'For use in parallel processing workflows including Brainsuite Cortical ' + 'Surface Extraction sequence. Connect datasink out_file to dataSinkDelay ' + 'to delay execution of BDP until dataSink has finished sinking outputs. ' + 'In particular, BDP may be run after BFC has finished. For more information ' + 'see http://brainsuite.org/processing/diffusion/pipeline/') phaseEncodingDirection = traits.Enum( - 'x', 'x-', 'y', 'y-', 'z', 'z-', + 'x', + 'x-', + 'y', + 'y-', + 'z', + 'z-', argstr='--dir=%s', - desc='Specifies the phase-encoding direction of the EPI (diffusion) images. ' - 'It is same as the dominant direction of distortion in the images. This ' - 'information is used to constrain the distortion correction along the ' - 'specified direction. Directions are represented by any one of x, x-, y, ' - 'y-, z or z-. "x" direction increases towards the right side of the ' - 'subject, while "x-" increases towards the left side of the subject. ' - 'Similarly, "y" and "y-" are along the anterior-posterior direction of ' - 'the subject, and "z" & "z-" are along the inferior-superior direction. ' - 'When this flag is not used, BDP uses "y" as the default phase-encoding ' - 'direction. ' - ) + desc= + 'Specifies the phase-encoding direction of the EPI (diffusion) images. ' + 'It is same as the dominant direction of distortion in the images. This ' + 'information is used to constrain the distortion correction along the ' + 'specified direction. Directions are represented by any one of x, x-, y, ' + 'y-, z or z-. "x" direction increases towards the right side of the ' + 'subject, while "x-" increases towards the left side of the subject. ' + 'Similarly, "y" and "y-" are along the anterior-posterior direction of ' + 'the subject, and "z" & "z-" are along the inferior-superior direction. ' + 'When this flag is not used, BDP uses "y" as the default phase-encoding ' + 'direction. ') echoSpacing = traits.Float( argstr='--echo-spacing=%f', - desc='Sets the echo spacing to t seconds, which is used for fieldmap-based ' - 'distortion correction. This flag is required when using fieldmapCorrection' + desc= + 'Sets the echo spacing to t seconds, which is used for fieldmap-based ' + 'distortion correction. This flag is required when using fieldmapCorrection' ) bValRatioThreshold = traits.Float( argstr='--bval-ratio-threshold %f', - desc='Sets a threshold which is used to determine b=0 images. When there are ' - 'no diffusion weighted image with b-value of zero, then BDP tries to use ' - 'diffusion weighted images with a low b-value in place of b=0 image. The ' - 'diffusion images with minimum b-value is used as b=0 image only if the ' - 'ratio of the maximum and minimum b-value is more than the specified ' - 'threshold. A lower value of threshold will allow diffusion images with ' - 'higher b-value to be used as b=0 image. The default value of this ' - 'threshold is set to 45, if this trait is not set. ' - ) + desc= + 'Sets a threshold which is used to determine b=0 images. When there are ' + 'no diffusion weighted image with b-value of zero, then BDP tries to use ' + 'diffusion weighted images with a low b-value in place of b=0 image. The ' + 'diffusion images with minimum b-value is used as b=0 image only if the ' + 'ratio of the maximum and minimum b-value is more than the specified ' + 'threshold. A lower value of threshold will allow diffusion images with ' + 'higher b-value to be used as b=0 image. The default value of this ' + 'threshold is set to 45, if this trait is not set. ') estimateTensors = traits.Bool( argstr='--tensors', - desc='Estimates diffusion tensors using a weighted log-linear estimation and ' - 'saves derived diffusion tensor parameters (FA, MD, axial, radial, L2, ' - 'L3). This is the default behavior if no diffusion modeling flags are ' - 'specified. The estimated diffusion tensors can be visualized by loading ' - 'the saved *.eig.nii.gz file in BrainSuite. BDP reports diffusivity (MD, ' - 'axial, radial, L2 and L3) in a unit which is reciprocal inverse of the ' - 'unit of input b-value. ' - ) + desc= + 'Estimates diffusion tensors using a weighted log-linear estimation and ' + 'saves derived diffusion tensor parameters (FA, MD, axial, radial, L2, ' + 'L3). This is the default behavior if no diffusion modeling flags are ' + 'specified. The estimated diffusion tensors can be visualized by loading ' + 'the saved *.eig.nii.gz file in BrainSuite. BDP reports diffusivity (MD, ' + 'axial, radial, L2 and L3) in a unit which is reciprocal inverse of the ' + 'unit of input b-value. ') estimateODF_FRACT = traits.Bool( argstr='--FRACT', - desc='Estimates ODFs using the Funk-Radon and Cosine Transformation (FRACT). ' - 'The outputs are saved in a separate directory with name "FRACT" and the ' - 'ODFs can be visualized by loading the saved ".odf" file in BrainSuite. ' + desc= + 'Estimates ODFs using the Funk-Radon and Cosine Transformation (FRACT). ' + 'The outputs are saved in a separate directory with name "FRACT" and the ' + 'ODFs can be visualized by loading the saved ".odf" file in BrainSuite. ' ) estimateODF_FRT = traits.Bool( argstr='--FRT', - desc='Estimates ODFs using Funk-Radon Transformation (FRT). The coefficient ' - 'maps for ODFs are saved in a separate directory with name "FRT" and the ' - 'ODFs can be visualized by loading the saved ".odf" file in BrainSuite. ' - 'The derived generalized-FA (GFA) maps are also saved in the output ' - 'directory. ' - ) + desc= + 'Estimates ODFs using Funk-Radon Transformation (FRT). The coefficient ' + 'maps for ODFs are saved in a separate directory with name "FRT" and the ' + 'ODFs can be visualized by loading the saved ".odf" file in BrainSuite. ' + 'The derived generalized-FA (GFA) maps are also saved in the output ' + 'directory. ') estimateODF_3DShore = traits.Float( argstr='--3dshore --diffusion_time_ms %f', - desc='Estimates ODFs using 3Dshore. Pass in diffusion time, in ms' - ) + desc='Estimates ODFs using 3Dshore. Pass in diffusion time, in ms') odfLambta = traits.Bool( argstr='--odf-lambda ', - desc='Sets the regularization parameter, lambda, of the Laplace-Beltrami ' - 'operator while estimating ODFs. The default value is set to 0.006 . This ' - 'can be used to set the appropriate regularization for the input ' - 'diffusion data. ' - ) + desc= + 'Sets the regularization parameter, lambda, of the Laplace-Beltrami ' + 'operator while estimating ODFs. The default value is set to 0.006 . This ' + 'can be used to set the appropriate regularization for the input ' + 'diffusion data. ') t1Mask = File( argstr='--t1-mask %s', - desc='Specifies the filename of the brain-mask file for input T1-weighted ' - 'image. This mask can be same as the brain mask generated during ' - 'BrainSuite extraction sequence. For best results, the mask should not ' - 'include any extra-meningial tissues from T1-weighted image. The mask ' - 'must be in the same coordinates as input T1-weighted image (i.e. should ' - 'overlay correctly with input .bfc.nii.gz file in ' - 'BrainSuite). This mask is used for co-registration and defining brain ' - 'boundary for statistics computation. The mask can be generated and/or ' - 'edited in BrainSuite. In case outputDiffusionCoordinates is also ' - 'used, this mask is first transformed to diffusion coordinate and the ' - 'transformed mask is used for defining brain boundary in diffusion ' - 'coordinates. When t1Mask is not set, BDP will try to use ' - 'fileprefix>.mask.nii.gz as brain-mask. If .mask.nii.gz is ' - 'not found, then BDP will use the input .bfc.nii.gz itself as ' - 'mask (i.e. all non-zero voxels in .bfc.nii.gz is assumed to ' - 'constitute brain mask). ' - ) + desc= + 'Specifies the filename of the brain-mask file for input T1-weighted ' + 'image. This mask can be same as the brain mask generated during ' + 'BrainSuite extraction sequence. For best results, the mask should not ' + 'include any extra-meningial tissues from T1-weighted image. The mask ' + 'must be in the same coordinates as input T1-weighted image (i.e. should ' + 'overlay correctly with input .bfc.nii.gz file in ' + 'BrainSuite). This mask is used for co-registration and defining brain ' + 'boundary for statistics computation. The mask can be generated and/or ' + 'edited in BrainSuite. In case outputDiffusionCoordinates is also ' + 'used, this mask is first transformed to diffusion coordinate and the ' + 'transformed mask is used for defining brain boundary in diffusion ' + 'coordinates. When t1Mask is not set, BDP will try to use ' + 'fileprefix>.mask.nii.gz as brain-mask. If .mask.nii.gz is ' + 'not found, then BDP will use the input .bfc.nii.gz itself as ' + 'mask (i.e. all non-zero voxels in .bfc.nii.gz is assumed to ' + 'constitute brain mask). ') dwiMask = File( argstr='--dwi-mask %s', - desc='Specifies the filename of the brain-mask file for diffusion data. This ' - 'mask is used only for co-registration purposes and can affect overall ' - 'quality of co-registration (see t1Mask for definition of brain mask ' - 'for statistics computation). The mask must be a 3D volume and should be ' - 'in the same coordinates as input Diffusion file/data (i.e. should ' - 'overlay correctly with input diffusion data in BrainSuite). For best ' - 'results, the mask should include only brain voxels (CSF voxels around ' - 'brain is also acceptable). When this flag is not used, BDP will generate ' - 'a pseudo mask using first b=0 image volume and would save it as ' - 'fileprefix>.dwi.RSA.mask.nii.gz. In case co-registration is not ' - 'accurate with automatically generated pseudo mask, BDP should be re-run ' - 'with a refined diffusion mask. The mask can be generated and/or edited ' - 'in BrainSuite. ' - ) + desc= + 'Specifies the filename of the brain-mask file for diffusion data. This ' + 'mask is used only for co-registration purposes and can affect overall ' + 'quality of co-registration (see t1Mask for definition of brain mask ' + 'for statistics computation). The mask must be a 3D volume and should be ' + 'in the same coordinates as input Diffusion file/data (i.e. should ' + 'overlay correctly with input diffusion data in BrainSuite). For best ' + 'results, the mask should include only brain voxels (CSF voxels around ' + 'brain is also acceptable). When this flag is not used, BDP will generate ' + 'a pseudo mask using first b=0 image volume and would save it as ' + 'fileprefix>.dwi.RSA.mask.nii.gz. In case co-registration is not ' + 'accurate with automatically generated pseudo mask, BDP should be re-run ' + 'with a refined diffusion mask. The mask can be generated and/or edited ' + 'in BrainSuite. ') rigidRegMeasure = traits.Enum( - 'MI', 'INVERSION', 'BDP', + 'MI', + 'INVERSION', + 'BDP', argstr='--rigid-reg-measure %s', desc='Defines the similarity measure to be used for rigid registration. ' - 'Possible measures are "MI", "INVERSION" and "BDP". MI measure uses ' - 'normalized mutual information based cost function. INVERSION measure ' - 'uses simpler cost function based on sum of squared difference by ' - 'exploiting the approximate inverse-contrast relationship in T1- and ' - 'T2-weighted images. BDP measure combines MI and INVERSION. It starts ' - 'with INVERSION measure and refines the result with MI measure. BDP is ' - 'the default measure when this trait is not set. ' - ) + 'Possible measures are "MI", "INVERSION" and "BDP". MI measure uses ' + 'normalized mutual information based cost function. INVERSION measure ' + 'uses simpler cost function based on sum of squared difference by ' + 'exploiting the approximate inverse-contrast relationship in T1- and ' + 'T2-weighted images. BDP measure combines MI and INVERSION. It starts ' + 'with INVERSION measure and refines the result with MI measure. BDP is ' + 'the default measure when this trait is not set. ') dcorrRegMeasure = traits.Enum( - 'MI', 'INVERSION-EPI', 'INVERSION-T1', 'INVERSION-BOTH', 'BDP', + 'MI', + 'INVERSION-EPI', + 'INVERSION-T1', + 'INVERSION-BOTH', + 'BDP', argstr='--dcorr-reg-method %s', desc='Defines the method for registration-based distortion correction. ' - 'Possible methods are "MI", "INVERSION-EPI", "INVERSION-T1", ' - 'INVERSION-BOTH", and "BDP". MI method uses normalized mutual ' - 'information based cost-function while estimating the distortion field. ' - 'INVERSION-based method uses simpler cost function based on sum of ' - 'squared difference by exploiting the known approximate contrast ' - 'relationship in T1- and T2-weighted images. T2-weighted EPI is inverted ' - 'when INVERSION-EPI is used; T1-image is inverted when INVERSION-T1 is ' - 'used; and both are inverted when INVERSION-BOTH is used. BDP method add ' - 'the MI-based refinement after the correction using INVERSION-BOTH ' - 'method. BDP is the default method when this trait is not set. ' - ) + 'Possible methods are "MI", "INVERSION-EPI", "INVERSION-T1", ' + 'INVERSION-BOTH", and "BDP". MI method uses normalized mutual ' + 'information based cost-function while estimating the distortion field. ' + 'INVERSION-based method uses simpler cost function based on sum of ' + 'squared difference by exploiting the known approximate contrast ' + 'relationship in T1- and T2-weighted images. T2-weighted EPI is inverted ' + 'when INVERSION-EPI is used; T1-image is inverted when INVERSION-T1 is ' + 'used; and both are inverted when INVERSION-BOTH is used. BDP method add ' + 'the MI-based refinement after the correction using INVERSION-BOTH ' + 'method. BDP is the default method when this trait is not set. ') dcorrWeight = traits.Float( argstr='--dcorr-regularization-wt %f', - desc='Sets the (scalar) weighting parameter for regularization penalty in ' - 'registration-based distortion correction. Set this trait to a single, non-negative ' - 'number which specifies the weight. A large regularization weight encourages ' - 'smoother distortion field at the cost of low measure of image similarity ' - 'after distortion correction. On the other hand, a smaller regularization ' - 'weight can result into higher measure of image similarity but with ' - 'unrealistic and unsmooth distortion field. A weight of 0.5 would reduce ' - 'the penalty to half of the default regularization penalty (By default, this weight ' - 'is set to 1.0). Similarly, a weight of 2.0 ' - 'would increase the penalty to twice of the default penalty. ' - ) + desc= + 'Sets the (scalar) weighting parameter for regularization penalty in ' + 'registration-based distortion correction. Set this trait to a single, non-negative ' + 'number which specifies the weight. A large regularization weight encourages ' + 'smoother distortion field at the cost of low measure of image similarity ' + 'after distortion correction. On the other hand, a smaller regularization ' + 'weight can result into higher measure of image similarity but with ' + 'unrealistic and unsmooth distortion field. A weight of 0.5 would reduce ' + 'the penalty to half of the default regularization penalty (By default, this weight ' + 'is set to 1.0). Similarly, a weight of 2.0 ' + 'would increase the penalty to twice of the default penalty. ') skipDistortionCorr = traits.Bool( argstr='--no-distortion-correction', desc='Skips distortion correction completely and performs only a rigid ' - 'registration of diffusion and T1-weighted image. This can be useful when ' - 'the input diffusion images do not have any distortion or they have been ' - 'corrected for distortion. ' - ) + 'registration of diffusion and T1-weighted image. This can be useful when ' + 'the input diffusion images do not have any distortion or they have been ' + 'corrected for distortion. ') skipNonuniformityCorr = traits.Bool( argstr='--no-nonuniformity-correction', desc='Skips intensity non-uniformity correction in b=0 image for ' - 'registration-based distortion correction. The intensity non-uniformity ' - 'correction does not affect any diffusion modeling. ' - ) + 'registration-based distortion correction. The intensity non-uniformity ' + 'correction does not affect any diffusion modeling. ') skipIntensityCorr = traits.Bool( - argstr='--no-intensity-correction', xor=['fieldmapCorrectionMethod'], - desc='Disables intensity correction when performing distortion correction. ' - 'Intensity correction can change the noise distribution in the corrected ' - 'image, but it does not affect estimated diffusion parameters like FA, ' - 'etc. ' - ) + argstr='--no-intensity-correction', + xor=['fieldmapCorrectionMethod'], + desc= + 'Disables intensity correction when performing distortion correction. ' + 'Intensity correction can change the noise distribution in the corrected ' + 'image, but it does not affect estimated diffusion parameters like FA, ' + 'etc. ') fieldmapCorrection = File( - argstr='--fieldmap-correction %s', requires=['echoSpacing'], - desc='Use an acquired fieldmap for distortion correction. The fieldmap must ' - 'have units of radians/second. Specify the filename of the fieldmap file. ' - 'The field of view (FOV) of the fieldmap scan must cover the FOV of the diffusion ' - 'scan. BDP will try to check the overlap of the FOV of the two scans and ' - 'will issue a warning/error if the diffusion scan"s FOV is not fully ' - 'covered by the fieldmap"s FOV. BDP uses all of the information saved in ' - 'the NIfTI header to compute the FOV. If you get this error and think ' - 'that it is incorrect, then it can be suppressed using the flag ' - 'ignore-fieldmap-FOV. Neither the image matrix size nor the imaging ' - 'grid resolution of the fieldmap needs to be the same as that of the ' - 'diffusion scan, but the fieldmap must be pre-registred to the diffusion ' - 'scan. BDP does NOT align the fieldmap to the diffusion scan, nor does it ' - 'check the alignment of the fieldmap and diffusion scans. Only NIfTI ' - 'files with extension of .nii or .nii.gz are supported. Fieldmap-based ' - 'distortion correction also requires the echoSpacing. Also ' - 'fieldmapCorrectionMethod allows you to define method for ' - 'distortion correction. least squares is the default method. ' - ) + argstr='--fieldmap-correction %s', + requires=['echoSpacing'], + desc= + 'Use an acquired fieldmap for distortion correction. The fieldmap must ' + 'have units of radians/second. Specify the filename of the fieldmap file. ' + 'The field of view (FOV) of the fieldmap scan must cover the FOV of the diffusion ' + 'scan. BDP will try to check the overlap of the FOV of the two scans and ' + 'will issue a warning/error if the diffusion scan"s FOV is not fully ' + 'covered by the fieldmap"s FOV. BDP uses all of the information saved in ' + 'the NIfTI header to compute the FOV. If you get this error and think ' + 'that it is incorrect, then it can be suppressed using the flag ' + 'ignore-fieldmap-FOV. Neither the image matrix size nor the imaging ' + 'grid resolution of the fieldmap needs to be the same as that of the ' + 'diffusion scan, but the fieldmap must be pre-registred to the diffusion ' + 'scan. BDP does NOT align the fieldmap to the diffusion scan, nor does it ' + 'check the alignment of the fieldmap and diffusion scans. Only NIfTI ' + 'files with extension of .nii or .nii.gz are supported. Fieldmap-based ' + 'distortion correction also requires the echoSpacing. Also ' + 'fieldmapCorrectionMethod allows you to define method for ' + 'distortion correction. least squares is the default method. ') fieldmapCorrectionMethod = traits.Enum( - 'pixelshift', 'leastsq', xor=['skipIntensityCorr'], + 'pixelshift', + 'leastsq', + xor=['skipIntensityCorr'], argstr='--fieldmap-correction-method %s', desc='Defines the distortion correction method while using fieldmap. ' - 'Possible methods are "pixelshift" and "leastsq". leastsq is the default ' - 'method when this flag is not used. Pixel-shift (pixelshift) method uses ' - 'image interpolation to un-distort the distorted diffusion images. Least ' - 'squares (leastsq) method uses a physical model of distortion which is ' - 'more accurate (and more computationally expensive) than pixel-shift ' - 'method.' - ) + 'Possible methods are "pixelshift" and "leastsq". leastsq is the default ' + 'method when this flag is not used. Pixel-shift (pixelshift) method uses ' + 'image interpolation to un-distort the distorted diffusion images. Least ' + 'squares (leastsq) method uses a physical model of distortion which is ' + 'more accurate (and more computationally expensive) than pixel-shift ' + 'method.') ignoreFieldmapFOV = traits.Bool( argstr='--ignore-fieldmap-fov', - desc='Supresses the error generated by an insufficient field of view of the ' - 'input fieldmap and continues with the processing. It is useful only when ' - 'used with fieldmap-based distortion correction. See ' - 'fieldmap-correction for a detailed explanation. ' - ) + desc= + 'Supresses the error generated by an insufficient field of view of the ' + 'input fieldmap and continues with the processing. It is useful only when ' + 'used with fieldmap-based distortion correction. See ' + 'fieldmap-correction for a detailed explanation. ') fieldmapSmooth = traits.Float( argstr='--fieldmap-smooth3=%f', desc='Applies 3D Gaussian smoothing with a standard deviation of S ' - 'millimeters (mm) to the input fieldmap before applying distortion ' - 'correction. This trait is only useful with ' - 'fieldmapCorrection. Skip this trait for no smoothing. ' - ) + 'millimeters (mm) to the input fieldmap before applying distortion ' + 'correction. This trait is only useful with ' + 'fieldmapCorrection. Skip this trait for no smoothing. ') transformDiffusionVolume = File( argstr='--transform-diffusion-volume %s', desc='This flag allows to define custom volumes in diffusion coordinate ' - 'which would be transformed into T1 coordinate in a rigid fashion. The ' - 'flag must be followed by the name of either a NIfTI file or of a folder ' - 'that contains one or more NIfTI files. All of the files must be in ' - 'diffusion coordinate, i.e. the files should overlay correctly with the ' - 'diffusion scan in BrainSuite. Only NIfTI files with an extension of .nii ' - 'or .nii.gz are supported. The transformed files are written to the ' - 'output directory with suffix ".T1_coord" in the filename and will not be ' - 'corrected for distortion, if any. The trait transformInterpolation can ' - 'be used to define the type of interpolation that would be used (default ' - 'is set to linear). If you are attempting to transform a label file or ' - 'mask file, use "nearest" interpolation method with transformInterpolation. ' - 'See also transformT1Volume and transformInterpolation' - ) + 'which would be transformed into T1 coordinate in a rigid fashion. The ' + 'flag must be followed by the name of either a NIfTI file or of a folder ' + 'that contains one or more NIfTI files. All of the files must be in ' + 'diffusion coordinate, i.e. the files should overlay correctly with the ' + 'diffusion scan in BrainSuite. Only NIfTI files with an extension of .nii ' + 'or .nii.gz are supported. The transformed files are written to the ' + 'output directory with suffix ".T1_coord" in the filename and will not be ' + 'corrected for distortion, if any. The trait transformInterpolation can ' + 'be used to define the type of interpolation that would be used (default ' + 'is set to linear). If you are attempting to transform a label file or ' + 'mask file, use "nearest" interpolation method with transformInterpolation. ' + 'See also transformT1Volume and transformInterpolation') transformT1Volume = File( argstr='--transform-t1-volume %s', desc='Same as transformDiffusionVolume except that files specified must ' - 'be in T1 coordinate, i.e. the files should overlay correctly with the ' - 'input .bfc.nii.gz files in BrainSuite. BDP transforms these ' - 'data/images from T1 coordinate to diffusion coordinate. The transformed ' - 'files are written to the output directory with suffix ".D_coord" in the ' - 'filename. See also transformDiffusionVolume and transformInterpolation. ' + 'be in T1 coordinate, i.e. the files should overlay correctly with the ' + 'input .bfc.nii.gz files in BrainSuite. BDP transforms these ' + 'data/images from T1 coordinate to diffusion coordinate. The transformed ' + 'files are written to the output directory with suffix ".D_coord" in the ' + 'filename. See also transformDiffusionVolume and transformInterpolation. ' ) transformInterpolation = traits.Enum( - 'linear', 'nearest', 'cubic', 'spline', + 'linear', + 'nearest', + 'cubic', + 'spline', argstr='--transform-interpolation %s', - desc='Defines the type of interpolation method which would be used while ' - 'transforming volumes defined by transformT1Volume and ' - 'transformDiffusionVolume. Possible methods are "linear", "nearest", ' - '"cubic" and "spline". By default, "linear" interpolation is used. ' - ) + desc= + 'Defines the type of interpolation method which would be used while ' + 'transforming volumes defined by transformT1Volume and ' + 'transformDiffusionVolume. Possible methods are "linear", "nearest", ' + '"cubic" and "spline". By default, "linear" interpolation is used. ') transformT1Surface = File( argstr='--transform-t1-surface %s', desc='Similar to transformT1Volume, except that this flag allows ' - 'transforming surfaces (instead of volumes) in T1 coordinate into ' - 'diffusion coordinate in a rigid fashion. The flag must be followed by ' - 'the name of either a .dfs file or of a folder that contains one or more ' - 'dfs files. All of the files must be in T1 coordinate, i.e. the files ' - 'should overlay correctly with the T1-weighted scan in BrainSuite. The ' - 'transformed files are written to the output directory with suffix ' - 'D_coord" in the filename. ' - ) + 'transforming surfaces (instead of volumes) in T1 coordinate into ' + 'diffusion coordinate in a rigid fashion. The flag must be followed by ' + 'the name of either a .dfs file or of a folder that contains one or more ' + 'dfs files. All of the files must be in T1 coordinate, i.e. the files ' + 'should overlay correctly with the T1-weighted scan in BrainSuite. The ' + 'transformed files are written to the output directory with suffix ' + 'D_coord" in the filename. ') transformDiffusionSurface = File( argstr='--transform-diffusion-surface %s', desc='Same as transformT1Volume, except that the .dfs files specified ' - 'must be in diffusion coordinate, i.e. the surface files should overlay ' - 'correctly with the diffusion scan in BrainSuite. The transformed files ' - 'are written to the output directory with suffix ".T1_coord" in the ' - 'filename. See also transformT1Volume. ' - ) + 'must be in diffusion coordinate, i.e. the surface files should overlay ' + 'correctly with the diffusion scan in BrainSuite. The transformed files ' + 'are written to the output directory with suffix ".T1_coord" in the ' + 'filename. See also transformT1Volume. ') transformDataOnly = traits.Bool( argstr='--transform-data-only', - desc='Skip all of the processing (co-registration, distortion correction and ' - 'tensor/ODF estimation) and directly start transformation of defined ' - 'custom volumes, mask and labels (using transformT1Volume, ' - 'transformDiffusionVolume, transformT1Surface, ' - 'transformDiffusionSurface, customDiffusionLabel, ' - 'customT1Label). This flag is useful when BDP was previously run on a ' - 'subject (or ) and some more data (volumes, mask or labels) ' - 'need to be transformed across the T1-diffusion coordinate spaces. This ' - 'assumes that all the necessary files were generated earlier and all of ' - 'the other flags MUST be used in the same way as they were in the initial ' - 'BDP run that processed the data. ' - ) + desc= + 'Skip all of the processing (co-registration, distortion correction and ' + 'tensor/ODF estimation) and directly start transformation of defined ' + 'custom volumes, mask and labels (using transformT1Volume, ' + 'transformDiffusionVolume, transformT1Surface, ' + 'transformDiffusionSurface, customDiffusionLabel, ' + 'customT1Label). This flag is useful when BDP was previously run on a ' + 'subject (or ) and some more data (volumes, mask or labels) ' + 'need to be transformed across the T1-diffusion coordinate spaces. This ' + 'assumes that all the necessary files were generated earlier and all of ' + 'the other flags MUST be used in the same way as they were in the initial ' + 'BDP run that processed the data. ') generateStats = traits.Bool( argstr='--generate-stats', - desc='Generate ROI-wise statistics of estimated diffusion tensor parameters. ' - 'Units of the reported statistics are same as that of the estimated ' - 'tensor parameters (see estimateTensors). Mean, variance, and voxel counts of ' - 'white matter(WM), grey matter(GM), and both WM and GM combined are ' - 'written for each estimated parameter in a separate comma-seperated value ' - 'csv) file. BDP uses the ROI labels generated by Surface-Volume ' - 'Registration (SVReg) in the BrainSuite extraction sequence. ' - 'Specifically, it looks for labels saved in either ' - 'fileprefix>.svreg.corr.label.nii.gz or .svreg.label.nii.gz. ' - 'In case both files are present, only the first file is used. Also see ' - 'customDiffusionLabel and customT1Label for specifying your own ' - 'ROIs. It is also possible to forgo computing the SVReg ROI-wise ' - 'statistics and only compute stats with custom labels if SVReg label is ' - 'missing. BDP also transfers (and saves) the label/mask files to ' - 'appropriate coordinates before computing statistics. Also see ' - 'outputDiffusionCoordinates for outputs in diffusion coordinate and ' - 'forcePartialROIStats for an important note about field of view of ' - 'diffusion and T1-weighted scans. ' - ) + desc= + 'Generate ROI-wise statistics of estimated diffusion tensor parameters. ' + 'Units of the reported statistics are same as that of the estimated ' + 'tensor parameters (see estimateTensors). Mean, variance, and voxel counts of ' + 'white matter(WM), grey matter(GM), and both WM and GM combined are ' + 'written for each estimated parameter in a separate comma-seperated value ' + 'csv) file. BDP uses the ROI labels generated by Surface-Volume ' + 'Registration (SVReg) in the BrainSuite extraction sequence. ' + 'Specifically, it looks for labels saved in either ' + 'fileprefix>.svreg.corr.label.nii.gz or .svreg.label.nii.gz. ' + 'In case both files are present, only the first file is used. Also see ' + 'customDiffusionLabel and customT1Label for specifying your own ' + 'ROIs. It is also possible to forgo computing the SVReg ROI-wise ' + 'statistics and only compute stats with custom labels if SVReg label is ' + 'missing. BDP also transfers (and saves) the label/mask files to ' + 'appropriate coordinates before computing statistics. Also see ' + 'outputDiffusionCoordinates for outputs in diffusion coordinate and ' + 'forcePartialROIStats for an important note about field of view of ' + 'diffusion and T1-weighted scans. ') onlyStats = traits.Bool( argstr='--generate-only-stats', - desc='Skip all of the processing (co-registration, distortion correction and ' - 'tensor/ODF estimation) and directly start computation of statistics. ' - 'This flag is useful when BDP was previously run on a subject (or ' - 'fileprefix>) and statistics need to be (re-)computed later. This ' - 'assumes that all the necessary files were generated earlier. All of the ' - 'other flags MUST be used in the same way as they were in the initial BDP ' - 'run that processed the data. ' - ) + desc= + 'Skip all of the processing (co-registration, distortion correction and ' + 'tensor/ODF estimation) and directly start computation of statistics. ' + 'This flag is useful when BDP was previously run on a subject (or ' + 'fileprefix>) and statistics need to be (re-)computed later. This ' + 'assumes that all the necessary files were generated earlier. All of the ' + 'other flags MUST be used in the same way as they were in the initial BDP ' + 'run that processed the data. ') forcePartialROIStats = traits.Bool( argstr='--force-partial-roi-stats', - desc='The field of view (FOV) of the diffusion and T1-weighted scans may ' - 'differ significantly in some situations. This may result in partial ' - 'acquisitions of some ROIs in the diffusion scan. By default, BDP does ' - 'not compute statistics for partially acquired ROIs and shows warnings. ' - 'This flag forces computation of statistics for all ROIs, including those ' - 'which are partially acquired. When this flag is used, number of missing ' - 'voxels are also reported for each ROI in statistics files. Number of ' - 'missing voxels are reported in the same coordinate system as the ' - 'statistics file. ' - ) + desc= + 'The field of view (FOV) of the diffusion and T1-weighted scans may ' + 'differ significantly in some situations. This may result in partial ' + 'acquisitions of some ROIs in the diffusion scan. By default, BDP does ' + 'not compute statistics for partially acquired ROIs and shows warnings. ' + 'This flag forces computation of statistics for all ROIs, including those ' + 'which are partially acquired. When this flag is used, number of missing ' + 'voxels are also reported for each ROI in statistics files. Number of ' + 'missing voxels are reported in the same coordinate system as the ' + 'statistics file. ') customDiffusionLabel = File( argstr='--custom-diffusion-label %s', - desc='BDP supports custom ROIs in addition to those generated by BrainSuite ' - 'SVReg) for ROI-wise statistics calculation. The flag must be followed ' - 'by the name of either a file (custom ROI file) or of a folder that ' - 'contains one or more ROI files. All of the files must be in diffusion ' - 'coordinate, i.e. the label files should overlay correctly with the ' - 'diffusion scan in BrainSuite. These input label files are also ' - 'transferred (and saved) to T1 coordinate for statistics in T1 ' - 'coordinate. BDP uses nearest-neighborhood interpolation for this ' - 'transformation. Only NIfTI files, with an extension of .nii or .nii.gz ' - 'are supported. In order to avoid confusion with other ROI IDs in the ' - 'statistic files, a 5-digit ROI ID is generated for each custom label ' - 'found and the mapping of ID to label file is saved in the file ' - 'fileprefix>.BDP_ROI_MAP.xml. Custom label files can also be generated ' - 'by using the label painter tool in BrainSuite. See also ' - 'customLabelXML' - ) + desc= + 'BDP supports custom ROIs in addition to those generated by BrainSuite ' + 'SVReg) for ROI-wise statistics calculation. The flag must be followed ' + 'by the name of either a file (custom ROI file) or of a folder that ' + 'contains one or more ROI files. All of the files must be in diffusion ' + 'coordinate, i.e. the label files should overlay correctly with the ' + 'diffusion scan in BrainSuite. These input label files are also ' + 'transferred (and saved) to T1 coordinate for statistics in T1 ' + 'coordinate. BDP uses nearest-neighborhood interpolation for this ' + 'transformation. Only NIfTI files, with an extension of .nii or .nii.gz ' + 'are supported. In order to avoid confusion with other ROI IDs in the ' + 'statistic files, a 5-digit ROI ID is generated for each custom label ' + 'found and the mapping of ID to label file is saved in the file ' + 'fileprefix>.BDP_ROI_MAP.xml. Custom label files can also be generated ' + 'by using the label painter tool in BrainSuite. See also ' + 'customLabelXML') customT1Label = File( argstr='--custom-t1-label %s', desc='Same as customDiffusionLabelexcept that the label files specified ' - 'must be in T1 coordinate, i.e. the label files should overlay correctly ' - 'with the T1-weighted scan in BrainSuite. If the trait ' - 'outputDiffusionCoordinates is also used then these input label files ' - 'are also transferred (and saved) to diffusion coordinate for statistics ' - 'in diffusion coordinate. BDP uses nearest-neighborhood interpolation for ' - 'this transformation. See also customLabelXML. ' - ) + 'must be in T1 coordinate, i.e. the label files should overlay correctly ' + 'with the T1-weighted scan in BrainSuite. If the trait ' + 'outputDiffusionCoordinates is also used then these input label files ' + 'are also transferred (and saved) to diffusion coordinate for statistics ' + 'in diffusion coordinate. BDP uses nearest-neighborhood interpolation for ' + 'this transformation. See also customLabelXML. ') customLabelXML = File( argstr='--custom-label-xml %s', - desc='BrainSuite saves a descriptions of the SVReg labels (ROI name, ID, ' - 'color, and description) in an .xml file ' - 'brainsuite_labeldescription.xml). BDP uses the ROI ID"s from this xml ' - 'file to report statistics. This flag allows for the use of a custom ' - 'label description xml file. The flag must be followed by an xml ' - 'filename. This can be useful when you want to limit the ROIs for which ' - 'you compute statistics. You can also use custom xml files to name your ' - 'own ROIs (assign ID"s) for custom labels. BrainSuite can save a label ' - 'description in .xml format after using the label painter tool to create ' - 'a ROI label. The xml file MUST be in the same format as BrainSuite"s ' - 'label description file (see brainsuite_labeldescription.xml for an ' - 'example). When this flag is used, NO 5-digit ROI ID is generated for ' - 'custom label files and NO Statistics will be calculated for ROIs not ' - 'identified in the custom xml file. See also customDiffusionLabel and ' - 'customT1Label.' - ) + desc= + 'BrainSuite saves a descriptions of the SVReg labels (ROI name, ID, ' + 'color, and description) in an .xml file ' + 'brainsuite_labeldescription.xml). BDP uses the ROI ID"s from this xml ' + 'file to report statistics. This flag allows for the use of a custom ' + 'label description xml file. The flag must be followed by an xml ' + 'filename. This can be useful when you want to limit the ROIs for which ' + 'you compute statistics. You can also use custom xml files to name your ' + 'own ROIs (assign ID"s) for custom labels. BrainSuite can save a label ' + 'description in .xml format after using the label painter tool to create ' + 'a ROI label. The xml file MUST be in the same format as BrainSuite"s ' + 'label description file (see brainsuite_labeldescription.xml for an ' + 'example). When this flag is used, NO 5-digit ROI ID is generated for ' + 'custom label files and NO Statistics will be calculated for ROIs not ' + 'identified in the custom xml file. See also customDiffusionLabel and ' + 'customT1Label.') outputSubdir = traits.Str( argstr='--output-subdir %s', - desc='By default, BDP writes out all the output (and intermediate) files in ' - 'the same directory (or folder) as the BFC file. This flag allows to ' - 'specify a sub-directory name in which output (and intermediate) files ' - 'would be written. BDP will create the sub-directory in the same ' - 'directory as BFC file. should be the name of the ' - 'sub-directory without any path. This can be useful to organize all ' - 'outputs generated by BDP in a separate sub-directory. ' - ) + desc= + 'By default, BDP writes out all the output (and intermediate) files in ' + 'the same directory (or folder) as the BFC file. This flag allows to ' + 'specify a sub-directory name in which output (and intermediate) files ' + 'would be written. BDP will create the sub-directory in the same ' + 'directory as BFC file. should be the name of the ' + 'sub-directory without any path. This can be useful to organize all ' + 'outputs generated by BDP in a separate sub-directory. ') outputDiffusionCoordinates = traits.Bool( argstr='--output-diffusion-coordinate', - desc='Enables estimation of diffusion tensors and/or ODFs (and statistics if ' - 'applicable) in the native diffusion coordinate in addition to the ' - 'default T1-coordinate. All native diffusion coordinate files are saved ' - 'in a seperate folder named "diffusion_coord_outputs". In case statistics ' - 'computation is required, it will also transform/save all label/mask ' - 'files required to diffusion coordinate (see generateStats for ' - 'details). ' - ) + desc= + 'Enables estimation of diffusion tensors and/or ODFs (and statistics if ' + 'applicable) in the native diffusion coordinate in addition to the ' + 'default T1-coordinate. All native diffusion coordinate files are saved ' + 'in a seperate folder named "diffusion_coord_outputs". In case statistics ' + 'computation is required, it will also transform/save all label/mask ' + 'files required to diffusion coordinate (see generateStats for ' + 'details). ') flagConfigFile = File( argstr='--flag-conf-file %s', - desc='Uses the defined file to specify BDP flags which can be useful for ' - 'batch processing. A flag configuration file is a plain text file which ' - 'can contain any number of BDP"s optional flags (and their parameters) ' - 'separated by whitespace. Everything coming after # until end-of-line is ' - 'treated as comment and is ignored. If a flag is defined in configuration ' - 'file and is also specified in the command used to run BDP, then the ' - 'later get preference and overrides the definition in configuration ' - 'file. ' - ) + desc= + 'Uses the defined file to specify BDP flags which can be useful for ' + 'batch processing. A flag configuration file is a plain text file which ' + 'can contain any number of BDP"s optional flags (and their parameters) ' + 'separated by whitespace. Everything coming after # until end-of-line is ' + 'treated as comment and is ignored. If a flag is defined in configuration ' + 'file and is also specified in the command used to run BDP, then the ' + 'later get preference and overrides the definition in configuration ' + 'file. ') outPrefix = traits.Str( argstr='--output-fileprefix %s', desc='Specifies output fileprefix when noStructuralRegistration is ' - 'used. The fileprefix can not start with a dash (-) and should be a ' - 'simple string reflecting the absolute path to desired location, along with outPrefix. When this flag is ' - 'not specified (and noStructuralRegistration is used) then the output ' - 'files have same file-base as the input diffusion file. This trait is ' - 'ignored when noStructuralRegistration is not used. ' - ) + 'used. The fileprefix can not start with a dash (-) and should be a ' + 'simple string reflecting the absolute path to desired location, along with outPrefix. When this flag is ' + 'not specified (and noStructuralRegistration is used) then the output ' + 'files have same file-base as the input diffusion file. This trait is ' + 'ignored when noStructuralRegistration is not used. ') threads = traits.Int( argstr='--threads=%d', desc='Sets the number of parallel process threads which can be used for ' - 'computations to N, where N must be an integer. Default value of N is ' - ' ' - ) + 'computations to N, where N must be an integer. Default value of N is ' + ' ') lowMemory = traits.Bool( argstr='--low-memory', desc='Activates low-memory mode. This will run the registration-based ' - 'distortion correction at a lower resolution, which could result in a ' - 'less-accurate correction. This should only be used when no other ' - 'alternative is available. ' - ) + 'distortion correction at a lower resolution, which could result in a ' + 'less-accurate correction. This should only be used when no other ' + 'alternative is available. ') ignoreMemory = traits.Bool( argstr='--ignore-memory', desc='Deactivates the inbuilt memory checks and forces BDP to run ' - 'registration-based distortion correction at its default resolution even ' - 'on machines with a low amount of memory. This may result in an ' - 'out-of-memory error when BDP cannot allocate sufficient memory. ' - ) + 'registration-based distortion correction at its default resolution even ' + 'on machines with a low amount of memory. This may result in an ' + 'out-of-memory error when BDP cannot allocate sufficient memory. ') class BDP(CommandLine): - """ BrainSuite Diffusion Pipeline (BDP) enables fusion of diffusion and structural MRI information for advanced image and connectivity analysis. @@ -1568,13 +1710,12 @@ def _format_arg(self, name, spec, value): class ThicknessPVCInputSpec(CommandLineInputSpec): subjectFilePrefix = traits.Str( - argstr='%s', mandatory=True, - desc='Absolute path and filename prefix of the subject data' - ) + argstr='%s', + mandatory=True, + desc='Absolute path and filename prefix of the subject data') class ThicknessPVC(CommandLine): - """ ThicknessPVC computes cortical thickness using partial tissue fractions. This thickness measure is then transferred to the atlas surface to @@ -1609,8 +1750,7 @@ def getFileName(inputName, suffix): dotRegex = regex.compile("[^.]+") # extract between last slash and first period inputNoExtension = dotRegex.findall(fullInput)[0] - return os.path.abspath( - ''.join((inputNoExtension, suffix))) + return os.path.abspath(''.join((inputNoExtension, suffix))) def l_outputs(self): @@ -1621,4 +1761,3 @@ def l_outputs(self): outputs[key] = name return outputs - diff --git a/nipype/interfaces/brainsuite/tests/test_auto_BDP.py b/nipype/interfaces/brainsuite/tests/test_auto_BDP.py index 8a3526360c..0160d9c709 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_BDP.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_BDP.py @@ -4,129 +4,105 @@ def test_BDP_inputs(): - input_map = dict(BVecBValPair=dict(argstr='--bvec %s --bval %s', - mandatory=True, - position=-1, - xor=['bMatrixFile'], - ), - args=dict(argstr='%s', - ), - bMatrixFile=dict(argstr='--bmat %s', - mandatory=True, - position=-1, - xor=['BVecBValPair'], - ), - bValRatioThreshold=dict(argstr='--bval-ratio-threshold %f', - ), - bfcFile=dict(argstr='%s', - mandatory=True, - position=0, - xor=['noStructuralRegistration'], - ), - customDiffusionLabel=dict(argstr='--custom-diffusion-label %s', - ), - customLabelXML=dict(argstr='--custom-label-xml %s', - ), - customT1Label=dict(argstr='--custom-t1-label %s', - ), - dataSinkDelay=dict(argstr='%s', - ), - dcorrRegMeasure=dict(argstr='--dcorr-reg-method %s', - ), - dcorrWeight=dict(argstr='--dcorr-regularization-wt %f', - ), - dwiMask=dict(argstr='--dwi-mask %s', - ), - echoSpacing=dict(argstr='--echo-spacing=%f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - estimateODF_3DShore=dict(argstr='--3dshore --diffusion_time_ms %f', - ), - estimateODF_FRACT=dict(argstr='--FRACT', - ), - estimateODF_FRT=dict(argstr='--FRT', - ), - estimateTensors=dict(argstr='--tensors', - ), - fieldmapCorrection=dict(argstr='--fieldmap-correction %s', - requires=['echoSpacing'], - ), - fieldmapCorrectionMethod=dict(argstr='--fieldmap-correction-method %s', - xor=['skipIntensityCorr'], - ), - fieldmapSmooth=dict(argstr='--fieldmap-smooth3=%f', - ), - flagConfigFile=dict(argstr='--flag-conf-file %s', - ), - forcePartialROIStats=dict(argstr='--force-partial-roi-stats', - ), - generateStats=dict(argstr='--generate-stats', - ), - ignoreFieldmapFOV=dict(argstr='--ignore-fieldmap-fov', - ), - ignoreMemory=dict(argstr='--ignore-memory', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputDiffusionData=dict(argstr='--nii %s', - mandatory=True, - position=-2, - ), - lowMemory=dict(argstr='--low-memory', - ), - noStructuralRegistration=dict(argstr='--no-structural-registration', - mandatory=True, - position=0, - xor=['bfcFile'], - ), - odfLambta=dict(argstr='--odf-lambda ', - ), - onlyStats=dict(argstr='--generate-only-stats', - ), - outPrefix=dict(argstr='--output-fileprefix %s', - ), - outputDiffusionCoordinates=dict(argstr='--output-diffusion-coordinate', - ), - outputSubdir=dict(argstr='--output-subdir %s', - ), - phaseEncodingDirection=dict(argstr='--dir=%s', - ), - rigidRegMeasure=dict(argstr='--rigid-reg-measure %s', - ), - skipDistortionCorr=dict(argstr='--no-distortion-correction', - ), - skipIntensityCorr=dict(argstr='--no-intensity-correction', - xor=['fieldmapCorrectionMethod'], - ), - skipNonuniformityCorr=dict(argstr='--no-nonuniformity-correction', - ), - t1Mask=dict(argstr='--t1-mask %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threads=dict(argstr='--threads=%d', - ), - transformDataOnly=dict(argstr='--transform-data-only', - ), - transformDiffusionSurface=dict(argstr='--transform-diffusion-surface %s', - ), - transformDiffusionVolume=dict(argstr='--transform-diffusion-volume %s', - ), - transformInterpolation=dict(argstr='--transform-interpolation %s', - ), - transformT1Surface=dict(argstr='--transform-t1-surface %s', - ), - transformT1Volume=dict(argstr='--transform-t1-volume %s', - ), + input_map = dict( + BVecBValPair=dict( + argstr='--bvec %s --bval %s', + mandatory=True, + position=-1, + xor=['bMatrixFile'], + ), + args=dict(argstr='%s', ), + bMatrixFile=dict( + argstr='--bmat %s', + mandatory=True, + position=-1, + xor=['BVecBValPair'], + ), + bValRatioThreshold=dict(argstr='--bval-ratio-threshold %f', ), + bfcFile=dict( + argstr='%s', + mandatory=True, + position=0, + xor=['noStructuralRegistration'], + ), + customDiffusionLabel=dict(argstr='--custom-diffusion-label %s', ), + customLabelXML=dict(argstr='--custom-label-xml %s', ), + customT1Label=dict(argstr='--custom-t1-label %s', ), + dataSinkDelay=dict(argstr='%s', ), + dcorrRegMeasure=dict(argstr='--dcorr-reg-method %s', ), + dcorrWeight=dict(argstr='--dcorr-regularization-wt %f', ), + dwiMask=dict(argstr='--dwi-mask %s', ), + echoSpacing=dict(argstr='--echo-spacing=%f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + estimateODF_3DShore=dict(argstr='--3dshore --diffusion_time_ms %f', ), + estimateODF_FRACT=dict(argstr='--FRACT', ), + estimateODF_FRT=dict(argstr='--FRT', ), + estimateTensors=dict(argstr='--tensors', ), + fieldmapCorrection=dict( + argstr='--fieldmap-correction %s', + requires=['echoSpacing'], + ), + fieldmapCorrectionMethod=dict( + argstr='--fieldmap-correction-method %s', + xor=['skipIntensityCorr'], + ), + fieldmapSmooth=dict(argstr='--fieldmap-smooth3=%f', ), + flagConfigFile=dict(argstr='--flag-conf-file %s', ), + forcePartialROIStats=dict(argstr='--force-partial-roi-stats', ), + generateStats=dict(argstr='--generate-stats', ), + ignoreFieldmapFOV=dict(argstr='--ignore-fieldmap-fov', ), + ignoreMemory=dict(argstr='--ignore-memory', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputDiffusionData=dict( + argstr='--nii %s', + mandatory=True, + position=-2, + ), + lowMemory=dict(argstr='--low-memory', ), + noStructuralRegistration=dict( + argstr='--no-structural-registration', + mandatory=True, + position=0, + xor=['bfcFile'], + ), + odfLambta=dict(argstr='--odf-lambda ', ), + onlyStats=dict(argstr='--generate-only-stats', ), + outPrefix=dict(argstr='--output-fileprefix %s', ), + outputDiffusionCoordinates=dict( + argstr='--output-diffusion-coordinate', ), + outputSubdir=dict(argstr='--output-subdir %s', ), + phaseEncodingDirection=dict(argstr='--dir=%s', ), + rigidRegMeasure=dict(argstr='--rigid-reg-measure %s', ), + skipDistortionCorr=dict(argstr='--no-distortion-correction', ), + skipIntensityCorr=dict( + argstr='--no-intensity-correction', + xor=['fieldmapCorrectionMethod'], + ), + skipNonuniformityCorr=dict(argstr='--no-nonuniformity-correction', ), + t1Mask=dict(argstr='--t1-mask %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threads=dict(argstr='--threads=%d', ), + transformDataOnly=dict(argstr='--transform-data-only', ), + transformDiffusionSurface=dict( + argstr='--transform-diffusion-surface %s', ), + transformDiffusionVolume=dict( + argstr='--transform-diffusion-volume %s', ), + transformInterpolation=dict(argstr='--transform-interpolation %s', ), + transformT1Surface=dict(argstr='--transform-t1-surface %s', ), + transformT1Volume=dict(argstr='--transform-t1-volume %s', ), ) inputs = BDP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py b/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py index 8183daa886..99641db850 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py @@ -4,85 +4,78 @@ def test_Bfc_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - biasEstimateConvergenceThreshold=dict(argstr='--beps %f', - ), - biasEstimateSpacing=dict(argstr='-s %d', - ), - biasFieldEstimatesOutputPrefix=dict(argstr='--biasprefix %s', - ), - biasRange=dict(argstr='%s', - ), - controlPointSpacing=dict(argstr='-c %d', - ), - convergenceThreshold=dict(argstr='--eps %f', - ), - correctWholeVolume=dict(argstr='--extrapolate', - ), - correctedImagesOutputPrefix=dict(argstr='--prefix %s', - ), - correctionScheduleFile=dict(argstr='--schedule %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - histogramRadius=dict(argstr='-r %d', - ), - histogramType=dict(argstr='%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMRIFile=dict(argstr='-i %s', - mandatory=True, - ), - inputMaskFile=dict(argstr='-m %s', - hash_files=False, - ), - intermediate_file_type=dict(argstr='%s', - ), - iterativeMode=dict(argstr='--iterate', - ), - maxBias=dict(argstr='-U %f', - usedefault=True, - ), - minBias=dict(argstr='-L %f', - usedefault=True, - ), - outputBiasField=dict(argstr='--bias %s', - hash_files=False, - ), - outputMRIVolume=dict(argstr='-o %s', - genfile=True, - hash_files=False, - ), - outputMaskedBiasField=dict(argstr='--maskedbias %s', - hash_files=False, - ), - splineLambda=dict(argstr='-w %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - verbosityLevel=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + biasEstimateConvergenceThreshold=dict(argstr='--beps %f', ), + biasEstimateSpacing=dict(argstr='-s %d', ), + biasFieldEstimatesOutputPrefix=dict(argstr='--biasprefix %s', ), + biasRange=dict(argstr='%s', ), + controlPointSpacing=dict(argstr='-c %d', ), + convergenceThreshold=dict(argstr='--eps %f', ), + correctWholeVolume=dict(argstr='--extrapolate', ), + correctedImagesOutputPrefix=dict(argstr='--prefix %s', ), + correctionScheduleFile=dict(argstr='--schedule %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + histogramRadius=dict(argstr='-r %d', ), + histogramType=dict(argstr='%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMRIFile=dict( + argstr='-i %s', + mandatory=True, + ), + inputMaskFile=dict( + argstr='-m %s', + hash_files=False, + ), + intermediate_file_type=dict(argstr='%s', ), + iterativeMode=dict(argstr='--iterate', ), + maxBias=dict( + argstr='-U %f', + usedefault=True, + ), + minBias=dict( + argstr='-L %f', + usedefault=True, + ), + outputBiasField=dict( + argstr='--bias %s', + hash_files=False, + ), + outputMRIVolume=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + ), + outputMaskedBiasField=dict( + argstr='--maskedbias %s', + hash_files=False, + ), + splineLambda=dict(argstr='-w %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + verbosityLevel=dict(argstr='-v %d', ), ) inputs = Bfc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Bfc_outputs(): - output_map = dict(correctionScheduleFile=dict(), - outputBiasField=dict(), - outputMRIVolume=dict(), - outputMaskedBiasField=dict(), + output_map = dict( + correctionScheduleFile=dict(), + outputBiasField=dict(), + outputMRIVolume=dict(), + outputMaskedBiasField=dict(), ) outputs = Bfc.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Bse.py b/nipype/interfaces/brainsuite/tests/test_auto_Bse.py index d79dc8baa0..9483e72266 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Bse.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Bse.py @@ -4,81 +4,95 @@ def test_Bse_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - diffusionConstant=dict(argstr='-d %f', - usedefault=True, - ), - diffusionIterations=dict(argstr='-n %d', - usedefault=True, - ), - dilateFinalMask=dict(argstr='-p', - usedefault=True, - ), - edgeDetectionConstant=dict(argstr='-s %f', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMRIFile=dict(argstr='-i %s', - mandatory=True, - ), - noRotate=dict(argstr='--norotate', - ), - outputCortexFile=dict(argstr='--cortex %s', - hash_files=False, - ), - outputDetailedBrainMask=dict(argstr='--hires %s', - hash_files=False, - ), - outputDiffusionFilter=dict(argstr='--adf %s', - hash_files=False, - ), - outputEdgeMap=dict(argstr='--edge %s', - hash_files=False, - ), - outputMRIVolume=dict(argstr='-o %s', - genfile=True, - hash_files=False, - ), - outputMaskFile=dict(argstr='--mask %s', - genfile=True, - hash_files=False, - ), - radius=dict(argstr='-r %f', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - trim=dict(argstr='--trim', - usedefault=True, - ), - verbosityLevel=dict(argstr='-v %f', - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + diffusionConstant=dict( + argstr='-d %f', + usedefault=True, + ), + diffusionIterations=dict( + argstr='-n %d', + usedefault=True, + ), + dilateFinalMask=dict( + argstr='-p', + usedefault=True, + ), + edgeDetectionConstant=dict( + argstr='-s %f', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMRIFile=dict( + argstr='-i %s', + mandatory=True, + ), + noRotate=dict(argstr='--norotate', ), + outputCortexFile=dict( + argstr='--cortex %s', + hash_files=False, + ), + outputDetailedBrainMask=dict( + argstr='--hires %s', + hash_files=False, + ), + outputDiffusionFilter=dict( + argstr='--adf %s', + hash_files=False, + ), + outputEdgeMap=dict( + argstr='--edge %s', + hash_files=False, + ), + outputMRIVolume=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + ), + outputMaskFile=dict( + argstr='--mask %s', + genfile=True, + hash_files=False, + ), + radius=dict( + argstr='-r %f', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + trim=dict( + argstr='--trim', + usedefault=True, + ), + verbosityLevel=dict( + argstr='-v %f', + usedefault=True, + ), ) inputs = Bse.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Bse_outputs(): - output_map = dict(outputCortexFile=dict(), - outputDetailedBrainMask=dict(), - outputDiffusionFilter=dict(), - outputEdgeMap=dict(), - outputMRIVolume=dict(), - outputMaskFile=dict(), + output_map = dict( + outputCortexFile=dict(), + outputDetailedBrainMask=dict(), + outputDiffusionFilter=dict(), + outputEdgeMap=dict(), + outputMRIVolume=dict(), + outputMaskFile=dict(), ) outputs = Bse.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py b/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py index ac78853d2b..3b66172e7a 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py @@ -4,73 +4,74 @@ def test_Cerebro_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - costFunction=dict(argstr='-c %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputAtlasLabelFile=dict(argstr='--atlaslabels %s', - mandatory=True, - ), - inputAtlasMRIFile=dict(argstr='--atlas %s', - mandatory=True, - ), - inputBrainMaskFile=dict(argstr='-m %s', - ), - inputMRIFile=dict(argstr='-i %s', - mandatory=True, - ), - keepTempFiles=dict(argstr='--keep', - ), - linearConvergence=dict(argstr='--linconv %f', - ), - outputAffineTransformFile=dict(argstr='--air %s', - genfile=True, - ), - outputCerebrumMaskFile=dict(argstr='-o %s', - genfile=True, - ), - outputLabelVolumeFile=dict(argstr='-l %s', - genfile=True, - ), - outputWarpTransformFile=dict(argstr='--warp %s', - genfile=True, - ), - tempDirectory=dict(argstr='--tempdir %s', - ), - tempDirectoryBase=dict(argstr='--tempdirbase %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - useCentroids=dict(argstr='--centroids', - ), - verbosity=dict(argstr='-v %d', - ), - warpConvergence=dict(argstr='--warpconv %f', - ), - warpLabel=dict(argstr='--warplevel %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + costFunction=dict( + argstr='-c %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputAtlasLabelFile=dict( + argstr='--atlaslabels %s', + mandatory=True, + ), + inputAtlasMRIFile=dict( + argstr='--atlas %s', + mandatory=True, + ), + inputBrainMaskFile=dict(argstr='-m %s', ), + inputMRIFile=dict( + argstr='-i %s', + mandatory=True, + ), + keepTempFiles=dict(argstr='--keep', ), + linearConvergence=dict(argstr='--linconv %f', ), + outputAffineTransformFile=dict( + argstr='--air %s', + genfile=True, + ), + outputCerebrumMaskFile=dict( + argstr='-o %s', + genfile=True, + ), + outputLabelVolumeFile=dict( + argstr='-l %s', + genfile=True, + ), + outputWarpTransformFile=dict( + argstr='--warp %s', + genfile=True, + ), + tempDirectory=dict(argstr='--tempdir %s', ), + tempDirectoryBase=dict(argstr='--tempdirbase %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + useCentroids=dict(argstr='--centroids', ), + verbosity=dict(argstr='-v %d', ), + warpConvergence=dict(argstr='--warpconv %f', ), + warpLabel=dict(argstr='--warplevel %d', ), ) inputs = Cerebro.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Cerebro_outputs(): - output_map = dict(outputAffineTransformFile=dict(), - outputCerebrumMaskFile=dict(), - outputLabelVolumeFile=dict(), - outputWarpTransformFile=dict(), + output_map = dict( + outputAffineTransformFile=dict(), + outputCerebrumMaskFile=dict(), + outputLabelVolumeFile=dict(), + outputWarpTransformFile=dict(), ) outputs = Cerebro.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py b/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py index badbcd7738..74288d931b 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py @@ -4,53 +4,56 @@ def test_Cortex_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - computeGCBoundary=dict(argstr='-g', - ), - computeWGBoundary=dict(argstr='-w', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - includeAllSubcorticalAreas=dict(argstr='-a', - usedefault=True, - ), - inputHemisphereLabelFile=dict(argstr='-h %s', - mandatory=True, - ), - inputTissueFractionFile=dict(argstr='-f %s', - mandatory=True, - ), - outputCerebrumMask=dict(argstr='-o %s', - genfile=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - tissueFractionThreshold=dict(argstr='-p %f', - usedefault=True, - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + computeGCBoundary=dict(argstr='-g', ), + computeWGBoundary=dict( + argstr='-w', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + includeAllSubcorticalAreas=dict( + argstr='-a', + usedefault=True, + ), + inputHemisphereLabelFile=dict( + argstr='-h %s', + mandatory=True, + ), + inputTissueFractionFile=dict( + argstr='-f %s', + mandatory=True, + ), + outputCerebrumMask=dict( + argstr='-o %s', + genfile=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + tissueFractionThreshold=dict( + argstr='-p %f', + usedefault=True, + ), + verbosity=dict(argstr='-v %d', ), ) inputs = Cortex.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Cortex_outputs(): - output_map = dict(outputCerebrumMask=dict(), - ) + output_map = dict(outputCerebrumMask=dict(), ) outputs = Cortex.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py b/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py index b96d456fce..dd1800782b 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py @@ -4,43 +4,41 @@ def test_Dewisp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskFile=dict(argstr='-i %s', - mandatory=True, - ), - maximumIterations=dict(argstr='-n %d', - ), - outputMaskFile=dict(argstr='-o %s', - genfile=True, - ), - sizeThreshold=dict(argstr='-t %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskFile=dict( + argstr='-i %s', + mandatory=True, + ), + maximumIterations=dict(argstr='-n %d', ), + outputMaskFile=dict( + argstr='-o %s', + genfile=True, + ), + sizeThreshold=dict(argstr='-t %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + verbosity=dict(argstr='-v %d', ), ) inputs = Dewisp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Dewisp_outputs(): - output_map = dict(outputMaskFile=dict(), - ) + output_map = dict(outputMaskFile=dict(), ) outputs = Dewisp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py b/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py index d9a1752fc7..964d05575c 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py @@ -4,68 +4,67 @@ def test_Dfs_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - curvatureWeighting=dict(argstr='-w %f', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputShadingVolume=dict(argstr='-c %s', - ), - inputVolumeFile=dict(argstr='-i %s', - mandatory=True, - ), - noNormalsFlag=dict(argstr='--nonormals', - ), - nonZeroTessellation=dict(argstr='-nz', - xor=('nonZeroTessellation', 'specialTessellation'), - ), - outputSurfaceFile=dict(argstr='-o %s', - genfile=True, - ), - postSmoothFlag=dict(argstr='--postsmooth', - ), - scalingPercentile=dict(argstr='-f %f', - ), - smoothingConstant=dict(argstr='-a %f', - usedefault=True, - ), - smoothingIterations=dict(argstr='-n %d', - usedefault=True, - ), - specialTessellation=dict(argstr='%s', - position=-1, - requires=['tessellationThreshold'], - xor=('nonZeroTessellation', 'specialTessellation'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tessellationThreshold=dict(argstr='%f', - ), - timer=dict(argstr='--timer', - ), - verbosity=dict(argstr='-v %d', - ), - zeroPadFlag=dict(argstr='-z', - ), + input_map = dict( + args=dict(argstr='%s', ), + curvatureWeighting=dict( + argstr='-w %f', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputShadingVolume=dict(argstr='-c %s', ), + inputVolumeFile=dict( + argstr='-i %s', + mandatory=True, + ), + noNormalsFlag=dict(argstr='--nonormals', ), + nonZeroTessellation=dict( + argstr='-nz', + xor=('nonZeroTessellation', 'specialTessellation'), + ), + outputSurfaceFile=dict( + argstr='-o %s', + genfile=True, + ), + postSmoothFlag=dict(argstr='--postsmooth', ), + scalingPercentile=dict(argstr='-f %f', ), + smoothingConstant=dict( + argstr='-a %f', + usedefault=True, + ), + smoothingIterations=dict( + argstr='-n %d', + usedefault=True, + ), + specialTessellation=dict( + argstr='%s', + position=-1, + requires=['tessellationThreshold'], + xor=('nonZeroTessellation', 'specialTessellation'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tessellationThreshold=dict(argstr='%f', ), + timer=dict(argstr='--timer', ), + verbosity=dict(argstr='-v %d', ), + zeroPadFlag=dict(argstr='-z', ), ) inputs = Dfs.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Dfs_outputs(): - output_map = dict(outputSurfaceFile=dict(), - ) + output_map = dict(outputSurfaceFile=dict(), ) outputs = Dfs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py b/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py index 3909149567..e5d30a6c94 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py @@ -4,55 +4,60 @@ def test_Hemisplit_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputHemisphereLabelFile=dict(argstr='-l %s', - mandatory=True, - ), - inputSurfaceFile=dict(argstr='-i %s', - mandatory=True, - ), - outputLeftHemisphere=dict(argstr='--left %s', - genfile=True, - ), - outputLeftPialHemisphere=dict(argstr='-pl %s', - genfile=True, - ), - outputRightHemisphere=dict(argstr='--right %s', - genfile=True, - ), - outputRightPialHemisphere=dict(argstr='-pr %s', - genfile=True, - ), - pialSurfaceFile=dict(argstr='-p %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputHemisphereLabelFile=dict( + argstr='-l %s', + mandatory=True, + ), + inputSurfaceFile=dict( + argstr='-i %s', + mandatory=True, + ), + outputLeftHemisphere=dict( + argstr='--left %s', + genfile=True, + ), + outputLeftPialHemisphere=dict( + argstr='-pl %s', + genfile=True, + ), + outputRightHemisphere=dict( + argstr='--right %s', + genfile=True, + ), + outputRightPialHemisphere=dict( + argstr='-pr %s', + genfile=True, + ), + pialSurfaceFile=dict(argstr='-p %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + verbosity=dict(argstr='-v %d', ), ) inputs = Hemisplit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Hemisplit_outputs(): - output_map = dict(outputLeftHemisphere=dict(), - outputLeftPialHemisphere=dict(), - outputRightHemisphere=dict(), - outputRightPialHemisphere=dict(), + output_map = dict( + outputLeftHemisphere=dict(), + outputLeftPialHemisphere=dict(), + outputRightHemisphere=dict(), + outputRightPialHemisphere=dict(), ) outputs = Hemisplit.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py b/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py index d161e2e6c0..637da5add5 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py @@ -4,75 +4,82 @@ def test_Pialmesh_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - exportPrefix=dict(argstr='--prefix %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskFile=dict(argstr='-m %s', - mandatory=True, - ), - inputSurfaceFile=dict(argstr='-i %s', - mandatory=True, - ), - inputTissueFractionFile=dict(argstr='-f %s', - mandatory=True, - ), - laplacianSmoothing=dict(argstr='--smooth %f', - usedefault=True, - ), - maxThickness=dict(argstr='--max %f', - usedefault=True, - ), - normalSmoother=dict(argstr='--nc %f', - usedefault=True, - ), - numIterations=dict(argstr='-n %d', - usedefault=True, - ), - outputInterval=dict(argstr='--interval %d', - usedefault=True, - ), - outputSurfaceFile=dict(argstr='-o %s', - genfile=True, - ), - recomputeNormals=dict(argstr='--norm', - ), - searchRadius=dict(argstr='-r %f', - usedefault=True, - ), - stepSize=dict(argstr='-s %f', - usedefault=True, - ), - tangentSmoother=dict(argstr='--tc %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - tissueThreshold=dict(argstr='-t %f', - usedefault=True, - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + exportPrefix=dict(argstr='--prefix %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskFile=dict( + argstr='-m %s', + mandatory=True, + ), + inputSurfaceFile=dict( + argstr='-i %s', + mandatory=True, + ), + inputTissueFractionFile=dict( + argstr='-f %s', + mandatory=True, + ), + laplacianSmoothing=dict( + argstr='--smooth %f', + usedefault=True, + ), + maxThickness=dict( + argstr='--max %f', + usedefault=True, + ), + normalSmoother=dict( + argstr='--nc %f', + usedefault=True, + ), + numIterations=dict( + argstr='-n %d', + usedefault=True, + ), + outputInterval=dict( + argstr='--interval %d', + usedefault=True, + ), + outputSurfaceFile=dict( + argstr='-o %s', + genfile=True, + ), + recomputeNormals=dict(argstr='--norm', ), + searchRadius=dict( + argstr='-r %f', + usedefault=True, + ), + stepSize=dict( + argstr='-s %f', + usedefault=True, + ), + tangentSmoother=dict(argstr='--tc %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + tissueThreshold=dict( + argstr='-t %f', + usedefault=True, + ), + verbosity=dict(argstr='-v %d', ), ) inputs = Pialmesh.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Pialmesh_outputs(): - output_map = dict(outputSurfaceFile=dict(), - ) + output_map = dict(outputSurfaceFile=dict(), ) outputs = Pialmesh.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py b/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py index 06695eab51..28efe8bd21 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py @@ -4,48 +4,48 @@ def test_Pvc_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMRIFile=dict(argstr='-i %s', - mandatory=True, - ), - inputMaskFile=dict(argstr='-m %s', - ), - outputLabelFile=dict(argstr='-o %s', - genfile=True, - ), - outputTissueFractionFile=dict(argstr='-f %s', - genfile=True, - ), - spatialPrior=dict(argstr='-l %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threeClassFlag=dict(argstr='-3', - ), - timer=dict(argstr='--timer', - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMRIFile=dict( + argstr='-i %s', + mandatory=True, + ), + inputMaskFile=dict(argstr='-m %s', ), + outputLabelFile=dict( + argstr='-o %s', + genfile=True, + ), + outputTissueFractionFile=dict( + argstr='-f %s', + genfile=True, + ), + spatialPrior=dict(argstr='-l %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threeClassFlag=dict(argstr='-3', ), + timer=dict(argstr='--timer', ), + verbosity=dict(argstr='-v %d', ), ) inputs = Pvc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Pvc_outputs(): - output_map = dict(outputLabelFile=dict(), - outputTissueFractionFile=dict(), + output_map = dict( + outputLabelFile=dict(), + outputTissueFractionFile=dict(), ) outputs = Pvc.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py b/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py index a5d7408cc6..8d93f3d12c 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py @@ -4,70 +4,61 @@ def test_SVReg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - atlasFilePrefix=dict(argstr="'%s'", - position=1, - ), - curveMatchingInstructions=dict(argstr="'-cur %s'", - ), - dataSinkDelay=dict(argstr='%s', - ), - displayModuleName=dict(argstr="'-m'", - ), - displayTimestamps=dict(argstr="'-t'", - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - iterations=dict(argstr="'-H %d'", - ), - keepIntermediates=dict(argstr="'-k'", - ), - pialSurfaceMaskDilation=dict(argstr="'-D %d'", - ), - refineOutputs=dict(argstr="'-r'", - ), - shortMessages=dict(argstr="'-gui'", - ), - skipToIntensityReg=dict(argstr="'-p'", - ), - skipToVolumeReg=dict(argstr="'-s'", - ), - skipVolumetricProcessing=dict(argstr="'-S'", - ), - subjectFilePrefix=dict(argstr="'%s'", - mandatory=True, - position=0, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - useCerebrumMask=dict(argstr="'-C'", - ), - useManualMaskFile=dict(argstr="'-cbm'", - ), - useMultiThreading=dict(argstr="'-P'", - ), - useSingleThreading=dict(argstr="'-U'", - ), - verbosity0=dict(argstr="'-v0'", - xor=('verbosity0', 'verbosity1', 'verbosity2'), - ), - verbosity1=dict(argstr="'-v1'", - xor=('verbosity0', 'verbosity1', 'verbosity2'), - ), - verbosity2=dict(argstr="'v2'", - xor=('verbosity0', 'verbosity1', 'verbosity2'), - ), + input_map = dict( + args=dict(argstr='%s', ), + atlasFilePrefix=dict( + argstr="'%s'", + position=1, + ), + curveMatchingInstructions=dict(argstr="'-cur %s'", ), + dataSinkDelay=dict(argstr='%s', ), + displayModuleName=dict(argstr="'-m'", ), + displayTimestamps=dict(argstr="'-t'", ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + iterations=dict(argstr="'-H %d'", ), + keepIntermediates=dict(argstr="'-k'", ), + pialSurfaceMaskDilation=dict(argstr="'-D %d'", ), + refineOutputs=dict(argstr="'-r'", ), + shortMessages=dict(argstr="'-gui'", ), + skipToIntensityReg=dict(argstr="'-p'", ), + skipToVolumeReg=dict(argstr="'-s'", ), + skipVolumetricProcessing=dict(argstr="'-S'", ), + subjectFilePrefix=dict( + argstr="'%s'", + mandatory=True, + position=0, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + useCerebrumMask=dict(argstr="'-C'", ), + useManualMaskFile=dict(argstr="'-cbm'", ), + useMultiThreading=dict(argstr="'-P'", ), + useSingleThreading=dict(argstr="'-U'", ), + verbosity0=dict( + argstr="'-v0'", + xor=('verbosity0', 'verbosity1', 'verbosity2'), + ), + verbosity1=dict( + argstr="'-v1'", + xor=('verbosity0', 'verbosity1', 'verbosity2'), + ), + verbosity2=dict( + argstr="'v2'", + xor=('verbosity0', 'verbosity1', 'verbosity2'), + ), ) inputs = SVReg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py b/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py index 404ce27a25..f055426fa3 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py @@ -4,47 +4,48 @@ def test_Scrubmask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - backgroundFillThreshold=dict(argstr='-b %d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - foregroundTrimThreshold=dict(argstr='-f %d', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskFile=dict(argstr='-i %s', - mandatory=True, - ), - numberIterations=dict(argstr='-n %d', - ), - outputMaskFile=dict(argstr='-o %s', - genfile=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + backgroundFillThreshold=dict( + argstr='-b %d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + foregroundTrimThreshold=dict( + argstr='-f %d', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskFile=dict( + argstr='-i %s', + mandatory=True, + ), + numberIterations=dict(argstr='-n %d', ), + outputMaskFile=dict( + argstr='-o %s', + genfile=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + verbosity=dict(argstr='-v %d', ), ) inputs = Scrubmask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Scrubmask_outputs(): - output_map = dict(outputMaskFile=dict(), - ) + output_map = dict(outputMaskFile=dict(), ) outputs = Scrubmask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py b/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py index 254461d7eb..6954826288 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py @@ -4,58 +4,51 @@ def test_Skullfinder_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bgLabelValue=dict(argstr='--bglabel %d', - ), - brainLabelValue=dict(argstr='--brainlabel %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMRIFile=dict(argstr='-i %s', - mandatory=True, - ), - inputMaskFile=dict(argstr='-m %s', - mandatory=True, - ), - lowerThreshold=dict(argstr='-l %d', - ), - outputLabelFile=dict(argstr='-o %s', - genfile=True, - ), - performFinalOpening=dict(argstr='--finalOpening', - ), - scalpLabelValue=dict(argstr='--scalplabel %d', - ), - skullLabelValue=dict(argstr='--skulllabel %d', - ), - spaceLabelValue=dict(argstr='--spacelabel %d', - ), - surfaceFilePrefix=dict(argstr='-s %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upperThreshold=dict(argstr='-u %d', - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + bgLabelValue=dict(argstr='--bglabel %d', ), + brainLabelValue=dict(argstr='--brainlabel %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMRIFile=dict( + argstr='-i %s', + mandatory=True, + ), + inputMaskFile=dict( + argstr='-m %s', + mandatory=True, + ), + lowerThreshold=dict(argstr='-l %d', ), + outputLabelFile=dict( + argstr='-o %s', + genfile=True, + ), + performFinalOpening=dict(argstr='--finalOpening', ), + scalpLabelValue=dict(argstr='--scalplabel %d', ), + skullLabelValue=dict(argstr='--skulllabel %d', ), + spaceLabelValue=dict(argstr='--spacelabel %d', ), + surfaceFilePrefix=dict(argstr='-s %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upperThreshold=dict(argstr='-u %d', ), + verbosity=dict(argstr='-v %d', ), ) inputs = Skullfinder.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Skullfinder_outputs(): - output_map = dict(outputLabelFile=dict(), - ) + output_map = dict(outputLabelFile=dict(), ) outputs = Skullfinder.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Tca.py b/nipype/interfaces/brainsuite/tests/test_auto_Tca.py index ec25d193ba..be55e4d72a 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Tca.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Tca.py @@ -4,47 +4,48 @@ def test_Tca_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - foregroundDelta=dict(argstr='--delta %d', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskFile=dict(argstr='-i %s', - mandatory=True, - ), - maxCorrectionSize=dict(argstr='-n %d', - ), - minCorrectionSize=dict(argstr='-m %d', - usedefault=True, - ), - outputMaskFile=dict(argstr='-o %s', - genfile=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timer=dict(argstr='--timer', - ), - verbosity=dict(argstr='-v %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + foregroundDelta=dict( + argstr='--delta %d', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskFile=dict( + argstr='-i %s', + mandatory=True, + ), + maxCorrectionSize=dict(argstr='-n %d', ), + minCorrectionSize=dict( + argstr='-m %d', + usedefault=True, + ), + outputMaskFile=dict( + argstr='-o %s', + genfile=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timer=dict(argstr='--timer', ), + verbosity=dict(argstr='-v %d', ), ) inputs = Tca.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Tca_outputs(): - output_map = dict(outputMaskFile=dict(), - ) + output_map = dict(outputMaskFile=dict(), ) outputs = Tca.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py b/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py index 8956e36da5..a79d0a7f85 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py @@ -4,25 +4,28 @@ def test_ThicknessPVC_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - subjectFilePrefix=dict(argstr='%s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + subjectFilePrefix=dict( + argstr='%s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ThicknessPVC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/bru2nii.py b/nipype/interfaces/bru2nii.py index 579b5229b9..550605d071 100644 --- a/nipype/interfaces/bru2nii.py +++ b/nipype/interfaces/bru2nii.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - """The bru2nii module provides basic functions for dicom conversion Change directory to provide relative paths for doctests @@ -8,24 +7,34 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os -from .base import (CommandLine, CommandLineInputSpec, - traits, TraitedSpec, isdefined, File, Directory) +from .base import (CommandLine, CommandLineInputSpec, traits, TraitedSpec, + isdefined, File, Directory) class Bru2InputSpec(CommandLineInputSpec): input_dir = Directory( - desc="Input Directory", exists=True, mandatory=True, position=-1, argstr="%s") + desc="Input Directory", + exists=True, + mandatory=True, + position=-1, + argstr="%s") actual_size = traits.Bool( - argstr='-a', desc="Keep actual size - otherwise x10 scale so animals match human.") + argstr='-a', + desc="Keep actual size - otherwise x10 scale so animals match human.") force_conversion = traits.Bool( - argstr='-f', desc="Force conversion of localizers images (multiple slice orientations).") + argstr='-f', + desc="Force conversion of localizers images (multiple slice " + "orientations).") append_protocol_name = traits.Bool( argstr='-p', desc="Append protocol name to output filename.") output_filename = traits.Str( - argstr="-o %s", desc="Output filename ('.nii' will be appended)", genfile=True) + argstr="-o %s", + desc="Output filename ('.nii' will be appended)", + genfile=True) class Bru2OutputSpec(TraitedSpec): @@ -33,7 +42,6 @@ class Bru2OutputSpec(TraitedSpec): class Bru2(CommandLine): - """Uses bru2nii's Bru2 to convert Bruker files Examples @@ -55,11 +63,12 @@ def _list_outputs(self): output_filename1 = os.path.abspath(self.inputs.output_filename) else: output_filename1 = self._gen_filename('output_filename') - outputs["nii_file"] = output_filename1+".nii" + outputs["nii_file"] = output_filename1 + ".nii" return outputs def _gen_filename(self, name): if name == 'output_filename': outfile = os.path.join( - os.getcwd(), os.path.basename(os.path.normpath(self.inputs.input_dir))) + os.getcwd(), + os.path.basename(os.path.normpath(self.inputs.input_dir))) return outfile diff --git a/nipype/interfaces/c3.py b/nipype/interfaces/c3.py index 334500874c..3a3284b32e 100644 --- a/nipype/interfaces/c3.py +++ b/nipype/interfaces/c3.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- -"""The ants module provides basic functions for interfacing with ants functions. +"""The ants module provides basic functions for interfacing with ants + functions. Change directory to provide relative paths for doctests >>> import os @@ -7,19 +8,24 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) -from .base import (CommandLineInputSpec, traits, TraitedSpec, - File, SEMLikeCommandLine) +from .base import (CommandLineInputSpec, traits, TraitedSpec, File, + SEMLikeCommandLine) class C3dAffineToolInputSpec(CommandLineInputSpec): reference_file = File(exists=True, argstr="-ref %s", position=1) source_file = File(exists=True, argstr='-src %s', position=2) transform_file = File(exists=True, argstr='%s', position=3) - itk_transform = traits.Either(traits.Bool, File(), hash_files=False, - desc="Export ITK transform.", - argstr="-oitk %s", position=5) + itk_transform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Export ITK transform.", + argstr="-oitk %s", + position=5) fsl2ras = traits.Bool(argstr='-fsl2ras', position=4) diff --git a/nipype/interfaces/camino/calib.py b/nipype/interfaces/camino/calib.py index c4c07fa71d..e1a4ac32b5 100644 --- a/nipype/interfaces/camino/calib.py +++ b/nipype/interfaces/camino/calib.py @@ -7,7 +7,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os @@ -17,48 +18,85 @@ class SFPICOCalibDataInputSpec(StdOutCommandLineInputSpec): - snr = traits.Float(argstr='-snr %f', units='NA', - desc=('Specifies the signal-to-noise ratio of the ' - 'non-diffusion-weighted measurements to use in simulations.')) - scheme_file = File(exists=True, argstr='-schemefile %s', mandatory=True, - desc='Specifies the scheme file for the diffusion MRI data') - info_file = File(desc='The name to be given to the information output filename.', - argstr='-infooutputfile %s', mandatory=True, genfile=True, - hash_files=False) # Genfile and hash_files? - trace = traits.Float(argstr='-trace %f', units='NA', - desc='Trace of the diffusion tensor(s) used in the test function.') - onedtfarange = traits.List(traits.Float, argstr='-onedtfarange %s', - minlen=2, maxlen=2, units='NA', - desc=('Minimum and maximum FA for the single tensor ' - 'synthetic data.')) - onedtfastep = traits.Float(argstr='-onedtfastep %f', units='NA', - desc=('FA step size controlling how many steps there are ' - 'between the minimum and maximum FA settings.')) - twodtfarange = traits.List(traits.Float, argstr='-twodtfarange %s', - minlen=2, maxlen=2, units='NA', - desc=('Minimum and maximum FA for the two tensor ' - 'synthetic data. FA is varied for both tensors ' - 'to give all the different permutations.')) - twodtfastep = traits.Float(argstr='-twodtfastep %f', units='NA', - desc=('FA step size controlling how many steps there are ' - 'between the minimum and maximum FA settings ' - 'for the two tensor cases.')) - twodtanglerange = traits.List(traits.Float, argstr='-twodtanglerange %s', - minlen=2, maxlen=2, units='NA', - desc=('Minimum and maximum crossing angles ' - 'between the two fibres.')) - twodtanglestep = traits.Float(argstr='-twodtanglestep %f', units='NA', - desc=('Angle step size controlling how many steps there are ' - 'between the minimum and maximum crossing angles for ' - 'the two tensor cases.')) - twodtmixmax = traits.Float(argstr='-twodtmixmax %f', units='NA', - desc=('Mixing parameter controlling the proportion of one fibre population ' - 'to the other. The minimum mixing parameter is (1 - twodtmixmax).')) - twodtmixstep = traits.Float(argstr='-twodtmixstep %f', units='NA', - desc=('Mixing parameter step size for the two tensor cases. ' - 'Specify how many mixing parameter increments to use.')) - seed = traits.Float(argstr='-seed %f', units='NA', - desc='Specifies the random seed to use for noise generation in simulation trials.') + snr = traits.Float( + argstr='-snr %f', + units='NA', + desc=('Specifies the signal-to-noise ratio of the ' + 'non-diffusion-weighted measurements to use in simulations.')) + scheme_file = File( + exists=True, + argstr='-schemefile %s', + mandatory=True, + desc='Specifies the scheme file for the diffusion MRI data') + info_file = File( + desc='The name to be given to the information output filename.', + argstr='-infooutputfile %s', + mandatory=True, + genfile=True, + hash_files=False) # Genfile and hash_files? + trace = traits.Float( + argstr='-trace %f', + units='NA', + desc='Trace of the diffusion tensor(s) used in the test function.') + onedtfarange = traits.List( + traits.Float, + argstr='-onedtfarange %s', + minlen=2, + maxlen=2, + units='NA', + desc=('Minimum and maximum FA for the single tensor ' + 'synthetic data.')) + onedtfastep = traits.Float( + argstr='-onedtfastep %f', + units='NA', + desc=('FA step size controlling how many steps there are ' + 'between the minimum and maximum FA settings.')) + twodtfarange = traits.List( + traits.Float, + argstr='-twodtfarange %s', + minlen=2, + maxlen=2, + units='NA', + desc=('Minimum and maximum FA for the two tensor ' + 'synthetic data. FA is varied for both tensors ' + 'to give all the different permutations.')) + twodtfastep = traits.Float( + argstr='-twodtfastep %f', + units='NA', + desc=('FA step size controlling how many steps there are ' + 'between the minimum and maximum FA settings ' + 'for the two tensor cases.')) + twodtanglerange = traits.List( + traits.Float, + argstr='-twodtanglerange %s', + minlen=2, + maxlen=2, + units='NA', + desc=('Minimum and maximum crossing angles ' + 'between the two fibres.')) + twodtanglestep = traits.Float( + argstr='-twodtanglestep %f', + units='NA', + desc=('Angle step size controlling how many steps there are ' + 'between the minimum and maximum crossing angles for ' + 'the two tensor cases.')) + twodtmixmax = traits.Float( + argstr='-twodtmixmax %f', + units='NA', + desc= + ('Mixing parameter controlling the proportion of one fibre population ' + 'to the other. The minimum mixing parameter is (1 - twodtmixmax).')) + twodtmixstep = traits.Float( + argstr='-twodtmixstep %f', + units='NA', + desc=('Mixing parameter step size for the two tensor cases. ' + 'Specify how many mixing parameter increments to use.')) + seed = traits.Float( + argstr='-seed %f', + units='NA', + desc= + 'Specifies the random seed to use for noise generation in simulation trials.' + ) class SFPICOCalibDataOutputSpec(TraitedSpec): @@ -134,42 +172,67 @@ def _gen_outfilename(self): class SFLUTGenInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='-inputfile %s', mandatory=True, - desc='Voxel-order data of the spherical functions peaks.') - info_file = File(argstr='-infofile %s', mandatory=True, - desc=('The Info file that corresponds to the calibration ' - 'datafile used in the reconstruction.')) - outputstem = traits.Str('LUT', argstr='-outputstem %s', - desc=('Define the name of the generated luts. The form of the filenames will be ' - '[outputstem]_oneFibreSurfaceCoeffs.Bdouble and ' - '[outputstem]_twoFibreSurfaceCoeffs.Bdouble'), - usedefault=True) - pdf = traits.Enum('bingham', 'watson', argstr='-pdf %s', - desc=('Sets the distribution to use for the calibration. The default is the Bingham ' - 'distribution, which allows elliptical probability density contours. ' - 'Currently supported options are: ' - ' bingham - The Bingham distribution, which allows elliptical probability ' - ' density contours. ' - ' watson - The Watson distribution. This distribution is rotationally symmetric.'), - usedefault=True) - binincsize = traits.Int(argstr='-binincsize %d', units='NA', - desc=('Sets the size of the bins. In the case of 2D histograms such as the ' - 'Bingham, the bins are always square. Default is 1.')) - minvectsperbin = traits.Int(argstr='-minvectsperbin %d', units='NA', - desc=('Specifies the minimum number of fibre-orientation estimates a bin ' - 'must contain before it is used in the lut line/surface generation. ' - 'Default is 50. If you get the error "no fibre-orientation estimates ' - 'in histogram!", the calibration data set is too small to get enough ' - 'samples in any of the histogram bins. You can decrease the minimum ' - 'number per bin to get things running in quick tests, but the sta- ' - 'tistics will not be reliable and for serious applications, you need ' - 'to increase the size of the calibration data set until the error goes.')) - directmap = traits.Bool(argstr='-directmap', - desc=('Use direct mapping between the eigenvalues and the distribution parameters ' - 'instead of the log of the eigenvalues.')) - order = traits.Int(argstr='-order %d', units='NA', - desc=('The order of the polynomial fitting the surface. Order 1 is linear. ' - 'Order 2 (default) is quadratic.')) + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + desc='Voxel-order data of the spherical functions peaks.') + info_file = File( + argstr='-infofile %s', + mandatory=True, + desc=('The Info file that corresponds to the calibration ' + 'datafile used in the reconstruction.')) + outputstem = traits.Str( + 'LUT', + argstr='-outputstem %s', + desc= + ('Define the name of the generated luts. The form of the filenames will be ' + '[outputstem]_oneFibreSurfaceCoeffs.Bdouble and ' + '[outputstem]_twoFibreSurfaceCoeffs.Bdouble'), + usedefault=True) + pdf = traits.Enum( + 'bingham', + 'watson', + argstr='-pdf %s', + desc= + ('Sets the distribution to use for the calibration. The default is the Bingham ' + 'distribution, which allows elliptical probability density contours. ' + 'Currently supported options are: ' + ' bingham - The Bingham distribution, which allows elliptical probability ' + ' density contours. ' + ' watson - The Watson distribution. This distribution is rotationally symmetric.' + ), + usedefault=True) + binincsize = traits.Int( + argstr='-binincsize %d', + units='NA', + desc= + ('Sets the size of the bins. In the case of 2D histograms such as the ' + 'Bingham, the bins are always square. Default is 1.')) + minvectsperbin = traits.Int( + argstr='-minvectsperbin %d', + units='NA', + desc= + ('Specifies the minimum number of fibre-orientation estimates a bin ' + 'must contain before it is used in the lut line/surface generation. ' + 'Default is 50. If you get the error "no fibre-orientation estimates ' + 'in histogram!", the calibration data set is too small to get enough ' + 'samples in any of the histogram bins. You can decrease the minimum ' + 'number per bin to get things running in quick tests, but the sta- ' + 'tistics will not be reliable and for serious applications, you need ' + 'to increase the size of the calibration data set until the error goes.' + )) + directmap = traits.Bool( + argstr='-directmap', + desc= + ('Use direct mapping between the eigenvalues and the distribution parameters ' + 'instead of the log of the eigenvalues.')) + order = traits.Int( + argstr='-order %d', + units='NA', + desc= + ('The order of the polynomial fitting the surface. Order 1 is linear. ' + 'Order 2 (default) is quadratic.')) class SFLUTGenOutputSpec(TraitedSpec): @@ -231,8 +294,10 @@ class SFLUTGen(StdOutCommandLine): def _list_outputs(self): outputs = self.output_spec().get() - outputs['lut_one_fibre'] = self.inputs.outputstem + '_oneFibreSurfaceCoeffs.Bdouble' - outputs['lut_two_fibres'] = self.inputs.outputstem + '_twoFibreSurfaceCoeffs.Bdouble' + outputs[ + 'lut_one_fibre'] = self.inputs.outputstem + '_oneFibreSurfaceCoeffs.Bdouble' + outputs[ + 'lut_two_fibres'] = self.inputs.outputstem + '_twoFibreSurfaceCoeffs.Bdouble' return outputs def _gen_outfilename(self): diff --git a/nipype/interfaces/camino/connectivity.py b/nipype/interfaces/camino/connectivity.py index 654d71b1f1..39e13e46c1 100644 --- a/nipype/interfaces/camino/connectivity.py +++ b/nipype/interfaces/camino/connectivity.py @@ -7,48 +7,76 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from ...utils.filemanip import split_filename -from ..base import (traits, TraitedSpec, File, - CommandLine, CommandLineInputSpec, isdefined) +from ..base import (traits, TraitedSpec, File, CommandLine, + CommandLineInputSpec, isdefined) class ConmatInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='-inputfile %s', mandatory=True, - desc='Streamlines as generated by the Track interface') - - target_file = File(exists=True, argstr='-targetfile %s', mandatory=True, - desc='An image containing targets, as used in ProcStreamlines interface.') - - scalar_file = File(exists=True, argstr='-scalarfile %s', - desc=('Optional scalar file for computing tract-based statistics. ' - 'Must be in the same space as the target file.'), - requires=['tract_stat']) - - targetname_file = File(exists=True, argstr='-targetnamefile %s', - desc=('Optional names of targets. This file should contain one entry per line, ' - 'with the target intensity followed by the name, separated by white space. ' - 'For example: ' - ' 1 some_brain_region ' - ' 2 some_other_region ' - 'These names will be used in the output. The names themselves should not ' - 'contain spaces or commas. The labels may be in any order but the output ' - 'matrices will be ordered by label intensity.')) - - tract_stat = traits.Enum("mean", "min", "max", "sum", "median", "var", argstr='-tractstat %s', units='NA', - desc=("Tract statistic to use. See TractStats for other options."), - requires=['scalar_file'], xor=['tract_prop']) - - tract_prop = traits.Enum("length", "endpointsep", argstr='-tractstat %s', - units='NA', xor=['tract_stat'], - desc=('Tract property average to compute in the connectivity matrix. ' - 'See TractStats for details.')) - - output_root = File(argstr='-outputroot %s', genfile=True, - desc=('filename root prepended onto the names of the output files. ' - 'The extension will be determined from the input.')) + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + desc='Streamlines as generated by the Track interface') + + target_file = File( + exists=True, + argstr='-targetfile %s', + mandatory=True, + desc= + 'An image containing targets, as used in ProcStreamlines interface.') + + scalar_file = File( + exists=True, + argstr='-scalarfile %s', + desc=('Optional scalar file for computing tract-based statistics. ' + 'Must be in the same space as the target file.'), + requires=['tract_stat']) + + targetname_file = File( + exists=True, + argstr='-targetnamefile %s', + desc= + ('Optional names of targets. This file should contain one entry per line, ' + 'with the target intensity followed by the name, separated by white space. ' + 'For example: ' + ' 1 some_brain_region ' + ' 2 some_other_region ' + 'These names will be used in the output. The names themselves should not ' + 'contain spaces or commas. The labels may be in any order but the output ' + 'matrices will be ordered by label intensity.')) + + tract_stat = traits.Enum( + "mean", + "min", + "max", + "sum", + "median", + "var", + argstr='-tractstat %s', + units='NA', + desc=("Tract statistic to use. See TractStats for other options."), + requires=['scalar_file'], + xor=['tract_prop']) + + tract_prop = traits.Enum( + "length", + "endpointsep", + argstr='-tractstat %s', + units='NA', + xor=['tract_stat'], + desc=('Tract property average to compute in the connectivity matrix. ' + 'See TractStats for details.')) + + output_root = File( + argstr='-outputroot %s', + genfile=True, + desc=('filename root prepended onto the names of the output files. ' + 'The extension will be determined from the input.')) class ConmatOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/camino/convert.py b/nipype/interfaces/camino/convert.py index 6cf8f4f253..3091efd348 100644 --- a/nipype/interfaces/camino/convert.py +++ b/nipype/interfaces/camino/convert.py @@ -7,36 +7,50 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import glob from ...utils.filemanip import split_filename -from ..base import (CommandLineInputSpec, CommandLine, traits, - TraitedSpec, File, StdOutCommandLine, - OutputMultiPath, StdOutCommandLineInputSpec, - isdefined) +from ..base import (CommandLineInputSpec, CommandLine, traits, TraitedSpec, + File, StdOutCommandLine, OutputMultiPath, + StdOutCommandLineInputSpec, isdefined) class Image2VoxelInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='-4dimage %s', - mandatory=True, position=1, - desc='4d image file') -# TODO convert list of files on the fly -# imagelist = File(exists=True, argstr='-imagelist %s', -# mandatory=True, position=1, -# desc='Name of a file containing a list of 3D images') -# -# imageprefix = traits.Str(argstr='-imageprefix %s', position=3, -# desc='Path to prepend onto filenames in the imagelist.') - - out_type = traits.Enum("float", "char", "short", "int", "long", "double", argstr='-outputdatatype %s', position=2, - desc='"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"', usedefault=True) + in_file = File( + exists=True, + argstr='-4dimage %s', + mandatory=True, + position=1, + desc='4d image file') + # TODO convert list of files on the fly + # imagelist = File(exists=True, argstr='-imagelist %s', + # mandatory=True, position=1, + # desc='Name of a file containing a list of 3D images') + # + # imageprefix = traits.Str(argstr='-imageprefix %s', position=3, + # desc='Path to prepend onto filenames in the imagelist.') + + out_type = traits.Enum( + "float", + "char", + "short", + "int", + "long", + "double", + argstr='-outputdatatype %s', + position=2, + desc= + '"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"', + usedefault=True) class Image2VoxelOutputSpec(TraitedSpec): - voxel_order = File(exists=True, desc='path/name of 4D volume in voxel order') + voxel_order = File( + exists=True, desc='path/name of 4D volume in voxel order') class Image2Voxel(StdOutCommandLine): @@ -70,29 +84,52 @@ def _gen_outfilename(self): class FSL2SchemeInputSpec(StdOutCommandLineInputSpec): - bvec_file = File(exists=True, argstr='-bvecfile %s', - mandatory=True, position=1, - desc='b vector file') - - bval_file = File(exists=True, argstr='-bvalfile %s', - mandatory=True, position=2, - desc='b value file') - - numscans = traits.Int(argstr='-numscans %d', units='NA', - desc="Output all measurements numerous (n) times, used when combining multiple scans from the same imaging session.") - - interleave = traits.Bool(argstr='-interleave', desc="Interleave repeated scans. Only used with -numscans.") - - bscale = traits.Float(argstr='-bscale %d', units='NA', - desc="Scaling factor to convert the b-values into different units. Default is 10^6.") - - diffusiontime = traits.Float(argstr='-diffusiontime %f', units='NA', - desc="Diffusion time") - - flipx = traits.Bool(argstr='-flipx', desc="Negate the x component of all the vectors.") - flipy = traits.Bool(argstr='-flipy', desc="Negate the y component of all the vectors.") - flipz = traits.Bool(argstr='-flipz', desc="Negate the z component of all the vectors.") - usegradmod = traits.Bool(argstr='-usegradmod', desc="Use the gradient magnitude to scale b. This option has no effect if your gradient directions have unit magnitude.") + bvec_file = File( + exists=True, + argstr='-bvecfile %s', + mandatory=True, + position=1, + desc='b vector file') + + bval_file = File( + exists=True, + argstr='-bvalfile %s', + mandatory=True, + position=2, + desc='b value file') + + numscans = traits.Int( + argstr='-numscans %d', + units='NA', + desc= + "Output all measurements numerous (n) times, used when combining multiple scans from the same imaging session." + ) + + interleave = traits.Bool( + argstr='-interleave', + desc="Interleave repeated scans. Only used with -numscans.") + + bscale = traits.Float( + argstr='-bscale %d', + units='NA', + desc= + "Scaling factor to convert the b-values into different units. Default is 10^6." + ) + + diffusiontime = traits.Float( + argstr='-diffusiontime %f', units='NA', desc="Diffusion time") + + flipx = traits.Bool( + argstr='-flipx', desc="Negate the x component of all the vectors.") + flipy = traits.Bool( + argstr='-flipy', desc="Negate the y component of all the vectors.") + flipz = traits.Bool( + argstr='-flipz', desc="Negate the z component of all the vectors.") + usegradmod = traits.Bool( + argstr='-usegradmod', + desc= + "Use the gradient magnitude to scale b. This option has no effect if your gradient directions have unit magnitude." + ) class FSL2SchemeOutputSpec(TraitedSpec): @@ -128,28 +165,61 @@ def _gen_outfilename(self): class VtkStreamlinesInputSpec(StdOutCommandLineInputSpec): - inputmodel = traits.Enum('raw', 'voxels', argstr='-inputmodel %s', desc='input model type (raw or voxels)', usedefault=True) - - in_file = File(exists=True, argstr=' < %s', - mandatory=True, position=-2, - desc='data file') - - voxeldims = traits.List(traits.Int, desc='voxel dimensions in mm', - argstr='-voxeldims %s', minlen=3, maxlen=3, position=4, - units='mm') - - seed_file = File(exists=False, argstr='-seedfile %s', position=1, - desc='image containing seed points') - - target_file = File(exists=False, argstr='-targetfile %s', position=2, - desc='image containing integer-valued target regions') - - scalar_file = File(exists=False, argstr='-scalarfile %s', position=3, - desc='image that is in the same physical space as the tracts') - - colourorient = traits.Bool(argstr='-colourorient', desc="Each point on the streamline is coloured by the local orientation.") - interpolatescalars = traits.Bool(argstr='-interpolatescalars', desc="the scalar value at each point on the streamline is calculated by trilinear interpolation") - interpolate = traits.Bool(argstr='-interpolate', desc="the scalar value at each point on the streamline is calculated by trilinear interpolation") + inputmodel = traits.Enum( + 'raw', + 'voxels', + argstr='-inputmodel %s', + desc='input model type (raw or voxels)', + usedefault=True) + + in_file = File( + exists=True, + argstr=' < %s', + mandatory=True, + position=-2, + desc='data file') + + voxeldims = traits.List( + traits.Int, + desc='voxel dimensions in mm', + argstr='-voxeldims %s', + minlen=3, + maxlen=3, + position=4, + units='mm') + + seed_file = File( + exists=False, + argstr='-seedfile %s', + position=1, + desc='image containing seed points') + + target_file = File( + exists=False, + argstr='-targetfile %s', + position=2, + desc='image containing integer-valued target regions') + + scalar_file = File( + exists=False, + argstr='-scalarfile %s', + position=3, + desc='image that is in the same physical space as the tracts') + + colourorient = traits.Bool( + argstr='-colourorient', + desc= + "Each point on the streamline is coloured by the local orientation.") + interpolatescalars = traits.Bool( + argstr='-interpolatescalars', + desc= + "the scalar value at each point on the streamline is calculated by trilinear interpolation" + ) + interpolate = traits.Bool( + argstr='-interpolate', + desc= + "the scalar value at each point on the streamline is calculated by trilinear interpolation" + ) class VtkStreamlinesOutputSpec(TraitedSpec): @@ -184,74 +254,170 @@ def _gen_outfilename(self): class ProcStreamlinesInputSpec(StdOutCommandLineInputSpec): - inputmodel = traits.Enum('raw', 'voxels', argstr='-inputmodel %s', desc='input model type (raw or voxels)', usedefault=True) - - in_file = File(exists=True, argstr='-inputfile %s', - mandatory=True, position=1, - desc='data file') - - maxtractpoints = traits.Int(argstr='-maxtractpoints %d', units='NA', - desc="maximum number of tract points") - mintractpoints = traits.Int(argstr='-mintractpoints %d', units='NA', - desc="minimum number of tract points") - maxtractlength = traits.Int(argstr='-maxtractlength %d', units='mm', - desc="maximum length of tracts") - mintractlength = traits.Int(argstr='-mintractlength %d', units='mm', - desc="minimum length of tracts") - datadims = traits.List(traits.Int, desc='data dimensions in voxels', - argstr='-datadims %s', minlen=3, maxlen=3, - units='voxels') - voxeldims = traits.List(traits.Int, desc='voxel dimensions in mm', - argstr='-voxeldims %s', minlen=3, maxlen=3, - units='mm') - seedpointmm = traits.List(traits.Int, desc='The coordinates of a single seed point for tractography in mm', - argstr='-seedpointmm %s', minlen=3, maxlen=3, - units='mm') - seedpointvox = traits.List(traits.Int, desc='The coordinates of a single seed point for tractography in voxels', - argstr='-seedpointvox %s', minlen=3, maxlen=3, - units='voxels') - seedfile = File(exists=False, argstr='-seedfile %s', - desc='Image Containing Seed Points') - regionindex = traits.Int(argstr='-regionindex %d', units='mm', - desc="index of specific region to process") - iterations = traits.Float(argstr='-iterations %d', units='NA', - desc="Number of streamlines generated for each seed. Not required when outputting streamlines, but needed to create PICo images. The default is 1 if the output is streamlines, and 5000 if the output is connection probability images.") - targetfile = File(exists=False, argstr='-targetfile %s', - desc='Image containing target volumes.') - allowmultitargets = traits.Bool(argstr='-allowmultitargets', desc="Allows streamlines to connect to multiple target volumes.") - directional = traits.List(traits.Int, desc='Splits the streamlines at the seed point and computes separate connection probabilities for each segment. Streamline segments are grouped according to their dot product with the vector (X, Y, Z). The ideal vector will be tangential to the streamline trajectory at the seed, such that the streamline projects from the seed along (X, Y, Z) and -(X, Y, Z). However, it is only necessary for the streamline trajectory to not be orthogonal to (X, Y, Z).', - argstr='-directional %s', minlen=3, maxlen=3, - units='NA') - waypointfile = File(exists=False, argstr='-waypointfile %s', - desc='Image containing waypoints. Waypoints are defined as regions of the image with the same intensity, where 0 is background and any value > 0 is a waypoint.') - truncateloops = traits.Bool(argstr='-truncateloops', desc="This option allows streamlines to enter a waypoint exactly once. After the streamline leaves the waypoint, it is truncated upon a second entry to the waypoint.") - discardloops = traits.Bool(argstr='-discardloops', desc="This option allows streamlines to enter a waypoint exactly once. After the streamline leaves the waypoint, the entire streamline is discarded upon a second entry to the waypoint.") - exclusionfile = File(exists=False, argstr='-exclusionfile %s', - desc='Image containing exclusion ROIs. This should be an Analyze 7.5 header / image file.hdr and file.img.') - truncateinexclusion = traits.Bool(argstr='-truncateinexclusion', desc="Retain segments of a streamline before entry to an exclusion ROI.") - - endpointfile = File(exists=False, argstr='-endpointfile %s', - desc='Image containing endpoint ROIs. This should be an Analyze 7.5 header / image file.hdr and file.img.') - - resamplestepsize = traits.Float(argstr='-resamplestepsize %d', units='NA', - desc="Each point on a streamline is tested for entry into target, exclusion or waypoint volumes. If the length between points on a tract is not much smaller than the voxel length, then streamlines may pass through part of a voxel without being counted. To avoid this, the program resamples streamlines such that the step size is one tenth of the smallest voxel dimension in the image. This increases the size of raw or oogl streamline output and incurs some performance penalty. The resample resolution can be controlled with this option or disabled altogether by passing a negative step size or by passing the -noresample option.") - - noresample = traits.Bool(argstr='-noresample', desc="Disables resampling of input streamlines. Resampling is automatically disabled if the input model is voxels.") - - outputtracts = traits.Bool(argstr='-outputtracts', desc="Output streamlines in raw binary format.") - - outputroot = File(exists=False, argstr='-outputroot %s', - desc='Prepended onto all output file names.') - - gzip = traits.Bool(argstr='-gzip', desc="save the output image in gzip format") - outputcp = traits.Bool(argstr='-outputcp', desc="output the connection probability map (Analyze image, float)", - requires=['outputroot', 'seedfile']) - outputsc = traits.Bool(argstr='-outputsc', desc="output the connection probability map (raw streamlines, int)", - requires=['outputroot', 'seedfile']) - outputacm = traits.Bool(argstr='-outputacm', desc="output all tracts in a single connection probability map (Analyze image)", - requires=['outputroot', 'seedfile']) - outputcbs = traits.Bool(argstr='-outputcbs', desc="outputs connectivity-based segmentation maps; requires target outputfile", - requires=['outputroot', 'targetfile', 'seedfile']) + inputmodel = traits.Enum( + 'raw', + 'voxels', + argstr='-inputmodel %s', + desc='input model type (raw or voxels)', + usedefault=True) + + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + position=1, + desc='data file') + + maxtractpoints = traits.Int( + argstr='-maxtractpoints %d', + units='NA', + desc="maximum number of tract points") + mintractpoints = traits.Int( + argstr='-mintractpoints %d', + units='NA', + desc="minimum number of tract points") + maxtractlength = traits.Int( + argstr='-maxtractlength %d', + units='mm', + desc="maximum length of tracts") + mintractlength = traits.Int( + argstr='-mintractlength %d', + units='mm', + desc="minimum length of tracts") + datadims = traits.List( + traits.Int, + desc='data dimensions in voxels', + argstr='-datadims %s', + minlen=3, + maxlen=3, + units='voxels') + voxeldims = traits.List( + traits.Int, + desc='voxel dimensions in mm', + argstr='-voxeldims %s', + minlen=3, + maxlen=3, + units='mm') + seedpointmm = traits.List( + traits.Int, + desc='The coordinates of a single seed point for tractography in mm', + argstr='-seedpointmm %s', + minlen=3, + maxlen=3, + units='mm') + seedpointvox = traits.List( + traits.Int, + desc= + 'The coordinates of a single seed point for tractography in voxels', + argstr='-seedpointvox %s', + minlen=3, + maxlen=3, + units='voxels') + seedfile = File( + exists=False, + argstr='-seedfile %s', + desc='Image Containing Seed Points') + regionindex = traits.Int( + argstr='-regionindex %d', + units='mm', + desc="index of specific region to process") + iterations = traits.Float( + argstr='-iterations %d', + units='NA', + desc= + "Number of streamlines generated for each seed. Not required when outputting streamlines, but needed to create PICo images. The default is 1 if the output is streamlines, and 5000 if the output is connection probability images." + ) + targetfile = File( + exists=False, + argstr='-targetfile %s', + desc='Image containing target volumes.') + allowmultitargets = traits.Bool( + argstr='-allowmultitargets', + desc="Allows streamlines to connect to multiple target volumes.") + directional = traits.List( + traits.Int, + desc= + 'Splits the streamlines at the seed point and computes separate connection probabilities for each segment. Streamline segments are grouped according to their dot product with the vector (X, Y, Z). The ideal vector will be tangential to the streamline trajectory at the seed, such that the streamline projects from the seed along (X, Y, Z) and -(X, Y, Z). However, it is only necessary for the streamline trajectory to not be orthogonal to (X, Y, Z).', + argstr='-directional %s', + minlen=3, + maxlen=3, + units='NA') + waypointfile = File( + exists=False, + argstr='-waypointfile %s', + desc= + 'Image containing waypoints. Waypoints are defined as regions of the image with the same intensity, where 0 is background and any value > 0 is a waypoint.' + ) + truncateloops = traits.Bool( + argstr='-truncateloops', + desc= + "This option allows streamlines to enter a waypoint exactly once. After the streamline leaves the waypoint, it is truncated upon a second entry to the waypoint." + ) + discardloops = traits.Bool( + argstr='-discardloops', + desc= + "This option allows streamlines to enter a waypoint exactly once. After the streamline leaves the waypoint, the entire streamline is discarded upon a second entry to the waypoint." + ) + exclusionfile = File( + exists=False, + argstr='-exclusionfile %s', + desc= + 'Image containing exclusion ROIs. This should be an Analyze 7.5 header / image file.hdr and file.img.' + ) + truncateinexclusion = traits.Bool( + argstr='-truncateinexclusion', + desc="Retain segments of a streamline before entry to an exclusion ROI." + ) + + endpointfile = File( + exists=False, + argstr='-endpointfile %s', + desc= + 'Image containing endpoint ROIs. This should be an Analyze 7.5 header / image file.hdr and file.img.' + ) + + resamplestepsize = traits.Float( + argstr='-resamplestepsize %d', + units='NA', + desc= + "Each point on a streamline is tested for entry into target, exclusion or waypoint volumes. If the length between points on a tract is not much smaller than the voxel length, then streamlines may pass through part of a voxel without being counted. To avoid this, the program resamples streamlines such that the step size is one tenth of the smallest voxel dimension in the image. This increases the size of raw or oogl streamline output and incurs some performance penalty. The resample resolution can be controlled with this option or disabled altogether by passing a negative step size or by passing the -noresample option." + ) + + noresample = traits.Bool( + argstr='-noresample', + desc= + "Disables resampling of input streamlines. Resampling is automatically disabled if the input model is voxels." + ) + + outputtracts = traits.Bool( + argstr='-outputtracts', + desc="Output streamlines in raw binary format.") + + outputroot = File( + exists=False, + argstr='-outputroot %s', + desc='Prepended onto all output file names.') + + gzip = traits.Bool( + argstr='-gzip', desc="save the output image in gzip format") + outputcp = traits.Bool( + argstr='-outputcp', + desc="output the connection probability map (Analyze image, float)", + requires=['outputroot', 'seedfile']) + outputsc = traits.Bool( + argstr='-outputsc', + desc="output the connection probability map (raw streamlines, int)", + requires=['outputroot', 'seedfile']) + outputacm = traits.Bool( + argstr='-outputacm', + desc= + "output all tracts in a single connection probability map (Analyze image)", + requires=['outputroot', 'seedfile']) + outputcbs = traits.Bool( + argstr='-outputcbs', + desc= + "outputs connectivity-based segmentation maps; requires target outputfile", + requires=['outputroot', 'targetfile', 'seedfile']) class ProcStreamlinesOutputSpec(TraitedSpec): @@ -291,7 +457,8 @@ def _run_interface(self, runtime): if not os.path.exists(base): os.makedirs(base) new_runtime = super(ProcStreamlines, self)._run_interface(runtime) - self.outputroot_files = glob.glob(os.path.join(os.getcwd(), actual_outputroot + '*')) + self.outputroot_files = glob.glob( + os.path.join(os.getcwd(), actual_outputroot + '*')) return new_runtime else: new_runtime = super(ProcStreamlines, self)._run_interface(runtime) @@ -313,16 +480,27 @@ def _gen_outfilename(self): class TractShredderInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=-2, desc='tract file') + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=-2, + desc='tract file') - offset = traits.Int(argstr='%d', units='NA', - desc='initial offset of offset tracts', position=1) + offset = traits.Int( + argstr='%d', + units='NA', + desc='initial offset of offset tracts', + position=1) - bunchsize = traits.Int(argstr='%d', units='NA', - desc='reads and outputs a group of bunchsize tracts', position=2) + bunchsize = traits.Int( + argstr='%d', + units='NA', + desc='reads and outputs a group of bunchsize tracts', + position=2) - space = traits.Int(argstr='%d', units='NA', - desc='skips space tracts', position=3) + space = traits.Int( + argstr='%d', units='NA', desc='skips space tracts', position=3) class TractShredderOutputSpec(TraitedSpec): @@ -365,22 +543,37 @@ def _gen_outfilename(self): class DT2NIfTIInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='-inputfile %s', mandatory=True, position=1, - desc='tract file') - - output_root = File(argstr='-outputroot %s', position=2, genfile=True, - desc='filename root prepended onto the names of three output files.') - - header_file = File(exists=True, argstr='-header %s', mandatory=True, position=3, - desc=' A Nifti .nii or .hdr file containing the header information') + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + position=1, + desc='tract file') + + output_root = File( + argstr='-outputroot %s', + position=2, + genfile=True, + desc='filename root prepended onto the names of three output files.') + + header_file = File( + exists=True, + argstr='-header %s', + mandatory=True, + position=3, + desc=' A Nifti .nii or .hdr file containing the header information') class DT2NIfTIOutputSpec(TraitedSpec): dt = File(exists=True, desc='diffusion tensors in NIfTI format') - exitcode = File(exists=True, desc='exit codes from Camino reconstruction in NIfTI format') + exitcode = File( + exists=True, + desc='exit codes from Camino reconstruction in NIfTI format') - lns0 = File(exists=True, desc='estimated lns0 from Camino reconstruction in NIfTI format') + lns0 = File( + exists=True, + desc='estimated lns0 from Camino reconstruction in NIfTI format') class DT2NIfTI(CommandLine): @@ -418,33 +611,54 @@ def _gen_filename(self, name): class NIfTIDT2CaminoInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='-inputfile %s', mandatory=True, position=1, - desc='A NIFTI-1 dataset containing diffusion tensors. The tensors are assumed to be ' - 'in lower-triangular order as specified by the NIFTI standard for the storage of ' - 'symmetric matrices. This file should be either a .nii or a .hdr file.') - - s0_file = File(argstr='-s0 %s', exists=True, - desc='File containing the unweighted signal for each voxel, may be a raw binary ' - 'file (specify type with -inputdatatype) or a supported image file.') - - lns0_file = File(argstr='-lns0 %s', exists=True, - desc='File containing the log of the unweighted signal for each voxel, may be a ' - 'raw binary file (specify type with -inputdatatype) or a supported image file.') - - bgmask = File(argstr='-bgmask %s', exists=True, - desc='Binary valued brain / background segmentation, may be a raw binary file ' - '(specify type with -maskdatatype) or a supported image file.') - - scaleslope = traits.Float(argstr='-scaleslope %s', - desc='A value v in the diffusion tensor is scaled to v * s + i. This is ' - 'applied after any scaling specified by the input image. Default is 1.0.') - - scaleinter = traits.Float(argstr='-scaleinter %s', - desc='A value v in the diffusion tensor is scaled to v * s + i. This is ' - 'applied after any scaling specified by the input image. Default is 0.0.') - - uppertriangular = traits.Bool(argstr='-uppertriangular %s', - desc='Specifies input in upper-triangular (VTK style) order.') + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + position=1, + desc= + 'A NIFTI-1 dataset containing diffusion tensors. The tensors are assumed to be ' + 'in lower-triangular order as specified by the NIFTI standard for the storage of ' + 'symmetric matrices. This file should be either a .nii or a .hdr file.' + ) + + s0_file = File( + argstr='-s0 %s', + exists=True, + desc= + 'File containing the unweighted signal for each voxel, may be a raw binary ' + 'file (specify type with -inputdatatype) or a supported image file.') + + lns0_file = File( + argstr='-lns0 %s', + exists=True, + desc= + 'File containing the log of the unweighted signal for each voxel, may be a ' + 'raw binary file (specify type with -inputdatatype) or a supported image file.' + ) + + bgmask = File( + argstr='-bgmask %s', + exists=True, + desc= + 'Binary valued brain / background segmentation, may be a raw binary file ' + '(specify type with -maskdatatype) or a supported image file.') + + scaleslope = traits.Float( + argstr='-scaleslope %s', + desc='A value v in the diffusion tensor is scaled to v * s + i. This is ' + 'applied after any scaling specified by the input image. Default is 1.0.' + ) + + scaleinter = traits.Float( + argstr='-scaleinter %s', + desc='A value v in the diffusion tensor is scaled to v * s + i. This is ' + 'applied after any scaling specified by the input image. Default is 0.0.' + ) + + uppertriangular = traits.Bool( + argstr='-uppertriangular %s', + desc='Specifies input in upper-triangular (VTK style) order.') class NIfTIDT2CaminoOutputSpec(TraitedSpec): @@ -488,22 +702,35 @@ def _gen_filename(self, name): class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=1, - desc='Tensor-fitted data filename') - - scheme_file = File(exists=True, argstr='%s', position=2, - desc=('Camino scheme file (b values / vectors, ' - 'see camino.fsl2scheme)')) - - readheader = File(exists=True, argstr='-readheader %s', position=3, - desc=('Reads header information from file and prints to ' - 'stdout. If this option is not specified, then the ' - 'program writes a header based on the other ' - 'arguments.')) - - printimagedims = File(exists=True, argstr='-printimagedims %s', position=3, - desc=('Prints image data and voxel dimensions as ' - 'Camino arguments and exits.')) + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=1, + desc='Tensor-fitted data filename') + + scheme_file = File( + exists=True, + argstr='%s', + position=2, + desc=('Camino scheme file (b values / vectors, ' + 'see camino.fsl2scheme)')) + + readheader = File( + exists=True, + argstr='-readheader %s', + position=3, + desc=('Reads header information from file and prints to ' + 'stdout. If this option is not specified, then the ' + 'program writes a header based on the other ' + 'arguments.')) + + printimagedims = File( + exists=True, + argstr='-printimagedims %s', + position=3, + desc=('Prints image data and voxel dimensions as ' + 'Camino arguments and exits.')) # How do we implement both file and enum (for the program) in one argument? # Is this option useful anyway? @@ -511,91 +738,141 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): # Prints data dimension (and type, if relevant) arguments for a specific # Camino program, where prog is one of shredder, scanner2voxel, # vcthreshselect, pdview, track. - printprogargs = File(exists=True, argstr='-printprogargs %s', position=3, - desc=('Prints data dimension (and type, if relevant) ' - 'arguments for a specific Camino program, where ' - 'prog is one of shredder, scanner2voxel, ' - 'vcthreshselect, pdview, track.')) - - printintelbyteorder = File(exists=True, argstr='-printintelbyteorder %s', - position=3, - desc=('Prints 1 if the header is little-endian, ' - '0 otherwise.')) - - printbigendian = File(exists=True, argstr='-printbigendian %s', position=3, - desc=('Prints 1 if the header is big-endian, 0 ' - 'otherwise.')) - - initfromheader = File(exists=True, argstr='-initfromheader %s', position=3, - desc=('Reads header information from file and ' - 'intializes a new header with the values read ' - 'from the file. You may replace any ' - 'combination of fields in the new header by ' - 'specifying subsequent options.')) - - data_dims = traits.List(traits.Int, desc='data dimensions in voxels', - argstr='-datadims %s', minlen=3, maxlen=3, - units='voxels') - - voxel_dims = traits.List(traits.Float, desc='voxel dimensions in mm', - argstr='-voxeldims %s', minlen=3, maxlen=3, - units='mm') - - centre = traits.List(traits.Int, argstr='-centre %s', minlen=3, maxlen=3, - units='mm', - desc=('Voxel specifying origin of Talairach ' - 'coordinate system for SPM, default [0 0 0].')) - - picoseed = traits.List(traits.Int, argstr='-picoseed %s', minlen=3, - maxlen=3, - desc=('Voxel specifying the seed (for PICo maps), ' - 'default [0 0 0].'), units='mm') - - nimages = traits.Int(argstr='-nimages %d', units='NA', - desc="Number of images in the img file. Default 1.") - - datatype = traits.Enum('byte', 'char', '[u]short', '[u]int', 'float', - 'complex', 'double', argstr='-datatype %s', - desc=('The char datatype is 8 bit (not the 16 bit ' - 'char of Java), as specified by the Analyze ' - '7.5 standard. The byte, ushort and uint ' - 'types are not part of the Analyze ' - 'specification but are supported by SPM.'), - mandatory=True) - - offset = traits.Int(argstr='-offset %d', units='NA', - desc=('According to the Analyze 7.5 standard, this is ' - 'the byte offset in the .img file at which ' - 'voxels start. This value can be negative to ' - 'specify that the absolute value is applied for ' - 'every image in the file.')) - - greylevels = traits.List(traits.Int, argstr='-gl %s', minlen=2, maxlen=2, - desc=('Minimum and maximum greylevels. Stored as ' - 'shorts in the header.'), units='NA') - - scaleslope = traits.Float(argstr='-scaleslope %d', units='NA', - desc=('Intensities in the image are scaled by ' - 'this factor by SPM and MRICro. Default is ' - '1.0.')) - - scaleinter = traits.Float(argstr='-scaleinter %d', units='NA', - desc=('Constant to add to the image intensities. ' - 'Used by SPM and MRIcro.')) - - description = traits.String(argstr='-description %s', - desc=('Short description - No spaces, max ' - 'length 79 bytes. Will be null ' - 'terminated automatically.')) - - intelbyteorder = traits.Bool(argstr='-intelbyteorder', - desc=("Write header in intel byte order " - "(little-endian).")) - - networkbyteorder = traits.Bool(argstr='-networkbyteorder', - desc=("Write header in network byte order " - "(big-endian). This is the default " - "for new headers.")) + printprogargs = File( + exists=True, + argstr='-printprogargs %s', + position=3, + desc=('Prints data dimension (and type, if relevant) ' + 'arguments for a specific Camino program, where ' + 'prog is one of shredder, scanner2voxel, ' + 'vcthreshselect, pdview, track.')) + + printintelbyteorder = File( + exists=True, + argstr='-printintelbyteorder %s', + position=3, + desc=('Prints 1 if the header is little-endian, ' + '0 otherwise.')) + + printbigendian = File( + exists=True, + argstr='-printbigendian %s', + position=3, + desc=('Prints 1 if the header is big-endian, 0 ' + 'otherwise.')) + + initfromheader = File( + exists=True, + argstr='-initfromheader %s', + position=3, + desc=('Reads header information from file and ' + 'intializes a new header with the values read ' + 'from the file. You may replace any ' + 'combination of fields in the new header by ' + 'specifying subsequent options.')) + + data_dims = traits.List( + traits.Int, + desc='data dimensions in voxels', + argstr='-datadims %s', + minlen=3, + maxlen=3, + units='voxels') + + voxel_dims = traits.List( + traits.Float, + desc='voxel dimensions in mm', + argstr='-voxeldims %s', + minlen=3, + maxlen=3, + units='mm') + + centre = traits.List( + traits.Int, + argstr='-centre %s', + minlen=3, + maxlen=3, + units='mm', + desc=('Voxel specifying origin of Talairach ' + 'coordinate system for SPM, default [0 0 0].')) + + picoseed = traits.List( + traits.Int, + argstr='-picoseed %s', + minlen=3, + maxlen=3, + desc=('Voxel specifying the seed (for PICo maps), ' + 'default [0 0 0].'), + units='mm') + + nimages = traits.Int( + argstr='-nimages %d', + units='NA', + desc="Number of images in the img file. Default 1.") + + datatype = traits.Enum( + 'byte', + 'char', + '[u]short', + '[u]int', + 'float', + 'complex', + 'double', + argstr='-datatype %s', + desc=('The char datatype is 8 bit (not the 16 bit ' + 'char of Java), as specified by the Analyze ' + '7.5 standard. The byte, ushort and uint ' + 'types are not part of the Analyze ' + 'specification but are supported by SPM.'), + mandatory=True) + + offset = traits.Int( + argstr='-offset %d', + units='NA', + desc=('According to the Analyze 7.5 standard, this is ' + 'the byte offset in the .img file at which ' + 'voxels start. This value can be negative to ' + 'specify that the absolute value is applied for ' + 'every image in the file.')) + + greylevels = traits.List( + traits.Int, + argstr='-gl %s', + minlen=2, + maxlen=2, + desc=('Minimum and maximum greylevels. Stored as ' + 'shorts in the header.'), + units='NA') + + scaleslope = traits.Float( + argstr='-scaleslope %d', + units='NA', + desc=('Intensities in the image are scaled by ' + 'this factor by SPM and MRICro. Default is ' + '1.0.')) + + scaleinter = traits.Float( + argstr='-scaleinter %d', + units='NA', + desc=('Constant to add to the image intensities. ' + 'Used by SPM and MRIcro.')) + + description = traits.String( + argstr='-description %s', + desc=('Short description - No spaces, max ' + 'length 79 bytes. Will be null ' + 'terminated automatically.')) + + intelbyteorder = traits.Bool( + argstr='-intelbyteorder', + desc=("Write header in intel byte order " + "(little-endian).")) + + networkbyteorder = traits.Bool( + argstr='-networkbyteorder', + desc=("Write header in network byte order " + "(big-endian). This is the default " + "for new headers.")) class AnalyzeHeaderOutputSpec(TraitedSpec): @@ -641,16 +918,27 @@ def _gen_outfilename(self): class ShredderInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=-2, desc='raw binary data file') - - offset = traits.Int(argstr='%d', units='NA', - desc='initial offset of offset bytes', position=1) - - chunksize = traits.Int(argstr='%d', units='NA', - desc='reads and outputs a chunk of chunksize bytes', position=2) - - space = traits.Int(argstr='%d', units='NA', - desc='skips space bytes', position=3) + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=-2, + desc='raw binary data file') + + offset = traits.Int( + argstr='%d', + units='NA', + desc='initial offset of offset bytes', + position=1) + + chunksize = traits.Int( + argstr='%d', + units='NA', + desc='reads and outputs a chunk of chunksize bytes', + position=2) + + space = traits.Int( + argstr='%d', units='NA', desc='skips space bytes', position=3) class ShredderOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/camino/dti.py b/nipype/interfaces/camino/dti.py index 5aba0560c1..a3b0f74c48 100644 --- a/nipype/interfaces/camino/dti.py +++ b/nipype/interfaces/camino/dti.py @@ -7,35 +7,51 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from ...utils.filemanip import split_filename -from ..base import (CommandLineInputSpec, CommandLine, traits, - TraitedSpec, File, Directory, StdOutCommandLine, - StdOutCommandLineInputSpec, isdefined, - InputMultiPath) +from ..base import (CommandLineInputSpec, CommandLine, traits, TraitedSpec, + File, Directory, StdOutCommandLine, + StdOutCommandLineInputSpec, isdefined, InputMultiPath) class DTIFitInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=1, - desc='voxel-order data filename') - - bgmask = File(argstr='-bgmask %s', exists=True, - desc=('Provides the name of a file containing a background mask computed using, ' - 'for example, FSL bet2 program. The mask file contains zero in background ' - 'voxels and non-zero in foreground.')) - - scheme_file = File(exists=True, argstr='%s', mandatory=True, position=2, - desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') - - non_linear = traits.Bool(argstr='-nonlinear', position=3, - desc="Use non-linear fitting instead of the default linear regression to the log measurements. ") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=1, + desc='voxel-order data filename') + + bgmask = File( + argstr='-bgmask %s', + exists=True, + desc= + ('Provides the name of a file containing a background mask computed using, ' + 'for example, FSL bet2 program. The mask file contains zero in background ' + 'voxels and non-zero in foreground.')) + + scheme_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=2, + desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') + + non_linear = traits.Bool( + argstr='-nonlinear', + position=3, + desc= + "Use non-linear fitting instead of the default linear regression to the log measurements. " + ) class DTIFitOutputSpec(TraitedSpec): - tensor_fitted = File(exists=True, desc='path/name of 4D volume in voxel order') + tensor_fitted = File( + exists=True, desc='path/name of 4D volume in voxel order') class DTIFit(StdOutCommandLine): @@ -75,40 +91,80 @@ def _gen_outfilename(self): class DTMetricInputSpec(CommandLineInputSpec): - eigen_data = File(exists=True, argstr='-inputfile %s', mandatory=True, - desc='voxel-order data filename') - - metric = traits.Enum('fa', 'md', 'rd', 'l1', 'l2', 'l3', 'tr', 'ra', '2dfa', 'cl', 'cp', 'cs', - argstr='-stat %s', mandatory=True, - desc=('Specifies the metric to compute. Possible choices are: ' - '"fa", "md", "rd", "l1", "l2", "l3", "tr", "ra", "2dfa", "cl", "cp" or "cs".')) - - inputdatatype = traits.Enum('double', 'float', 'long', 'int', 'short', 'char', - argstr='-inputdatatype %s', usedefault=True, - desc=('Specifies the data type of the input data. ' - 'The data type can be any of the following strings: ' - '"char", "short", "int", "long", "float" or "double".' - 'Default is double data type')) - - outputdatatype = traits.Enum('double', 'float', 'long', 'int', 'short', 'char', - argstr='-outputdatatype %s', usedefault=True, - desc=('Specifies the data type of the output data. ' - 'The data type can be any of the following strings: ' - '"char", "short", "int", "long", "float" or "double".' - 'Default is double data type')) - - data_header = File(argstr='-header %s', exists=True, - desc=('A Nifti .nii or .nii.gz file containing the header information. ' - 'Usually this will be the header of the raw data file from which ' - 'the diffusion tensors were reconstructed.')) - - outputfile = File(argstr='-outputfile %s', genfile=True, - desc=('Output name. Output will be a .nii.gz file if data_header is provided and' - 'in voxel order with outputdatatype datatype (default: double) otherwise.')) + eigen_data = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + desc='voxel-order data filename') + + metric = traits.Enum( + 'fa', + 'md', + 'rd', + 'l1', + 'l2', + 'l3', + 'tr', + 'ra', + '2dfa', + 'cl', + 'cp', + 'cs', + argstr='-stat %s', + mandatory=True, + desc= + ('Specifies the metric to compute. Possible choices are: ' + '"fa", "md", "rd", "l1", "l2", "l3", "tr", "ra", "2dfa", "cl", "cp" or "cs".' + )) + + inputdatatype = traits.Enum( + 'double', + 'float', + 'long', + 'int', + 'short', + 'char', + argstr='-inputdatatype %s', + usedefault=True, + desc=('Specifies the data type of the input data. ' + 'The data type can be any of the following strings: ' + '"char", "short", "int", "long", "float" or "double".' + 'Default is double data type')) + + outputdatatype = traits.Enum( + 'double', + 'float', + 'long', + 'int', + 'short', + 'char', + argstr='-outputdatatype %s', + usedefault=True, + desc=('Specifies the data type of the output data. ' + 'The data type can be any of the following strings: ' + '"char", "short", "int", "long", "float" or "double".' + 'Default is double data type')) + + data_header = File( + argstr='-header %s', + exists=True, + desc=( + 'A Nifti .nii or .nii.gz file containing the header information. ' + 'Usually this will be the header of the raw data file from which ' + 'the diffusion tensors were reconstructed.')) + + outputfile = File( + argstr='-outputfile %s', + genfile=True, + desc= + ('Output name. Output will be a .nii.gz file if data_header is provided and' + 'in voxel order with outputdatatype datatype (default: double) otherwise.' + )) class DTMetricOutputSpec(TraitedSpec): - metric_stats = File(exists=True, desc='Diffusion Tensor statistics of the chosen metric') + metric_stats = File( + exists=True, desc='Diffusion Tensor statistics of the chosen metric') class DTMetric(CommandLine): @@ -182,52 +238,132 @@ def _gen_model_options(): # @NoSelf Generate all possible permutations of < multi - tensor > < single - tensor > options """ - single_tensor = ['dt', 'restore', 'algdt', 'nldt_pos', 'nldt', 'ldt_wtd'] - multi_tensor = ['cylcyl', 'cylcyl_eq', 'pospos', 'pospos_eq', 'poscyl', 'poscyl_eq', - 'cylcylcyl', 'cylcylcyl_eq', 'pospospos', 'pospospos_eq', - 'posposcyl', 'posposcyl_eq', 'poscylcyl', 'poscylcyl_eq'] + single_tensor = [ + 'dt', 'restore', 'algdt', 'nldt_pos', 'nldt', 'ldt_wtd' + ] + multi_tensor = [ + 'cylcyl', 'cylcyl_eq', 'pospos', 'pospos_eq', 'poscyl', + 'poscyl_eq', 'cylcylcyl', 'cylcylcyl_eq', 'pospospos', + 'pospospos_eq', 'posposcyl', 'posposcyl_eq', 'poscylcyl', + 'poscylcyl_eq' + ] other = ['adc', 'ball_stick'] model_list = single_tensor model_list.extend(other) - model_list.extend([multi + ' ' + single for multi in multi_tensor for single in single_tensor]) + model_list.extend([ + multi + ' ' + single for multi in multi_tensor + for single in single_tensor + ]) return model_list - model = traits.Enum(_gen_model_options(), argstr='-model %s', mandatory=True, desc='Specifies the model to be fit to the data.') - - in_file = File(exists=True, argstr='-inputfile %s', mandatory=True, desc='voxel-order data filename') - - inputdatatype = traits.Enum('float', 'char', 'short', 'int', 'long', 'double', argstr='-inputdatatype %s', - desc='Specifies the data type of the input file: "char", "short", "int", "long", "float" or "double". The input file must have BIG-ENDIAN ordering. By default, the input type is "float".') - - scheme_file = File(exists=True, argstr='-schemefile %s', mandatory=True, - desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') - - outputfile = File(argstr='-outputfile %s', desc='Filename of the output file.') - - outlier = File(argstr='-outliermap %s', exists=True, desc='Specifies the name of the file to contain the outlier map generated by the RESTORE algorithm.') - - noisemap = File(argstr='-noisemap %s', exists=True, desc='Specifies the name of the file to contain the estimated noise variance on the diffusion-weighted signal, generated by a weighted tensor fit. The data type of this file is big-endian double.') - - residualmap = File(argstr='-residualmap %s', exists=True, desc='Specifies the name of the file to contain the weighted residual errors after computing a weighted linear tensor fit. One value is produced per measurement, in voxel order.The data type of this file is big-endian double. Images of the residuals for each measurement can be extracted with shredder.') - - sigma = traits.Float(argstr='-sigma %G', desc='Specifies the standard deviation of the noise in the data. Required by the RESTORE algorithm.') - - bgthresh = traits.Float(argstr='-bgthresh %G', desc='Sets a threshold on the average q=0 measurement to separate foreground and background. The program does not process background voxels, but outputs the same number of values in background voxels and foreground voxels. Each value is zero in background voxels apart from the exit code which is -1.') - - bgmask = File(argstr='-bgmask %s', exists=True, desc='Provides the name of a file containing a background mask computed using, for example, FSL\'s bet2 program. The mask file contains zero in background voxels and non-zero in foreground.') - - cfthresh = traits.Float(argstr='-csfthresh %G', desc='Sets a threshold on the average q=0 measurement to determine which voxels are CSF. This program does not treat CSF voxels any different to other voxels.') - - fixedmodq = traits.List(traits.Float, argstr='-fixedmod %s', minlen=4, maxlen=4, desc='Specifies a spherical acquisition scheme with M measurements with q=0 and N measurements with |q|=Q and diffusion time tau. The N measurements with |q|=Q have unique directions. The program reads in the directions from the files in directory PointSets.') - - fixedbvalue = traits.List(traits.Float, argstr='-fixedbvalue %s', minlen=3, maxlen=3, desc='As above, but specifies . The resulting scheme is the same whether you specify b directly or indirectly using -fixedmodq.') - - tau = traits.Float(argstr='-tau %G', desc='Sets the diffusion time separately. This overrides the diffusion time specified in a scheme file or by a scheme index for both the acquisition scheme and in the data synthesis.') + model = traits.Enum( + _gen_model_options(), + argstr='-model %s', + mandatory=True, + desc='Specifies the model to be fit to the data.') + + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + desc='voxel-order data filename') + + inputdatatype = traits.Enum( + 'float', + 'char', + 'short', + 'int', + 'long', + 'double', + argstr='-inputdatatype %s', + desc= + 'Specifies the data type of the input file: "char", "short", "int", "long", "float" or "double". The input file must have BIG-ENDIAN ordering. By default, the input type is "float".' + ) + + scheme_file = File( + exists=True, + argstr='-schemefile %s', + mandatory=True, + desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') + + outputfile = File( + argstr='-outputfile %s', desc='Filename of the output file.') + + outlier = File( + argstr='-outliermap %s', + exists=True, + desc= + 'Specifies the name of the file to contain the outlier map generated by the RESTORE algorithm.' + ) + + noisemap = File( + argstr='-noisemap %s', + exists=True, + desc= + 'Specifies the name of the file to contain the estimated noise variance on the diffusion-weighted signal, generated by a weighted tensor fit. The data type of this file is big-endian double.' + ) + + residualmap = File( + argstr='-residualmap %s', + exists=True, + desc= + 'Specifies the name of the file to contain the weighted residual errors after computing a weighted linear tensor fit. One value is produced per measurement, in voxel order.The data type of this file is big-endian double. Images of the residuals for each measurement can be extracted with shredder.' + ) + + sigma = traits.Float( + argstr='-sigma %G', + desc= + 'Specifies the standard deviation of the noise in the data. Required by the RESTORE algorithm.' + ) + + bgthresh = traits.Float( + argstr='-bgthresh %G', + desc= + 'Sets a threshold on the average q=0 measurement to separate foreground and background. The program does not process background voxels, but outputs the same number of values in background voxels and foreground voxels. Each value is zero in background voxels apart from the exit code which is -1.' + ) + + bgmask = File( + argstr='-bgmask %s', + exists=True, + desc= + 'Provides the name of a file containing a background mask computed using, for example, FSL\'s bet2 program. The mask file contains zero in background voxels and non-zero in foreground.' + ) + + cfthresh = traits.Float( + argstr='-csfthresh %G', + desc= + 'Sets a threshold on the average q=0 measurement to determine which voxels are CSF. This program does not treat CSF voxels any different to other voxels.' + ) + + fixedmodq = traits.List( + traits.Float, + argstr='-fixedmod %s', + minlen=4, + maxlen=4, + desc= + 'Specifies a spherical acquisition scheme with M measurements with q=0 and N measurements with |q|=Q and diffusion time tau. The N measurements with |q|=Q have unique directions. The program reads in the directions from the files in directory PointSets.' + ) + + fixedbvalue = traits.List( + traits.Float, + argstr='-fixedbvalue %s', + minlen=3, + maxlen=3, + desc= + 'As above, but specifies . The resulting scheme is the same whether you specify b directly or indirectly using -fixedmodq.' + ) + + tau = traits.Float( + argstr='-tau %G', + desc= + 'Sets the diffusion time separately. This overrides the diffusion time specified in a scheme file or by a scheme index for both the acquisition scheme and in the data synthesis.' + ) class ModelFitOutputSpec(TraitedSpec): - fitted_data = File(exists=True, desc='output file of 4D volume in voxel order') + fitted_data = File( + exists=True, desc='output file of 4D volume in voxel order') class ModelFit(StdOutCommandLine): @@ -265,45 +401,79 @@ def _gen_outfilename(self): class DTLUTGenInputSpec(StdOutCommandLineInputSpec): - lrange = traits.List(traits.Float, desc='Index to one-tensor LUTs. This is the ratio L1/L3 and L2 / L3.' - 'The LUT is square, with half the values calculated (because L2 / L3 cannot be less than L1 / L3 by definition).' - 'The minimum must be >= 1. For comparison, a ratio L1 / L3 = 10 with L2 / L3 = 1 corresponds to an FA of 0.891, ' - 'and L1 / L3 = 15 with L2 / L3 = 1 corresponds to an FA of 0.929. The default range is 1 to 10.', - argstr='-lrange %s', minlen=2, maxlen=2, position=1, - units='NA') - - frange = traits.List(traits.Float, desc='Index to two-tensor LUTs. This is the fractional anisotropy' - ' of the two tensors. The default is 0.3 to 0.94', - argstr='-frange %s', minlen=2, maxlen=2, position=1, - units='NA') - - step = traits.Float(argstr='-step %f', units='NA', - desc='Distance between points in the LUT.' - 'For example, if lrange is 1 to 10 and the step is 0.1, LUT entries will be computed ' - 'at L1 / L3 = 1, 1.1, 1.2 ... 10.0 and at L2 / L3 = 1.0, 1.1 ... L1 / L3.' - 'For single tensor LUTs, the default step is 0.2, for two-tensor LUTs it is 0.02.') - - samples = traits.Int(argstr='-samples %d', units='NA', - desc='The number of synthetic measurements to generate at each point in the LUT. The default is 2000.') - - snr = traits.Float(argstr='-snr %f', units='NA', - desc='The signal to noise ratio of the unweighted (q = 0) measurements.' - 'This should match the SNR (in white matter) of the images that the LUTs are used with.') - - bingham = traits.Bool(argstr='-bingham', desc="Compute a LUT for the Bingham PDF. This is the default.") + lrange = traits.List( + traits.Float, + desc='Index to one-tensor LUTs. This is the ratio L1/L3 and L2 / L3.' + 'The LUT is square, with half the values calculated (because L2 / L3 cannot be less than L1 / L3 by definition).' + 'The minimum must be >= 1. For comparison, a ratio L1 / L3 = 10 with L2 / L3 = 1 corresponds to an FA of 0.891, ' + 'and L1 / L3 = 15 with L2 / L3 = 1 corresponds to an FA of 0.929. The default range is 1 to 10.', + argstr='-lrange %s', + minlen=2, + maxlen=2, + position=1, + units='NA') + + frange = traits.List( + traits.Float, + desc='Index to two-tensor LUTs. This is the fractional anisotropy' + ' of the two tensors. The default is 0.3 to 0.94', + argstr='-frange %s', + minlen=2, + maxlen=2, + position=1, + units='NA') + + step = traits.Float( + argstr='-step %f', + units='NA', + desc='Distance between points in the LUT.' + 'For example, if lrange is 1 to 10 and the step is 0.1, LUT entries will be computed ' + 'at L1 / L3 = 1, 1.1, 1.2 ... 10.0 and at L2 / L3 = 1.0, 1.1 ... L1 / L3.' + 'For single tensor LUTs, the default step is 0.2, for two-tensor LUTs it is 0.02.' + ) + + samples = traits.Int( + argstr='-samples %d', + units='NA', + desc= + 'The number of synthetic measurements to generate at each point in the LUT. The default is 2000.' + ) + + snr = traits.Float( + argstr='-snr %f', + units='NA', + desc='The signal to noise ratio of the unweighted (q = 0) measurements.' + 'This should match the SNR (in white matter) of the images that the LUTs are used with.' + ) + + bingham = traits.Bool( + argstr='-bingham', + desc="Compute a LUT for the Bingham PDF. This is the default.") acg = traits.Bool(argstr='-acg', desc="Compute a LUT for the ACG PDF.") - watson = traits.Bool(argstr='-watson', desc="Compute a LUT for the Watson PDF.") + watson = traits.Bool( + argstr='-watson', desc="Compute a LUT for the Watson PDF.") - inversion = traits.Int(argstr='-inversion %d', units='NA', - desc='Index of the inversion to use. The default is 1 (linear single tensor inversion).') + inversion = traits.Int( + argstr='-inversion %d', + units='NA', + desc= + 'Index of the inversion to use. The default is 1 (linear single tensor inversion).' + ) - trace = traits.Float(argstr='-trace %G', units='NA', - desc='Trace of the diffusion tensor(s) used in the test function in the LUT generation. The default is 2100E-12 m^2 s^-1.') + trace = traits.Float( + argstr='-trace %G', + units='NA', + desc= + 'Trace of the diffusion tensor(s) used in the test function in the LUT generation. The default is 2100E-12 m^2 s^-1.' + ) - scheme_file = File(argstr='-schemefile %s', mandatory=True, position=2, - desc='The scheme file of the images to be processed using this LUT.') + scheme_file = File( + argstr='-schemefile %s', + mandatory=True, + position=2, + desc='The scheme file of the images to be processed using this LUT.') class DTLUTGenOutputSpec(TraitedSpec): @@ -347,35 +517,65 @@ def _gen_outfilename(self): class PicoPDFsInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=1, - desc='voxel-order data filename') - - inputmodel = traits.Enum('dt', 'multitensor', 'pds', - argstr='-inputmodel %s', position=2, desc='input model type', usedefault=True) - - luts = InputMultiPath(File(exists=True), argstr='-luts %s', mandatory=True, - desc='Files containing the lookup tables.' - 'For tensor data, one lut must be specified for each type of inversion used in the image (one-tensor, two-tensor, three-tensor).' - 'For pds, the number of LUTs must match -numpds (it is acceptable to use the same LUT several times - see example, above).' - 'These LUTs may be generated with dtlutgen.') - - pdf = traits.Enum('bingham', 'watson', 'acg', - argstr='-pdf %s', position=4, desc=' Specifies the PDF to use. There are three choices:' - 'watson - The Watson distribution. This distribution is rotationally symmetric.' - 'bingham - The Bingham distributionn, which allows elliptical probability density contours.' - 'acg - The Angular Central Gaussian distribution, which also allows elliptical probability density contours', usedefault=True) - - directmap = traits.Bool(argstr='-directmap', desc="Only applicable when using pds as the inputmodel. Use direct mapping between the eigenvalues and the distribution parameters instead of the log of the eigenvalues.") - - maxcomponents = traits.Int(argstr='-maxcomponents %d', units='NA', - desc='The maximum number of tensor components in a voxel (default 2) for multitensor data.' - 'Currently, only the default is supported, but future releases may allow the input of three-tensor data using this option.') - - numpds = traits.Int(argstr='-numpds %d', units='NA', - desc='The maximum number of PDs in a voxel (default 3) for PD data.' - 'This option determines the size of the input and output voxels.' - 'This means that the data file may be large enough to accomodate three or more PDs,' - 'but does not mean that any of the voxels are classified as containing three or more PDs.') + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=1, + desc='voxel-order data filename') + + inputmodel = traits.Enum( + 'dt', + 'multitensor', + 'pds', + argstr='-inputmodel %s', + position=2, + desc='input model type', + usedefault=True) + + luts = InputMultiPath( + File(exists=True), + argstr='-luts %s', + mandatory=True, + desc='Files containing the lookup tables.' + 'For tensor data, one lut must be specified for each type of inversion used in the image (one-tensor, two-tensor, three-tensor).' + 'For pds, the number of LUTs must match -numpds (it is acceptable to use the same LUT several times - see example, above).' + 'These LUTs may be generated with dtlutgen.') + + pdf = traits.Enum( + 'bingham', + 'watson', + 'acg', + argstr='-pdf %s', + position=4, + desc=' Specifies the PDF to use. There are three choices:' + 'watson - The Watson distribution. This distribution is rotationally symmetric.' + 'bingham - The Bingham distributionn, which allows elliptical probability density contours.' + 'acg - The Angular Central Gaussian distribution, which also allows elliptical probability density contours', + usedefault=True) + + directmap = traits.Bool( + argstr='-directmap', + desc= + "Only applicable when using pds as the inputmodel. Use direct mapping between the eigenvalues and the distribution parameters instead of the log of the eigenvalues." + ) + + maxcomponents = traits.Int( + argstr='-maxcomponents %d', + units='NA', + desc= + 'The maximum number of tensor components in a voxel (default 2) for multitensor data.' + 'Currently, only the default is supported, but future releases may allow the input of three-tensor data using this option.' + ) + + numpds = traits.Int( + argstr='-numpds %d', + units='NA', + desc='The maximum number of PDs in a voxel (default 3) for PD data.' + 'This option determines the size of the input and output voxels.' + 'This means that the data file may be large enough to accomodate three or more PDs,' + 'but does not mean that any of the voxels are classified as containing three or more PDs.' + ) class PicoPDFsOutputSpec(TraitedSpec): @@ -411,139 +611,195 @@ def _gen_outfilename(self): class TrackInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='-inputfile %s', position=1, - desc='input data file') - - seed_file = File(exists=True, argstr='-seedfile %s', position=2, - desc='seed file') - - inputmodel = traits.Enum('dt', 'multitensor', 'sfpeak', 'pico', 'repbs_dt', - 'repbs_multitensor', 'ballstick', 'wildbs_dt', - 'bayesdirac', 'bayesdirac_dt', 'bedpostx_dyad', - 'bedpostx', argstr='-inputmodel %s', - desc='input model type', usedefault=True) - - tracker = traits.Enum('fact', 'euler', 'rk4', argstr='-tracker %s', - desc=("The tracking algorithm controls streamlines are " - "generated from the data. The choices are: " - "- FACT, which follows the local fibre orientation " - "in each voxel. No interpolation is used." - "- EULER, which uses a fixed step size along the " - "local fibre orientation. With nearest-neighbour " - "interpolation, this method may be very similar to " - "FACT, except that the step size is fixed, whereas " - "FACT steps extend to the boundary of the next voxel " - "(distance variable depending on the entry and exit " - "points to the voxel)." - "- RK4: Fourth-order Runge-Kutta method. The step " - "size is fixed, however the eventual direction of " - "the step is determined by taking and averaging a " - "series of partial steps."), usedefault=True) - - interpolator = traits.Enum('nn', 'prob_nn', 'linear', argstr='-interpolator %s', - desc=("The interpolation algorithm determines how " - "the fiber orientation(s) are defined at a given " - "continuous point within the input image. " - "Interpolators are only used when the tracking " - "algorithm is not FACT. The choices are: " - "- NN: Nearest-neighbour interpolation, just " - "uses the local voxel data directly." - "- PROB_NN: Probabilistic nearest-neighbor " - "interpolation, similar to the method pro- " - "posed by Behrens et al [Magnetic Resonance " - "in Medicine, 50:1077-1088, 2003]. The data " - "is not interpolated, but at each point we " - "randomly choose one of the 8 voxels sur- " - "rounding a point. The probability of choosing " - "a particular voxel is based on how close the " - "point is to the centre of that voxel." - "- LINEAR: Linear interpolation of the vector " - "field containing the principal directions at " - "each point.")) - - stepsize = traits.Float(argstr='-stepsize %f', requires=['tracker'], - desc=('Step size for EULER and RK4 tracking. ' - 'The default is 1mm.')) - - inputdatatype = traits.Enum('float', 'double', argstr='-inputdatatype %s', - desc='input file type') - - gzip = traits.Bool(argstr='-gzip', desc="save the output image in gzip format") - - maxcomponents = traits.Int(argstr='-maxcomponents %d', units='NA', - desc=("The maximum number of tensor components in a " - "voxel. This determines the size of the input " - "file and does not say anything about the " - "voxel classification. The default is 2 if " - "the input model is multitensor and 1 if the " - "input model is dt.")) - - numpds = traits.Int(argstr='-numpds %d', units='NA', - desc=("The maximum number of PDs in a voxel for input " - "models sfpeak and pico. The default is 3 for input " - "model sfpeak and 1 for input model pico. This option " - "determines the size of the voxels in the input file " - "and does not affect tracking. For tensor data, use " - "the -maxcomponents option.")) - - data_dims = traits.List(traits.Int, desc='data dimensions in voxels', - argstr='-datadims %s', minlen=3, maxlen=3, - units='voxels') - - voxel_dims = traits.List(traits.Float, desc='voxel dimensions in mm', - argstr='-voxeldims %s', minlen=3, maxlen=3, - units='mm') - - ipthresh = traits.Float(argstr='-ipthresh %f', - desc=('Curvature threshold for tracking, expressed as ' - 'the minimum dot product between two streamline ' - 'orientations calculated over the length of a ' - 'voxel. If the dot product between the previous ' - 'and current directions is less than this ' - 'threshold, then the streamline terminates. The ' - 'default setting will terminate fibres that curve ' - 'by more than 80 degrees. Set this to -1.0 to ' - 'disable curvature checking completely.')) - - curvethresh = traits.Float(argstr='-curvethresh %f', - desc=('Curvature threshold for tracking, expressed ' - 'as the maximum angle (in degrees) between ' - 'between two streamline orientations ' - 'calculated over the length of a voxel. If ' - 'the angle is greater than this, then the ' - 'streamline terminates.')) - - curveinterval = traits.Float(argstr='-curveinterval %f', requires=['curvethresh'], - desc=('Interval over which the curvature threshold ' - 'should be evaluated, in mm. The default is ' - '5mm. When using the default curvature ' - 'threshold of 90 degrees, this means that ' - 'streamlines will terminate if they curve by ' - 'more than 90 degrees over a path length ' - 'of 5mm.')) - - anisthresh = traits.Float(argstr='-anisthresh %f', - desc=('Terminate fibres that enter a voxel with lower ' - 'anisotropy than the threshold.')) - - anisfile = File(argstr='-anisfile %s', exists=True, - desc=('File containing the anisotropy map. This is required to ' - 'apply an anisotropy threshold with non tensor data. If ' - 'the map issupplied it is always used, even in tensor ' - 'data.')) - - outputtracts = traits.Enum('float', 'double', 'oogl', argstr='-outputtracts %s', - desc='output tract file type') - - out_file = File(argstr='-outputfile %s', position=-1, genfile=True, - desc='output data file') - - output_root = File(exists=False, argstr='-outputroot %s', position=-1, - desc='root directory for output') + in_file = File( + exists=True, + argstr='-inputfile %s', + position=1, + desc='input data file') + + seed_file = File( + exists=True, argstr='-seedfile %s', position=2, desc='seed file') + + inputmodel = traits.Enum( + 'dt', + 'multitensor', + 'sfpeak', + 'pico', + 'repbs_dt', + 'repbs_multitensor', + 'ballstick', + 'wildbs_dt', + 'bayesdirac', + 'bayesdirac_dt', + 'bedpostx_dyad', + 'bedpostx', + argstr='-inputmodel %s', + desc='input model type', + usedefault=True) + + tracker = traits.Enum( + 'fact', + 'euler', + 'rk4', + argstr='-tracker %s', + desc=("The tracking algorithm controls streamlines are " + "generated from the data. The choices are: " + "- FACT, which follows the local fibre orientation " + "in each voxel. No interpolation is used." + "- EULER, which uses a fixed step size along the " + "local fibre orientation. With nearest-neighbour " + "interpolation, this method may be very similar to " + "FACT, except that the step size is fixed, whereas " + "FACT steps extend to the boundary of the next voxel " + "(distance variable depending on the entry and exit " + "points to the voxel)." + "- RK4: Fourth-order Runge-Kutta method. The step " + "size is fixed, however the eventual direction of " + "the step is determined by taking and averaging a " + "series of partial steps."), + usedefault=True) + + interpolator = traits.Enum( + 'nn', + 'prob_nn', + 'linear', + argstr='-interpolator %s', + desc=("The interpolation algorithm determines how " + "the fiber orientation(s) are defined at a given " + "continuous point within the input image. " + "Interpolators are only used when the tracking " + "algorithm is not FACT. The choices are: " + "- NN: Nearest-neighbour interpolation, just " + "uses the local voxel data directly." + "- PROB_NN: Probabilistic nearest-neighbor " + "interpolation, similar to the method pro- " + "posed by Behrens et al [Magnetic Resonance " + "in Medicine, 50:1077-1088, 2003]. The data " + "is not interpolated, but at each point we " + "randomly choose one of the 8 voxels sur- " + "rounding a point. The probability of choosing " + "a particular voxel is based on how close the " + "point is to the centre of that voxel." + "- LINEAR: Linear interpolation of the vector " + "field containing the principal directions at " + "each point.")) + + stepsize = traits.Float( + argstr='-stepsize %f', + requires=['tracker'], + desc=('Step size for EULER and RK4 tracking. ' + 'The default is 1mm.')) + + inputdatatype = traits.Enum( + 'float', 'double', argstr='-inputdatatype %s', desc='input file type') + + gzip = traits.Bool( + argstr='-gzip', desc="save the output image in gzip format") + + maxcomponents = traits.Int( + argstr='-maxcomponents %d', + units='NA', + desc=("The maximum number of tensor components in a " + "voxel. This determines the size of the input " + "file and does not say anything about the " + "voxel classification. The default is 2 if " + "the input model is multitensor and 1 if the " + "input model is dt.")) + + numpds = traits.Int( + argstr='-numpds %d', + units='NA', + desc=("The maximum number of PDs in a voxel for input " + "models sfpeak and pico. The default is 3 for input " + "model sfpeak and 1 for input model pico. This option " + "determines the size of the voxels in the input file " + "and does not affect tracking. For tensor data, use " + "the -maxcomponents option.")) + + data_dims = traits.List( + traits.Int, + desc='data dimensions in voxels', + argstr='-datadims %s', + minlen=3, + maxlen=3, + units='voxels') + + voxel_dims = traits.List( + traits.Float, + desc='voxel dimensions in mm', + argstr='-voxeldims %s', + minlen=3, + maxlen=3, + units='mm') + + ipthresh = traits.Float( + argstr='-ipthresh %f', + desc=('Curvature threshold for tracking, expressed as ' + 'the minimum dot product between two streamline ' + 'orientations calculated over the length of a ' + 'voxel. If the dot product between the previous ' + 'and current directions is less than this ' + 'threshold, then the streamline terminates. The ' + 'default setting will terminate fibres that curve ' + 'by more than 80 degrees. Set this to -1.0 to ' + 'disable curvature checking completely.')) + + curvethresh = traits.Float( + argstr='-curvethresh %f', + desc=('Curvature threshold for tracking, expressed ' + 'as the maximum angle (in degrees) between ' + 'between two streamline orientations ' + 'calculated over the length of a voxel. If ' + 'the angle is greater than this, then the ' + 'streamline terminates.')) + + curveinterval = traits.Float( + argstr='-curveinterval %f', + requires=['curvethresh'], + desc=('Interval over which the curvature threshold ' + 'should be evaluated, in mm. The default is ' + '5mm. When using the default curvature ' + 'threshold of 90 degrees, this means that ' + 'streamlines will terminate if they curve by ' + 'more than 90 degrees over a path length ' + 'of 5mm.')) + + anisthresh = traits.Float( + argstr='-anisthresh %f', + desc=('Terminate fibres that enter a voxel with lower ' + 'anisotropy than the threshold.')) + + anisfile = File( + argstr='-anisfile %s', + exists=True, + desc=('File containing the anisotropy map. This is required to ' + 'apply an anisotropy threshold with non tensor data. If ' + 'the map issupplied it is always used, even in tensor ' + 'data.')) + + outputtracts = traits.Enum( + 'float', + 'double', + 'oogl', + argstr='-outputtracts %s', + desc='output tract file type') + + out_file = File( + argstr='-outputfile %s', + position=-1, + genfile=True, + desc='output data file') + + output_root = File( + exists=False, + argstr='-outputroot %s', + position=-1, + desc='root directory for output') class TrackOutputSpec(TraitedSpec): - tracked = File(exists=True, desc='output file containing reconstructed tracts') + tracked = File( + exists=True, desc='output file containing reconstructed tracts') class Track(CommandLine): @@ -611,9 +867,20 @@ def __init__(self, command=None, **inputs): class TrackPICoInputSpec(TrackInputSpec): - pdf = traits.Enum('bingham', 'watson', 'acg', argstr='-pdf %s', desc='Specifies the model for PICo parameters. The default is "bingham.') - - iterations = traits.Int(argstr='-iterations %d', units='NA', desc="Number of streamlines to generate at each seed point. The default is 5000.") + pdf = traits.Enum( + 'bingham', + 'watson', + 'acg', + argstr='-pdf %s', + desc='Specifies the model for PICo parameters. The default is "bingham.' + ) + + iterations = traits.Int( + argstr='-iterations %d', + units='NA', + desc= + "Number of streamlines to generate at each seed point. The default is 5000." + ) class TrackPICo(Track): @@ -638,13 +905,18 @@ def __init__(self, command=None, **inputs): class TrackBedpostxDeterInputSpec(TrackInputSpec): - bedpostxdir = Directory(argstr='-bedpostxdir %s', mandatory=True, exists=True, - desc=('Directory containing bedpostx output')) + bedpostxdir = Directory( + argstr='-bedpostxdir %s', + mandatory=True, + exists=True, + desc=('Directory containing bedpostx output')) - min_vol_frac = traits.Float(argstr='-bedpostxminf %d', units='NA', - desc=("Zeros out compartments in bedpostx data " - "with a mean volume fraction f of less than " - "min_vol_frac. The default is 0.01.")) + min_vol_frac = traits.Float( + argstr='-bedpostxminf %d', + units='NA', + desc=("Zeros out compartments in bedpostx data " + "with a mean volume fraction f of less than " + "min_vol_frac. The default is 0.01.")) class TrackBedpostxDeter(Track): @@ -679,17 +951,24 @@ def __init__(self, command=None, **inputs): class TrackBedpostxProbaInputSpec(TrackInputSpec): - bedpostxdir = Directory(argstr='-bedpostxdir %s', mandatory=True, exists=True, - desc=('Directory containing bedpostx output')) - - min_vol_frac = traits.Float(argstr='-bedpostxminf %d', units='NA', - desc=("Zeros out compartments in bedpostx data " - "with a mean volume fraction f of less than " - "min_vol_frac. The default is 0.01.")) - - iterations = traits.Int(argstr='-iterations %d', units='NA', - desc=("Number of streamlines to generate at each " - "seed point. The default is 1.")) + bedpostxdir = Directory( + argstr='-bedpostxdir %s', + mandatory=True, + exists=True, + desc=('Directory containing bedpostx output')) + + min_vol_frac = traits.Float( + argstr='-bedpostxminf %d', + units='NA', + desc=("Zeros out compartments in bedpostx data " + "with a mean volume fraction f of less than " + "min_vol_frac. The default is 0.01.")) + + iterations = traits.Int( + argstr='-iterations %d', + units='NA', + desc=("Number of streamlines to generate at each " + "seed point. The default is 1.")) class TrackBedpostxProba(Track): @@ -729,27 +1008,66 @@ def __init__(self, command=None, **inputs): class TrackBayesDiracInputSpec(TrackInputSpec): - scheme_file = File(argstr='-schemefile %s', mandatory=True, exists=True, - desc=('The scheme file corresponding to the data being ' - 'processed.')) - - iterations = traits.Int(argstr='-iterations %d', units='NA', - desc=("Number of streamlines to generate at each " - "seed point. The default is 5000.")) - - pdf = traits.Enum('bingham', 'watson', 'acg', argstr='-pdf %s', desc='Specifies the model for PICo priors (not the curvature priors). The default is "bingham".') - - pointset = traits.Int(argstr='-pointset %s', desc='Index to the point set to use for Bayesian likelihood calculation. The index specifies a set of evenly distributed points on the unit sphere, where each point x defines two possible step directions (x or -x) for the streamline path. A larger number indexes a larger point set, which gives higher angular resolution at the expense of computation time. The default is index 1, which gives 1922 points, index 0 gives 1082 points, index 2 gives 3002 points.') - - datamodel = traits.Enum('cylsymmdt', 'ballstick', argstr='-datamodel %s', desc='Model of the data for Bayesian tracking. The default model is "cylsymmdt", a diffusion tensor with cylindrical symmetry about e_1, ie L1 >= L_2 = L_3. The other model is "ballstick", the partial volume model (see ballstickfit).') - - curvepriork = traits.Float(argstr='-curvepriork %G', desc='Concentration parameter for the prior distribution on fibre orientations given the fibre orientation at the previous step. Larger values of k make curvature less likely.') - - curvepriorg = traits.Float(argstr='-curvepriorg %G', desc='Concentration parameter for the prior distribution on fibre orientations given the fibre orientation at the previous step. Larger values of g make curvature less likely.') - - extpriorfile = File(exists=True, argstr='-extpriorfile %s', desc='Path to a PICo image produced by picopdfs. The PDF in each voxel is used as a prior for the fibre orientation in Bayesian tracking. The prior image must be in the same space as the diffusion data.') - - extpriordatatype = traits.Enum('float', 'double', argstr='-extpriordatatype %s', desc='Datatype of the prior image. The default is "double".') + scheme_file = File( + argstr='-schemefile %s', + mandatory=True, + exists=True, + desc=('The scheme file corresponding to the data being ' + 'processed.')) + + iterations = traits.Int( + argstr='-iterations %d', + units='NA', + desc=("Number of streamlines to generate at each " + "seed point. The default is 5000.")) + + pdf = traits.Enum( + 'bingham', + 'watson', + 'acg', + argstr='-pdf %s', + desc= + 'Specifies the model for PICo priors (not the curvature priors). The default is "bingham".' + ) + + pointset = traits.Int( + argstr='-pointset %s', + desc= + 'Index to the point set to use for Bayesian likelihood calculation. The index specifies a set of evenly distributed points on the unit sphere, where each point x defines two possible step directions (x or -x) for the streamline path. A larger number indexes a larger point set, which gives higher angular resolution at the expense of computation time. The default is index 1, which gives 1922 points, index 0 gives 1082 points, index 2 gives 3002 points.' + ) + + datamodel = traits.Enum( + 'cylsymmdt', + 'ballstick', + argstr='-datamodel %s', + desc= + 'Model of the data for Bayesian tracking. The default model is "cylsymmdt", a diffusion tensor with cylindrical symmetry about e_1, ie L1 >= L_2 = L_3. The other model is "ballstick", the partial volume model (see ballstickfit).' + ) + + curvepriork = traits.Float( + argstr='-curvepriork %G', + desc= + 'Concentration parameter for the prior distribution on fibre orientations given the fibre orientation at the previous step. Larger values of k make curvature less likely.' + ) + + curvepriorg = traits.Float( + argstr='-curvepriorg %G', + desc= + 'Concentration parameter for the prior distribution on fibre orientations given the fibre orientation at the previous step. Larger values of g make curvature less likely.' + ) + + extpriorfile = File( + exists=True, + argstr='-extpriorfile %s', + desc= + 'Path to a PICo image produced by picopdfs. The PDF in each voxel is used as a prior for the fibre orientation in Bayesian tracking. The prior image must be in the same space as the diffusion data.' + ) + + extpriordatatype = traits.Enum( + 'float', + 'double', + argstr='-extpriordatatype %s', + desc='Datatype of the prior image. The default is "double".') class TrackBayesDirac(Track): @@ -794,15 +1112,37 @@ def __init__(self, command=None, **inputs): class TrackBootstrapInputSpec(TrackInputSpec): - scheme_file = File(argstr='-schemefile %s', mandatory=True, exists=True, desc='The scheme file corresponding to the data being processed.') - - iterations = traits.Int(argstr='-iterations %d', units='NA', desc="Number of streamlines to generate at each seed point.") - - inversion = traits.Int(argstr='-inversion %s', desc='Tensor reconstruction algorithm for repetition bootstrapping. Default is 1 (linear reconstruction, single tensor).') - - bsdatafiles = traits.List(File(exists=True), mandatory=True, argstr='-bsdatafile %s', desc='Specifies files containing raw data for repetition bootstrapping. Use -inputfile for wild bootstrap data.') - - bgmask = File(argstr='-bgmask %s', exists=True, desc='Provides the name of a file containing a background mask computed using, for example, FSL\'s bet2 program. The mask file contains zero in background voxels and non-zero in foreground.') + scheme_file = File( + argstr='-schemefile %s', + mandatory=True, + exists=True, + desc='The scheme file corresponding to the data being processed.') + + iterations = traits.Int( + argstr='-iterations %d', + units='NA', + desc="Number of streamlines to generate at each seed point.") + + inversion = traits.Int( + argstr='-inversion %s', + desc= + 'Tensor reconstruction algorithm for repetition bootstrapping. Default is 1 (linear reconstruction, single tensor).' + ) + + bsdatafiles = traits.List( + File(exists=True), + mandatory=True, + argstr='-bsdatafile %s', + desc= + 'Specifies files containing raw data for repetition bootstrapping. Use -inputfile for wild bootstrap data.' + ) + + bgmask = File( + argstr='-bgmask %s', + exists=True, + desc= + 'Provides the name of a file containing a background mask computed using, for example, FSL\'s bet2 program. The mask file contains zero in background voxels and non-zero in foreground.' + ) class TrackBootstrap(Track): @@ -828,30 +1168,57 @@ def __init__(self, command=None, **inputs): class ComputeMeanDiffusivityInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=1, - desc='Tensor-fitted data filename') - - scheme_file = File(exists=True, argstr='%s', position=2, - desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=1, + desc='Tensor-fitted data filename') + + scheme_file = File( + exists=True, + argstr='%s', + position=2, + desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') out_file = File(argstr="> %s", position=-1, genfile=True) - inputmodel = traits.Enum('dt', 'twotensor', 'threetensor', - argstr='-inputmodel %s', - desc='Specifies the model that the input tensor data contains parameters for.' - 'Possible model types are: "dt" (diffusion-tensor data), "twotensor" (two-tensor data), ' - '"threetensor" (three-tensor data). By default, the program assumes that the input data ' - 'contains a single diffusion tensor in each voxel.') - - inputdatatype = traits.Enum('char', 'short', 'int', 'long', 'float', 'double', - argstr='-inputdatatype %s', - desc='Specifies the data type of the input file. The data type can be any of the' - 'following strings: "char", "short", "int", "long", "float" or "double".') - - outputdatatype = traits.Enum('char', 'short', 'int', 'long', 'float', 'double', - argstr='-outputdatatype %s', - desc='Specifies the data type of the output data. The data type can be any of the' - 'following strings: "char", "short", "int", "long", "float" or "double".') + inputmodel = traits.Enum( + 'dt', + 'twotensor', + 'threetensor', + argstr='-inputmodel %s', + desc= + 'Specifies the model that the input tensor data contains parameters for.' + 'Possible model types are: "dt" (diffusion-tensor data), "twotensor" (two-tensor data), ' + '"threetensor" (three-tensor data). By default, the program assumes that the input data ' + 'contains a single diffusion tensor in each voxel.') + + inputdatatype = traits.Enum( + 'char', + 'short', + 'int', + 'long', + 'float', + 'double', + argstr='-inputdatatype %s', + desc= + 'Specifies the data type of the input file. The data type can be any of the' + 'following strings: "char", "short", "int", "long", "float" or "double".' + ) + + outputdatatype = traits.Enum( + 'char', + 'short', + 'int', + 'long', + 'float', + 'double', + argstr='-outputdatatype %s', + desc= + 'Specifies the data type of the output data. The data type can be any of the' + 'following strings: "char", "short", "int", "long", "float" or "double".' + ) class ComputeMeanDiffusivityOutputSpec(TraitedSpec): @@ -886,28 +1253,56 @@ def _gen_outfilename(self): class ComputeFractionalAnisotropyInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=1, - desc='Tensor-fitted data filename') - - scheme_file = File(exists=True, argstr='%s', position=2, - desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') - - inputmodel = traits.Enum('dt', 'twotensor', 'threetensor', 'multitensor', - argstr='-inputmodel %s', - desc='Specifies the model that the input tensor data contains parameters for.' - 'Possible model types are: "dt" (diffusion-tensor data), "twotensor" (two-tensor data), ' - '"threetensor" (three-tensor data). By default, the program assumes that the input data ' - 'contains a single diffusion tensor in each voxel.') - - inputdatatype = traits.Enum('char', 'short', 'int', 'long', 'float', 'double', - argstr='-inputdatatype %s', - desc='Specifies the data type of the input file. The data type can be any of the' - 'following strings: "char", "short", "int", "long", "float" or "double".') - - outputdatatype = traits.Enum('char', 'short', 'int', 'long', 'float', 'double', - argstr='-outputdatatype %s', - desc='Specifies the data type of the output data. The data type can be any of the' - 'following strings: "char", "short", "int", "long", "float" or "double".') + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=1, + desc='Tensor-fitted data filename') + + scheme_file = File( + exists=True, + argstr='%s', + position=2, + desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') + + inputmodel = traits.Enum( + 'dt', + 'twotensor', + 'threetensor', + 'multitensor', + argstr='-inputmodel %s', + desc= + 'Specifies the model that the input tensor data contains parameters for.' + 'Possible model types are: "dt" (diffusion-tensor data), "twotensor" (two-tensor data), ' + '"threetensor" (three-tensor data). By default, the program assumes that the input data ' + 'contains a single diffusion tensor in each voxel.') + + inputdatatype = traits.Enum( + 'char', + 'short', + 'int', + 'long', + 'float', + 'double', + argstr='-inputdatatype %s', + desc= + 'Specifies the data type of the input file. The data type can be any of the' + 'following strings: "char", "short", "int", "long", "float" or "double".' + ) + + outputdatatype = traits.Enum( + 'char', + 'short', + 'int', + 'long', + 'float', + 'double', + argstr='-outputdatatype %s', + desc= + 'Specifies the data type of the output data. The data type can be any of the' + 'following strings: "char", "short", "int", "long", "float" or "double".' + ) class ComputeFractionalAnisotropyOutputSpec(TraitedSpec): @@ -948,28 +1343,56 @@ def _gen_outfilename(self): class ComputeTensorTraceInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=1, - desc='Tensor-fitted data filename') - - scheme_file = File(exists=True, argstr='%s', position=2, - desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') - - inputmodel = traits.Enum('dt', 'twotensor', 'threetensor', 'multitensor', - argstr='-inputmodel %s', - desc='Specifies the model that the input tensor data contains parameters for.' - 'Possible model types are: "dt" (diffusion-tensor data), "twotensor" (two-tensor data), ' - '"threetensor" (three-tensor data). By default, the program assumes that the input data ' - 'contains a single diffusion tensor in each voxel.') - - inputdatatype = traits.Enum('char', 'short', 'int', 'long', 'float', 'double', - argstr='-inputdatatype %s', - desc='Specifies the data type of the input file. The data type can be any of the' - 'following strings: "char", "short", "int", "long", "float" or "double".') - - outputdatatype = traits.Enum('char', 'short', 'int', 'long', 'float', 'double', - argstr='-outputdatatype %s', - desc='Specifies the data type of the output data. The data type can be any of the' - 'following strings: "char", "short", "int", "long", "float" or "double".') + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=1, + desc='Tensor-fitted data filename') + + scheme_file = File( + exists=True, + argstr='%s', + position=2, + desc='Camino scheme file (b values / vectors, see camino.fsl2scheme)') + + inputmodel = traits.Enum( + 'dt', + 'twotensor', + 'threetensor', + 'multitensor', + argstr='-inputmodel %s', + desc= + 'Specifies the model that the input tensor data contains parameters for.' + 'Possible model types are: "dt" (diffusion-tensor data), "twotensor" (two-tensor data), ' + '"threetensor" (three-tensor data). By default, the program assumes that the input data ' + 'contains a single diffusion tensor in each voxel.') + + inputdatatype = traits.Enum( + 'char', + 'short', + 'int', + 'long', + 'float', + 'double', + argstr='-inputdatatype %s', + desc= + 'Specifies the data type of the input file. The data type can be any of the' + 'following strings: "char", "short", "int", "long", "float" or "double".' + ) + + outputdatatype = traits.Enum( + 'char', + 'short', + 'int', + 'long', + 'float', + 'double', + argstr='-outputdatatype %s', + desc= + 'Specifies the data type of the output data. The data type can be any of the' + 'following strings: "char", "short", "int", "long", "float" or "double".' + ) class ComputeTensorTraceOutputSpec(TraitedSpec): @@ -1012,25 +1435,54 @@ def _gen_outfilename(self): class ComputeEigensystemInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='< %s', mandatory=True, position=1, desc='Tensor-fitted data filename') - - inputmodel = traits.Enum('dt', 'multitensor', argstr='-inputmodel %s', desc='Specifies the model that the input data contains parameters for. Possible model types are: "dt" (diffusion-tensor data) and "multitensor"') - - maxcomponents = traits.Int(argstr='-maxcomponents %d', desc='The maximum number of tensor components in a voxel of the input data.') - - inputdatatype = traits.Enum('double', 'float', 'long', 'int', 'short', 'char', - argstr='-inputdatatype %s', usedefault=True, - desc=('Specifies the data type of the input data. ' - 'The data type can be any of the following strings: ' - '"char", "short", "int", "long", "float" or "double".' - 'Default is double data type')) - - outputdatatype = traits.Enum('double', 'float', 'long', 'int', 'short', 'char', - argstr='-outputdatatype %s', usedefault=True, - desc=('Specifies the data type of the output data. ' - 'The data type can be any of the following strings: ' - '"char", "short", "int", "long", "float" or "double".' - 'Default is double data type')) + in_file = File( + exists=True, + argstr='< %s', + mandatory=True, + position=1, + desc='Tensor-fitted data filename') + + inputmodel = traits.Enum( + 'dt', + 'multitensor', + argstr='-inputmodel %s', + desc= + 'Specifies the model that the input data contains parameters for. Possible model types are: "dt" (diffusion-tensor data) and "multitensor"' + ) + + maxcomponents = traits.Int( + argstr='-maxcomponents %d', + desc= + 'The maximum number of tensor components in a voxel of the input data.' + ) + + inputdatatype = traits.Enum( + 'double', + 'float', + 'long', + 'int', + 'short', + 'char', + argstr='-inputdatatype %s', + usedefault=True, + desc=('Specifies the data type of the input data. ' + 'The data type can be any of the following strings: ' + '"char", "short", "int", "long", "float" or "double".' + 'Default is double data type')) + + outputdatatype = traits.Enum( + 'double', + 'float', + 'long', + 'int', + 'short', + 'char', + argstr='-outputdatatype %s', + usedefault=True, + desc=('Specifies the data type of the output data. ' + 'The data type can be any of the following strings: ' + '"char", "short", "int", "long", "float" or "double".' + 'Default is double data type')) class ComputeEigensystemOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/camino/odf.py b/nipype/interfaces/camino/odf.py index 5f16726dfc..ccc5f2e277 100644 --- a/nipype/interfaces/camino/odf.py +++ b/nipype/interfaces/camino/odf.py @@ -7,7 +7,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os @@ -17,24 +18,43 @@ class QBallMXInputSpec(StdOutCommandLineInputSpec): - basistype = traits.Enum('rbf', 'sh', argstr='-basistype %s', - desc=('Basis function type. "rbf" to use radial basis functions ' - '"sh" to use spherical harmonics'), usedefault=True) - scheme_file = File(exists=True, argstr='-schemefile %s', mandatory=True, - desc='Specifies the scheme file for the diffusion MRI data') - order = traits.Int(argstr='-order %d', units='NA', - desc=('Specific to sh. Maximum order of the spherical harmonic series. ' - 'Default is 4.')) - rbfpointset = traits.Int(argstr='-rbfpointset %d', units='NA', - desc=('Specific to rbf. Sets the number of radial basis functions to use. ' - 'The value specified must be present in the Pointsets directory. ' - 'The default value is 246.')) - rbfsigma = traits.Float(argstr='-rbfsigma %f', units='NA', - desc=('Specific to rbf. Sets the width of the interpolating basis functions. ' - 'The default value is 0.2618 (15 degrees).')) - smoothingsigma = traits.Float(argstr='-smoothingsigma %f', units='NA', - desc=('Specific to rbf. Sets the width of the smoothing basis functions. ' - 'The default value is 0.1309 (7.5 degrees).')) + basistype = traits.Enum( + 'rbf', + 'sh', + argstr='-basistype %s', + desc=('Basis function type. "rbf" to use radial basis functions ' + '"sh" to use spherical harmonics'), + usedefault=True) + scheme_file = File( + exists=True, + argstr='-schemefile %s', + mandatory=True, + desc='Specifies the scheme file for the diffusion MRI data') + order = traits.Int( + argstr='-order %d', + units='NA', + desc=( + 'Specific to sh. Maximum order of the spherical harmonic series. ' + 'Default is 4.')) + rbfpointset = traits.Int( + argstr='-rbfpointset %d', + units='NA', + desc=( + 'Specific to rbf. Sets the number of radial basis functions to use. ' + 'The value specified must be present in the Pointsets directory. ' + 'The default value is 246.')) + rbfsigma = traits.Float( + argstr='-rbfsigma %f', + units='NA', + desc= + ('Specific to rbf. Sets the width of the interpolating basis functions. ' + 'The default value is 0.2618 (15 degrees).')) + smoothingsigma = traits.Float( + argstr='-smoothingsigma %f', + units='NA', + desc=( + 'Specific to rbf. Sets the width of the smoothing basis functions. ' + 'The default value is 0.1309 (7.5 degrees).')) class QBallMXOutputSpec(TraitedSpec): @@ -95,18 +115,32 @@ def _gen_outfilename(self): class LinReconInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=1, - desc='voxel-order data filename') - scheme_file = File(exists=True, argstr='%s', mandatory=True, position=2, - desc='Specifies the scheme file for the diffusion MRI data') - qball_mat = File(exists=True, argstr='%s', mandatory=True, position=3, - desc='Linear transformation matrix.') - normalize = traits.Bool(argstr='-normalize', - desc=('Normalize the measurements and discard ' - 'the zero measurements before the linear transform.')) - log = traits.Bool(argstr='-log', - desc=('Transform the log measurements rather than the ' - 'measurements themselves')) + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=1, + desc='voxel-order data filename') + scheme_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=2, + desc='Specifies the scheme file for the diffusion MRI data') + qball_mat = File( + exists=True, + argstr='%s', + mandatory=True, + position=3, + desc='Linear transformation matrix.') + normalize = traits.Bool( + argstr='-normalize', + desc=('Normalize the measurements and discard ' + 'the zero measurements before the linear transform.')) + log = traits.Bool( + argstr='-log', + desc=('Transform the log measurements rather than the ' + 'measurements themselves')) bgmask = File(exists=True, argstr='-bgmask %s', desc='background mask') @@ -172,32 +206,65 @@ def _gen_outfilename(self): class MESDInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='-inputfile %s', mandatory=True, position=1, - desc='voxel-order data filename') - inverter = traits.Enum('SPIKE', 'PAS', argstr='-filter %s', position=2, mandatory=True, - desc=('The inversion index specifies the type of inversion to perform on the data.' - 'The currently available choices are:' - 'Inverter name | Inverter parameters' - '---------------|------------------' - 'SPIKE | bd (b-value x diffusivity along the fibre.)' - 'PAS | r')) - inverter_param = traits.Float(argstr='%f', units='NA', position=3, mandatory=True, - desc=('Parameter associated with the inverter. Cf. inverter description for' - 'more information.')) - fastmesd = traits.Bool(argstr='-fastmesd', requires=['mepointset'], - desc=('Turns off numerical integration checks and fixes the integration point set size at that of' - 'the index specified by -basepointset..')) - mepointset = traits.Int(argstr='-mepointset %d', units='NA', - desc=('Use a set of directions other than those in the scheme file for the deconvolution kernel.' - 'The number refers to the number of directions on the unit sphere. For example, ' - '"-mepointset 54" uses the directions in "camino/PointSets/Elec054.txt".')) - scheme_file = File(exists=True, argstr='-schemefile %s', mandatory=True, - desc='Specifies the scheme file for the diffusion MRI data') + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + position=1, + desc='voxel-order data filename') + inverter = traits.Enum( + 'SPIKE', + 'PAS', + argstr='-filter %s', + position=2, + mandatory=True, + desc= + ('The inversion index specifies the type of inversion to perform on the data.' + 'The currently available choices are:' + 'Inverter name | Inverter parameters' + '---------------|------------------' + 'SPIKE | bd (b-value x diffusivity along the fibre.)' + 'PAS | r')) + inverter_param = traits.Float( + argstr='%f', + units='NA', + position=3, + mandatory=True, + desc= + ('Parameter associated with the inverter. Cf. inverter description for' + 'more information.')) + fastmesd = traits.Bool( + argstr='-fastmesd', + requires=['mepointset'], + desc= + ('Turns off numerical integration checks and fixes the integration point set size at that of' + 'the index specified by -basepointset..')) + mepointset = traits.Int( + argstr='-mepointset %d', + units='NA', + desc= + ('Use a set of directions other than those in the scheme file for the deconvolution kernel.' + 'The number refers to the number of directions on the unit sphere. For example, ' + '"-mepointset 54" uses the directions in "camino/PointSets/Elec054.txt".' + )) + scheme_file = File( + exists=True, + argstr='-schemefile %s', + mandatory=True, + desc='Specifies the scheme file for the diffusion MRI data') bgmask = File(exists=True, argstr='-bgmask %s', desc='background mask') - inputdatatype = traits.Enum('float', 'char', 'short', 'int', 'long', 'double', argstr='-inputdatatype %s', - desc=('Specifies the data type of the input file: "char", "short", "int", "long",' - '"float" or "double". The input file must have BIG-ENDIAN ordering.' - 'By default, the input type is "float".')) + inputdatatype = traits.Enum( + 'float', + 'char', + 'short', + 'int', + 'long', + 'double', + argstr='-inputdatatype %s', + desc= + ('Specifies the data type of the input file: "char", "short", "int", "long",' + '"float" or "double". The input file must have BIG-ENDIAN ordering.' + 'By default, the input type is "float".')) class MESDOutputSpec(TraitedSpec): @@ -296,54 +363,97 @@ def _gen_outfilename(self): class SFPeaksInputSpec(StdOutCommandLineInputSpec): - in_file = File(exists=True, argstr='-inputfile %s', mandatory=True, - desc='Voxel-order data of spherical functions') - inputmodel = traits.Enum('sh', 'maxent', 'rbf', argstr='-inputmodel %s', mandatory=True, - desc=('Type of functions input via in_file. Currently supported options are: ' - ' sh - Spherical harmonic series. Specify the maximum order of the SH series ' - ' with the "order" attribute if different from the default of 4. ' - ' maxent - Maximum entropy representations output by MESD. The reconstruction ' - ' directions input to MESD must be specified. By default this is the ' - ' same set of gradient directions (excluding zero gradients) in the ' - ' scheme file, so specify the "schemefile" attribute unless the ' - ' "mepointset" attribute was set in MESD. ' - ' rbf - Sums of radial basis functions. Specify the pointset with the attribute ' - ' "rbfpointset" if different from the default. See QBallMX.')) - order = traits.Int(argstr='-order %d', units='NA', - desc='Specific to sh. Maximum order of the spherical harmonic series.') - scheme_file = File(exists=True, argstr='%s', - desc='Specific to maxent. Specifies the scheme file.') - rbfpointset = traits.Int(argstr='-rbfpointset %d', units='NA', - desc=('Specific to rbf. Sets the number of radial basis functions to use. ' - 'The value specified must be present in the Pointsets directory. ' - 'The default value is 246.')) - mepointset = traits.Int(argstr='-mepointset %d', units='NA', - desc=('Use a set of directions other than those in the scheme file for the deconvolution ' - 'kernel. The number refers to the number of directions on the unit sphere. ' - 'For example, "mepointset = 54" uses the directions in "camino/PointSets/Elec054.txt" ' - 'Use this option only if you told MESD to use a custom set of directions with the same ' - 'option. Otherwise, specify the scheme file with the "schemefile" attribute.')) - numpds = traits.Int(argstr='-numpds %d', units='NA', - desc='The largest number of peak directions to output in each voxel.') - noconsistencycheck = traits.Bool(argstr='-noconsistencycheck', - desc='Turns off the consistency check. The output shows all consistencies as true.') - searchradius = traits.Float(argstr='-searchradius %f', units='NA', - desc='The search radius in the peak finding algorithm. The default is 0.4 (cf. "density")') - density = traits.Int(argstr='-density %d', units='NA', - desc=('The number of randomly rotated icosahedra to use in constructing the set of points for ' - 'random sampling in the peak finding algorithm. Default is 1000, which works well for very ' - 'spiky maxent functions. For other types of function, it is reasonable to set the density ' - 'much lower and increase the search radius slightly, which speeds up the computation.')) - pointset = traits.Int(argstr='-pointset %d', units='NA', - desc=('To sample using an evenly distributed set of points instead. The integer can be ' - '0, 1, ..., 7. Index 0 gives 1082 points, 1 gives 1922, 2 gives 3002, 3 gives 4322, ' - '4 gives 5882, 5 gives 8672, 6 gives 12002, 7 gives 15872.')) - pdthresh = traits.Float(argstr='-pdthresh %f', units='NA', - desc=('Base threshold on the actual peak direction strength divided by the mean of the ' - 'function. The default is 1.0 (the peak must be equal or greater than the mean).')) - stdsfrommean = traits.Float(argstr='-stdsfrommean %f', units='NA', - desc=('This is the number of standard deviations of the function to be added to the ' - '"pdthresh" attribute in the peak directions pruning.')) + in_file = File( + exists=True, + argstr='-inputfile %s', + mandatory=True, + desc='Voxel-order data of spherical functions') + inputmodel = traits.Enum( + 'sh', + 'maxent', + 'rbf', + argstr='-inputmodel %s', + mandatory=True, + desc= + ('Type of functions input via in_file. Currently supported options are: ' + ' sh - Spherical harmonic series. Specify the maximum order of the SH series ' + ' with the "order" attribute if different from the default of 4. ' + ' maxent - Maximum entropy representations output by MESD. The reconstruction ' + ' directions input to MESD must be specified. By default this is the ' + ' same set of gradient directions (excluding zero gradients) in the ' + ' scheme file, so specify the "schemefile" attribute unless the ' + ' "mepointset" attribute was set in MESD. ' + ' rbf - Sums of radial basis functions. Specify the pointset with the attribute ' + ' "rbfpointset" if different from the default. See QBallMX.')) + order = traits.Int( + argstr='-order %d', + units='NA', + desc='Specific to sh. Maximum order of the spherical harmonic series.') + scheme_file = File( + exists=True, + argstr='%s', + desc='Specific to maxent. Specifies the scheme file.') + rbfpointset = traits.Int( + argstr='-rbfpointset %d', + units='NA', + desc=( + 'Specific to rbf. Sets the number of radial basis functions to use. ' + 'The value specified must be present in the Pointsets directory. ' + 'The default value is 246.')) + mepointset = traits.Int( + argstr='-mepointset %d', + units='NA', + desc= + ('Use a set of directions other than those in the scheme file for the deconvolution ' + 'kernel. The number refers to the number of directions on the unit sphere. ' + 'For example, "mepointset = 54" uses the directions in "camino/PointSets/Elec054.txt" ' + 'Use this option only if you told MESD to use a custom set of directions with the same ' + 'option. Otherwise, specify the scheme file with the "schemefile" attribute.' + )) + numpds = traits.Int( + argstr='-numpds %d', + units='NA', + desc='The largest number of peak directions to output in each voxel.') + noconsistencycheck = traits.Bool( + argstr='-noconsistencycheck', + desc= + 'Turns off the consistency check. The output shows all consistencies as true.' + ) + searchradius = traits.Float( + argstr='-searchradius %f', + units='NA', + desc= + 'The search radius in the peak finding algorithm. The default is 0.4 (cf. "density")' + ) + density = traits.Int( + argstr='-density %d', + units='NA', + desc= + ('The number of randomly rotated icosahedra to use in constructing the set of points for ' + 'random sampling in the peak finding algorithm. Default is 1000, which works well for very ' + 'spiky maxent functions. For other types of function, it is reasonable to set the density ' + 'much lower and increase the search radius slightly, which speeds up the computation.' + )) + pointset = traits.Int( + argstr='-pointset %d', + units='NA', + desc= + ('To sample using an evenly distributed set of points instead. The integer can be ' + '0, 1, ..., 7. Index 0 gives 1082 points, 1 gives 1922, 2 gives 3002, 3 gives 4322, ' + '4 gives 5882, 5 gives 8672, 6 gives 12002, 7 gives 15872.')) + pdthresh = traits.Float( + argstr='-pdthresh %f', + units='NA', + desc= + ('Base threshold on the actual peak direction strength divided by the mean of the ' + 'function. The default is 1.0 (the peak must be equal or greater than the mean).' + )) + stdsfrommean = traits.Float( + argstr='-stdsfrommean %f', + units='NA', + desc= + ('This is the number of standard deviations of the function to be added to the ' + '"pdthresh" attribute in the peak directions pruning.')) class SFPeaksOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py b/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py index 953a2688ac..7ed97f05c4 100644 --- a/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py +++ b/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py @@ -4,94 +4,110 @@ def test_AnalyzeHeader_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - centre=dict(argstr='-centre %s', - units='mm', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - datatype=dict(argstr='-datatype %s', - mandatory=True, - ), - description=dict(argstr='-description %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - greylevels=dict(argstr='-gl %s', - units='NA', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=1, - ), - initfromheader=dict(argstr='-initfromheader %s', - position=3, - ), - intelbyteorder=dict(argstr='-intelbyteorder', - ), - networkbyteorder=dict(argstr='-networkbyteorder', - ), - nimages=dict(argstr='-nimages %d', - units='NA', - ), - offset=dict(argstr='-offset %d', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - picoseed=dict(argstr='-picoseed %s', - units='mm', - ), - printbigendian=dict(argstr='-printbigendian %s', - position=3, - ), - printimagedims=dict(argstr='-printimagedims %s', - position=3, - ), - printintelbyteorder=dict(argstr='-printintelbyteorder %s', - position=3, - ), - printprogargs=dict(argstr='-printprogargs %s', - position=3, - ), - readheader=dict(argstr='-readheader %s', - position=3, - ), - scaleinter=dict(argstr='-scaleinter %d', - units='NA', - ), - scaleslope=dict(argstr='-scaleslope %d', - units='NA', - ), - scheme_file=dict(argstr='%s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + args=dict(argstr='%s', ), + centre=dict( + argstr='-centre %s', + units='mm', + ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + datatype=dict( + argstr='-datatype %s', + mandatory=True, + ), + description=dict(argstr='-description %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + greylevels=dict( + argstr='-gl %s', + units='NA', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=1, + ), + initfromheader=dict( + argstr='-initfromheader %s', + position=3, + ), + intelbyteorder=dict(argstr='-intelbyteorder', ), + networkbyteorder=dict(argstr='-networkbyteorder', ), + nimages=dict( + argstr='-nimages %d', + units='NA', + ), + offset=dict( + argstr='-offset %d', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + picoseed=dict( + argstr='-picoseed %s', + units='mm', + ), + printbigendian=dict( + argstr='-printbigendian %s', + position=3, + ), + printimagedims=dict( + argstr='-printimagedims %s', + position=3, + ), + printintelbyteorder=dict( + argstr='-printintelbyteorder %s', + position=3, + ), + printprogargs=dict( + argstr='-printprogargs %s', + position=3, + ), + readheader=dict( + argstr='-readheader %s', + position=3, + ), + scaleinter=dict( + argstr='-scaleinter %d', + units='NA', + ), + scaleslope=dict( + argstr='-scaleslope %d', + units='NA', + ), + scheme_file=dict( + argstr='%s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = AnalyzeHeader.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AnalyzeHeader_outputs(): - output_map = dict(header=dict(), - ) + output_map = dict(header=dict(), ) outputs = AnalyzeHeader.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py b/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py index 422e6eceeb..8639947361 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py @@ -4,47 +4,49 @@ def test_ComputeEigensystem_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - usedefault=True, - ), - inputmodel=dict(argstr='-inputmodel %s', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - outputdatatype=dict(argstr='-outputdatatype %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=1, + ), + inputdatatype=dict( + argstr='-inputdatatype %s', + usedefault=True, + ), + inputmodel=dict(argstr='-inputmodel %s', ), + maxcomponents=dict(argstr='-maxcomponents %d', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + outputdatatype=dict( + argstr='-outputdatatype %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ComputeEigensystem.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeEigensystem_outputs(): - output_map = dict(eigen=dict(), - ) + output_map = dict(eigen=dict(), ) outputs = ComputeEigensystem.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py b/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py index 81afa66e5f..4403f11d19 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py @@ -4,46 +4,46 @@ def test_ComputeFractionalAnisotropy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - outputdatatype=dict(argstr='-outputdatatype %s', - ), - scheme_file=dict(argstr='%s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict(argstr='-inputmodel %s', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + outputdatatype=dict(argstr='-outputdatatype %s', ), + scheme_file=dict( + argstr='%s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ComputeFractionalAnisotropy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeFractionalAnisotropy_outputs(): - output_map = dict(fa=dict(), - ) + output_map = dict(fa=dict(), ) outputs = ComputeFractionalAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py b/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py index 9981b8d017..83859ff6cd 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py @@ -4,46 +4,46 @@ def test_ComputeMeanDiffusivity_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - outputdatatype=dict(argstr='-outputdatatype %s', - ), - scheme_file=dict(argstr='%s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict(argstr='-inputmodel %s', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + outputdatatype=dict(argstr='-outputdatatype %s', ), + scheme_file=dict( + argstr='%s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ComputeMeanDiffusivity.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeMeanDiffusivity_outputs(): - output_map = dict(md=dict(), - ) + output_map = dict(md=dict(), ) outputs = ComputeMeanDiffusivity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py b/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py index c3a41aa877..fd5bf2dab0 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py @@ -4,46 +4,46 @@ def test_ComputeTensorTrace_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - outputdatatype=dict(argstr='-outputdatatype %s', - ), - scheme_file=dict(argstr='%s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict(argstr='-inputmodel %s', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + outputdatatype=dict(argstr='-outputdatatype %s', ), + scheme_file=dict( + argstr='%s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ComputeTensorTrace.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeTensorTrace_outputs(): - output_map = dict(trace=dict(), - ) + output_map = dict(trace=dict(), ) outputs = ComputeTensorTrace.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Conmat.py b/nipype/interfaces/camino/tests/test_auto_Conmat.py index b55c60be67..dd1e64c1cc 100644 --- a/nipype/interfaces/camino/tests/test_auto_Conmat.py +++ b/nipype/interfaces/camino/tests/test_auto_Conmat.py @@ -4,52 +4,59 @@ def test_Conmat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - ), - output_root=dict(argstr='-outputroot %s', - genfile=True, - ), - scalar_file=dict(argstr='-scalarfile %s', - requires=['tract_stat'], - ), - target_file=dict(argstr='-targetfile %s', - mandatory=True, - ), - targetname_file=dict(argstr='-targetnamefile %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tract_prop=dict(argstr='-tractstat %s', - units='NA', - xor=['tract_stat'], - ), - tract_stat=dict(argstr='-tractstat %s', - requires=['scalar_file'], - units='NA', - xor=['tract_prop'], - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + ), + output_root=dict( + argstr='-outputroot %s', + genfile=True, + ), + scalar_file=dict( + argstr='-scalarfile %s', + requires=['tract_stat'], + ), + target_file=dict( + argstr='-targetfile %s', + mandatory=True, + ), + targetname_file=dict(argstr='-targetnamefile %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tract_prop=dict( + argstr='-tractstat %s', + units='NA', + xor=['tract_stat'], + ), + tract_stat=dict( + argstr='-tractstat %s', + requires=['scalar_file'], + units='NA', + xor=['tract_prop'], + ), ) inputs = Conmat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Conmat_outputs(): - output_map = dict(conmat_sc=dict(), - conmat_ts=dict(), + output_map = dict( + conmat_sc=dict(), + conmat_ts=dict(), ) outputs = Conmat.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py b/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py index 1de87ea032..98c6f77b96 100644 --- a/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py +++ b/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py @@ -4,42 +4,47 @@ def test_DT2NIfTI_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - header_file=dict(argstr='-header %s', - mandatory=True, - position=3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - position=1, - ), - output_root=dict(argstr='-outputroot %s', - genfile=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + header_file=dict( + argstr='-header %s', + mandatory=True, + position=3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + position=1, + ), + output_root=dict( + argstr='-outputroot %s', + genfile=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DT2NIfTI.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DT2NIfTI_outputs(): - output_map = dict(dt=dict(), - exitcode=dict(), - lns0=dict(), + output_map = dict( + dt=dict(), + exitcode=dict(), + lns0=dict(), ) outputs = DT2NIfTI.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_DTIFit.py b/nipype/interfaces/camino/tests/test_auto_DTIFit.py index 2210c1c41c..7a1558d55b 100644 --- a/nipype/interfaces/camino/tests/test_auto_DTIFit.py +++ b/nipype/interfaces/camino/tests/test_auto_DTIFit.py @@ -4,46 +4,49 @@ def test_DTIFit_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bgmask=dict(argstr='-bgmask %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - non_linear=dict(argstr='-nonlinear', - position=3, - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - scheme_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bgmask=dict(argstr='-bgmask %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + non_linear=dict( + argstr='-nonlinear', + position=3, + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + scheme_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DTIFit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTIFit_outputs(): - output_map = dict(tensor_fitted=dict(), - ) + output_map = dict(tensor_fitted=dict(), ) outputs = DTIFit.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py b/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py index 77f8f701dd..a98f69fa2f 100644 --- a/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py +++ b/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py @@ -4,66 +4,72 @@ def test_DTLUTGen_inputs(): - input_map = dict(acg=dict(argstr='-acg', - ), - args=dict(argstr='%s', - ), - bingham=dict(argstr='-bingham', - ), - environ=dict(nohash=True, - usedefault=True, - ), - frange=dict(argstr='-frange %s', - position=1, - units='NA', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inversion=dict(argstr='-inversion %d', - units='NA', - ), - lrange=dict(argstr='-lrange %s', - position=1, - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - samples=dict(argstr='-samples %d', - units='NA', - ), - scheme_file=dict(argstr='-schemefile %s', - mandatory=True, - position=2, - ), - snr=dict(argstr='-snr %f', - units='NA', - ), - step=dict(argstr='-step %f', - units='NA', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trace=dict(argstr='-trace %G', - units='NA', - ), - watson=dict(argstr='-watson', - ), + input_map = dict( + acg=dict(argstr='-acg', ), + args=dict(argstr='%s', ), + bingham=dict(argstr='-bingham', ), + environ=dict( + nohash=True, + usedefault=True, + ), + frange=dict( + argstr='-frange %s', + position=1, + units='NA', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inversion=dict( + argstr='-inversion %d', + units='NA', + ), + lrange=dict( + argstr='-lrange %s', + position=1, + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + samples=dict( + argstr='-samples %d', + units='NA', + ), + scheme_file=dict( + argstr='-schemefile %s', + mandatory=True, + position=2, + ), + snr=dict( + argstr='-snr %f', + units='NA', + ), + step=dict( + argstr='-step %f', + units='NA', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trace=dict( + argstr='-trace %G', + units='NA', + ), + watson=dict(argstr='-watson', ), ) inputs = DTLUTGen.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTLUTGen_outputs(): - output_map = dict(dtLUT=dict(), - ) + output_map = dict(dtLUT=dict(), ) outputs = DTLUTGen.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_DTMetric.py b/nipype/interfaces/camino/tests/test_auto_DTMetric.py index ffb95b0e89..37460e925a 100644 --- a/nipype/interfaces/camino/tests/test_auto_DTMetric.py +++ b/nipype/interfaces/camino/tests/test_auto_DTMetric.py @@ -4,46 +4,50 @@ def test_DTMetric_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - data_header=dict(argstr='-header %s', - ), - eigen_data=dict(argstr='-inputfile %s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - usedefault=True, - ), - metric=dict(argstr='-stat %s', - mandatory=True, - ), - outputdatatype=dict(argstr='-outputdatatype %s', - usedefault=True, - ), - outputfile=dict(argstr='-outputfile %s', - genfile=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + data_header=dict(argstr='-header %s', ), + eigen_data=dict( + argstr='-inputfile %s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputdatatype=dict( + argstr='-inputdatatype %s', + usedefault=True, + ), + metric=dict( + argstr='-stat %s', + mandatory=True, + ), + outputdatatype=dict( + argstr='-outputdatatype %s', + usedefault=True, + ), + outputfile=dict( + argstr='-outputfile %s', + genfile=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DTMetric.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTMetric_outputs(): - output_map = dict(metric_stats=dict(), - ) + output_map = dict(metric_stats=dict(), ) outputs = DTMetric.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py b/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py index d3aaf0ec2e..07231d20a2 100644 --- a/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py +++ b/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py @@ -4,60 +4,61 @@ def test_FSL2Scheme_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bscale=dict(argstr='-bscale %d', - units='NA', - ), - bval_file=dict(argstr='-bvalfile %s', - mandatory=True, - position=2, - ), - bvec_file=dict(argstr='-bvecfile %s', - mandatory=True, - position=1, - ), - diffusiontime=dict(argstr='-diffusiontime %f', - units='NA', - ), - environ=dict(nohash=True, - usedefault=True, - ), - flipx=dict(argstr='-flipx', - ), - flipy=dict(argstr='-flipy', - ), - flipz=dict(argstr='-flipz', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interleave=dict(argstr='-interleave', - ), - numscans=dict(argstr='-numscans %d', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - usegradmod=dict(argstr='-usegradmod', - ), + input_map = dict( + args=dict(argstr='%s', ), + bscale=dict( + argstr='-bscale %d', + units='NA', + ), + bval_file=dict( + argstr='-bvalfile %s', + mandatory=True, + position=2, + ), + bvec_file=dict( + argstr='-bvecfile %s', + mandatory=True, + position=1, + ), + diffusiontime=dict( + argstr='-diffusiontime %f', + units='NA', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flipx=dict(argstr='-flipx', ), + flipy=dict(argstr='-flipy', ), + flipz=dict(argstr='-flipz', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interleave=dict(argstr='-interleave', ), + numscans=dict( + argstr='-numscans %d', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + usegradmod=dict(argstr='-usegradmod', ), ) inputs = FSL2Scheme.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FSL2Scheme_outputs(): - output_map = dict(scheme=dict(), - ) + output_map = dict(scheme=dict(), ) outputs = FSL2Scheme.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py b/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py index bbb8690129..cccc941bce 100644 --- a/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py +++ b/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py @@ -4,41 +4,44 @@ def test_Image2Voxel_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-4dimage %s', - mandatory=True, - position=1, - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - out_type=dict(argstr='-outputdatatype %s', - position=2, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-4dimage %s', + mandatory=True, + position=1, + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + out_type=dict( + argstr='-outputdatatype %s', + position=2, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Image2Voxel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Image2Voxel_outputs(): - output_map = dict(voxel_order=dict(), - ) + output_map = dict(voxel_order=dict(), ) outputs = Image2Voxel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ImageStats.py b/nipype/interfaces/camino/tests/test_auto_ImageStats.py index be0425cd89..4028ef22c3 100644 --- a/nipype/interfaces/camino/tests/test_auto_ImageStats.py +++ b/nipype/interfaces/camino/tests/test_auto_ImageStats.py @@ -4,43 +4,47 @@ def test_ImageStats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='-images %s', - mandatory=True, - position=-1, - ), - out_type=dict(argstr='-outputdatatype %s', - usedefault=True, - ), - output_root=dict(argstr='-outputroot %s', - mandatory=True, - ), - stat=dict(argstr='-stat %s', - mandatory=True, - units='NA', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='-images %s', + mandatory=True, + position=-1, + ), + out_type=dict( + argstr='-outputdatatype %s', + usedefault=True, + ), + output_root=dict( + argstr='-outputroot %s', + mandatory=True, + ), + stat=dict( + argstr='-stat %s', + mandatory=True, + units='NA', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ImageStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ImageStats_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ImageStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_LinRecon.py b/nipype/interfaces/camino/tests/test_auto_LinRecon.py index 193bf51422..9a50503578 100644 --- a/nipype/interfaces/camino/tests/test_auto_LinRecon.py +++ b/nipype/interfaces/camino/tests/test_auto_LinRecon.py @@ -4,51 +4,52 @@ def test_LinRecon_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bgmask=dict(argstr='-bgmask %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - log=dict(argstr='-log', - ), - normalize=dict(argstr='-normalize', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - qball_mat=dict(argstr='%s', - mandatory=True, - position=3, - ), - scheme_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bgmask=dict(argstr='-bgmask %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + log=dict(argstr='-log', ), + normalize=dict(argstr='-normalize', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + qball_mat=dict( + argstr='%s', + mandatory=True, + position=3, + ), + scheme_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = LinRecon.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LinRecon_outputs(): - output_map = dict(recon_data=dict(), - ) + output_map = dict(recon_data=dict(), ) outputs = LinRecon.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_MESD.py b/nipype/interfaces/camino/tests/test_auto_MESD.py index ccd2f94a0c..d80c3aa7ab 100644 --- a/nipype/interfaces/camino/tests/test_auto_MESD.py +++ b/nipype/interfaces/camino/tests/test_auto_MESD.py @@ -4,59 +4,64 @@ def test_MESD_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bgmask=dict(argstr='-bgmask %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fastmesd=dict(argstr='-fastmesd', - requires=['mepointset'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inverter=dict(argstr='-filter %s', - mandatory=True, - position=2, - ), - inverter_param=dict(argstr='%f', - mandatory=True, - position=3, - units='NA', - ), - mepointset=dict(argstr='-mepointset %d', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - scheme_file=dict(argstr='-schemefile %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bgmask=dict(argstr='-bgmask %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fastmesd=dict( + argstr='-fastmesd', + requires=['mepointset'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inverter=dict( + argstr='-filter %s', + mandatory=True, + position=2, + ), + inverter_param=dict( + argstr='%f', + mandatory=True, + position=3, + units='NA', + ), + mepointset=dict( + argstr='-mepointset %d', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + scheme_file=dict( + argstr='-schemefile %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MESD.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MESD_outputs(): - output_map = dict(mesd_data=dict(), - ) + output_map = dict(mesd_data=dict(), ) outputs = MESD.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ModelFit.py b/nipype/interfaces/camino/tests/test_auto_ModelFit.py index bb88c3032b..cb61ead239 100644 --- a/nipype/interfaces/camino/tests/test_auto_ModelFit.py +++ b/nipype/interfaces/camino/tests/test_auto_ModelFit.py @@ -4,66 +4,58 @@ def test_ModelFit_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bgmask=dict(argstr='-bgmask %s', - ), - bgthresh=dict(argstr='-bgthresh %G', - ), - cfthresh=dict(argstr='-csfthresh %G', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedbvalue=dict(argstr='-fixedbvalue %s', - ), - fixedmodq=dict(argstr='-fixedmod %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - model=dict(argstr='-model %s', - mandatory=True, - ), - noisemap=dict(argstr='-noisemap %s', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - outlier=dict(argstr='-outliermap %s', - ), - outputfile=dict(argstr='-outputfile %s', - ), - residualmap=dict(argstr='-residualmap %s', - ), - scheme_file=dict(argstr='-schemefile %s', - mandatory=True, - ), - sigma=dict(argstr='-sigma %G', - ), - tau=dict(argstr='-tau %G', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bgmask=dict(argstr='-bgmask %s', ), + bgthresh=dict(argstr='-bgthresh %G', ), + cfthresh=dict(argstr='-csfthresh %G', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedbvalue=dict(argstr='-fixedbvalue %s', ), + fixedmodq=dict(argstr='-fixedmod %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + model=dict( + argstr='-model %s', + mandatory=True, + ), + noisemap=dict(argstr='-noisemap %s', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + outlier=dict(argstr='-outliermap %s', ), + outputfile=dict(argstr='-outputfile %s', ), + residualmap=dict(argstr='-residualmap %s', ), + scheme_file=dict( + argstr='-schemefile %s', + mandatory=True, + ), + sigma=dict(argstr='-sigma %G', ), + tau=dict(argstr='-tau %G', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ModelFit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ModelFit_outputs(): - output_map = dict(fitted_data=dict(), - ) + output_map = dict(fitted_data=dict(), ) outputs = ModelFit.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py b/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py index dd3c97bb5f..4e3f551125 100644 --- a/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py +++ b/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py @@ -4,49 +4,45 @@ def test_NIfTIDT2Camino_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bgmask=dict(argstr='-bgmask %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - position=1, - ), - lns0_file=dict(argstr='-lns0 %s', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - s0_file=dict(argstr='-s0 %s', - ), - scaleinter=dict(argstr='-scaleinter %s', - ), - scaleslope=dict(argstr='-scaleslope %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uppertriangular=dict(argstr='-uppertriangular %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + bgmask=dict(argstr='-bgmask %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + position=1, + ), + lns0_file=dict(argstr='-lns0 %s', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + s0_file=dict(argstr='-s0 %s', ), + scaleinter=dict(argstr='-scaleinter %s', ), + scaleslope=dict(argstr='-scaleslope %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uppertriangular=dict(argstr='-uppertriangular %s', ), ) inputs = NIfTIDT2Camino.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NIfTIDT2Camino_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = NIfTIDT2Camino.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py b/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py index db40520152..6bb755ff82 100644 --- a/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py +++ b/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py @@ -4,56 +4,62 @@ def test_PicoPDFs_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - directmap=dict(argstr='-directmap', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=1, - ), - inputmodel=dict(argstr='-inputmodel %s', - position=2, - usedefault=True, - ), - luts=dict(argstr='-luts %s', - mandatory=True, - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - pdf=dict(argstr='-pdf %s', - position=4, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + directmap=dict(argstr='-directmap', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=1, + ), + inputmodel=dict( + argstr='-inputmodel %s', + position=2, + usedefault=True, + ), + luts=dict( + argstr='-luts %s', + mandatory=True, + ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + pdf=dict( + argstr='-pdf %s', + position=4, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = PicoPDFs.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PicoPDFs_outputs(): - output_map = dict(pdfs=dict(), - ) + output_map = dict(pdfs=dict(), ) outputs = PicoPDFs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py b/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py index ad2c4df2a5..986e18c4f9 100644 --- a/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py +++ b/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py @@ -4,114 +4,122 @@ def test_ProcStreamlines_inputs(): - input_map = dict(allowmultitargets=dict(argstr='-allowmultitargets', - ), - args=dict(argstr='%s', - ), - datadims=dict(argstr='-datadims %s', - units='voxels', - ), - directional=dict(argstr='-directional %s', - units='NA', - ), - discardloops=dict(argstr='-discardloops', - ), - endpointfile=dict(argstr='-endpointfile %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclusionfile=dict(argstr='-exclusionfile %s', - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - position=1, - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - iterations=dict(argstr='-iterations %d', - units='NA', - ), - maxtractlength=dict(argstr='-maxtractlength %d', - units='mm', - ), - maxtractpoints=dict(argstr='-maxtractpoints %d', - units='NA', - ), - mintractlength=dict(argstr='-mintractlength %d', - units='mm', - ), - mintractpoints=dict(argstr='-mintractpoints %d', - units='NA', - ), - noresample=dict(argstr='-noresample', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - outputacm=dict(argstr='-outputacm', - requires=['outputroot', 'seedfile'], - ), - outputcbs=dict(argstr='-outputcbs', - requires=['outputroot', 'targetfile', 'seedfile'], - ), - outputcp=dict(argstr='-outputcp', - requires=['outputroot', 'seedfile'], - ), - outputroot=dict(argstr='-outputroot %s', - ), - outputsc=dict(argstr='-outputsc', - requires=['outputroot', 'seedfile'], - ), - outputtracts=dict(argstr='-outputtracts', - ), - regionindex=dict(argstr='-regionindex %d', - units='mm', - ), - resamplestepsize=dict(argstr='-resamplestepsize %d', - units='NA', - ), - seedfile=dict(argstr='-seedfile %s', - ), - seedpointmm=dict(argstr='-seedpointmm %s', - units='mm', - ), - seedpointvox=dict(argstr='-seedpointvox %s', - units='voxels', - ), - targetfile=dict(argstr='-targetfile %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - truncateinexclusion=dict(argstr='-truncateinexclusion', - ), - truncateloops=dict(argstr='-truncateloops', - ), - voxeldims=dict(argstr='-voxeldims %s', - units='mm', - ), - waypointfile=dict(argstr='-waypointfile %s', - ), + input_map = dict( + allowmultitargets=dict(argstr='-allowmultitargets', ), + args=dict(argstr='%s', ), + datadims=dict( + argstr='-datadims %s', + units='voxels', + ), + directional=dict( + argstr='-directional %s', + units='NA', + ), + discardloops=dict(argstr='-discardloops', ), + endpointfile=dict(argstr='-endpointfile %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclusionfile=dict(argstr='-exclusionfile %s', ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + position=1, + ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + iterations=dict( + argstr='-iterations %d', + units='NA', + ), + maxtractlength=dict( + argstr='-maxtractlength %d', + units='mm', + ), + maxtractpoints=dict( + argstr='-maxtractpoints %d', + units='NA', + ), + mintractlength=dict( + argstr='-mintractlength %d', + units='mm', + ), + mintractpoints=dict( + argstr='-mintractpoints %d', + units='NA', + ), + noresample=dict(argstr='-noresample', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + outputacm=dict( + argstr='-outputacm', + requires=['outputroot', 'seedfile'], + ), + outputcbs=dict( + argstr='-outputcbs', + requires=['outputroot', 'targetfile', 'seedfile'], + ), + outputcp=dict( + argstr='-outputcp', + requires=['outputroot', 'seedfile'], + ), + outputroot=dict(argstr='-outputroot %s', ), + outputsc=dict( + argstr='-outputsc', + requires=['outputroot', 'seedfile'], + ), + outputtracts=dict(argstr='-outputtracts', ), + regionindex=dict( + argstr='-regionindex %d', + units='mm', + ), + resamplestepsize=dict( + argstr='-resamplestepsize %d', + units='NA', + ), + seedfile=dict(argstr='-seedfile %s', ), + seedpointmm=dict( + argstr='-seedpointmm %s', + units='mm', + ), + seedpointvox=dict( + argstr='-seedpointvox %s', + units='voxels', + ), + targetfile=dict(argstr='-targetfile %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + truncateinexclusion=dict(argstr='-truncateinexclusion', ), + truncateloops=dict(argstr='-truncateloops', ), + voxeldims=dict( + argstr='-voxeldims %s', + units='mm', + ), + waypointfile=dict(argstr='-waypointfile %s', ), ) inputs = ProcStreamlines.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ProcStreamlines_outputs(): - output_map = dict(outputroot_files=dict(), - proc=dict(), + output_map = dict( + outputroot_files=dict(), + proc=dict(), ) outputs = ProcStreamlines.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_QBallMX.py b/nipype/interfaces/camino/tests/test_auto_QBallMX.py index bcdf5ba627..dd360414e5 100644 --- a/nipype/interfaces/camino/tests/test_auto_QBallMX.py +++ b/nipype/interfaces/camino/tests/test_auto_QBallMX.py @@ -4,51 +4,58 @@ def test_QBallMX_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - basistype=dict(argstr='-basistype %s', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - order=dict(argstr='-order %d', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - rbfpointset=dict(argstr='-rbfpointset %d', - units='NA', - ), - rbfsigma=dict(argstr='-rbfsigma %f', - units='NA', - ), - scheme_file=dict(argstr='-schemefile %s', - mandatory=True, - ), - smoothingsigma=dict(argstr='-smoothingsigma %f', - units='NA', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + basistype=dict( + argstr='-basistype %s', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + order=dict( + argstr='-order %d', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + rbfpointset=dict( + argstr='-rbfpointset %d', + units='NA', + ), + rbfsigma=dict( + argstr='-rbfsigma %f', + units='NA', + ), + scheme_file=dict( + argstr='-schemefile %s', + mandatory=True, + ), + smoothingsigma=dict( + argstr='-smoothingsigma %f', + units='NA', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = QBallMX.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_QBallMX_outputs(): - output_map = dict(qmat=dict(), - ) + output_map = dict(qmat=dict(), ) outputs = QBallMX.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py b/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py index 3bb61363e1..514483628a 100644 --- a/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py +++ b/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py @@ -4,56 +4,65 @@ def test_SFLUTGen_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - binincsize=dict(argstr='-binincsize %d', - units='NA', - ), - directmap=dict(argstr='-directmap', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - ), - info_file=dict(argstr='-infofile %s', - mandatory=True, - ), - minvectsperbin=dict(argstr='-minvectsperbin %d', - units='NA', - ), - order=dict(argstr='-order %d', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - outputstem=dict(argstr='-outputstem %s', - usedefault=True, - ), - pdf=dict(argstr='-pdf %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + binincsize=dict( + argstr='-binincsize %d', + units='NA', + ), + directmap=dict(argstr='-directmap', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + ), + info_file=dict( + argstr='-infofile %s', + mandatory=True, + ), + minvectsperbin=dict( + argstr='-minvectsperbin %d', + units='NA', + ), + order=dict( + argstr='-order %d', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + outputstem=dict( + argstr='-outputstem %s', + usedefault=True, + ), + pdf=dict( + argstr='-pdf %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SFLUTGen.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SFLUTGen_outputs(): - output_map = dict(lut_one_fibre=dict(), - lut_two_fibres=dict(), + output_map = dict( + lut_one_fibre=dict(), + lut_two_fibres=dict(), ) outputs = SFLUTGen.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py b/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py index 2d2cbc6ba5..cc45f8380d 100644 --- a/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py +++ b/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py @@ -4,74 +4,90 @@ def test_SFPICOCalibData_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - info_file=dict(argstr='-infooutputfile %s', - genfile=True, - hash_files=False, - mandatory=True, - ), - onedtfarange=dict(argstr='-onedtfarange %s', - units='NA', - ), - onedtfastep=dict(argstr='-onedtfastep %f', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - scheme_file=dict(argstr='-schemefile %s', - mandatory=True, - ), - seed=dict(argstr='-seed %f', - units='NA', - ), - snr=dict(argstr='-snr %f', - units='NA', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trace=dict(argstr='-trace %f', - units='NA', - ), - twodtanglerange=dict(argstr='-twodtanglerange %s', - units='NA', - ), - twodtanglestep=dict(argstr='-twodtanglestep %f', - units='NA', - ), - twodtfarange=dict(argstr='-twodtfarange %s', - units='NA', - ), - twodtfastep=dict(argstr='-twodtfastep %f', - units='NA', - ), - twodtmixmax=dict(argstr='-twodtmixmax %f', - units='NA', - ), - twodtmixstep=dict(argstr='-twodtmixstep %f', - units='NA', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + info_file=dict( + argstr='-infooutputfile %s', + genfile=True, + hash_files=False, + mandatory=True, + ), + onedtfarange=dict( + argstr='-onedtfarange %s', + units='NA', + ), + onedtfastep=dict( + argstr='-onedtfastep %f', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + scheme_file=dict( + argstr='-schemefile %s', + mandatory=True, + ), + seed=dict( + argstr='-seed %f', + units='NA', + ), + snr=dict( + argstr='-snr %f', + units='NA', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trace=dict( + argstr='-trace %f', + units='NA', + ), + twodtanglerange=dict( + argstr='-twodtanglerange %s', + units='NA', + ), + twodtanglestep=dict( + argstr='-twodtanglestep %f', + units='NA', + ), + twodtfarange=dict( + argstr='-twodtfarange %s', + units='NA', + ), + twodtfastep=dict( + argstr='-twodtfastep %f', + units='NA', + ), + twodtmixmax=dict( + argstr='-twodtmixmax %f', + units='NA', + ), + twodtmixstep=dict( + argstr='-twodtmixstep %f', + units='NA', + ), ) inputs = SFPICOCalibData.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SFPICOCalibData_outputs(): - output_map = dict(PICOCalib=dict(), - calib_info=dict(), + output_map = dict( + PICOCalib=dict(), + calib_info=dict(), ) outputs = SFPICOCalibData.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_SFPeaks.py b/nipype/interfaces/camino/tests/test_auto_SFPeaks.py index 00bb953015..9012865037 100644 --- a/nipype/interfaces/camino/tests/test_auto_SFPeaks.py +++ b/nipype/interfaces/camino/tests/test_auto_SFPeaks.py @@ -4,70 +4,80 @@ def test_SFPeaks_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - density=dict(argstr='-density %d', - units='NA', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - mandatory=True, - ), - inputmodel=dict(argstr='-inputmodel %s', - mandatory=True, - ), - mepointset=dict(argstr='-mepointset %d', - units='NA', - ), - noconsistencycheck=dict(argstr='-noconsistencycheck', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - order=dict(argstr='-order %d', - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - pdthresh=dict(argstr='-pdthresh %f', - units='NA', - ), - pointset=dict(argstr='-pointset %d', - units='NA', - ), - rbfpointset=dict(argstr='-rbfpointset %d', - units='NA', - ), - scheme_file=dict(argstr='%s', - ), - searchradius=dict(argstr='-searchradius %f', - units='NA', - ), - stdsfrommean=dict(argstr='-stdsfrommean %f', - units='NA', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + density=dict( + argstr='-density %d', + units='NA', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + mandatory=True, + ), + inputmodel=dict( + argstr='-inputmodel %s', + mandatory=True, + ), + mepointset=dict( + argstr='-mepointset %d', + units='NA', + ), + noconsistencycheck=dict(argstr='-noconsistencycheck', ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + order=dict( + argstr='-order %d', + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + pdthresh=dict( + argstr='-pdthresh %f', + units='NA', + ), + pointset=dict( + argstr='-pointset %d', + units='NA', + ), + rbfpointset=dict( + argstr='-rbfpointset %d', + units='NA', + ), + scheme_file=dict(argstr='%s', ), + searchradius=dict( + argstr='-searchradius %f', + units='NA', + ), + stdsfrommean=dict( + argstr='-stdsfrommean %f', + units='NA', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SFPeaks.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SFPeaks_outputs(): - output_map = dict(peaks=dict(), - ) + output_map = dict(peaks=dict(), ) outputs = SFPeaks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Shredder.py b/nipype/interfaces/camino/tests/test_auto_Shredder.py index 695c529d3c..16d1655e54 100644 --- a/nipype/interfaces/camino/tests/test_auto_Shredder.py +++ b/nipype/interfaces/camino/tests/test_auto_Shredder.py @@ -4,49 +4,54 @@ def test_Shredder_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - chunksize=dict(argstr='%d', - position=2, - units='NA', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=-2, - ), - offset=dict(argstr='%d', - position=1, - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - space=dict(argstr='%d', - position=3, - units='NA', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + chunksize=dict( + argstr='%d', + position=2, + units='NA', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=-2, + ), + offset=dict( + argstr='%d', + position=1, + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + space=dict( + argstr='%d', + position=3, + units='NA', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Shredder.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Shredder_outputs(): - output_map = dict(shredded=dict(), - ) + output_map = dict(shredded=dict(), ) outputs = Shredder.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Track.py b/nipype/interfaces/camino/tests/test_auto_Track.py index 510a970f39..fed31e1506 100644 --- a/nipype/interfaces/camino/tests/test_auto_Track.py +++ b/nipype/interfaces/camino/tests/test_auto_Track.py @@ -4,82 +4,86 @@ def test_Track_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = Track.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Track_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = Track.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py b/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py index d422972863..4b2e9776f2 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py @@ -4,82 +4,86 @@ def test_TrackBallStick_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = TrackBallStick.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackBallStick_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = TrackBallStick.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py b/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py index 9fd6c6caac..51f4486b80 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py @@ -4,102 +4,101 @@ def test_TrackBayesDirac_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvepriorg=dict(argstr='-curvepriorg %G', - ), - curvepriork=dict(argstr='-curvepriork %G', - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - datamodel=dict(argstr='-datamodel %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - extpriordatatype=dict(argstr='-extpriordatatype %s', - ), - extpriorfile=dict(argstr='-extpriorfile %s', - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - iterations=dict(argstr='-iterations %d', - units='NA', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - pdf=dict(argstr='-pdf %s', - ), - pointset=dict(argstr='-pointset %s', - ), - scheme_file=dict(argstr='-schemefile %s', - mandatory=True, - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvepriorg=dict(argstr='-curvepriorg %G', ), + curvepriork=dict(argstr='-curvepriork %G', ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + datamodel=dict(argstr='-datamodel %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + extpriordatatype=dict(argstr='-extpriordatatype %s', ), + extpriorfile=dict(argstr='-extpriorfile %s', ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + iterations=dict( + argstr='-iterations %d', + units='NA', + ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + pdf=dict(argstr='-pdf %s', ), + pointset=dict(argstr='-pointset %s', ), + scheme_file=dict( + argstr='-schemefile %s', + mandatory=True, + ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = TrackBayesDirac.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackBayesDirac_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = TrackBayesDirac.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py index 7d23187cd5..c0c95abc2d 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py @@ -4,88 +4,94 @@ def test_TrackBedpostxDeter_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - bedpostxdir=dict(argstr='-bedpostxdir %s', - mandatory=True, - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - min_vol_frac=dict(argstr='-bedpostxminf %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + bedpostxdir=dict( + argstr='-bedpostxdir %s', + mandatory=True, + ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + min_vol_frac=dict( + argstr='-bedpostxminf %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = TrackBedpostxDeter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackBedpostxDeter_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = TrackBedpostxDeter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py index 37d2e719dd..9b5068df24 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py @@ -4,91 +4,98 @@ def test_TrackBedpostxProba_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - bedpostxdir=dict(argstr='-bedpostxdir %s', - mandatory=True, - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - iterations=dict(argstr='-iterations %d', - units='NA', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - min_vol_frac=dict(argstr='-bedpostxminf %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + bedpostxdir=dict( + argstr='-bedpostxdir %s', + mandatory=True, + ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + iterations=dict( + argstr='-iterations %d', + units='NA', + ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + min_vol_frac=dict( + argstr='-bedpostxminf %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = TrackBedpostxProba.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackBedpostxProba_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = TrackBedpostxProba.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py b/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py index 6f340c75bf..9f1207e7f8 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py @@ -4,95 +4,100 @@ def test_TrackBootstrap_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - bgmask=dict(argstr='-bgmask %s', - ), - bsdatafiles=dict(argstr='-bsdatafile %s', - mandatory=True, - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - inversion=dict(argstr='-inversion %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - iterations=dict(argstr='-iterations %d', - units='NA', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - scheme_file=dict(argstr='-schemefile %s', - mandatory=True, - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + bgmask=dict(argstr='-bgmask %s', ), + bsdatafiles=dict( + argstr='-bsdatafile %s', + mandatory=True, + ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + inversion=dict(argstr='-inversion %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + iterations=dict( + argstr='-iterations %d', + units='NA', + ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + scheme_file=dict( + argstr='-schemefile %s', + mandatory=True, + ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = TrackBootstrap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackBootstrap_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = TrackBootstrap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackDT.py b/nipype/interfaces/camino/tests/test_auto_TrackDT.py index 6e4e13fd67..c2915d6328 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackDT.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackDT.py @@ -4,82 +4,86 @@ def test_TrackDT_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = TrackDT.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackDT_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = TrackDT.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackPICo.py b/nipype/interfaces/camino/tests/test_auto_TrackPICo.py index 814aa7d597..862c998692 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackPICo.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackPICo.py @@ -4,87 +4,91 @@ def test_TrackPICo_inputs(): - input_map = dict(anisfile=dict(argstr='-anisfile %s', - ), - anisthresh=dict(argstr='-anisthresh %f', - ), - args=dict(argstr='%s', - ), - curveinterval=dict(argstr='-curveinterval %f', - requires=['curvethresh'], - ), - curvethresh=dict(argstr='-curvethresh %f', - ), - data_dims=dict(argstr='-datadims %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gzip=dict(argstr='-gzip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-inputfile %s', - position=1, - ), - inputdatatype=dict(argstr='-inputdatatype %s', - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolator=dict(argstr='-interpolator %s', - ), - ipthresh=dict(argstr='-ipthresh %f', - ), - iterations=dict(argstr='-iterations %d', - units='NA', - ), - maxcomponents=dict(argstr='-maxcomponents %d', - units='NA', - ), - numpds=dict(argstr='-numpds %d', - units='NA', - ), - out_file=dict(argstr='-outputfile %s', - genfile=True, - position=-1, - ), - output_root=dict(argstr='-outputroot %s', - position=-1, - ), - outputtracts=dict(argstr='-outputtracts %s', - ), - pdf=dict(argstr='-pdf %s', - ), - seed_file=dict(argstr='-seedfile %s', - position=2, - ), - stepsize=dict(argstr='-stepsize %f', - requires=['tracker'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracker=dict(argstr='-tracker %s', - usedefault=True, - ), - voxel_dims=dict(argstr='-voxeldims %s', - units='mm', - ), + input_map = dict( + anisfile=dict(argstr='-anisfile %s', ), + anisthresh=dict(argstr='-anisthresh %f', ), + args=dict(argstr='%s', ), + curveinterval=dict( + argstr='-curveinterval %f', + requires=['curvethresh'], + ), + curvethresh=dict(argstr='-curvethresh %f', ), + data_dims=dict( + argstr='-datadims %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict(argstr='-gzip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-inputfile %s', + position=1, + ), + inputdatatype=dict(argstr='-inputdatatype %s', ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolator=dict(argstr='-interpolator %s', ), + ipthresh=dict(argstr='-ipthresh %f', ), + iterations=dict( + argstr='-iterations %d', + units='NA', + ), + maxcomponents=dict( + argstr='-maxcomponents %d', + units='NA', + ), + numpds=dict( + argstr='-numpds %d', + units='NA', + ), + out_file=dict( + argstr='-outputfile %s', + genfile=True, + position=-1, + ), + output_root=dict( + argstr='-outputroot %s', + position=-1, + ), + outputtracts=dict(argstr='-outputtracts %s', ), + pdf=dict(argstr='-pdf %s', ), + seed_file=dict( + argstr='-seedfile %s', + position=2, + ), + stepsize=dict( + argstr='-stepsize %f', + requires=['tracker'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracker=dict( + argstr='-tracker %s', + usedefault=True, + ), + voxel_dims=dict( + argstr='-voxeldims %s', + units='mm', + ), ) inputs = TrackPICo.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackPICo_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = TrackPICo.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TractShredder.py b/nipype/interfaces/camino/tests/test_auto_TractShredder.py index 9d53cd246f..88bd401cca 100644 --- a/nipype/interfaces/camino/tests/test_auto_TractShredder.py +++ b/nipype/interfaces/camino/tests/test_auto_TractShredder.py @@ -4,49 +4,54 @@ def test_TractShredder_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bunchsize=dict(argstr='%d', - position=2, - units='NA', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='< %s', - mandatory=True, - position=-2, - ), - offset=dict(argstr='%d', - position=1, - units='NA', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - space=dict(argstr='%d', - position=3, - units='NA', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bunchsize=dict( + argstr='%d', + position=2, + units='NA', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='< %s', + mandatory=True, + position=-2, + ), + offset=dict( + argstr='%d', + position=1, + units='NA', + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + space=dict( + argstr='%d', + position=3, + units='NA', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TractShredder.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TractShredder_outputs(): - output_map = dict(shredded=dict(), - ) + output_map = dict(shredded=dict(), ) outputs = TractShredder.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py b/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py index 1f7d8483a3..ae259948a8 100644 --- a/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py +++ b/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py @@ -4,59 +4,63 @@ def test_VtkStreamlines_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - colourorient=dict(argstr='-colourorient', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr=' < %s', - mandatory=True, - position=-2, - ), - inputmodel=dict(argstr='-inputmodel %s', - usedefault=True, - ), - interpolate=dict(argstr='-interpolate', - ), - interpolatescalars=dict(argstr='-interpolatescalars', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - scalar_file=dict(argstr='-scalarfile %s', - position=3, - ), - seed_file=dict(argstr='-seedfile %s', - position=1, - ), - target_file=dict(argstr='-targetfile %s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxeldims=dict(argstr='-voxeldims %s', - position=4, - units='mm', - ), + input_map = dict( + args=dict(argstr='%s', ), + colourorient=dict(argstr='-colourorient', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr=' < %s', + mandatory=True, + position=-2, + ), + inputmodel=dict( + argstr='-inputmodel %s', + usedefault=True, + ), + interpolate=dict(argstr='-interpolate', ), + interpolatescalars=dict(argstr='-interpolatescalars', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + scalar_file=dict( + argstr='-scalarfile %s', + position=3, + ), + seed_file=dict( + argstr='-seedfile %s', + position=1, + ), + target_file=dict( + argstr='-targetfile %s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxeldims=dict( + argstr='-voxeldims %s', + position=4, + units='mm', + ), ) inputs = VtkStreamlines.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VtkStreamlines_outputs(): - output_map = dict(vtk=dict(), - ) + output_map = dict(vtk=dict(), ) outputs = VtkStreamlines.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/utils.py b/nipype/interfaces/camino/utils.py index 0cb07d89f5..1146927dc5 100644 --- a/nipype/interfaces/camino/utils.py +++ b/nipype/interfaces/camino/utils.py @@ -7,7 +7,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from ..base import (traits, TraitedSpec, File, CommandLine, @@ -16,25 +17,49 @@ class ImageStatsInputSpec(CommandLineInputSpec): - in_files = InputMultiPath(File(exists=True), argstr='-images %s', mandatory=True, - position=-1, desc=('List of images to process. They must ' - 'be in the same space and have the same ' - 'dimensions.')) - stat = traits.Enum("min", "max", "mean", "median", "sum", "std", "var", - argstr='-stat %s', units='NA', mandatory=True, - desc="The statistic to compute.") + in_files = InputMultiPath( + File(exists=True), + argstr='-images %s', + mandatory=True, + position=-1, + desc=('List of images to process. They must ' + 'be in the same space and have the same ' + 'dimensions.')) + stat = traits.Enum( + "min", + "max", + "mean", + "median", + "sum", + "std", + "var", + argstr='-stat %s', + units='NA', + mandatory=True, + desc="The statistic to compute.") - out_type = traits.Enum("float", "char", "short", "int", "long", "double", - argstr='-outputdatatype %s', usedefault=True, - desc=('A Camino data type string, default is "float". ' - 'Type must be signed.')) - output_root = File(argstr='-outputroot %s', mandatory=True, - desc=('Filename root prepended onto the names of the output ' - ' files. The extension will be determined from the input.')) + out_type = traits.Enum( + "float", + "char", + "short", + "int", + "long", + "double", + argstr='-outputdatatype %s', + usedefault=True, + desc=('A Camino data type string, default is "float". ' + 'Type must be signed.')) + output_root = File( + argstr='-outputroot %s', + mandatory=True, + desc=('Filename root prepended onto the names of the output ' + ' files. The extension will be determined from the input.')) class ImageStatsOutputSpec(TraitedSpec): - out_file = File(exists=True, desc='Path of the file computed with the statistic chosen') + out_file = File( + exists=True, + desc='Path of the file computed with the statistic chosen') class ImageStats(CommandLine): diff --git a/nipype/interfaces/camino2trackvis/convert.py b/nipype/interfaces/camino2trackvis/convert.py index b9032ba1cd..fd20442438 100644 --- a/nipype/interfaces/camino2trackvis/convert.py +++ b/nipype/interfaces/camino2trackvis/convert.py @@ -9,7 +9,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os @@ -18,26 +19,54 @@ class Camino2TrackvisInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='-i %s', mandatory=True, position=1, - desc='The input .Bfloat (camino) file.') - - out_file = File(argstr='-o %s', genfile=True, position=2, - desc='The filename to which to write the .trk (trackvis) file.') - - min_length = traits.Float(argstr='-l %d', position=3, - units='mm', desc='The minimum length of tracts to output') - - data_dims = traits.List(traits.Int, argstr='-d %s', sep=',', - mandatory=True, position=4, minlen=3, maxlen=3, - desc='Three comma-separated integers giving the number of voxels along each dimension of the source scans.') - - voxel_dims = traits.List(traits.Float, argstr='-x %s', sep=',', - mandatory=True, position=5, minlen=3, maxlen=3, - desc='Three comma-separated numbers giving the size of each voxel in mm.') + in_file = File( + exists=True, + argstr='-i %s', + mandatory=True, + position=1, + desc='The input .Bfloat (camino) file.') + + out_file = File( + argstr='-o %s', + genfile=True, + position=2, + desc='The filename to which to write the .trk (trackvis) file.') + + min_length = traits.Float( + argstr='-l %d', + position=3, + units='mm', + desc='The minimum length of tracts to output') + + data_dims = traits.List( + traits.Int, + argstr='-d %s', + sep=',', + mandatory=True, + position=4, + minlen=3, + maxlen=3, + desc= + 'Three comma-separated integers giving the number of voxels along each dimension of the source scans.' + ) + + voxel_dims = traits.List( + traits.Float, + argstr='-x %s', + sep=',', + mandatory=True, + position=5, + minlen=3, + maxlen=3, + desc= + 'Three comma-separated numbers giving the size of each voxel in mm.') # Change to enum with all combinations? i.e. LAS, LPI, RAS, etc.. - voxel_order = File(argstr='--voxel-order %s', mandatory=True, position=6, - desc='Set the order in which various directions were stored.\ + voxel_order = File( + argstr='--voxel-order %s', + mandatory=True, + position=6, + desc='Set the order in which various directions were stored.\ Specify with three letters consisting of one each \ from the pairs LR, AP, and SI. These stand for Left-Right, \ Anterior-Posterior, and Superior-Inferior. \ @@ -45,12 +74,17 @@ class Camino2TrackvisInputSpec(CommandLineInputSpec): be the direction of increasing order. \ Read coordinate system from a NIfTI file.') - nifti_file = File(argstr='--nifti %s', exists=True, - position=7, desc='Read coordinate system from a NIfTI file.') + nifti_file = File( + argstr='--nifti %s', + exists=True, + position=7, + desc='Read coordinate system from a NIfTI file.') class Camino2TrackvisOutputSpec(TraitedSpec): - trackvis = File(exists=True, desc='The filename to which to write the .trk (trackvis) file.') + trackvis = File( + exists=True, + desc='The filename to which to write the .trk (trackvis) file.') class Camino2Trackvis(CommandLine): @@ -107,19 +141,30 @@ class Trackvis2CaminoInputSpec(CommandLineInputSpec): >>> t2c.run() # doctest: +SKIP """ - in_file = File(exists=True, argstr='-i %s', - mandatory=True, position=1, - desc='The input .trk (trackvis) file.') + in_file = File( + exists=True, + argstr='-i %s', + mandatory=True, + position=1, + desc='The input .trk (trackvis) file.') - out_file = File(argstr='-o %s', genfile=True, - position=2, desc='The filename to which to write the .Bfloat (camino).') + out_file = File( + argstr='-o %s', + genfile=True, + position=2, + desc='The filename to which to write the .Bfloat (camino).') - append_file = File(exists=True, argstr='-a %s', - position=2, desc='A file to which the append the .Bfloat data. ') + append_file = File( + exists=True, + argstr='-a %s', + position=2, + desc='A file to which the append the .Bfloat data. ') class Trackvis2CaminoOutputSpec(TraitedSpec): - camino = File(exists=True, desc='The filename to which to write the .Bfloat (camino).') + camino = File( + exists=True, + desc='The filename to which to write the .Bfloat (camino).') class Trackvis2Camino(CommandLine): diff --git a/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py b/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py index 7c3049e98a..cfa87befb0 100644 --- a/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py +++ b/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py @@ -4,58 +4,65 @@ def test_Camino2Trackvis_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - data_dims=dict(argstr='-d %s', - mandatory=True, - position=4, - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=1, - ), - min_length=dict(argstr='-l %d', - position=3, - units='mm', - ), - nifti_file=dict(argstr='--nifti %s', - position=7, - ), - out_file=dict(argstr='-o %s', - genfile=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel_dims=dict(argstr='-x %s', - mandatory=True, - position=5, - sep=',', - ), - voxel_order=dict(argstr='--voxel-order %s', - mandatory=True, - position=6, - ), + input_map = dict( + args=dict(argstr='%s', ), + data_dims=dict( + argstr='-d %s', + mandatory=True, + position=4, + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=1, + ), + min_length=dict( + argstr='-l %d', + position=3, + units='mm', + ), + nifti_file=dict( + argstr='--nifti %s', + position=7, + ), + out_file=dict( + argstr='-o %s', + genfile=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel_dims=dict( + argstr='-x %s', + mandatory=True, + position=5, + sep=',', + ), + voxel_order=dict( + argstr='--voxel-order %s', + mandatory=True, + position=6, + ), ) inputs = Camino2Trackvis.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Camino2Trackvis_outputs(): - output_map = dict(trackvis=dict(), - ) + output_map = dict(trackvis=dict(), ) outputs = Camino2Trackvis.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py b/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py index 4caa6e1ab9..64300a1398 100644 --- a/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py +++ b/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py @@ -4,40 +4,43 @@ def test_Trackvis2Camino_inputs(): - input_map = dict(append_file=dict(argstr='-a %s', - position=2, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=1, - ), - out_file=dict(argstr='-o %s', - genfile=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + append_file=dict( + argstr='-a %s', + position=2, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=1, + ), + out_file=dict( + argstr='-o %s', + genfile=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Trackvis2Camino.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Trackvis2Camino_outputs(): - output_map = dict(camino=dict(), - ) + output_map = dict(camino=dict(), ) outputs = Trackvis2Camino.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cmtk/cmtk.py b/nipype/interfaces/cmtk/cmtk.py index 2f29bbb2e2..c7ca43cd4e 100644 --- a/nipype/interfaces/cmtk/cmtk.py +++ b/nipype/interfaces/cmtk/cmtk.py @@ -9,7 +9,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, open import pickle @@ -68,7 +69,7 @@ def length(xyz, along=False): if along: return np.array([0]) return 0 - dists = np.sqrt((np.diff(xyz, axis=0) ** 2).sum(axis=1)) + dists = np.sqrt((np.diff(xyz, axis=0)**2).sum(axis=1)) if along: return np.cumsum(dists) return np.sum(dists) @@ -84,7 +85,8 @@ def get_rois_crossed(pointsmm, roiData, voxelSize): z = int(pointsmm[j, 2] / float(voxelSize[2])) if not roiData[x, y, z] == 0: rois_crossed.append(roiData[x, y, z]) - rois_crossed = list(dict.fromkeys(rois_crossed).keys()) # Removed duplicates from the list + rois_crossed = list( + dict.fromkeys(rois_crossed).keys()) # Removed duplicates from the list return rois_crossed @@ -118,11 +120,13 @@ def create_allpoints_cmat(streamlines, roiData, voxelSize, n_rois): list_of_roi_crossed_lists.append(list(rois_crossed)) final_fiber_ids.append(i) - connectivity_matrix = get_connectivity_matrix(n_rois, list_of_roi_crossed_lists) + connectivity_matrix = get_connectivity_matrix(n_rois, + list_of_roi_crossed_lists) dis = n_fib - len(final_fiber_ids) - iflogger.info('Found %i (%f percent out of %i fibers) fibers that start or ' - 'terminate in a voxel which is not labeled. (orphans)', - dis, dis * 100.0 / n_fib, n_fib) + iflogger.info( + 'Found %i (%f percent out of %i fibers) fibers that start or ' + 'terminate in a voxel which is not labeled. (orphans)', dis, + dis * 100.0 / n_fib, n_fib) iflogger.info('Valid fibers: %i (%f percent)', n_fib - dis, 100 - dis * 100.0 / n_fib) iflogger.info('Returning the intersecting point connectivity matrix') @@ -146,7 +150,6 @@ def create_endpoints_array(fib, voxelSize): n = len(fib) endpoints = np.zeros((n, 2, 3)) endpointsmm = np.zeros((n, 2, 3)) - pc = -1 # Computation for each fiber for i, fi in enumerate(fib): @@ -175,7 +178,13 @@ def create_endpoints_array(fib, voxelSize): return (endpoints, endpointsmm) -def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_name, endpoint_name, intersections=False): +def cmat(track_file, + roi_file, + resolution_network_file, + matrix_name, + matrix_mat_name, + endpoint_name, + intersections=False): """ Create the connection matrix for each resolution using fibers and ROIs. """ stats = {} @@ -225,27 +234,38 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ G.add_node(int(u), **d) # compute a position for the node based on the mean position of the # ROI in voxel coordinates (segmentation volume ) - xyz = tuple(np.mean(np.where(np.flipud(roiData) == int(d["dn_correspondence_id"])), axis=1)) + xyz = tuple( + np.mean( + np.where( + np.flipud(roiData) == int(d["dn_correspondence_id"])), + axis=1)) G.nodes[int(u)]['dn_position'] = tuple([xyz[0], xyz[2], -xyz[1]]) if intersections: iflogger.info("Filtering tractography from intersections") - intersection_matrix, final_fiber_ids = create_allpoints_cmat(fib, roiData, roiVoxelSize, nROIs) - finalfibers_fname = op.abspath(endpoint_name + '_intersections_streamline_final.trk') - stats['intersections_n_fib'] = save_fibers(hdr, fib, finalfibers_fname, final_fiber_ids) + intersection_matrix, final_fiber_ids = create_allpoints_cmat( + fib, roiData, roiVoxelSize, nROIs) + finalfibers_fname = op.abspath( + endpoint_name + '_intersections_streamline_final.trk') + stats['intersections_n_fib'] = save_fibers(hdr, fib, finalfibers_fname, + final_fiber_ids) intersection_matrix = np.matrix(intersection_matrix) I = G.copy() H = nx.from_numpy_matrix(np.matrix(intersection_matrix)) - H = nx.relabel_nodes(H, lambda x: x + 1) # relabel nodes so they start at 1 - I.add_weighted_edges_from(((u, v, d['weight']) for u, v, d in H.edges(data=True))) + H = nx.relabel_nodes( + H, lambda x: x + 1) # relabel nodes so they start at 1 + I.add_weighted_edges_from( + ((u, v, d['weight']) for u, v, d in H.edges(data=True))) dis = 0 for i in range(endpoints.shape[0]): # ROI start => ROI end try: - startROI = int(roiData[endpoints[i, 0, 0], endpoints[i, 0, 1], endpoints[i, 0, 2]]) - endROI = int(roiData[endpoints[i, 1, 0], endpoints[i, 1, 1], endpoints[i, 1, 2]]) + startROI = int(roiData[endpoints[i, 0, 0], endpoints[i, 0, 1], + endpoints[i, 0, 2]]) + endROI = int(roiData[endpoints[i, 1, 0], endpoints[i, 1, 1], + endpoints[i, 1, 2]]) except IndexError: iflogger.error('AN INDEXERROR EXCEPTION OCCURED FOR FIBER %s. ' 'PLEASE CHECK ENDPOINT GENERATION', i) @@ -258,8 +278,11 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ continue if startROI > nROIs or endROI > nROIs: - iflogger.error("Start or endpoint of fiber terminate in a voxel which is labeled higher") - iflogger.error("than is expected by the parcellation node information.") + iflogger.error( + "Start or endpoint of fiber terminate in a voxel which is labeled higher" + ) + iflogger.error( + "than is expected by the parcellation node information.") iflogger.error("Start ROI: %i, End ROI: %i", startROI, endROI) iflogger.error("This needs bugfixing!") continue @@ -278,7 +301,8 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ final_fibers_idx.append(i) # Add edge to graph - if G.has_edge(startROI, endROI) and 'fiblist' in G.edge[startROI][endROI]: + if G.has_edge(startROI, + endROI) and 'fiblist' in G.edge[startROI][endROI]: G.edge[startROI][endROI]['fiblist'].append(i) else: G.add_edge(startROI, endROI, fiblist=[i]) @@ -300,9 +324,10 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ # make final fiber labels as array final_fiberlabels_array = np.array(final_fiberlabels, dtype=int) - iflogger.info('Found %i (%f percent out of %i fibers) fibers that start or ' - 'terminate in a voxel which is not labeled. (orphans)', - dis, dis * 100.0 / n, n) + iflogger.info( + 'Found %i (%f percent out of %i fibers) fibers that start or ' + 'terminate in a voxel which is not labeled. (orphans)', dis, + dis * 100.0 / n, n) iflogger.info('Valid fibers: %i (%f%%)', n - dis, 100 - dis * 100.0 / n) numfib = nx.Graph() @@ -315,10 +340,14 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ di = {} if 'fiblist' in d: di['number_of_fibers'] = len(d['fiblist']) - idx = np.where((final_fiberlabels_array[:, 0] == int(u)) & (final_fiberlabels_array[:, 1] == int(v)))[0] - di['fiber_length_mean'] = float(np.mean(final_fiberlength_array[idx])) - di['fiber_length_median'] = float(np.median(final_fiberlength_array[idx])) - di['fiber_length_std'] = float(np.std(final_fiberlength_array[idx])) + idx = np.where((final_fiberlabels_array[:, 0] == int(u)) & + (final_fiberlabels_array[:, 1] == int(v)))[0] + di['fiber_length_mean'] = float( + np.mean(final_fiberlength_array[idx])) + di['fiber_length_median'] = float( + np.median(final_fiberlength_array[idx])) + di['fiber_length_std'] = float( + np.std(final_fiberlength_array[idx])) else: di['number_of_fibers'] = 0 di['fiber_length_mean'] = 0 @@ -347,7 +376,8 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ if intersections: path, name, ext = split_filename(matrix_name) intersection_matrix_name = op.abspath(name + '_intersections') + ext - iflogger.info('Writing intersection network as %s', intersection_matrix_name) + iflogger.info('Writing intersection network as %s', + intersection_matrix_name) nx.write_gpickle(I, intersection_matrix_name) path, name, ext = split_filename(matrix_mat_name) @@ -361,15 +391,18 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ if intersections: intersect_dict = {'intersections': intersection_matrix} intersection_matrix_mat_name = op.abspath(name + '_intersections') + ext - iflogger.info('Writing intersection matrix as %s', intersection_matrix_mat_name) + iflogger.info('Writing intersection matrix as %s', + intersection_matrix_mat_name) sio.savemat(intersection_matrix_mat_name, intersect_dict) - mean_fiber_length_matrix_name = op.abspath(name + '_mean_fiber_length') + ext + mean_fiber_length_matrix_name = op.abspath( + name + '_mean_fiber_length') + ext iflogger.info('Writing matlab mean fiber length matrix as %s', mean_fiber_length_matrix_name) sio.savemat(mean_fiber_length_matrix_name, fibmean_dict) - median_fiber_length_matrix_name = op.abspath(name + '_median_fiber_length') + ext + median_fiber_length_matrix_name = op.abspath( + name + '_median_fiber_length') + ext iflogger.info('Writing matlab median fiber length matrix as %s', median_fiber_length_matrix_name) sio.savemat(median_fiber_length_matrix_name, fibmedian_dict) @@ -384,19 +417,27 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ np.save(fiberlengths_fname, final_fiberlength_array) fiberlabels_fname = op.abspath(endpoint_name + '_filtered_fiberslabel.npy') - iflogger.info('Storing all fiber labels (with orphans) as %s', fiberlabels_fname) - np.save(fiberlabels_fname, np.array(fiberlabels, dtype=np.int32),) - - fiberlabels_noorphans_fname = op.abspath(endpoint_name + '_final_fiberslabels.npy') + iflogger.info('Storing all fiber labels (with orphans) as %s', + fiberlabels_fname) + np.save( + fiberlabels_fname, + np.array(fiberlabels, dtype=np.int32), + ) + + fiberlabels_noorphans_fname = op.abspath( + endpoint_name + '_final_fiberslabels.npy') iflogger.info('Storing final fiber labels (no orphans) as %s', fiberlabels_noorphans_fname) np.save(fiberlabels_noorphans_fname, final_fiberlabels_array) iflogger.info("Filtering tractography - keeping only no orphan fibers") finalfibers_fname = op.abspath(endpoint_name + '_streamline_final.trk') - stats['endpoint_n_fib'] = save_fibers(hdr, fib, finalfibers_fname, final_fibers_idx) - stats['endpoints_percent'] = float(stats['endpoint_n_fib']) / float(stats['orig_n_fib']) * 100 - stats['intersections_percent'] = float(stats['intersections_n_fib']) / float(stats['orig_n_fib']) * 100 + stats['endpoint_n_fib'] = save_fibers(hdr, fib, finalfibers_fname, + final_fibers_idx) + stats['endpoints_percent'] = float(stats['endpoint_n_fib']) / float( + stats['orig_n_fib']) * 100 + stats['intersections_percent'] = float( + stats['intersections_n_fib']) / float(stats['orig_n_fib']) * 100 out_stats_file = op.abspath(endpoint_name + '_statistics.mat') iflogger.info('Saving matrix creation statistics as %s', out_stats_file) @@ -417,38 +458,107 @@ def save_fibers(oldhdr, oldfib, fname, indices): class CreateMatrixInputSpec(TraitedSpec): - roi_file = File(exists=True, mandatory=True, desc='Freesurfer aparc+aseg file') + roi_file = File( + exists=True, mandatory=True, desc='Freesurfer aparc+aseg file') tract_file = File(exists=True, mandatory=True, desc='Trackvis tract file') - resolution_network_file = File(exists=True, mandatory=True, desc='Parcellation files from Connectome Mapping Toolkit') - count_region_intersections = traits.Bool(False, usedefault=True, desc='Counts all of the fiber-region traversals in the connectivity matrix (requires significantly more computational time)') - out_matrix_file = File(genfile=True, desc='NetworkX graph describing the connectivity') - out_matrix_mat_file = File('cmatrix.mat', usedefault=True, desc='Matlab matrix describing the connectivity') - out_mean_fiber_length_matrix_mat_file = File(genfile=True, desc='Matlab matrix describing the mean fiber lengths between each node.') - out_median_fiber_length_matrix_mat_file = File(genfile=True, desc='Matlab matrix describing the mean fiber lengths between each node.') - out_fiber_length_std_matrix_mat_file = File(genfile=True, desc='Matlab matrix describing the deviation in fiber lengths connecting each node.') - out_intersection_matrix_mat_file = File(genfile=True, desc='Matlab connectivity matrix if all region/fiber intersections are counted.') - out_endpoint_array_name = File(genfile=True, desc='Name for the generated endpoint arrays') + resolution_network_file = File( + exists=True, + mandatory=True, + desc='Parcellation files from Connectome Mapping Toolkit') + count_region_intersections = traits.Bool( + False, + usedefault=True, + desc= + 'Counts all of the fiber-region traversals in the connectivity matrix (requires significantly more computational time)' + ) + out_matrix_file = File( + genfile=True, desc='NetworkX graph describing the connectivity') + out_matrix_mat_file = File( + 'cmatrix.mat', + usedefault=True, + desc='Matlab matrix describing the connectivity') + out_mean_fiber_length_matrix_mat_file = File( + genfile=True, + desc= + 'Matlab matrix describing the mean fiber lengths between each node.') + out_median_fiber_length_matrix_mat_file = File( + genfile=True, + desc= + 'Matlab matrix describing the mean fiber lengths between each node.') + out_fiber_length_std_matrix_mat_file = File( + genfile=True, + desc= + 'Matlab matrix describing the deviation in fiber lengths connecting each node.' + ) + out_intersection_matrix_mat_file = File( + genfile=True, + desc= + 'Matlab connectivity matrix if all region/fiber intersections are counted.' + ) + out_endpoint_array_name = File( + genfile=True, desc='Name for the generated endpoint arrays') class CreateMatrixOutputSpec(TraitedSpec): - matrix_file = File(desc='NetworkX graph describing the connectivity', exists=True) - intersection_matrix_file = File(desc='NetworkX graph describing the connectivity', exists=True) - matrix_files = OutputMultiPath(File(desc='All of the gpickled network files output by this interface', exists=True)) - matlab_matrix_files = OutputMultiPath(File(desc='All of the MATLAB .mat files output by this interface', exists=True)) - matrix_mat_file = File(desc='Matlab matrix describing the connectivity', exists=True) - intersection_matrix_mat_file = File(desc='Matlab matrix describing the mean fiber lengths between each node.', exists=True) - mean_fiber_length_matrix_mat_file = File(desc='Matlab matrix describing the mean fiber lengths between each node.', exists=True) - median_fiber_length_matrix_mat_file = File(desc='Matlab matrix describing the median fiber lengths between each node.', exists=True) - fiber_length_std_matrix_mat_file = File(desc='Matlab matrix describing the deviation in fiber lengths connecting each node.', exists=True) - endpoint_file = File(desc='Saved Numpy array with the endpoints of each fiber', exists=True) - endpoint_file_mm = File(desc='Saved Numpy array with the endpoints of each fiber (in millimeters)', exists=True) - fiber_length_file = File(desc='Saved Numpy array with the lengths of each fiber', exists=True) - fiber_label_file = File(desc='Saved Numpy array with the labels for each fiber', exists=True) - fiber_labels_noorphans = File(desc='Saved Numpy array with the labels for each non-orphan fiber', exists=True) - filtered_tractography = File(desc='TrackVis file containing only those fibers originate in one and terminate in another region', exists=True) - filtered_tractography_by_intersections = File(desc='TrackVis file containing all fibers which connect two regions', exists=True) - filtered_tractographies = OutputMultiPath(File(desc='TrackVis file containing only those fibers originate in one and terminate in another region', exists=True)) - stats_file = File(desc='Saved Matlab .mat file with the number of fibers saved at each stage', exists=True) + matrix_file = File( + desc='NetworkX graph describing the connectivity', exists=True) + intersection_matrix_file = File( + desc='NetworkX graph describing the connectivity', exists=True) + matrix_files = OutputMultiPath( + File( + desc='All of the gpickled network files output by this interface', + exists=True)) + matlab_matrix_files = OutputMultiPath( + File( + desc='All of the MATLAB .mat files output by this interface', + exists=True)) + matrix_mat_file = File( + desc='Matlab matrix describing the connectivity', exists=True) + intersection_matrix_mat_file = File( + desc= + 'Matlab matrix describing the mean fiber lengths between each node.', + exists=True) + mean_fiber_length_matrix_mat_file = File( + desc= + 'Matlab matrix describing the mean fiber lengths between each node.', + exists=True) + median_fiber_length_matrix_mat_file = File( + desc= + 'Matlab matrix describing the median fiber lengths between each node.', + exists=True) + fiber_length_std_matrix_mat_file = File( + desc= + 'Matlab matrix describing the deviation in fiber lengths connecting each node.', + exists=True) + endpoint_file = File( + desc='Saved Numpy array with the endpoints of each fiber', exists=True) + endpoint_file_mm = File( + desc= + 'Saved Numpy array with the endpoints of each fiber (in millimeters)', + exists=True) + fiber_length_file = File( + desc='Saved Numpy array with the lengths of each fiber', exists=True) + fiber_label_file = File( + desc='Saved Numpy array with the labels for each fiber', exists=True) + fiber_labels_noorphans = File( + desc='Saved Numpy array with the labels for each non-orphan fiber', + exists=True) + filtered_tractography = File( + desc= + 'TrackVis file containing only those fibers originate in one and terminate in another region', + exists=True) + filtered_tractography_by_intersections = File( + desc='TrackVis file containing all fibers which connect two regions', + exists=True) + filtered_tractographies = OutputMultiPath( + File( + desc= + 'TrackVis file containing only those fibers originate in one and terminate in another region', + exists=True)) + stats_file = File( + desc= + 'Saved Matlab .mat file with the number of fibers saved at each stage', + exists=True) class CreateMatrix(BaseInterface): @@ -482,19 +592,25 @@ def _run_interface(self, runtime): matrix_mat_file = matrix_mat_file + ext if isdefined(self.inputs.out_mean_fiber_length_matrix_mat_file): - mean_fiber_length_matrix_mat_file = op.abspath(self.inputs.out_mean_fiber_length_matrix_mat_file) + mean_fiber_length_matrix_mat_file = op.abspath( + self.inputs.out_mean_fiber_length_matrix_mat_file) else: - mean_fiber_length_matrix_name = op.abspath(self._gen_outfilename('_mean_fiber_length.mat')) + mean_fiber_length_matrix_name = op.abspath( + self._gen_outfilename('_mean_fiber_length.mat')) if isdefined(self.inputs.out_median_fiber_length_matrix_mat_file): - median_fiber_length_matrix_mat_file = op.abspath(self.inputs.out_median_fiber_length_matrix_mat_file) + median_fiber_length_matrix_mat_file = op.abspath( + self.inputs.out_median_fiber_length_matrix_mat_file) else: - median_fiber_length_matrix_name = op.abspath(self._gen_outfilename('_median_fiber_length.mat')) + median_fiber_length_matrix_name = op.abspath( + self._gen_outfilename('_median_fiber_length.mat')) if isdefined(self.inputs.out_fiber_length_std_matrix_mat_file): - fiber_length_std_matrix_mat_file = op.abspath(self.inputs.out_fiber_length_std_matrix_mat_file) + fiber_length_std_matrix_mat_file = op.abspath( + self.inputs.out_fiber_length_std_matrix_mat_file) else: - fiber_length_std_matrix_name = op.abspath(self._gen_outfilename('_fiber_length_std.mat')) + fiber_length_std_matrix_name = op.abspath( + self._gen_outfilename('_fiber_length_std.mat')) if not isdefined(self.inputs.out_endpoint_array_name): _, endpoint_name, _ = split_filename(self.inputs.tract_file) @@ -502,8 +618,9 @@ def _run_interface(self, runtime): else: endpoint_name = op.abspath(self.inputs.out_endpoint_array_name) - cmat(self.inputs.tract_file, self.inputs.roi_file, self.inputs.resolution_network_file, - matrix_file, matrix_mat_file, endpoint_name, self.inputs.count_region_intersections) + cmat(self.inputs.tract_file, self.inputs.roi_file, + self.inputs.resolution_network_file, matrix_file, matrix_mat_file, + endpoint_name, self.inputs.count_region_intersections) return runtime def _list_outputs(self): @@ -511,10 +628,12 @@ def _list_outputs(self): if isdefined(self.inputs.out_matrix_file): path, name, _ = split_filename(self.inputs.out_matrix_file) out_matrix_file = op.abspath(name + '.pck') - out_intersection_matrix_file = op.abspath(name + '_intersections.pck') + out_intersection_matrix_file = op.abspath( + name + '_intersections.pck') else: out_matrix_file = op.abspath(self._gen_outfilename('.pck')) - out_intersection_matrix_file = op.abspath(self._gen_outfilename('_intersections.pck')) + out_intersection_matrix_file = op.abspath( + self._gen_outfilename('_intersections.pck')) outputs['matrix_file'] = out_matrix_file outputs['intersection_matrix_file'] = out_intersection_matrix_file @@ -527,54 +646,89 @@ def _list_outputs(self): outputs['matrix_mat_file'] = matrix_mat_file if isdefined(self.inputs.out_mean_fiber_length_matrix_mat_file): - outputs['mean_fiber_length_matrix_mat_file'] = op.abspath(self.inputs.out_mean_fiber_length_matrix_mat_file) + outputs['mean_fiber_length_matrix_mat_file'] = op.abspath( + self.inputs.out_mean_fiber_length_matrix_mat_file) else: - outputs['mean_fiber_length_matrix_mat_file'] = op.abspath(self._gen_outfilename('_mean_fiber_length.mat')) + outputs['mean_fiber_length_matrix_mat_file'] = op.abspath( + self._gen_outfilename('_mean_fiber_length.mat')) if isdefined(self.inputs.out_median_fiber_length_matrix_mat_file): - outputs['median_fiber_length_matrix_mat_file'] = op.abspath(self.inputs.out_median_fiber_length_matrix_mat_file) + outputs['median_fiber_length_matrix_mat_file'] = op.abspath( + self.inputs.out_median_fiber_length_matrix_mat_file) else: - outputs['median_fiber_length_matrix_mat_file'] = op.abspath(self._gen_outfilename('_median_fiber_length.mat')) + outputs['median_fiber_length_matrix_mat_file'] = op.abspath( + self._gen_outfilename('_median_fiber_length.mat')) if isdefined(self.inputs.out_fiber_length_std_matrix_mat_file): - outputs['fiber_length_std_matrix_mat_file'] = op.abspath(self.inputs.out_fiber_length_std_matrix_mat_file) + outputs['fiber_length_std_matrix_mat_file'] = op.abspath( + self.inputs.out_fiber_length_std_matrix_mat_file) else: - outputs['fiber_length_std_matrix_mat_file'] = op.abspath(self._gen_outfilename('_fiber_length_std.mat')) + outputs['fiber_length_std_matrix_mat_file'] = op.abspath( + self._gen_outfilename('_fiber_length_std.mat')) if isdefined(self.inputs.out_intersection_matrix_mat_file): - outputs['intersection_matrix_mat_file'] = op.abspath(self.inputs.out_intersection_matrix_mat_file) + outputs['intersection_matrix_mat_file'] = op.abspath( + self.inputs.out_intersection_matrix_mat_file) else: - outputs['intersection_matrix_mat_file'] = op.abspath(self._gen_outfilename('_intersections.mat')) + outputs['intersection_matrix_mat_file'] = op.abspath( + self._gen_outfilename('_intersections.mat')) if isdefined(self.inputs.out_endpoint_array_name): endpoint_name = self.inputs.out_endpoint_array_name - outputs['endpoint_file'] = op.abspath(self.inputs.out_endpoint_array_name + '_endpoints.npy') - outputs['endpoint_file_mm'] = op.abspath(self.inputs.out_endpoint_array_name + '_endpointsmm.npy') - outputs['fiber_length_file'] = op.abspath(self.inputs.out_endpoint_array_name + '_final_fiberslength.npy') - outputs['fiber_label_file'] = op.abspath(self.inputs.out_endpoint_array_name + '_filtered_fiberslabel.npy') - outputs['fiber_labels_noorphans'] = op.abspath(self.inputs.out_endpoint_array_name + '_final_fiberslabels.npy') + outputs['endpoint_file'] = op.abspath( + self.inputs.out_endpoint_array_name + '_endpoints.npy') + outputs['endpoint_file_mm'] = op.abspath( + self.inputs.out_endpoint_array_name + '_endpointsmm.npy') + outputs['fiber_length_file'] = op.abspath( + self.inputs.out_endpoint_array_name + '_final_fiberslength.npy' + ) + outputs['fiber_label_file'] = op.abspath( + self.inputs.out_endpoint_array_name + + '_filtered_fiberslabel.npy') + outputs['fiber_labels_noorphans'] = op.abspath( + self.inputs.out_endpoint_array_name + '_final_fiberslabels.npy' + ) else: _, endpoint_name, _ = split_filename(self.inputs.tract_file) - outputs['endpoint_file'] = op.abspath(endpoint_name + '_endpoints.npy') - outputs['endpoint_file_mm'] = op.abspath(endpoint_name + '_endpointsmm.npy') - outputs['fiber_length_file'] = op.abspath(endpoint_name + '_final_fiberslength.npy') - outputs['fiber_label_file'] = op.abspath(endpoint_name + '_filtered_fiberslabel.npy') - outputs['fiber_labels_noorphans'] = op.abspath(endpoint_name + '_final_fiberslabels.npy') + outputs['endpoint_file'] = op.abspath( + endpoint_name + '_endpoints.npy') + outputs['endpoint_file_mm'] = op.abspath( + endpoint_name + '_endpointsmm.npy') + outputs['fiber_length_file'] = op.abspath( + endpoint_name + '_final_fiberslength.npy') + outputs['fiber_label_file'] = op.abspath( + endpoint_name + '_filtered_fiberslabel.npy') + outputs['fiber_labels_noorphans'] = op.abspath( + endpoint_name + '_final_fiberslabels.npy') if self.inputs.count_region_intersections: - outputs['matrix_files'] = [out_matrix_file, out_intersection_matrix_file] - outputs['matlab_matrix_files'] = [outputs['matrix_mat_file'], - outputs['mean_fiber_length_matrix_mat_file'], outputs['median_fiber_length_matrix_mat_file'], - outputs['fiber_length_std_matrix_mat_file'], outputs['intersection_matrix_mat_file']] + outputs['matrix_files'] = [ + out_matrix_file, out_intersection_matrix_file + ] + outputs['matlab_matrix_files'] = [ + outputs['matrix_mat_file'], + outputs['mean_fiber_length_matrix_mat_file'], + outputs['median_fiber_length_matrix_mat_file'], + outputs['fiber_length_std_matrix_mat_file'], + outputs['intersection_matrix_mat_file'] + ] else: outputs['matrix_files'] = [out_matrix_file] - outputs['matlab_matrix_files'] = [outputs['matrix_mat_file'], - outputs['mean_fiber_length_matrix_mat_file'], outputs['median_fiber_length_matrix_mat_file'], - outputs['fiber_length_std_matrix_mat_file']] - - outputs['filtered_tractography'] = op.abspath(endpoint_name + '_streamline_final.trk') - outputs['filtered_tractography_by_intersections'] = op.abspath(endpoint_name + '_intersections_streamline_final.trk') - outputs['filtered_tractographies'] = [outputs['filtered_tractography'], outputs['filtered_tractography_by_intersections']] + outputs['matlab_matrix_files'] = [ + outputs['matrix_mat_file'], + outputs['mean_fiber_length_matrix_mat_file'], + outputs['median_fiber_length_matrix_mat_file'], + outputs['fiber_length_std_matrix_mat_file'] + ] + + outputs['filtered_tractography'] = op.abspath( + endpoint_name + '_streamline_final.trk') + outputs['filtered_tractography_by_intersections'] = op.abspath( + endpoint_name + '_intersections_streamline_final.trk') + outputs['filtered_tractographies'] = [ + outputs['filtered_tractography'], + outputs['filtered_tractography_by_intersections'] + ] outputs['stats_file'] = op.abspath(endpoint_name + '_statistics.mat') return outputs @@ -589,12 +743,23 @@ def _gen_outfilename(self, ext): class ROIGenInputSpec(BaseInterfaceInputSpec): - aparc_aseg_file = File(exists=True, mandatory=True, desc='Freesurfer aparc+aseg file') - LUT_file = File(exists=True, xor=['use_freesurfer_LUT'], desc='Custom lookup table (cf. FreeSurferColorLUT.txt)') - use_freesurfer_LUT = traits.Bool(xor=['LUT_file'], desc='Boolean value; Set to True to use default Freesurfer LUT, False for custom LUT') - freesurfer_dir = Directory(requires=['use_freesurfer_LUT'], desc='Freesurfer main directory') - out_roi_file = File(genfile=True, desc='Region of Interest file for connectivity mapping') - out_dict_file = File(genfile=True, desc='Label dictionary saved in Pickle format') + aparc_aseg_file = File( + exists=True, mandatory=True, desc='Freesurfer aparc+aseg file') + LUT_file = File( + exists=True, + xor=['use_freesurfer_LUT'], + desc='Custom lookup table (cf. FreeSurferColorLUT.txt)') + use_freesurfer_LUT = traits.Bool( + xor=['LUT_file'], + desc= + 'Boolean value; Set to True to use default Freesurfer LUT, False for custom LUT' + ) + freesurfer_dir = Directory( + requires=['use_freesurfer_LUT'], desc='Freesurfer main directory') + out_roi_file = File( + genfile=True, desc='Region of Interest file for connectivity mapping') + out_dict_file = File( + genfile=True, desc='Label dictionary saved in Pickle format') class ROIGenOutputSpec(TraitedSpec): @@ -642,7 +807,8 @@ def _run_interface(self, runtime): self.LUT_file = self.inputs.freesurfer_dir + '/FreeSurferColorLUT.txt' iflogger.info('Using Freesurfer LUT: %s', self.LUT_file) prefix = 'fsLUT' - elif not self.inputs.use_freesurfer_LUT and isdefined(self.inputs.LUT_file): + elif not self.inputs.use_freesurfer_LUT and isdefined( + self.inputs.LUT_file): self.LUT_file = op.abspath(self.inputs.LUT_file) lutpath, lutname, lutext = split_filename(self.LUT_file) iflogger.info('Using Custom LUT file: %s', lutname + lutext) @@ -663,32 +829,61 @@ def _run_interface(self, runtime): if write_dict: iflogger.info('Lookup table: %s', op.abspath(self.LUT_file)) - LUTlabelsRGBA = np.loadtxt(self.LUT_file, skiprows=4, usecols=[0, 1, 2, 3, 4, 5], comments='#', - dtype={'names': ('index', 'label', 'R', 'G', 'B', 'A'), 'formats': ('int', '|S30', 'int', 'int', 'int', 'int')}) + LUTlabelsRGBA = np.loadtxt( + self.LUT_file, + skiprows=4, + usecols=[0, 1, 2, 3, 4, 5], + comments='#', + dtype={ + 'names': ('index', 'label', 'R', 'G', 'B', 'A'), + 'formats': ('int', '|S30', 'int', 'int', 'int', 'int') + }) numLUTLabels = np.size(LUTlabelsRGBA) if numLUTLabels < numDataLabels: - iflogger.error('LUT file provided does not contain all of the regions in the image') + iflogger.error( + 'LUT file provided does not contain all of the regions in the image' + ) iflogger.error('Removing unmapped regions') iflogger.info('Number of labels in LUT: %s', numLUTLabels) LUTlabelDict = {} - """ Create dictionary for input LUT table""" for labels in range(0, numLUTLabels): - LUTlabelDict[LUTlabelsRGBA[labels][0]] = [LUTlabelsRGBA[labels][1], LUTlabelsRGBA[labels][2], LUTlabelsRGBA[labels][3], LUTlabelsRGBA[labels][4], LUTlabelsRGBA[labels][5]] + LUTlabelDict[LUTlabelsRGBA[labels][0]] = [ + LUTlabelsRGBA[labels][1], LUTlabelsRGBA[labels][2], + LUTlabelsRGBA[labels][3], LUTlabelsRGBA[labels][4], + LUTlabelsRGBA[labels][5] + ] iflogger.info('Printing LUT label dictionary') iflogger.info(LUTlabelDict) mapDict = {} - MAPPING = [[1, 2012], [2, 2019], [3, 2032], [4, 2014], [5, 2020], [6, 2018], [7, 2027], [8, 2028], [9, 2003], [10, 2024], [11, 2017], [12, 2026], - [13, 2002], [14, 2023], [15, 2010], [16, 2022], [17, 2031], [18, 2029], [19, 2008], [20, 2025], [21, 2005], [22, 2021], [23, 2011], - [24, 2013], [25, 2007], [26, 2016], [27, 2006], [28, 2033], [29, 2009], [30, 2015], [31, 2001], [32, 2030], [33, 2034], [34, 2035], - [35, 49], [36, 50], [37, 51], [38, 52], [39, 58], [40, 53], [41, 54], [42, 1012], [43, 1019], [44, 1032], [45, 1014], [46, 1020], [47, 1018], - [48, 1027], [49, 1028], [50, 1003], [51, 1024], [52, 1017], [53, 1026], [54, 1002], [55, 1023], [56, 1010], [57, 1022], [58, 1031], - [59, 1029], [60, 1008], [61, 1025], [62, 1005], [63, 1021], [64, 1011], [65, 1013], [66, 1007], [67, 1016], [68, 1006], [69, 1033], - [70, 1009], [71, 1015], [72, 1001], [73, 1030], [74, 1034], [75, 1035], [76, 10], [77, 11], [78, 12], [79, 13], [80, 26], [81, 17], - [82, 18], [83, 16]] - + MAPPING = [[1, 2012], [2, 2019], [3, 2032], [4, 2014], [5, 2020], [ + 6, 2018 + ], [7, 2027], [8, 2028], [9, 2003], [10, 2024], [11, 2017], [12, 2026], + [13, 2002], [14, 2023], [15, 2010], [16, 2022], [17, 2031], + [18, 2029], [19, 2008], [20, 2025], [21, 2005], [22, 2021], + [23, 2011], [24, 2013], [25, 2007], [26, 2016], [27, 2006], + [28, 2033], [29, 2009], [30, 2015], [31, 2001], [32, 2030], + [33, 2034], [34, 2035], [35, 49], [36, 50], [37, 51], [ + 38, 52 + ], [39, 58], [40, 53], [41, 54], [42, 1012], [43, 1019], [ + 44, 1032 + ], [45, 1014], [46, 1020], [47, 1018], [48, 1027], [ + 49, 1028 + ], [50, 1003], [51, 1024], [52, 1017], [53, 1026], [ + 54, 1002 + ], [55, 1023], [56, 1010], [57, 1022], [58, 1031], [ + 59, 1029 + ], [60, 1008], [61, 1025], [62, 1005], [63, 1021], [ + 64, 1011 + ], [65, 1013], [66, 1007], [67, 1016], [68, 1006], [ + 69, 1033 + ], [70, 1009], [71, 1015], [72, 1001], [73, 1030], [ + 74, 1034 + ], [75, 1035], [76, 10], [77, 11], [78, 12], [79, 13], [ + 80, 26 + ], [81, 17], [82, 18], [83, 16]] """ Create empty grey matter mask, Populate with only those regions defined in the mapping.""" niiGM = np.zeros(niiAPARCdata.shape, dtype=np.uint) for ma in MAPPING: @@ -712,7 +907,10 @@ def _run_interface(self, runtime): del GMlabelDict GMlabelDict = {} GMlabelDict['labels'] = LUTlabelDict[label][0] - GMlabelDict['colors'] = [LUTlabelDict[label][1], LUTlabelDict[label][2], LUTlabelDict[label][3]] + GMlabelDict['colors'] = [ + LUTlabelDict[label][1], LUTlabelDict[label][2], + LUTlabelDict[label][3] + ] GMlabelDict['a'] = LUTlabelDict[label][4] labelDict[label] = GMlabelDict @@ -722,7 +920,8 @@ def _run_interface(self, runtime): nb.save(roi_image, roi_file) if write_dict: - iflogger.info('Saving Dictionary File to %s in Pickle format', dict_file) + iflogger.info('Saving Dictionary File to %s in Pickle format', + dict_file) with open(dict_file, 'w') as f: pickle.dump(labelDict, f) return runtime @@ -743,7 +942,8 @@ def _gen_outfilename(self, ext): _, name, _ = split_filename(self.inputs.aparc_aseg_file) if self.inputs.use_freesurfer_LUT: prefix = 'fsLUT' - elif not self.inputs.use_freesurfer_LUT and isdefined(self.inputs.LUT_file): + elif not self.inputs.use_freesurfer_LUT and isdefined( + self.inputs.LUT_file): lutpath, lutname, lutext = split_filename(self.inputs.LUT_file) prefix = lutname else: @@ -756,19 +956,28 @@ def create_nodes(roi_file, resolution_network_file, out_filename): gp = nx.read_graphml(resolution_network_file) roi_image = nb.load(roi_file, mmap=NUMPY_MMAP) roiData = roi_image.get_data() - nROIs = len(gp.nodes()) for u, d in gp.nodes(data=True): G.add_node(int(u), **d) - xyz = tuple(np.mean(np.where(np.flipud(roiData) == int(d["dn_correspondence_id"])), axis=1)) + xyz = tuple( + np.mean( + np.where(np.flipud(roiData) == int(d["dn_correspondence_id"])), + axis=1)) G.nodes[int(u)]['dn_position'] = tuple([xyz[0], xyz[2], -xyz[1]]) nx.write_gpickle(G, out_filename) return out_filename class CreateNodesInputSpec(BaseInterfaceInputSpec): - roi_file = File(exists=True, mandatory=True, desc='Region of interest file') - resolution_network_file = File(exists=True, mandatory=True, desc='Parcellation file from Connectome Mapping Toolkit') - out_filename = File('nodenetwork.pck', usedefault=True, desc='Output gpickled network with the nodes defined.') + roi_file = File( + exists=True, mandatory=True, desc='Region of interest file') + resolution_network_file = File( + exists=True, + mandatory=True, + desc='Parcellation file from Connectome Mapping Toolkit') + out_filename = File( + 'nodenetwork.pck', + usedefault=True, + desc='Output gpickled network with the nodes defined.') class CreateNodesOutputSpec(TraitedSpec): @@ -794,8 +1003,10 @@ class CreateNodes(BaseInterface): def _run_interface(self, runtime): iflogger.info('Creating nodes...') - create_nodes(self.inputs.roi_file, self.inputs.resolution_network_file, self.inputs.out_filename) - iflogger.info('Saving node network to %s', op.abspath(self.inputs.out_filename)) + create_nodes(self.inputs.roi_file, self.inputs.resolution_network_file, + self.inputs.out_filename) + iflogger.info('Saving node network to %s', + op.abspath(self.inputs.out_filename)) return runtime def _list_outputs(self): diff --git a/nipype/interfaces/cmtk/convert.py b/nipype/interfaces/cmtk/convert.py index 7cc9af1000..fc2dd98f28 100644 --- a/nipype/interfaces/cmtk/convert.py +++ b/nipype/interfaces/cmtk/convert.py @@ -7,7 +7,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import os.path as op @@ -17,8 +18,8 @@ from ...utils.misc import package_check from ...utils.filemanip import split_filename -from ..base import (BaseInterface, BaseInterfaceInputSpec, traits, - File, TraitedSpec, InputMultiPath, isdefined) +from ..base import (BaseInterface, BaseInterfaceInputSpec, traits, File, + TraitedSpec, InputMultiPath, isdefined) have_cfflib = True try: @@ -30,17 +31,27 @@ class CFFConverterInputSpec(BaseInterfaceInputSpec): - graphml_networks = InputMultiPath(File(exists=True), desc='list of graphML networks') - gpickled_networks = InputMultiPath(File(exists=True), desc='list of gpickled Networkx graphs') - - gifti_surfaces = InputMultiPath(File(exists=True), desc='list of GIFTI surfaces') - gifti_labels = InputMultiPath(File(exists=True), desc='list of GIFTI labels') - nifti_volumes = InputMultiPath(File(exists=True), desc='list of NIFTI volumes') - tract_files = InputMultiPath(File(exists=True), desc='list of Trackvis fiber files') - - timeseries_files = InputMultiPath(File(exists=True), desc='list of HDF5 timeseries files') - script_files = InputMultiPath(File(exists=True), desc='list of script files to include') - data_files = InputMultiPath(File(exists=True), desc='list of external data files (i.e. Numpy, HD5, XML) ') + graphml_networks = InputMultiPath( + File(exists=True), desc='list of graphML networks') + gpickled_networks = InputMultiPath( + File(exists=True), desc='list of gpickled Networkx graphs') + + gifti_surfaces = InputMultiPath( + File(exists=True), desc='list of GIFTI surfaces') + gifti_labels = InputMultiPath( + File(exists=True), desc='list of GIFTI labels') + nifti_volumes = InputMultiPath( + File(exists=True), desc='list of NIFTI volumes') + tract_files = InputMultiPath( + File(exists=True), desc='list of Trackvis fiber files') + + timeseries_files = InputMultiPath( + File(exists=True), desc='list of HDF5 timeseries files') + script_files = InputMultiPath( + File(exists=True), desc='list of script files to include') + data_files = InputMultiPath( + File(exists=True), + desc='list of external data files (i.e. Numpy, HD5, XML) ') title = traits.Str(desc='Connectome Title') creator = traits.Str(desc='Creator') @@ -51,9 +62,13 @@ class CFFConverterInputSpec(BaseInterfaceInputSpec): references = traits.Str(desc='References') relation = traits.Str(desc='Relation') species = traits.Str('Homo sapiens', desc='Species', usedefault=True) - description = traits.Str('Created with the Nipype CFF converter', desc='Description', usedefault=True) + description = traits.Str( + 'Created with the Nipype CFF converter', + desc='Description', + usedefault=True) - out_file = File('connectome.cff', usedefault=True, desc='Output connectome file') + out_file = File( + 'connectome.cff', usedefault=True, desc='Output connectome file') class CFFConverterOutputSpec(TraitedSpec): @@ -150,7 +165,8 @@ def _run_interface(self, runtime): if isdefined(self.inputs.gifti_surfaces): for surf in self.inputs.gifti_surfaces: _, surf_name, _ = split_filename(surf) - csurf = cf.CSurface.create_from_gifti("Surface %d - %s" % (count, surf_name), surf) + csurf = cf.CSurface.create_from_gifti("Surface %d - %s" % + (count, surf_name), surf) csurf.fileformat = 'Gifti' csurf.dtype = 'Surfaceset' a.add_connectome_surface(csurf) @@ -160,7 +176,8 @@ def _run_interface(self, runtime): if isdefined(self.inputs.gifti_labels): for label in self.inputs.gifti_labels: _, label_name, _ = split_filename(label) - csurf = cf.CSurface.create_from_gifti("Surface Label %d - %s" % (count, label_name), label) + csurf = cf.CSurface.create_from_gifti( + "Surface Label %d - %s" % (count, label_name), label) csurf.fileformat = 'Gifti' csurf.dtype = 'Labels' a.add_connectome_surface(csurf) @@ -208,12 +225,19 @@ def _list_outputs(self): class MergeCNetworksInputSpec(BaseInterfaceInputSpec): - in_files = InputMultiPath(File(exists=True), mandatory=True, desc='List of CFF files to extract networks from') - out_file = File('merged_network_connectome.cff', usedefault=True, desc='Output CFF file with all the networks added') + in_files = InputMultiPath( + File(exists=True), + mandatory=True, + desc='List of CFF files to extract networks from') + out_file = File( + 'merged_network_connectome.cff', + usedefault=True, + desc='Output CFF file with all the networks added') class MergeCNetworksOutputSpec(TraitedSpec): - connectome_file = File(exists=True, desc='Output CFF file with all the networks added') + connectome_file = File( + exists=True, desc='Output CFF file with all the networks added') class MergeCNetworks(BaseInterface): @@ -247,7 +271,8 @@ def _run_interface(self, runtime): extracted_networks.append(ne) # Add networks to new connectome - newcon = cf.connectome(title='All CNetworks', connectome_network=extracted_networks) + newcon = cf.connectome( + title='All CNetworks', connectome_network=extracted_networks) # Setting additional metadata metadata = newcon.get_connectome_meta() metadata.set_creator('My Name') diff --git a/nipype/interfaces/cmtk/nbs.py b/nipype/interfaces/cmtk/nbs.py index 7410227565..954b4d53df 100644 --- a/nipype/interfaces/cmtk/nbs.py +++ b/nipype/interfaces/cmtk/nbs.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op @@ -10,9 +11,8 @@ from ... import logging from ...utils.misc import package_check -from ..base import (BaseInterface, BaseInterfaceInputSpec, traits, - File, TraitedSpec, InputMultiPath, - OutputMultiPath, isdefined) +from ..base import (BaseInterface, BaseInterfaceInputSpec, traits, File, + TraitedSpec, InputMultiPath, OutputMultiPath, isdefined) iflogger = logging.getLogger('interface') have_cv = True @@ -33,30 +33,63 @@ def ntwks_to_matrices(in_files, edge_key): graph = nx.read_gpickle(name) for u, v, d in graph.edges(data=True): try: - graph[u][v]['weight'] = d[edge_key] # Setting the edge requested edge value as weight value + graph[u][v]['weight'] = d[ + edge_key] # Setting the edge requested edge value as weight value except: - raise KeyError("the graph edges do not have {} attribute".format(edge_key)) + raise KeyError( + "the graph edges do not have {} attribute".format( + edge_key)) matrix[:, :, idx] = nx.to_numpy_matrix(graph) # Retrieve the matrix return matrix class NetworkBasedStatisticInputSpec(BaseInterfaceInputSpec): - in_group1 = InputMultiPath(File(exists=True), mandatory=True, desc='Networks for the first group of subjects') - in_group2 = InputMultiPath(File(exists=True), mandatory=True, desc='Networks for the second group of subjects') - node_position_network = File(desc='An optional network used to position the nodes for the output networks') - number_of_permutations = traits.Int(1000, usedefault=True, desc='Number of permutations to perform') + in_group1 = InputMultiPath( + File(exists=True), + mandatory=True, + desc='Networks for the first group of subjects') + in_group2 = InputMultiPath( + File(exists=True), + mandatory=True, + desc='Networks for the second group of subjects') + node_position_network = File( + desc= + 'An optional network used to position the nodes for the output networks' + ) + number_of_permutations = traits.Int( + 1000, usedefault=True, desc='Number of permutations to perform') threshold = traits.Float(3, usedefault=True, desc='T-statistic threshold') - t_tail = traits.Enum('left', 'right', 'both', usedefault=True, desc='Can be one of "left", "right", or "both"') - edge_key = traits.Str('number_of_fibers', usedefault=True, desc='Usually "number_of_fibers, "fiber_length_mean", "fiber_length_std" for matrices made with CMTK' - 'Sometimes "weight" or "value" for functional networks.') - out_nbs_network = File(desc='Output network with edges identified by the NBS') - out_nbs_pval_network = File(desc='Output network with p-values to weight the edges identified by the NBS') + t_tail = traits.Enum( + 'left', + 'right', + 'both', + usedefault=True, + desc='Can be one of "left", "right", or "both"') + edge_key = traits.Str( + 'number_of_fibers', + usedefault=True, + desc= + 'Usually "number_of_fibers, "fiber_length_mean", "fiber_length_std" for matrices made with CMTK' + 'Sometimes "weight" or "value" for functional networks.') + out_nbs_network = File( + desc='Output network with edges identified by the NBS') + out_nbs_pval_network = File( + desc= + 'Output network with p-values to weight the edges identified by the NBS' + ) class NetworkBasedStatisticOutputSpec(TraitedSpec): - nbs_network = File(exists=True, desc='Output network with edges identified by the NBS') - nbs_pval_network = File(exists=True, desc='Output network with p-values to weight the edges identified by the NBS') - network_files = OutputMultiPath(File(exists=True), desc='Output network with edges identified by the NBS') + nbs_network = File( + exists=True, desc='Output network with edges identified by the NBS') + nbs_pval_network = File( + exists=True, + desc= + 'Output network with p-values to weight the edges identified by the NBS' + ) + network_files = OutputMultiPath( + File(exists=True), + desc='Output network with edges identified by the NBS') class NetworkBasedStatistic(BaseInterface): @@ -88,7 +121,8 @@ def _run_interface(self, runtime): K = self.inputs.number_of_permutations TAIL = self.inputs.t_tail edge_key = self.inputs.edge_key - details = edge_key + '-thresh-' + str(THRESH) + '-k-' + str(K) + '-tail-' + TAIL + '.pck' + details = edge_key + '-thresh-' + str(THRESH) + '-k-' + str( + K) + '-tail-' + TAIL + '.pck' # Fill in the data from the networks X = ntwks_to_matrices(self.inputs.in_group1, edge_key) @@ -143,7 +177,8 @@ def _list_outputs(self): K = self.inputs.number_of_permutations TAIL = self.inputs.t_tail edge_key = self.inputs.edge_key - details = edge_key + '-thresh-' + str(THRESH) + '-k-' + str(K) + '-tail-' + TAIL + '.pck' + details = edge_key + '-thresh-' + str(THRESH) + '-k-' + str( + K) + '-tail-' + TAIL + '.pck' path = op.abspath('NBS_Result_' + details) pval_path = op.abspath('NBS_P_vals_' + details) diff --git a/nipype/interfaces/cmtk/nx.py b/nipype/interfaces/cmtk/nx.py index ec3c01336c..1072188cbc 100644 --- a/nipype/interfaces/cmtk/nx.py +++ b/nipype/interfaces/cmtk/nx.py @@ -9,7 +9,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, open, range import os.path as op @@ -68,18 +69,23 @@ def fix_keys_for_gexf(orig): if 'dn_fsname' in orig.nodes[node]: newnodedata['label'] = orig.nodes[node]['dn_fsname'] ntwk.add_node(str(node), **newnodedata) - if 'dn_position' in ntwk.nodes[str(node)] and 'dn_position' in newnodedata: - ntwk.nodes[str(node)]['dn_position'] = str(newnodedata['dn_position']) + if 'dn_position' in ntwk.nodes[str( + node)] and 'dn_position' in newnodedata: + ntwk.nodes[str(node)]['dn_position'] = str( + newnodedata['dn_position']) for edge in edges: data = {} data = orig.edge[edge[0]][edge[1]] ntwk.add_edge(str(edge[0]), str(edge[1]), **data) if 'fiber_length_mean' in ntwk.edge[str(edge[0])][str(edge[1])]: - ntwk.edge[str(edge[0])][str(edge[1])]['fiber_length_mean'] = str(data['fiber_length_mean']) + ntwk.edge[str(edge[0])][str(edge[1])]['fiber_length_mean'] = str( + data['fiber_length_mean']) if 'fiber_length_std' in ntwk.edge[str(edge[0])][str(edge[1])]: - ntwk.edge[str(edge[0])][str(edge[1])]['fiber_length_std'] = str(data['fiber_length_std']) + ntwk.edge[str(edge[0])][str(edge[1])]['fiber_length_std'] = str( + data['fiber_length_std']) if 'number_of_fibers' in ntwk.edge[str(edge[0])][str(edge[1])]: - ntwk.edge[str(edge[0])][str(edge[1])]['number_of_fibers'] = str(data['number_of_fibers']) + ntwk.edge[str(edge[0])][str(edge[1])]['number_of_fibers'] = str( + data['number_of_fibers']) if 'value' in ntwk.edge[str(edge[0])][str(edge[1])]: ntwk.edge[str(edge[0])][str(edge[1])]['value'] = str(data['value']) return ntwk @@ -121,7 +127,8 @@ def average_networks(in_files, ntwk_res_file, group_id): # Sums all the relevant variables for index, subject in enumerate(in_files): tmp = nx.read_gpickle(subject) - iflogger.info('File %s has %i edges', subject, tmp.number_of_edges()) + iflogger.info('File %s has %i edges', subject, + tmp.number_of_edges()) edges = list(tmp.edges()) for edge in edges: data = {} @@ -165,7 +172,8 @@ def average_networks(in_files, ntwk_res_file, group_id): data[key] = data[key] / len(in_files) ntwk.edge[edge[0]][edge[1]] = data avg_ntwk.add_edge(edge[0], edge[1], **data) - edge_dict['count'][edge[0] - 1][edge[1] - 1] = ntwk.edge[edge[0]][edge[1]]['count'] + edge_dict['count'][edge[0] - 1][edge[1] - 1] = ntwk.edge[edge[0]][ + edge[1]]['count'] iflogger.info('After thresholding, the average network has %i edges', avg_ntwk.number_of_edges()) @@ -175,7 +183,8 @@ def average_networks(in_files, ntwk_res_file, group_id): data = avg_ntwk.edge[edge[0]][edge[1]] for key in list(data.keys()): if not key == 'count': - edge_dict[key] = np.zeros((avg_ntwk.number_of_nodes(), avg_ntwk.number_of_nodes())) + edge_dict[key] = np.zeros((avg_ntwk.number_of_nodes(), + avg_ntwk.number_of_nodes())) edge_dict[key][edge[0] - 1][edge[1] - 1] = data[key] for key in list(edge_dict.keys()): @@ -207,15 +216,19 @@ def compute_node_measures(ntwk, calculate_cliques=False): iflogger.info('...Computing degree...') measures['degree'] = np.array(list(ntwk.degree().values())) iflogger.info('...Computing load centrality...') - measures['load_centrality'] = np.array(list(nx.load_centrality(ntwk).values())) + measures['load_centrality'] = np.array( + list(nx.load_centrality(ntwk).values())) iflogger.info('...Computing betweenness centrality...') - measures['betweenness_centrality'] = np.array(list(nx.betweenness_centrality(ntwk).values())) + measures['betweenness_centrality'] = np.array( + list(nx.betweenness_centrality(ntwk).values())) iflogger.info('...Computing degree centrality...') - measures['degree_centrality'] = np.array(list(nx.degree_centrality(ntwk).values())) + measures['degree_centrality'] = np.array( + list(nx.degree_centrality(ntwk).values())) iflogger.info('...Computing closeness centrality...') - measures['closeness_centrality'] = np.array(list(nx.closeness_centrality(ntwk).values())) -# iflogger.info('...Computing eigenvector centrality...') -# measures['eigenvector_centrality'] = np.array(nx.eigenvector_centrality(ntwk, max_iter=100000).values()) + measures['closeness_centrality'] = np.array( + list(nx.closeness_centrality(ntwk).values())) + # iflogger.info('...Computing eigenvector centrality...') + # measures['eigenvector_centrality'] = np.array(nx.eigenvector_centrality(ntwk, max_iter=100000).values()) iflogger.info('...Computing triangles...') measures['triangles'] = np.array(list(nx.triangles(ntwk).values())) iflogger.info('...Computing clustering...') @@ -231,9 +244,11 @@ def compute_node_measures(ntwk, calculate_cliques=False): measures['isolates'] = binarized if calculate_cliques: iflogger.info('...Calculating node clique number') - measures['node_clique_number'] = np.array(list(nx.node_clique_number(ntwk).values())) + measures['node_clique_number'] = np.array( + list(nx.node_clique_number(ntwk).values())) iflogger.info('...Computing number of cliques for each node...') - measures['number_of_cliques'] = np.array(list(nx.number_of_cliques(ntwk).values())) + measures['number_of_cliques'] = np.array( + list(nx.number_of_cliques(ntwk).values())) return measures @@ -263,7 +278,8 @@ def compute_dict_measures(ntwk): return measures -def compute_singlevalued_measures(ntwk, weighted=True, calculate_cliques=False): +def compute_singlevalued_measures(ntwk, weighted=True, + calculate_cliques=False): """ Returns a single value per network """ @@ -273,16 +289,20 @@ def compute_singlevalued_measures(ntwk, weighted=True, calculate_cliques=False): try: measures['degree_pearsonr'] = nx.degree_pearsonr(ntwk) except AttributeError: # For NetworkX 1.6 - measures['degree_pearsonr'] = nx.degree_pearson_correlation_coefficient(ntwk) + measures[ + 'degree_pearsonr'] = nx.degree_pearson_correlation_coefficient( + ntwk) iflogger.info('...Computing degree assortativity...') try: measures['degree_assortativity'] = nx.degree_assortativity(ntwk) except AttributeError: - measures['degree_assortativity'] = nx.degree_assortativity_coefficient(ntwk) + measures['degree_assortativity'] = nx.degree_assortativity_coefficient( + ntwk) iflogger.info('...Computing transitivity...') measures['transitivity'] = nx.transitivity(ntwk) iflogger.info('...Computing number of connected_components...') - measures['number_connected_components'] = nx.number_connected_components(ntwk) + measures['number_connected_components'] = nx.number_connected_components( + ntwk) iflogger.info('...Computing graph density...') measures['graph_density'] = nx.density(ntwk) iflogger.info('...Recording number of edges...') @@ -293,13 +313,18 @@ def compute_singlevalued_measures(ntwk, weighted=True, calculate_cliques=False): measures['average_clustering'] = nx.average_clustering(ntwk) if nx.is_connected(ntwk): iflogger.info('...Calculating average shortest path length...') - measures['average_shortest_path_length'] = nx.average_shortest_path_length(ntwk, weighted) + measures[ + 'average_shortest_path_length'] = nx.average_shortest_path_length( + ntwk, weighted) else: iflogger.info('...Calculating average shortest path length...') - measures['average_shortest_path_length'] = nx.average_shortest_path_length(nx.connected_component_subgraphs(ntwk)[0], weighted) + measures[ + 'average_shortest_path_length'] = nx.average_shortest_path_length( + nx.connected_component_subgraphs(ntwk)[0], weighted) if calculate_cliques: iflogger.info('...Computing graph clique number...') - measures['graph_clique_number'] = nx.graph_clique_number(ntwk) # out of memory error + measures['graph_clique_number'] = nx.graph_clique_number( + ntwk) # out of memory error return measures @@ -343,31 +368,78 @@ def add_edge_data(edge_array, ntwk, above=0, below=0): class NetworkXMetricsInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True, desc='Input network') - out_k_core = File('k_core', usedefault=True, desc='Computed k-core network stored as a NetworkX pickle.') - out_k_shell = File('k_shell', usedefault=True, desc='Computed k-shell network stored as a NetworkX pickle.') - out_k_crust = File('k_crust', usedefault=True, desc='Computed k-crust network stored as a NetworkX pickle.') - treat_as_weighted_graph = traits.Bool(True, usedefault=True, desc='Some network metrics can be calculated while considering only a binarized version of the graph') - compute_clique_related_measures = traits.Bool(False, usedefault=True, desc='Computing clique-related measures (e.g. node clique number) can be very time consuming') - out_global_metrics_matlab = File(genfile=True, desc='Output node metrics in MATLAB .mat format') - out_node_metrics_matlab = File(genfile=True, desc='Output node metrics in MATLAB .mat format') - out_edge_metrics_matlab = File(genfile=True, desc='Output edge metrics in MATLAB .mat format') - out_pickled_extra_measures = File('extra_measures', usedefault=True, desc='Network measures for group 1 that return dictionaries stored as a Pickle.') + out_k_core = File( + 'k_core', + usedefault=True, + desc='Computed k-core network stored as a NetworkX pickle.') + out_k_shell = File( + 'k_shell', + usedefault=True, + desc='Computed k-shell network stored as a NetworkX pickle.') + out_k_crust = File( + 'k_crust', + usedefault=True, + desc='Computed k-crust network stored as a NetworkX pickle.') + treat_as_weighted_graph = traits.Bool( + True, + usedefault=True, + desc= + 'Some network metrics can be calculated while considering only a binarized version of the graph' + ) + compute_clique_related_measures = traits.Bool( + False, + usedefault=True, + desc= + 'Computing clique-related measures (e.g. node clique number) can be very time consuming' + ) + out_global_metrics_matlab = File( + genfile=True, desc='Output node metrics in MATLAB .mat format') + out_node_metrics_matlab = File( + genfile=True, desc='Output node metrics in MATLAB .mat format') + out_edge_metrics_matlab = File( + genfile=True, desc='Output edge metrics in MATLAB .mat format') + out_pickled_extra_measures = File( + 'extra_measures', + usedefault=True, + desc= + 'Network measures for group 1 that return dictionaries stored as a Pickle.' + ) class NetworkXMetricsOutputSpec(TraitedSpec): - gpickled_network_files = OutputMultiPath(File(desc='Output gpickled network files')) - matlab_matrix_files = OutputMultiPath(File(desc='Output network metrics in MATLAB .mat format')) - global_measures_matlab = File(desc='Output global metrics in MATLAB .mat format') - node_measures_matlab = File(desc='Output node metrics in MATLAB .mat format') - edge_measures_matlab = File(desc='Output edge metrics in MATLAB .mat format') - node_measure_networks = OutputMultiPath(File(desc='Output gpickled network files for all node-based measures')) - edge_measure_networks = OutputMultiPath(File(desc='Output gpickled network files for all edge-based measures')) - k_networks = OutputMultiPath(File(desc='Output gpickled network files for the k-core, k-shell, and k-crust networks')) + gpickled_network_files = OutputMultiPath( + File(desc='Output gpickled network files')) + matlab_matrix_files = OutputMultiPath( + File(desc='Output network metrics in MATLAB .mat format')) + global_measures_matlab = File( + desc='Output global metrics in MATLAB .mat format') + node_measures_matlab = File( + desc='Output node metrics in MATLAB .mat format') + edge_measures_matlab = File( + desc='Output edge metrics in MATLAB .mat format') + node_measure_networks = OutputMultiPath( + File(desc='Output gpickled network files for all node-based measures')) + edge_measure_networks = OutputMultiPath( + File(desc='Output gpickled network files for all edge-based measures')) + k_networks = OutputMultiPath( + File( + desc= + 'Output gpickled network files for the k-core, k-shell, and k-crust networks' + )) k_core = File(desc='Computed k-core network stored as a NetworkX pickle.') - k_shell = File(desc='Computed k-shell network stored as a NetworkX pickle.') - k_crust = File(desc='Computed k-crust network stored as a NetworkX pickle.') - pickled_extra_measures = File(desc='Network measures for the group that return dictionaries, stored as a Pickle.') - matlab_dict_measures = OutputMultiPath(File(desc='Network measures for the group that return dictionaries, stored as matlab matrices.')) + k_shell = File( + desc='Computed k-shell network stored as a NetworkX pickle.') + k_crust = File( + desc='Computed k-crust network stored as a NetworkX pickle.') + pickled_extra_measures = File( + desc= + 'Network measures for the group that return dictionaries, stored as a Pickle.' + ) + matlab_dict_measures = OutputMultiPath( + File( + desc= + 'Network measures for the group that return dictionaries, stored as matlab matrices.' + )) class NetworkXMetrics(BaseInterface): @@ -401,11 +473,13 @@ def _run_interface(self, runtime): calculate_cliques = self.inputs.compute_clique_related_measures weighted = self.inputs.treat_as_weighted_graph - global_measures = compute_singlevalued_measures(ntwk, weighted, calculate_cliques) + global_measures = compute_singlevalued_measures( + ntwk, weighted, calculate_cliques) if isdefined(self.inputs.out_global_metrics_matlab): global_out_file = op.abspath(self.inputs.out_global_metrics_matlab) else: - global_out_file = op.abspath(self._gen_outfilename('globalmetrics', 'mat')) + global_out_file = op.abspath( + self._gen_outfilename('globalmetrics', 'mat')) sio.savemat(global_out_file, global_measures, oned_as='column') matlab.append(global_out_file) @@ -418,7 +492,8 @@ def _run_interface(self, runtime): if isdefined(self.inputs.out_node_metrics_matlab): node_out_file = op.abspath(self.inputs.out_node_metrics_matlab) else: - node_out_file = op.abspath(self._gen_outfilename('nodemetrics', 'mat')) + node_out_file = op.abspath( + self._gen_outfilename('nodemetrics', 'mat')) sio.savemat(node_out_file, node_measures, oned_as='column') matlab.append(node_out_file) gpickled.extend(nodentwks) @@ -432,7 +507,8 @@ def _run_interface(self, runtime): if isdefined(self.inputs.out_edge_metrics_matlab): edge_out_file = op.abspath(self.inputs.out_edge_metrics_matlab) else: - edge_out_file = op.abspath(self._gen_outfilename('edgemetrics', 'mat')) + edge_out_file = op.abspath( + self._gen_outfilename('edgemetrics', 'mat')) sio.savemat(edge_out_file, edge_measures, oned_as='column') matlab.append(edge_out_file) gpickled.extend(edgentwks) @@ -440,16 +516,21 @@ def _run_interface(self, runtime): ntwk_measures = compute_network_measures(ntwk) for key in list(ntwk_measures.keys()): if key == 'k_core': - out_file = op.abspath(self._gen_outfilename(self.inputs.out_k_core, 'pck')) + out_file = op.abspath( + self._gen_outfilename(self.inputs.out_k_core, 'pck')) if key == 'k_shell': - out_file = op.abspath(self._gen_outfilename(self.inputs.out_k_shell, 'pck')) + out_file = op.abspath( + self._gen_outfilename(self.inputs.out_k_shell, 'pck')) if key == 'k_crust': - out_file = op.abspath(self._gen_outfilename(self.inputs.out_k_crust, 'pck')) + out_file = op.abspath( + self._gen_outfilename(self.inputs.out_k_crust, 'pck')) nx.write_gpickle(ntwk_measures[key], out_file) kntwks.append(out_file) gpickled.extend(kntwks) - out_pickled_extra_measures = op.abspath(self._gen_outfilename(self.inputs.out_pickled_extra_measures, 'pck')) + out_pickled_extra_measures = op.abspath( + self._gen_outfilename(self.inputs.out_pickled_extra_measures, + 'pck')) dict_measures = compute_dict_measures(ntwk) iflogger.info('Saving extra measure file to %s in Pickle format', op.abspath(out_pickled_extra_measures)) @@ -482,19 +563,30 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self.output_spec().get() - outputs["k_core"] = op.abspath(self._gen_outfilename(self.inputs.out_k_core, 'pck')) - outputs["k_shell"] = op.abspath(self._gen_outfilename(self.inputs.out_k_shell, 'pck')) - outputs["k_crust"] = op.abspath(self._gen_outfilename(self.inputs.out_k_crust, 'pck')) + outputs["k_core"] = op.abspath( + self._gen_outfilename(self.inputs.out_k_core, 'pck')) + outputs["k_shell"] = op.abspath( + self._gen_outfilename(self.inputs.out_k_shell, 'pck')) + outputs["k_crust"] = op.abspath( + self._gen_outfilename(self.inputs.out_k_crust, 'pck')) outputs["gpickled_network_files"] = gpickled outputs["k_networks"] = kntwks outputs["node_measure_networks"] = nodentwks outputs["edge_measure_networks"] = edgentwks outputs["matlab_dict_measures"] = dicts - outputs["global_measures_matlab"] = op.abspath(self._gen_outfilename('globalmetrics', 'mat')) - outputs["node_measures_matlab"] = op.abspath(self._gen_outfilename('nodemetrics', 'mat')) - outputs["edge_measures_matlab"] = op.abspath(self._gen_outfilename('edgemetrics', 'mat')) - outputs["matlab_matrix_files"] = [outputs["global_measures_matlab"], outputs["node_measures_matlab"], outputs["edge_measures_matlab"]] - outputs["pickled_extra_measures"] = op.abspath(self._gen_outfilename(self.inputs.out_pickled_extra_measures, 'pck')) + outputs["global_measures_matlab"] = op.abspath( + self._gen_outfilename('globalmetrics', 'mat')) + outputs["node_measures_matlab"] = op.abspath( + self._gen_outfilename('nodemetrics', 'mat')) + outputs["edge_measures_matlab"] = op.abspath( + self._gen_outfilename('edgemetrics', 'mat')) + outputs["matlab_matrix_files"] = [ + outputs["global_measures_matlab"], outputs["node_measures_matlab"], + outputs["edge_measures_matlab"] + ] + outputs["pickled_extra_measures"] = op.abspath( + self._gen_outfilename(self.inputs.out_pickled_extra_measures, + 'pck')) return outputs def _gen_outfilename(self, name, ext): @@ -502,18 +594,27 @@ def _gen_outfilename(self, name, ext): class AverageNetworksInputSpec(BaseInterfaceInputSpec): - in_files = InputMultiPath(File(exists=True), mandatory=True, desc='Networks for a group of subjects') - resolution_network_file = File(exists=True, desc='Parcellation files from Connectome Mapping Toolkit. This is not necessary' - ', but if included, the interface will output the statistical maps as networkx graphs.') + in_files = InputMultiPath( + File(exists=True), + mandatory=True, + desc='Networks for a group of subjects') + resolution_network_file = File( + exists=True, + desc= + 'Parcellation files from Connectome Mapping Toolkit. This is not necessary' + ', but if included, the interface will output the statistical maps as networkx graphs.' + ) group_id = traits.Str('group1', usedefault=True, desc='ID for group') - out_gpickled_groupavg = File(desc='Average network saved as a NetworkX .pck') + out_gpickled_groupavg = File( + desc='Average network saved as a NetworkX .pck') out_gexf_groupavg = File(desc='Average network saved as a .gexf file') class AverageNetworksOutputSpec(TraitedSpec): gpickled_groupavg = File(desc='Average network saved as a NetworkX .pck') gexf_groupavg = File(desc='Average network saved as a .gexf file') - matlab_groupavgs = OutputMultiPath(File(desc='Average network saved as a .gexf file')) + matlab_groupavgs = OutputMultiPath( + File(desc='Average network saved as a .gexf file')) class AverageNetworks(BaseInterface): @@ -542,20 +643,27 @@ def _run_interface(self, runtime): ntwk_res_file = self.inputs.in_files[0] global matlab_network_list - network_name, matlab_network_list = average_networks(self.inputs.in_files, ntwk_res_file, self.inputs.group_id) + network_name, matlab_network_list = average_networks( + self.inputs.in_files, ntwk_res_file, self.inputs.group_id) return runtime def _list_outputs(self): outputs = self.output_spec().get() if not isdefined(self.inputs.out_gpickled_groupavg): - outputs["gpickled_groupavg"] = op.abspath(self._gen_outfilename(self.inputs.group_id + '_average', 'pck')) + outputs["gpickled_groupavg"] = op.abspath( + self._gen_outfilename(self.inputs.group_id + '_average', + 'pck')) else: - outputs["gpickled_groupavg"] = op.abspath(self.inputs.out_gpickled_groupavg) + outputs["gpickled_groupavg"] = op.abspath( + self.inputs.out_gpickled_groupavg) if not isdefined(self.inputs.out_gexf_groupavg): - outputs["gexf_groupavg"] = op.abspath(self._gen_outfilename(self.inputs.group_id + '_average', 'gexf')) + outputs["gexf_groupavg"] = op.abspath( + self._gen_outfilename(self.inputs.group_id + '_average', + 'gexf')) else: - outputs["gexf_groupavg"] = op.abspath(self.inputs.out_gexf_groupavg) + outputs["gexf_groupavg"] = op.abspath( + self.inputs.out_gexf_groupavg) outputs["matlab_groupavgs"] = matlab_network_list return outputs diff --git a/nipype/interfaces/cmtk/parcellation.py b/nipype/interfaces/cmtk/parcellation.py index 22214c0036..272fd22df9 100644 --- a/nipype/interfaces/cmtk/parcellation.py +++ b/nipype/interfaces/cmtk/parcellation.py @@ -9,7 +9,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range import os @@ -23,8 +24,8 @@ from ... import logging from ...utils.misc import package_check -from ..base import (BaseInterface, BaseInterfaceInputSpec, traits, - File, TraitedSpec, Directory, isdefined) +from ..base import (BaseInterface, BaseInterfaceInputSpec, traits, File, + TraitedSpec, Directory, isdefined) iflogger = logging.getLogger('interface') have_cmp = True @@ -46,8 +47,8 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): cmp_config = cmp.configuration.PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" for hemi in ['lh', 'rh']: - spath = cmp_config._get_lausanne_parcellation( - 'Lausanne2008')[parcellation_name]['fs_label_subdir_name'] % hemi + spath = cmp_config._get_lausanne_parcellation('Lausanne2008')[ + parcellation_name]['fs_label_subdir_name'] % hemi paths.append(spath) for p in paths: try: @@ -129,21 +130,24 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): log = cmp_config.get_logger() for out in comp: - mris_cmd = 'mris_ca_label %s %s "%s/surf/%s.sphere.reg" "%s" "%s" ' % (subject_id, out[0], - op.join(subjects_dir, subject_id), out[0], cmp_config.get_lausanne_atlas(out[1]), op.join(fs_label_dir, out[2])) + mris_cmd = 'mris_ca_label %s %s "%s/surf/%s.sphere.reg" "%s" "%s" ' % ( + subject_id, out[0], op.join(subjects_dir, subject_id), out[0], + cmp_config.get_lausanne_atlas(out[1]), + op.join(fs_label_dir, out[2])) runCmd(mris_cmd, log) iflogger.info('-----------') annot = '--annotation "%s"' % out[4] - mri_an_cmd = 'mri_annotation2label --subject %s --hemi %s --outdir "%s" %s' % (subject_id, out[0], op.join(output_dir, out[3]), annot) + mri_an_cmd = 'mri_annotation2label --subject %s --hemi %s --outdir "%s" %s' % ( + subject_id, out[0], op.join(output_dir, out[3]), annot) iflogger.info(mri_an_cmd) runCmd(mri_an_cmd, log) iflogger.info('-----------') iflogger.info(os.environ['SUBJECTS_DIR']) - # extract cc and unknown to add to tractography mask, we do not want this as a region of interest - # in FS 5.0, unknown and corpuscallosum are not available for the 35 scale (why?), - # but for the other scales only, take the ones from _60 + # extract cc and unknown to add to tractography mask, we do not want this as a region of interest + # in FS 5.0, unknown and corpuscallosum are not available for the 35 scale (why?), + # but for the other scales only, take the ones from _60 rhun = op.join(output_dir, 'rh.unknown.label') lhun = op.join(output_dir, 'lh.unknown.label') rhco = op.join(output_dir, 'rh.corpuscallosum.label') @@ -152,15 +156,21 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): op.join(output_dir, 'regenerated_rh_60', 'rh.unknown.label'), rhun) shutil.copy( op.join(output_dir, 'regenerated_lh_60', 'lh.unknown.label'), lhun) - shutil.copy(op.join( - output_dir, 'regenerated_rh_60', 'rh.corpuscallosum.label'), rhco) - shutil.copy(op.join( - output_dir, 'regenerated_lh_60', 'lh.corpuscallosum.label'), lhco) + shutil.copy( + op.join(output_dir, 'regenerated_rh_60', 'rh.corpuscallosum.label'), + rhco) + shutil.copy( + op.join(output_dir, 'regenerated_lh_60', 'lh.corpuscallosum.label'), + lhco) - mri_cmd = """mri_label2vol --label "%s" --label "%s" --label "%s" --label "%s" --temp "%s" --o "%s" --identity """ % (rhun, lhun, rhco, lhco, op.join(op.join(subjects_dir, subject_id), 'mri', 'orig.mgz'), op.join(fs_label_dir, 'cc_unknown.nii.gz')) + mri_cmd = """mri_label2vol --label "%s" --label "%s" --label "%s" --label "%s" --temp "%s" --o "%s" --identity """ % ( + rhun, lhun, rhco, lhco, + op.join(op.join(subjects_dir, subject_id), 'mri', 'orig.mgz'), + op.join(fs_label_dir, 'cc_unknown.nii.gz')) runCmd(mri_cmd, log) runCmd('mris_volmask %s' % subject_id, log) - mri_cmd = 'mri_convert -i "%s/mri/ribbon.mgz" -o "%s/mri/ribbon.nii.gz"' % (op.join(subjects_dir, subject_id), op.join(subjects_dir, subject_id)) + mri_cmd = 'mri_convert -i "%s/mri/ribbon.mgz" -o "%s/mri/ribbon.nii.gz"' % ( + op.join(subjects_dir, subject_id), op.join(subjects_dir, subject_id)) runCmd(mri_cmd, log) mri_cmd = 'mri_convert -i "%s/mri/aseg.mgz" -o "%s/mri/aseg.nii.gz"' % ( op.join(subjects_dir, subject_id), op.join(subjects_dir, subject_id)) @@ -178,8 +188,8 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): cmp_config = cmp.configuration.PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" log = cmp_config.get_logger() - parval = cmp_config._get_lausanne_parcellation( - 'Lausanne2008')[parcellation_name] + parval = cmp_config._get_lausanne_parcellation('Lausanne2008')[ + parcellation_name] pgpath = parval['node_information_graphml'] aseg = nb.load(op.join(fs_dir, 'mri', 'aseg.nii.gz')) asegd = aseg.get_data() @@ -204,8 +214,9 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): dist[x, y, z] = np.sqrt(np.sum(np.multiply(distxyz, distxyz))) iflogger.info("Working on parcellation: ") - iflogger.info(cmp_config._get_lausanne_parcellation( - 'Lausanne2008')[parcellation_name]) + iflogger.info( + cmp_config._get_lausanne_parcellation('Lausanne2008')[ + parcellation_name]) iflogger.info("========================") pg = nx.read_graphml(pgpath) # each node represents a brain region @@ -240,8 +251,8 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): iflogger.info('Region %s of %s', count, pg.number_of_nodes()) iflogger.info('---------------------') - labelpath = op.join( - output_dir, parval['fs_label_subdir_name'] % hemi) + labelpath = op.join(output_dir, + parval['fs_label_subdir_name'] % hemi) # construct .label file name fname = '%s.%s.label' % (hemi, brv['dn_fsname']) @@ -249,8 +260,9 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): # execute fs mri_label2vol to generate volume roi from the label file # store it in temporary file to be overwritten for each region - mri_cmd = 'mri_label2vol --label "%s" --temp "%s" --o "%s" --identity' % (op.join(labelpath, fname), - op.join(fs_dir, 'mri', 'orig.mgz'), op.join(output_dir, 'tmp.nii.gz')) + mri_cmd = 'mri_label2vol --label "%s" --temp "%s" --o "%s" --identity' % ( + op.join(labelpath, fname), op.join(fs_dir, 'mri', 'orig.mgz'), + op.join(output_dir, 'tmp.nii.gz')) runCmd(mri_cmd, log) tmp = nb.load(op.join(output_dir, 'tmp.nii.gz')) @@ -306,8 +318,8 @@ def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): fs_dir = op.join(subjects_dir, subject_id) cmp_config = cmp.configuration.PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" - pgpath = cmp_config._get_lausanne_parcellation( - 'Lausanne2008')[parcellation_name]['node_information_graphml'] + pgpath = cmp_config._get_lausanne_parcellation('Lausanne2008')[ + parcellation_name]['node_information_graphml'] # load ribbon as basis for white matter mask fsmask = nb.load(op.join(fs_dir, 'mri', 'ribbon.nii.gz')) fsmaskd = fsmask.get_data() @@ -348,35 +360,21 @@ def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): # lateral ventricles, thalamus proper and caudate # the latter two removed for better erosion, but put back afterwards - idx = np.where((asegd == 4) | - (asegd == 43) | - (asegd == 11) | - (asegd == 50) | - (asegd == 31) | - (asegd == 63) | - (asegd == 10) | - (asegd == 49)) + idx = np.where((asegd == 4) | (asegd == 43) | (asegd == 11) | (asegd == 50) + | (asegd == 31) | (asegd == 63) | (asegd == 10) + | (asegd == 49)) csfA[idx] = 1 csfA = imerode(imerode(csfA, se1), se) # thalmus proper and cuadate are put back because they are not lateral ventricles - idx = np.where((asegd == 11) | - (asegd == 50) | - (asegd == 10) | - (asegd == 49)) + idx = np.where((asegd == 11) | (asegd == 50) | (asegd == 10) + | (asegd == 49)) csfA[idx] = 0 # REST CSF, IE 3RD AND 4TH VENTRICULE AND EXTRACEREBRAL CSF - idx = np.where((asegd == 5) | - (asegd == 14) | - (asegd == 15) | - (asegd == 24) | - (asegd == 44) | - (asegd == 72) | - (asegd == 75) | - (asegd == 76) | - (asegd == 213) | - (asegd == 221)) + idx = np.where((asegd == 5) | (asegd == 14) | (asegd == 15) | (asegd == 24) + | (asegd == 44) | (asegd == 72) | (asegd == 75) + | (asegd == 76) | (asegd == 213) | (asegd == 221)) # 43 ??, 4?? 213?, 221? # more to discuss. for i in [5, 14, 15, 24, 44, 72, 75, 76, 213, 221]: @@ -411,10 +409,12 @@ def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): remaining[idx] = 1 # now remove all the structures from the white matter - idx = np.where( - (csfA != 0) | (csfB != 0) | (gr_ncl != 0) | (remaining != 0)) + idx = np.where((csfA != 0) | (csfB != 0) | (gr_ncl != 0) + | (remaining != 0)) wmmask[idx] = 0 - iflogger.info("Removing lateral ventricles and eroded grey nuclei and brainstem from white matter mask") + iflogger.info( + "Removing lateral ventricles and eroded grey nuclei and brainstem from white matter mask" + ) # ADD voxels from 'cc_unknown.nii.gz' dataset ccun = nb.load(op.join(fs_dir, 'label', 'cc_unknown.nii.gz')) @@ -444,7 +444,8 @@ def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): nb.save(img, wm_out) -def crop_and_move_datasets(subject_id, subjects_dir, fs_dir, parcellation_name, out_roi_file, dilation): +def crop_and_move_datasets(subject_id, subjects_dir, fs_dir, parcellation_name, + out_roi_file, dilation): fs_dir = op.join(subjects_dir, subject_id) cmp_config = cmp.configuration.PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" @@ -452,16 +453,14 @@ def crop_and_move_datasets(subject_id, subjects_dir, fs_dir, parcellation_name, output_dir = op.abspath(op.curdir) iflogger.info('Cropping and moving datasets to %s', output_dir) - ds = [ - (op.join(fs_dir, 'mri', 'aseg.nii.gz'), - op.abspath('aseg.nii.gz')), - (op.join(fs_dir, 'mri', 'ribbon.nii.gz'), - op.abspath('ribbon.nii.gz')), - (op.join(fs_dir, 'mri', 'fsmask_1mm.nii.gz'), - op.abspath('fsmask_1mm.nii.gz')), - (op.join(fs_dir, 'label', 'cc_unknown.nii.gz'), - op.abspath('cc_unknown.nii.gz')) - ] + ds = [(op.join(fs_dir, 'mri', 'aseg.nii.gz'), + op.abspath('aseg.nii.gz')), (op.join(fs_dir, 'mri', + 'ribbon.nii.gz'), + op.abspath('ribbon.nii.gz')), + (op.join(fs_dir, 'mri', 'fsmask_1mm.nii.gz'), + op.abspath('fsmask_1mm.nii.gz')), (op.join(fs_dir, 'label', + 'cc_unknown.nii.gz'), + op.abspath('cc_unknown.nii.gz'))] ds.append((op.abspath('ROI_%s.nii.gz' % parcellation_name), op.abspath('ROI_HR_th.nii.gz'))) @@ -475,8 +474,9 @@ def crop_and_move_datasets(subject_id, subjects_dir, fs_dir, parcellation_name, raise Exception('File %s does not exist.' % d[0]) # reslice to original volume because the roi creation with freesurfer # changed to 256x256x256 resolution - mri_cmd = 'mri_convert -rl "%s" -rt nearest "%s" -nc "%s"' % ( - orig, d[0], d[1]) + mri_cmd = 'mri_convert -rl "%s" -rt nearest "%s" -nc "%s"' % (orig, + d[0], + d[1]) runCmd(mri_cmd, log) @@ -494,12 +494,12 @@ def extract(Z, shape, position, fill): """ R = np.ones(shape, dtype=Z.dtype) * \ fill # initialize output block to the fill value - P = np.array( - list(position)).astype(int) # position coordinates(numpy array) - Rs = np.array( - list(R.shape)).astype(int) # output block dimensions (numpy array) - Zs = np.array( - list(Z.shape)).astype(int) # original volume dimensions (numpy array) + P = np.array(list(position)).astype( + int) # position coordinates(numpy array) + Rs = np.array(list(R.shape)).astype( + int) # output block dimensions (numpy array) + Zs = np.array(list(Z.shape)).astype( + int) # original volume dimensions (numpy array) R_start = np.zeros(len(shape)).astype(int) R_stop = np.array(list(shape)).astype(int) @@ -510,40 +510,51 @@ def extract(Z, shape, position, fill): Z_stop_cor = (np.minimum(Z_stop, Zs)).tolist() # handle borders R_stop = R_stop - (Z_stop - Z_stop_cor) - R[R_start[0]:R_stop[0], R_start[1]:R_stop[1], R_start[2]:R_stop[2]] = Z[Z_start_cor[0]:Z_stop_cor[0], Z_start_cor[1]:Z_stop_cor[1], Z_start_cor[2]:Z_stop_cor[2]] + R[R_start[0]:R_stop[0], R_start[1]:R_stop[1], R_start[2]:R_stop[ + 2]] = Z[Z_start_cor[0]:Z_stop_cor[0], Z_start_cor[1]:Z_stop_cor[1], + Z_start_cor[2]:Z_stop_cor[2]] return R class ParcellateInputSpec(BaseInterfaceInputSpec): subject_id = traits.String(mandatory=True, desc='Subject ID') - parcellation_name = traits.Enum('scale500', ['scale33', 'scale60', 'scale125', 'scale250', 'scale500'], usedefault=True) + parcellation_name = traits.Enum( + 'scale500', ['scale33', 'scale60', 'scale125', 'scale250', 'scale500'], + usedefault=True) freesurfer_dir = Directory(exists=True, desc='Freesurfer main directory') subjects_dir = Directory(exists=True, desc='Freesurfer subjects directory') out_roi_file = File( genfile=True, desc='Region of Interest file for connectivity mapping') - dilation = traits.Bool(False, usedefault=True, - desc='Dilate cortical parcels? Useful for fMRI connectivity') + dilation = traits.Bool( + False, + usedefault=True, + desc='Dilate cortical parcels? Useful for fMRI connectivity') class ParcellateOutputSpec(TraitedSpec): roi_file = File( exists=True, desc='Region of Interest file for connectivity mapping') - roiv_file = File(desc='Region of Interest file for fMRI connectivity mapping') + roiv_file = File( + desc='Region of Interest file for fMRI connectivity mapping') white_matter_mask_file = File(exists=True, desc='White matter mask file') cc_unknown_file = File( desc='Image file with regions labelled as unknown cortical structures', exists=True) - ribbon_file = File(desc='Image file detailing the cortical ribbon', - exists=True) + ribbon_file = File( + desc='Image file detailing the cortical ribbon', exists=True) aseg_file = File( - desc='Automated segmentation file converted from Freesurfer "subjects" directory', + desc= + 'Automated segmentation file converted from Freesurfer "subjects" directory', exists=True) roi_file_in_structural_space = File( - desc='ROI image resliced to the dimensions of the original structural image', + desc= + 'ROI image resliced to the dimensions of the original structural image', exists=True) dilated_roi_file_in_structural_space = File( - desc='dilated ROI image resliced to the dimensions of the original structural image') + desc= + 'dilated ROI image resliced to the dimensions of the original structural image' + ) class Parcellate(BaseInterface): @@ -573,14 +584,24 @@ def _run_interface(self, runtime): if self.inputs.subjects_dir: os.environ.update({'SUBJECTS_DIR': self.inputs.subjects_dir}) - if not os.path.exists(op.join(self.inputs.subjects_dir, self.inputs.subject_id)): + if not os.path.exists( + op.join(self.inputs.subjects_dir, self.inputs.subject_id)): raise Exception iflogger.info("ROI_HR_th.nii.gz / fsmask_1mm.nii.gz CREATION") iflogger.info("=============================================") - create_annot_label(self.inputs.subject_id, self.inputs.subjects_dir, self.inputs.freesurfer_dir, self.inputs.parcellation_name) - create_roi(self.inputs.subject_id, self.inputs.subjects_dir, self.inputs.freesurfer_dir, self.inputs.parcellation_name, self.inputs.dilation) - create_wm_mask(self.inputs.subject_id, self.inputs.subjects_dir, self.inputs.freesurfer_dir, self.inputs.parcellation_name) - crop_and_move_datasets(self.inputs.subject_id, self.inputs.subjects_dir, self.inputs.freesurfer_dir, self.inputs.parcellation_name, self.inputs.out_roi_file, self.inputs.dilation) + create_annot_label(self.inputs.subject_id, self.inputs.subjects_dir, + self.inputs.freesurfer_dir, + self.inputs.parcellation_name) + create_roi(self.inputs.subject_id, self.inputs.subjects_dir, + self.inputs.freesurfer_dir, self.inputs.parcellation_name, + self.inputs.dilation) + create_wm_mask(self.inputs.subject_id, self.inputs.subjects_dir, + self.inputs.freesurfer_dir, + self.inputs.parcellation_name) + crop_and_move_datasets( + self.inputs.subject_id, self.inputs.subjects_dir, + self.inputs.freesurfer_dir, self.inputs.parcellation_name, + self.inputs.out_roi_file, self.inputs.dilation) return runtime def _list_outputs(self): @@ -591,8 +612,8 @@ def _list_outputs(self): outputs['roi_file'] = op.abspath( self._gen_outfilename('nii.gz', 'ROI')) if self.inputs.dilation is True: - outputs['roiv_file'] = op.abspath(self._gen_outfilename( - 'nii.gz', 'ROIv')) + outputs['roiv_file'] = op.abspath( + self._gen_outfilename('nii.gz', 'ROIv')) outputs['white_matter_mask_file'] = op.abspath('fsmask_1mm.nii.gz') outputs['cc_unknown_file'] = op.abspath('cc_unknown.nii.gz') outputs['ribbon_file'] = op.abspath('ribbon.nii.gz') diff --git a/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py b/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py index 567de03ab3..a2cc1bf9c5 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py +++ b/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py @@ -4,29 +4,28 @@ def test_AverageNetworks_inputs(): - input_map = dict(group_id=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(mandatory=True, - ), - out_gexf_groupavg=dict(), - out_gpickled_groupavg=dict(), - resolution_network_file=dict(), + input_map = dict( + group_id=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict(mandatory=True, ), + out_gexf_groupavg=dict(), + out_gpickled_groupavg=dict(), + resolution_network_file=dict(), ) inputs = AverageNetworks.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AverageNetworks_outputs(): - output_map = dict(gexf_groupavg=dict(), - gpickled_groupavg=dict(), - matlab_groupavgs=dict(), + output_map = dict( + gexf_groupavg=dict(), + gpickled_groupavg=dict(), + matlab_groupavgs=dict(), ) outputs = AverageNetworks.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py b/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py index cf62691f3b..1c26049f02 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py +++ b/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py @@ -4,44 +4,40 @@ def test_CFFConverter_inputs(): - input_map = dict(creator=dict(), - data_files=dict(), - description=dict(usedefault=True, - ), - email=dict(), - gifti_labels=dict(), - gifti_surfaces=dict(), - gpickled_networks=dict(), - graphml_networks=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - license=dict(), - nifti_volumes=dict(), - out_file=dict(usedefault=True, - ), - publisher=dict(), - references=dict(), - relation=dict(), - rights=dict(), - script_files=dict(), - species=dict(usedefault=True, - ), - timeseries_files=dict(), - title=dict(), - tract_files=dict(), + input_map = dict( + creator=dict(), + data_files=dict(), + description=dict(usedefault=True, ), + email=dict(), + gifti_labels=dict(), + gifti_surfaces=dict(), + gpickled_networks=dict(), + graphml_networks=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + license=dict(), + nifti_volumes=dict(), + out_file=dict(usedefault=True, ), + publisher=dict(), + references=dict(), + relation=dict(), + rights=dict(), + script_files=dict(), + species=dict(usedefault=True, ), + timeseries_files=dict(), + title=dict(), + tract_files=dict(), ) inputs = CFFConverter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CFFConverter_outputs(): - output_map = dict(connectome_file=dict(), - ) + output_map = dict(connectome_file=dict(), ) outputs = CFFConverter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py b/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py index 474f22dfd1..60e8596f5e 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py +++ b/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py @@ -4,55 +4,44 @@ def test_CreateMatrix_inputs(): - input_map = dict(count_region_intersections=dict(usedefault=True, - ), - out_endpoint_array_name=dict(genfile=True, - ), - out_fiber_length_std_matrix_mat_file=dict(genfile=True, - ), - out_intersection_matrix_mat_file=dict(genfile=True, - ), - out_matrix_file=dict(genfile=True, - ), - out_matrix_mat_file=dict(usedefault=True, - ), - out_mean_fiber_length_matrix_mat_file=dict(genfile=True, - ), - out_median_fiber_length_matrix_mat_file=dict(genfile=True, - ), - resolution_network_file=dict(mandatory=True, - ), - roi_file=dict(mandatory=True, - ), - tract_file=dict(mandatory=True, - ), + input_map = dict( + count_region_intersections=dict(usedefault=True, ), + out_endpoint_array_name=dict(genfile=True, ), + out_fiber_length_std_matrix_mat_file=dict(genfile=True, ), + out_intersection_matrix_mat_file=dict(genfile=True, ), + out_matrix_file=dict(genfile=True, ), + out_matrix_mat_file=dict(usedefault=True, ), + out_mean_fiber_length_matrix_mat_file=dict(genfile=True, ), + out_median_fiber_length_matrix_mat_file=dict(genfile=True, ), + resolution_network_file=dict(mandatory=True, ), + roi_file=dict(mandatory=True, ), + tract_file=dict(mandatory=True, ), ) inputs = CreateMatrix.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CreateMatrix_outputs(): - output_map = dict(endpoint_file=dict(), - endpoint_file_mm=dict(), - fiber_label_file=dict(), - fiber_labels_noorphans=dict(), - fiber_length_file=dict(), - fiber_length_std_matrix_mat_file=dict(), - filtered_tractographies=dict(), - filtered_tractography=dict(), - filtered_tractography_by_intersections=dict(), - intersection_matrix_file=dict(), - intersection_matrix_mat_file=dict(), - matlab_matrix_files=dict(), - matrix_file=dict(), - matrix_files=dict(), - matrix_mat_file=dict(), - mean_fiber_length_matrix_mat_file=dict(), - median_fiber_length_matrix_mat_file=dict(), - stats_file=dict(), + output_map = dict( + endpoint_file=dict(), + endpoint_file_mm=dict(), + fiber_label_file=dict(), + fiber_labels_noorphans=dict(), + fiber_length_file=dict(), + fiber_length_std_matrix_mat_file=dict(), + filtered_tractographies=dict(), + filtered_tractography=dict(), + filtered_tractography_by_intersections=dict(), + intersection_matrix_file=dict(), + intersection_matrix_mat_file=dict(), + matlab_matrix_files=dict(), + matrix_file=dict(), + matrix_files=dict(), + matrix_mat_file=dict(), + mean_fiber_length_matrix_mat_file=dict(), + median_fiber_length_matrix_mat_file=dict(), + stats_file=dict(), ) outputs = CreateMatrix.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py b/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py index 42efb72dfd..42e639d5cd 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py +++ b/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py @@ -4,27 +4,23 @@ def test_CreateNodes_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_filename=dict(usedefault=True, - ), - resolution_network_file=dict(mandatory=True, - ), - roi_file=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_filename=dict(usedefault=True, ), + resolution_network_file=dict(mandatory=True, ), + roi_file=dict(mandatory=True, ), ) inputs = CreateNodes.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CreateNodes_outputs(): - output_map = dict(node_network=dict(), - ) + output_map = dict(node_network=dict(), ) outputs = CreateNodes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py b/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py index 2323461f35..b97ebfa65f 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py +++ b/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py @@ -4,25 +4,22 @@ def test_MergeCNetworks_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(mandatory=True, - ), - out_file=dict(usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict(mandatory=True, ), + out_file=dict(usedefault=True, ), ) inputs = MergeCNetworks.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MergeCNetworks_outputs(): - output_map = dict(connectome_file=dict(), - ) + output_map = dict(connectome_file=dict(), ) outputs = MergeCNetworks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py b/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py index 27f607c530..33db760531 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py +++ b/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py @@ -4,37 +4,32 @@ def test_NetworkBasedStatistic_inputs(): - input_map = dict(edge_key=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_group1=dict(mandatory=True, - ), - in_group2=dict(mandatory=True, - ), - node_position_network=dict(), - number_of_permutations=dict(usedefault=True, - ), - out_nbs_network=dict(), - out_nbs_pval_network=dict(), - t_tail=dict(usedefault=True, - ), - threshold=dict(usedefault=True, - ), + input_map = dict( + edge_key=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_group1=dict(mandatory=True, ), + in_group2=dict(mandatory=True, ), + node_position_network=dict(), + number_of_permutations=dict(usedefault=True, ), + out_nbs_network=dict(), + out_nbs_pval_network=dict(), + t_tail=dict(usedefault=True, ), + threshold=dict(usedefault=True, ), ) inputs = NetworkBasedStatistic.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NetworkBasedStatistic_outputs(): - output_map = dict(nbs_network=dict(), - nbs_pval_network=dict(), - network_files=dict(), + output_map = dict( + nbs_network=dict(), + nbs_pval_network=dict(), + network_files=dict(), ) outputs = NetworkBasedStatistic.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py b/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py index a8ccc8dd06..0673c2019e 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py +++ b/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py @@ -4,52 +4,43 @@ def test_NetworkXMetrics_inputs(): - input_map = dict(compute_clique_related_measures=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - out_edge_metrics_matlab=dict(genfile=True, - ), - out_global_metrics_matlab=dict(genfile=True, - ), - out_k_core=dict(usedefault=True, - ), - out_k_crust=dict(usedefault=True, - ), - out_k_shell=dict(usedefault=True, - ), - out_node_metrics_matlab=dict(genfile=True, - ), - out_pickled_extra_measures=dict(usedefault=True, - ), - treat_as_weighted_graph=dict(usedefault=True, - ), + input_map = dict( + compute_clique_related_measures=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + out_edge_metrics_matlab=dict(genfile=True, ), + out_global_metrics_matlab=dict(genfile=True, ), + out_k_core=dict(usedefault=True, ), + out_k_crust=dict(usedefault=True, ), + out_k_shell=dict(usedefault=True, ), + out_node_metrics_matlab=dict(genfile=True, ), + out_pickled_extra_measures=dict(usedefault=True, ), + treat_as_weighted_graph=dict(usedefault=True, ), ) inputs = NetworkXMetrics.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NetworkXMetrics_outputs(): - output_map = dict(edge_measure_networks=dict(), - edge_measures_matlab=dict(), - global_measures_matlab=dict(), - gpickled_network_files=dict(), - k_core=dict(), - k_crust=dict(), - k_networks=dict(), - k_shell=dict(), - matlab_dict_measures=dict(), - matlab_matrix_files=dict(), - node_measure_networks=dict(), - node_measures_matlab=dict(), - pickled_extra_measures=dict(), + output_map = dict( + edge_measure_networks=dict(), + edge_measures_matlab=dict(), + global_measures_matlab=dict(), + gpickled_network_files=dict(), + k_core=dict(), + k_crust=dict(), + k_networks=dict(), + k_shell=dict(), + matlab_dict_measures=dict(), + matlab_matrix_files=dict(), + node_measure_networks=dict(), + node_measures_matlab=dict(), + pickled_extra_measures=dict(), ) outputs = NetworkXMetrics.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py b/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py index 8de2e0bf9a..2835586bf7 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py +++ b/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py @@ -4,37 +4,34 @@ def test_Parcellate_inputs(): - input_map = dict(dilation=dict(usedefault=True, - ), - freesurfer_dir=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_roi_file=dict(genfile=True, - ), - parcellation_name=dict(usedefault=True, - ), - subject_id=dict(mandatory=True, - ), - subjects_dir=dict(), + input_map = dict( + dilation=dict(usedefault=True, ), + freesurfer_dir=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_roi_file=dict(genfile=True, ), + parcellation_name=dict(usedefault=True, ), + subject_id=dict(mandatory=True, ), + subjects_dir=dict(), ) inputs = Parcellate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Parcellate_outputs(): - output_map = dict(aseg_file=dict(), - cc_unknown_file=dict(), - dilated_roi_file_in_structural_space=dict(), - ribbon_file=dict(), - roi_file=dict(), - roi_file_in_structural_space=dict(), - roiv_file=dict(), - white_matter_mask_file=dict(), + output_map = dict( + aseg_file=dict(), + cc_unknown_file=dict(), + dilated_roi_file_in_structural_space=dict(), + ribbon_file=dict(), + roi_file=dict(), + roi_file_in_structural_space=dict(), + roiv_file=dict(), + white_matter_mask_file=dict(), ) outputs = Parcellate.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py b/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py index a1c65f4db6..87c08bcdf4 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py +++ b/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py @@ -4,33 +4,28 @@ def test_ROIGen_inputs(): - input_map = dict(LUT_file=dict(xor=['use_freesurfer_LUT'], - ), - aparc_aseg_file=dict(mandatory=True, - ), - freesurfer_dir=dict(requires=['use_freesurfer_LUT'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_dict_file=dict(genfile=True, - ), - out_roi_file=dict(genfile=True, - ), - use_freesurfer_LUT=dict(xor=['LUT_file'], - ), + input_map = dict( + LUT_file=dict(xor=['use_freesurfer_LUT'], ), + aparc_aseg_file=dict(mandatory=True, ), + freesurfer_dir=dict(requires=['use_freesurfer_LUT'], ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_dict_file=dict(genfile=True, ), + out_roi_file=dict(genfile=True, ), + use_freesurfer_LUT=dict(xor=['LUT_file'], ), ) inputs = ROIGen.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ROIGen_outputs(): - output_map = dict(dict_file=dict(), - roi_file=dict(), + output_map = dict( + dict_file=dict(), + roi_file=dict(), ) outputs = ROIGen.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_nbs.py b/nipype/interfaces/cmtk/tests/test_nbs.py index 03a7aa8619..e3e527ec81 100644 --- a/nipype/interfaces/cmtk/tests/test_nbs.py +++ b/nipype/interfaces/cmtk/tests/test_nbs.py @@ -11,12 +11,13 @@ except Exception as e: have_cv = False + @pytest.fixture() def creating_graphs(tmpdir): graphlist = [] - graphnames = ["name"+str(i) for i in range(6)] + graphnames = ["name" + str(i) for i in range(6)] for idx, name in enumerate(graphnames): - graph = np.random.rand(10,10) + graph = np.random.rand(10, 10) G = nx.from_numpy_matrix(graph) out_file = tmpdir.strpath + graphnames[idx] + '.pck' # Save as pck file @@ -25,7 +26,8 @@ def creating_graphs(tmpdir): return graphlist -@pytest.mark.skipif(have_cv, reason="tests for import error, cviewer available") +@pytest.mark.skipif( + have_cv, reason="tests for import error, cviewer available") def test_importerror(creating_graphs, tmpdir): tmpdir.chdir() graphlist = creating_graphs @@ -44,7 +46,7 @@ def test_importerror(creating_graphs, tmpdir): @pytest.mark.skipif(not have_cv, reason="cviewer has to be available") def test_keyerror(creating_graphs): - graphlist =creating_graphs + graphlist = creating_graphs group1 = graphlist[:3] group2 = graphlist[3:] diff --git a/nipype/interfaces/dcm2nii.py b/nipype/interfaces/dcm2nii.py index 22e9375609..f4e8065b36 100644 --- a/nipype/interfaces/dcm2nii.py +++ b/nipype/interfaces/dcm2nii.py @@ -7,53 +7,83 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, open import os import re from copy import deepcopy from ..utils.filemanip import split_filename -from .base import (CommandLine, CommandLineInputSpec, - InputMultiPath, traits, TraitedSpec, - OutputMultiPath, isdefined, - File, Directory) +from .base import (CommandLine, CommandLineInputSpec, InputMultiPath, traits, + TraitedSpec, OutputMultiPath, isdefined, File, Directory) class Dcm2niiInputSpec(CommandLineInputSpec): - source_names = InputMultiPath(File(exists=True), argstr="%s", position=-1, - copyfile=False, mandatory=True, xor=['source_dir']) - source_dir = Directory(exists=True, argstr="%s", position=-1, mandatory=True, - xor=['source_names']) - anonymize = traits.Bool(True, argstr='-a', usedefault=True, - desc="Remove identifying information") - config_file = File(exists=True, argstr="-b %s", genfile=True, - desc="Load settings from specified inifile") - collapse_folders = traits.Bool(True, argstr='-c', usedefault=True, - desc="Collapse input folders") - date_in_filename = traits.Bool(True, argstr='-d', usedefault=True, - desc="Date in filename") - events_in_filename = traits.Bool(True, argstr='-e', usedefault=True, - desc="Events (series/acq) in filename") - source_in_filename = traits.Bool(False, argstr='-f', usedefault=True, - desc="Source filename") - gzip_output = traits.Bool(False, argstr='-g', usedefault=True, - desc="Gzip output (.gz)") - id_in_filename = traits.Bool(False, argstr='-i', usedefault=True, - desc="ID in filename") - nii_output = traits.Bool(True, argstr='-n', usedefault=True, - desc="Save as .nii - if no, create .hdr/.img pair") - output_dir = Directory(exists=True, argstr='-o %s', genfile=True, - desc="Output dir - if unspecified, source directory is used") - protocol_in_filename = traits.Bool(True, argstr='-p', usedefault=True, - desc="Protocol in filename") - reorient = traits.Bool(argstr='-r', desc="Reorient image to nearest orthogonal") - spm_analyze = traits.Bool(argstr='-s', xor=['nii_output'], - desc="SPM2/Analyze not SPM5/NIfTI") - convert_all_pars = traits.Bool(True, argstr='-v', usedefault=True, - desc="Convert every image in directory") - reorient_and_crop = traits.Bool(False, argstr='-x', usedefault=True, - desc="Reorient and crop 3D images") + source_names = InputMultiPath( + File(exists=True), + argstr="%s", + position=-1, + copyfile=False, + mandatory=True, + xor=['source_dir']) + source_dir = Directory( + exists=True, + argstr="%s", + position=-1, + mandatory=True, + xor=['source_names']) + anonymize = traits.Bool( + True, + argstr='-a', + usedefault=True, + desc="Remove identifying information") + config_file = File( + exists=True, + argstr="-b %s", + genfile=True, + desc="Load settings from specified inifile") + collapse_folders = traits.Bool( + True, argstr='-c', usedefault=True, desc="Collapse input folders") + date_in_filename = traits.Bool( + True, argstr='-d', usedefault=True, desc="Date in filename") + events_in_filename = traits.Bool( + True, + argstr='-e', + usedefault=True, + desc="Events (series/acq) in filename") + source_in_filename = traits.Bool( + False, argstr='-f', usedefault=True, desc="Source filename") + gzip_output = traits.Bool( + False, argstr='-g', usedefault=True, desc="Gzip output (.gz)") + id_in_filename = traits.Bool( + False, argstr='-i', usedefault=True, desc="ID in filename") + nii_output = traits.Bool( + True, + argstr='-n', + usedefault=True, + desc="Save as .nii - if no, create .hdr/.img pair") + output_dir = Directory( + exists=True, + argstr='-o %s', + genfile=True, + desc="Output dir - if unspecified, source directory is used") + protocol_in_filename = traits.Bool( + True, argstr='-p', usedefault=True, desc="Protocol in filename") + reorient = traits.Bool( + argstr='-r', desc="Reorient image to nearest orthogonal") + spm_analyze = traits.Bool( + argstr='-s', xor=['nii_output'], desc="SPM2/Analyze not SPM5/NIfTI") + convert_all_pars = traits.Bool( + True, + argstr='-v', + usedefault=True, + desc="Convert every image in directory") + reorient_and_crop = traits.Bool( + False, + argstr='-x', + usedefault=True, + desc="Reorient and crop 3D images") class Dcm2niiOutputSpec(TraitedSpec): @@ -96,10 +126,13 @@ class Dcm2nii(CommandLine): _cmd = 'dcm2nii' def _format_arg(self, opt, spec, val): - if opt in ['anonymize', 'collapse_folders', 'date_in_filename', 'events_in_filename', - 'source_in_filename', 'gzip_output', 'id_in_filename', 'nii_output', - 'protocol_in_filename', 'reorient', 'spm_analyze', 'convert_all_pars', - 'reorient_and_crop']: + if opt in [ + 'anonymize', 'collapse_folders', 'date_in_filename', + 'events_in_filename', 'source_in_filename', 'gzip_output', + 'id_in_filename', 'nii_output', 'protocol_in_filename', + 'reorient', 'spm_analyze', 'convert_all_pars', + 'reorient_and_crop' + ]: spec = deepcopy(spec) if val: spec.argstr += ' y' @@ -113,10 +146,9 @@ def _format_arg(self, opt, spec, val): def _run_interface(self, runtime): self._config_created = False new_runtime = super(Dcm2nii, self)._run_interface(runtime) - (self.output_files, - self.reoriented_files, - self.reoriented_and_cropped_files, - self.bvecs, self.bvals) = self._parse_stdout(new_runtime.stdout) + (self.output_files, self.reoriented_files, + self.reoriented_and_cropped_files, self.bvecs, + self.bvals) = self._parse_stdout(new_runtime.stdout) if self._config_created: os.remove('config.ini') return new_runtime @@ -137,7 +169,8 @@ def _parse_stdout(self, stdout): elif line.startswith("GZip..."): # for gzipped output files are not absolute fname = line[len("GZip..."):] - if len(files) and os.path.basename(files[-1]) == fname[:-3]: + if len(files) and os.path.basename( + files[-1]) == fname[:-3]: # we are seeing a previously reported conversion # as being saved in gzipped form -- remove the # obsolete, uncompressed file @@ -158,7 +191,7 @@ def _parse_stdout(self, stdout): for l in (bvecs, bvals): l[-1] = os.path.join( os.path.dirname(l[-1]), - 'x%s' % (os.path.basename(l[-1]),)) + 'x%s' % (os.path.basename(l[-1]), )) elif re.search('.*->(.*)', line): val = re.search('.*->(.*)', line) val = val.groups()[0] @@ -171,7 +204,7 @@ def _parse_stdout(self, stdout): out_file = val if out_file: - if not out_file in files: + if out_file not in files: files.append(out_file) last_added_file = out_file continue @@ -181,11 +214,14 @@ def _parse_stdout(self, stdout): skip = True continue elif line.startswith("Cropping NIfTI/Analyze image "): - base, filename = os.path.split(line[len("Cropping NIfTI/Analyze image "):]) + base, filename = os.path.split( + line[len("Cropping NIfTI/Analyze image "):]) filename = "c" + filename - if os.path.exists(os.path.join(base, filename)) or self.inputs.reorient_and_crop: + if os.path.exists(os.path.join( + base, filename)) or self.inputs.reorient_and_crop: # if reorient&crop is true but the file doesn't exist, this errors when setting outputs - reoriented_and_cropped_files.append(os.path.join(base, filename)) + reoriented_and_cropped_files.append( + os.path.join(base, filename)) skip = True continue @@ -196,7 +232,8 @@ def _list_outputs(self): outputs = self.output_spec().get() outputs['converted_files'] = self.output_files outputs['reoriented_files'] = self.reoriented_files - outputs['reoriented_and_cropped_files'] = self.reoriented_and_cropped_files + outputs[ + 'reoriented_and_cropped_files'] = self.reoriented_and_cropped_files outputs['bvecs'] = self.bvecs outputs['bvals'] = self.bvals return outputs @@ -215,28 +252,49 @@ def _gen_filename(self, name): class Dcm2niixInputSpec(CommandLineInputSpec): - source_names = InputMultiPath(File(exists=True), argstr="%s", position=-1, - copyfile=False, mandatory=True, xor=['source_dir']) - source_dir = Directory(exists=True, argstr="%s", position=-1, mandatory=True, - xor=['source_names']) - out_filename = traits.Str('%t%p', argstr="-f %s", usedefault=True, - desc="Output filename") - output_dir = Directory(exists=True, argstr='-o %s', genfile=True, - desc="Output directory") - bids_format = traits.Bool(True, argstr='-b', usedefault=True, - desc="Create a BIDS sidecar file") - compress = traits.Enum('i', ['y','i','n'], argstr='-z %s', usedefault=True, - desc="Gzip compress images - [y=pigz, i=internal, n=no]") - merge_imgs = traits.Bool(False, argstr='-m', usedefault=True, - desc="merge 2D slices from same series") - single_file = traits.Bool(False, argstr='-s', usedefault=True, - desc="Convert only one image (filename as last input") - verbose = traits.Bool(False, argstr='-v', usedefault=True, - desc="Verbose output") - crop = traits.Bool(False, argstr='-x', usedefault=True, - desc="Crop 3D T1 acquisitions") - has_private = traits.Bool(False, argstr='-t', usedefault=True, - desc="Flag if text notes includes private patient details") + source_names = InputMultiPath( + File(exists=True), + argstr="%s", + position=-1, + copyfile=False, + mandatory=True, + xor=['source_dir']) + source_dir = Directory( + exists=True, + argstr="%s", + position=-1, + mandatory=True, + xor=['source_names']) + out_filename = traits.Str( + '%t%p', argstr="-f %s", usedefault=True, desc="Output filename") + output_dir = Directory( + exists=True, argstr='-o %s', genfile=True, desc="Output directory") + bids_format = traits.Bool( + True, argstr='-b', usedefault=True, desc="Create a BIDS sidecar file") + compress = traits.Enum( + 'i', ['y', 'i', 'n'], + argstr='-z %s', + usedefault=True, + desc="Gzip compress images - [y=pigz, i=internal, n=no]") + merge_imgs = traits.Bool( + False, + argstr='-m', + usedefault=True, + desc="merge 2D slices from same series") + single_file = traits.Bool( + False, + argstr='-s', + usedefault=True, + desc="Convert only one image (filename as last input") + verbose = traits.Bool( + False, argstr='-v', usedefault=True, desc="Verbose output") + crop = traits.Bool( + False, argstr='-x', usedefault=True, desc="Crop 3D T1 acquisitions") + has_private = traits.Bool( + False, + argstr='-t', + usedefault=True, + desc="Flag if text notes includes private patient details") class Dcm2niixOutputSpec(TraitedSpec): @@ -271,8 +329,10 @@ class Dcm2niix(CommandLine): _cmd = 'dcm2niix' def _format_arg(self, opt, spec, val): - if opt in ['bids_format', 'merge_imgs', 'single_file', 'verbose', 'crop', - 'has_private']: + if opt in [ + 'bids_format', 'merge_imgs', 'single_file', 'verbose', 'crop', + 'has_private' + ]: spec = deepcopy(spec) if val: spec.argstr += ' y' @@ -286,11 +346,11 @@ def _format_arg(self, opt, spec, val): def _run_interface(self, runtime): new_runtime = super(Dcm2niix, self)._run_interface(runtime) if self.inputs.bids_format: - (self.output_files, self.bvecs, - self.bvals, self.bids) = self._parse_stdout(new_runtime.stdout) + (self.output_files, self.bvecs, self.bvals, + self.bids) = self._parse_stdout(new_runtime.stdout) else: - (self.output_files, self.bvecs, - self.bvals) = self._parse_stdout(new_runtime.stdout) + (self.output_files, self.bvecs, self.bvals) = self._parse_stdout( + new_runtime.stdout) return new_runtime def _parse_stdout(self, stdout): @@ -303,7 +363,7 @@ def _parse_stdout(self, stdout): for line in stdout.split("\n"): if not skip: out_file = None - if line.startswith("Convert "): # output + if line.startswith("Convert "): # output fname = str(re.search('\S+/\S+', line).group(0)) if isdefined(self.inputs.output_dir): output_dir = self.inputs.output_dir diff --git a/nipype/interfaces/dcmstack.py b/nipype/interfaces/dcmstack.py index 9e49f2b326..80a26365f1 100644 --- a/nipype/interfaces/dcmstack.py +++ b/nipype/interfaces/dcmstack.py @@ -8,7 +8,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from os import path as op @@ -19,15 +20,10 @@ import nibabel as nb import imghdr -from .base import ( - TraitedSpec, DynamicTraitedSpec, - InputMultiPath, File, Directory, - traits, BaseInterface, - isdefined, Undefined -) +from .base import (TraitedSpec, DynamicTraitedSpec, InputMultiPath, File, + Directory, traits, BaseInterface, isdefined, Undefined) from ..utils import NUMPY_MMAP - have_dcmstack = True try: import dicom @@ -50,14 +46,16 @@ def sanitize_path_comp(path_comp): class NiftiGeneratorBaseInputSpec(TraitedSpec): out_format = traits.Str(desc="String which can be formatted with " "meta data to create the output filename(s)") - out_ext = traits.Str('.nii.gz', usedefault=True, - desc="Determines output file type") - out_path = Directory(desc='output path, current working directory if not set') + out_ext = traits.Str( + '.nii.gz', usedefault=True, desc="Determines output file type") + out_path = Directory( + desc='output path, current working directory if not set') class NiftiGeneratorBase(BaseInterface): '''Base class for interfaces that produce Nifti files, potentially with embedded meta data.''' + def _get_out_path(self, meta, idx=None): '''Return the output path for the gernerated Nifti.''' if self.inputs.out_format: @@ -97,17 +95,20 @@ def _get_out_path(self, meta, idx=None): class DcmStackInputSpec(NiftiGeneratorBaseInputSpec): - dicom_files = traits.Either(InputMultiPath(File(exists=True)), - Directory(exists=True), - traits.Str(), - mandatory=True) + dicom_files = traits.Either( + InputMultiPath(File(exists=True)), + Directory(exists=True), + traits.Str(), + mandatory=True) embed_meta = traits.Bool(desc="Embed DICOM meta data into result") exclude_regexes = traits.List(desc="Meta data to exclude, suplementing " "any default exclude filters") include_regexes = traits.List(desc="Meta data to include, overriding any " "exclude filters") - force_read = traits.Bool(True, usedefault=True, - desc=('Force reading files without DICM marker')) + force_read = traits.Bool( + True, + usedefault=True, + desc=('Force reading files without DICM marker')) class DcmStackOutputSpec(TraitedSpec): @@ -153,7 +154,8 @@ def _run_interface(self, runtime): stack = dcmstack.DicomStack(meta_filter=meta_filter) for src_path in src_paths: if not imghdr.what(src_path) == "gif": - src_dcm = dicom.read_file(src_path, force=self.inputs.force_read) + src_dcm = dicom.read_file( + src_path, force=self.inputs.force_read) stack.add_dcm(src_dcm) nii = stack.to_nifti(embed_meta=True) nw = NiftiWrapper(nii) @@ -203,16 +205,15 @@ def _list_outputs(self): class LookupMetaInputSpec(TraitedSpec): - in_file = File(mandatory=True, - exists=True, - desc='The input Nifti file') - meta_keys = traits.Either(traits.List(), - traits.Dict(), - mandatory=True, - desc=("List of meta data keys to lookup, or a " - "dict where keys specify the meta data keys to " - "lookup and the values specify the output names") - ) + in_file = File(mandatory=True, exists=True, desc='The input Nifti file') + meta_keys = traits.Either( + traits.List(), + traits.Dict(), + mandatory=True, + desc=("List of meta data keys to lookup, or a " + "dict where keys specify the meta data " + "keys to lookup and the values specify " + "the output names")) class LookupMeta(BaseInterface): @@ -299,26 +300,26 @@ def _run_interface(self, runtime): dest = NiftiWrapper(dest_nii, make_empty=True) classes = src.meta_ext.get_valid_classes() if self.inputs.include_classes: - classes = [cls - for cls in classes - if cls in self.inputs.include_classes - ] + classes = [ + cls for cls in classes if cls in self.inputs.include_classes + ] if self.inputs.exclude_classes: - classes = [cls - for cls in classes - if cls not in self.inputs.exclude_classes - ] + classes = [ + cls for cls in classes + if cls not in self.inputs.exclude_classes + ] for cls in classes: src_dict = src.meta_ext.get_class_dict(cls) dest_dict = dest.meta_ext.get_class_dict(cls) dest_dict.update(src_dict) - # Update the shape and slice dimension to reflect the meta extension update. + # Update the shape and slice dimension to reflect the meta extension + # update. dest.meta_ext.slice_dim = src.meta_ext.slice_dim dest.meta_ext.shape = src.meta_ext.shape - self.out_path = op.join(os.getcwd(), - op.basename(self.inputs.dest_file)) + self.out_path = op.join(os.getcwd(), op.basename( + self.inputs.dest_file)) dest.to_filename(self.out_path) return runtime @@ -330,12 +331,12 @@ def _list_outputs(self): class MergeNiftiInputSpec(NiftiGeneratorBaseInputSpec): - in_files = traits.List(mandatory=True, - desc="List of Nifti files to merge") - sort_order = traits.Either(traits.Str(), - traits.List(), - desc="One or more meta data keys to " - "sort files by.") + in_files = traits.List(mandatory=True, desc="List of Nifti files to merge") + sort_order = traits.Either( + traits.Str(), + traits.List(), + desc="One or more meta data keys to " + "sort files by.") merge_dim = traits.Int(desc="Dimension to merge along. If not " "specified, the last singular or " "non-existant dimension is used.") @@ -360,12 +361,8 @@ class MergeNifti(NiftiGeneratorBase): output_spec = MergeNiftiOutputSpec def _run_interface(self, runtime): - niis = [nb.load(fn, mmap=NUMPY_MMAP) - for fn in self.inputs.in_files - ] - nws = [NiftiWrapper(nii, make_empty=True) - for nii in niis - ] + niis = [nb.load(fn, mmap=NUMPY_MMAP) for fn in self.inputs.in_files] + nws = [NiftiWrapper(nii, make_empty=True) for nii in niis] if self.inputs.sort_order: sort_order = self.inputs.sort_order if isinstance(sort_order, (str, bytes)): @@ -394,8 +391,7 @@ class SplitNiftiInputSpec(NiftiGeneratorBaseInputSpec): class SplitNiftiOutputSpec(TraitedSpec): - out_list = traits.List(File(exists=True), - desc="Split Nifti files") + out_list = traits.List(File(exists=True), desc="Split Nifti files") class SplitNifti(NiftiGeneratorBase): diff --git a/nipype/interfaces/diffusion_toolkit/base.py b/nipype/interfaces/diffusion_toolkit/base.py index 0e3c5a400a..c8e3a17c61 100644 --- a/nipype/interfaces/diffusion_toolkit/base.py +++ b/nipype/interfaces/diffusion_toolkit/base.py @@ -13,7 +13,8 @@ See the docstrings for the individual classes for 'working' examples. """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object import re from ..base import CommandLine @@ -47,8 +48,8 @@ def version(): Version number as string or None if FSL not found """ - clout = CommandLine(command='dti_recon', - terminal_output='allatonce').run() + clout = CommandLine( + command='dti_recon', terminal_output='allatonce').run() if clout.runtime.returncode is not 0: return None diff --git a/nipype/interfaces/diffusion_toolkit/dti.py b/nipype/interfaces/diffusion_toolkit/dti.py index ead0e222c6..8881c109a1 100644 --- a/nipype/interfaces/diffusion_toolkit/dti.py +++ b/nipype/interfaces/diffusion_toolkit/dti.py @@ -10,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, open import os @@ -22,27 +23,55 @@ __docformat__ = 'restructuredtext' + class DTIReconInputSpec(CommandLineInputSpec): - DWI = File(desc='Input diffusion volume', argstr='%s', exists=True, mandatory=True, position=1) - out_prefix = traits.Str("dti", desc='Output file prefix', argstr='%s', usedefault=True, position=2) - output_type = traits.Enum('nii', 'analyze', 'ni1', 'nii.gz', argstr='-ot %s', desc='output file type', usedefault=True) - bvecs = File(exists=True, desc='b vectors file', - argstr='-gm %s', mandatory=True) + DWI = File( + desc='Input diffusion volume', + argstr='%s', + exists=True, + mandatory=True, + position=1) + out_prefix = traits.Str( + "dti", + desc='Output file prefix', + argstr='%s', + usedefault=True, + position=2) + output_type = traits.Enum( + 'nii', + 'analyze', + 'ni1', + 'nii.gz', + argstr='-ot %s', + desc='output file type', + usedefault=True) + bvecs = File( + exists=True, desc='b vectors file', argstr='-gm %s', mandatory=True) bvals = File(exists=True, desc='b values file', mandatory=True) n_averages = traits.Int(desc='Number of averages', argstr='-nex %s') - image_orientation_vectors = traits.List(traits.Float(), minlen=6, maxlen=6, desc="""specify image orientation vectors. if just one argument given, + image_orientation_vectors = traits.List( + traits.Float(), + minlen=6, + maxlen=6, + desc="""specify image orientation vectors. if just one argument given, will treat it as filename and read the orientation vectors from the file. if 6 arguments are given, will treat them as 6 float numbers and construct the 1st and 2nd vector and calculate the 3rd one automatically. this information will be used to determine image orientation, - as well as to adjust gradient vectors with oblique angle when""", argstr="-iop %f") - oblique_correction = traits.Bool(desc="""when oblique angle(s) applied, some SIEMENS dti protocols do not + as well as to adjust gradient vectors with oblique angle when""", + argstr="-iop %f") + oblique_correction = traits.Bool( + desc="""when oblique angle(s) applied, some SIEMENS dti protocols do not adjust gradient accordingly, thus it requires adjustment for correct - diffusion tensor calculation""", argstr="-oc") - b0_threshold = traits.Float(desc="""program will use b0 image with the given threshold to mask out high + diffusion tensor calculation""", + argstr="-oc") + b0_threshold = traits.Float( + desc= + """program will use b0 image with the given threshold to mask out high background of fa/adc maps. by default it will calculate threshold - automatically. but if it failed, you need to set it manually.""", argstr="-b0_th") + automatically. but if it failed, you need to set it manually.""", + argstr="-b0_th") class DTIReconOutputSpec(TraitedSpec): @@ -74,18 +103,30 @@ def _create_gradient_matrix(self, bvecs_file, bvals_file): with open(bvals_file) as fbvals: bvals = [val for val in re.split('\s+', fbvals.readline().strip())] with open(bvecs_file) as fbvecs: - bvecs_y = [val for val in re.split('\s+', fbvecs.readline().strip())] - bvecs_z = [val for val in re.split('\s+', fbvecs.readline().strip())] - bvecs_x = [val for val in re.split('\s+', fbvecs.readline().strip())] + bvecs_y = [ + val for val in re.split('\s+', + fbvecs.readline().strip()) + ] + bvecs_z = [ + val for val in re.split('\s+', + fbvecs.readline().strip()) + ] + bvecs_x = [ + val for val in re.split('\s+', + fbvecs.readline().strip()) + ] with open(_gradient_matrix_file, 'w') as gradient_matrix_f: for i in range(len(bvals)): - gradient_matrix_f.write("%s, %s, %s, %s\n" % (bvecs_x[i], bvecs_y[i], bvecs_z[i], bvals[i])) + gradient_matrix_f.write("%s, %s, %s, %s\n" % + (bvecs_x[i], bvecs_y[i], bvecs_z[i], + bvals[i])) return _gradient_matrix_file def _format_arg(self, name, spec, value): if name == "bvecs": - new_val = self._create_gradient_matrix(self.inputs.bvecs, self.inputs.bvals) + new_val = self._create_gradient_matrix(self.inputs.bvecs, + self.inputs.bvals) return super(DTIRecon, self)._format_arg("bvecs", spec, new_val) return super(DTIRecon, self)._format_arg(name, spec, value) @@ -94,58 +135,132 @@ def _list_outputs(self): output_type = self.inputs.output_type outputs = self.output_spec().get() - outputs['ADC'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_adc.' + output_type)) - outputs['B0'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_b0.' + output_type)) - outputs['L1'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_e1.' + output_type)) - outputs['L2'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_e2.' + output_type)) - outputs['L3'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_e3.' + output_type)) - outputs['exp'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_exp.' + output_type)) - outputs['FA'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_fa.' + output_type)) - outputs['FA_color'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_fa_color.' + output_type)) - outputs['tensor'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_tensor.' + output_type)) - outputs['V1'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_v1.' + output_type)) - outputs['V2'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_v2.' + output_type)) - outputs['V3'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_v3.' + output_type)) + outputs['ADC'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_adc.' + output_type)) + outputs['B0'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_b0.' + output_type)) + outputs['L1'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_e1.' + output_type)) + outputs['L2'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_e2.' + output_type)) + outputs['L3'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_e3.' + output_type)) + outputs['exp'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_exp.' + output_type)) + outputs['FA'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_fa.' + output_type)) + outputs['FA_color'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_fa_color.' + output_type)) + outputs['tensor'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_tensor.' + output_type)) + outputs['V1'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_v1.' + output_type)) + outputs['V2'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_v2.' + output_type)) + outputs['V3'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_v3.' + output_type)) return outputs class DTITrackerInputSpec(CommandLineInputSpec): tensor_file = File(exists=True, desc="reconstructed tensor file") - input_type = traits.Enum('nii', 'analyze', 'ni1', 'nii.gz', desc="""input and output file type. accepted values are: + input_type = traits.Enum( + 'nii', + 'analyze', + 'ni1', + 'nii.gz', + desc="""input and output file type. accepted values are: analyze -> analyze format 7.5 ni1 -> nifti format saved in seperate .hdr and .img file nii -> nifti format with one .nii file nii.gz -> nifti format with compression - default type is 'nii'""", argstr="-it %s") - tracking_method = traits.Enum('fact', 'rk2', 'tl', 'sl', desc="""fact -> use FACT method for tracking. this is the default method. + default type is 'nii'""", + argstr="-it %s") + tracking_method = traits.Enum( + 'fact', + 'rk2', + 'tl', + 'sl', + desc="""fact -> use FACT method for tracking. this is the default method. rk2 -> use 2nd order runge-kutta method for tracking. tl -> use tensorline method for tracking. - sl -> use interpolated streamline method with fixed step-length""", argstr="-%s") - step_length = traits.Float(desc="""set step length, in the unit of minimum voxel size. + sl -> use interpolated streamline method with fixed step-length""", + argstr="-%s") + step_length = traits.Float( + desc="""set step length, in the unit of minimum voxel size. default value is 0.5 for interpolated streamline method - and 0.1 for other methods""", argstr="-l %f") - angle_threshold = traits.Float(desc="set angle threshold. default value is 35 degree", argstr="-at %f") - angle_threshold_weight = traits.Float(desc="set angle threshold weighting factor. weighting will be be applied \ - on top of the angle_threshold", argstr="-atw %f") - random_seed = traits.Int(desc="use random location in a voxel instead of the center of the voxel \ - to seed. can also define number of seed per voxel. default is 1", argstr="-rseed %d") - invert_x = traits.Bool(desc="invert x component of the vector", argstr="-ix") - invert_y = traits.Bool(desc="invert y component of the vector", argstr="-iy") - invert_z = traits.Bool(desc="invert z component of the vector", argstr="-iz") - swap_xy = traits.Bool(desc="swap x & y vectors while tracking", argstr="-sxy") - swap_yz = traits.Bool(desc="swap y & z vectors while tracking", argstr="-syz") - swap_zx = traits.Bool(desc="swap x & z vectors while tracking", argstr="-szx") - mask1_file = File(desc="first mask image", mandatory=True, argstr="-m %s", position=2) - mask1_threshold = traits.Float(desc="threshold value for the first mask image, if not given, the program will \ - try automatically find the threshold", position=3) + and 0.1 for other methods""", + argstr="-l %f") + angle_threshold = traits.Float( + desc="set angle threshold. default value is 35 degree", + argstr="-at %f") + angle_threshold_weight = traits.Float( + desc= + "set angle threshold weighting factor. weighting will be be applied \ + on top of the angle_threshold", + argstr="-atw %f") + random_seed = traits.Int( + desc="use random location in a voxel instead of the center of the voxel \ + to seed. can also define number of seed per voxel. default is 1", + argstr="-rseed %d") + invert_x = traits.Bool( + desc="invert x component of the vector", argstr="-ix") + invert_y = traits.Bool( + desc="invert y component of the vector", argstr="-iy") + invert_z = traits.Bool( + desc="invert z component of the vector", argstr="-iz") + swap_xy = traits.Bool( + desc="swap x & y vectors while tracking", argstr="-sxy") + swap_yz = traits.Bool( + desc="swap y & z vectors while tracking", argstr="-syz") + swap_zx = traits.Bool( + desc="swap x & z vectors while tracking", argstr="-szx") + mask1_file = File( + desc="first mask image", mandatory=True, argstr="-m %s", position=2) + mask1_threshold = traits.Float( + desc= + "threshold value for the first mask image, if not given, the program will \ + try automatically find the threshold", + position=3) mask2_file = File(desc="second mask image", argstr="-m2 %s", position=4) - mask2_threshold = traits.Float(desc="threshold value for the second mask image, if not given, the program will \ - try automatically find the threshold", position=5) - input_data_prefix = traits.Str("dti", desc="for internal naming use only", position=0, argstr="%s", usedefault=True) - output_file = File("tracks.trk", "file containing tracks", argstr="%s", position=1, usedefault=True) - output_mask = File(desc="output a binary mask file in analyze format", argstr="-om %s") - primary_vector = traits.Enum('v2', 'v3', desc="which vector to use for fibre tracking: v2 or v3. If not set use v1", argstr="-%s") + mask2_threshold = traits.Float( + desc= + "threshold value for the second mask image, if not given, the program will \ + try automatically find the threshold", + position=5) + input_data_prefix = traits.Str( + "dti", + desc="for internal naming use only", + position=0, + argstr="%s", + usedefault=True) + output_file = File( + "tracks.trk", + "file containing tracks", + argstr="%s", + position=1, + usedefault=True) + output_mask = File( + desc="output a binary mask file in analyze format", argstr="-om %s") + primary_vector = traits.Enum( + 'v2', + 'v3', + desc= + "which vector to use for fibre tracking: v2 or v3. If not set use v1", + argstr="-%s") class DTITrackerOutputSpec(TraitedSpec): @@ -161,7 +276,10 @@ class DTITracker(CommandLine): def _run_interface(self, runtime): _, _, ext = split_filename(self.inputs.tensor_file) - copyfile(self.inputs.tensor_file, os.path.abspath(self.inputs.input_data_prefix + "_tensor" + ext), copy=False) + copyfile( + self.inputs.tensor_file, + os.path.abspath(self.inputs.input_data_prefix + "_tensor" + ext), + copy=False) return super(DTITracker, self)._run_interface(runtime) diff --git a/nipype/interfaces/diffusion_toolkit/odf.py b/nipype/interfaces/diffusion_toolkit/odf.py index ee7933f64c..c289adeb01 100644 --- a/nipype/interfaces/diffusion_toolkit/odf.py +++ b/nipype/interfaces/diffusion_toolkit/odf.py @@ -10,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range import os @@ -22,35 +23,66 @@ __docformat__ = 'restructuredtext' + class HARDIMatInputSpec(CommandLineInputSpec): - bvecs = File(exists=True, desc='b vectors file', - argstr='%s', position=1, mandatory=True) + bvecs = File( + exists=True, + desc='b vectors file', + argstr='%s', + position=1, + mandatory=True) bvals = File(exists=True, desc='b values file', mandatory=True) - out_file = File("recon_mat.dat", desc='output matrix file', argstr='%s', usedefault=True, position=2) - order = traits.Int(argstr='-order %s', desc="""maximum order of spherical harmonics. must be even number. default + out_file = File( + "recon_mat.dat", + desc='output matrix file', + argstr='%s', + usedefault=True, + position=2) + order = traits.Int( + argstr='-order %s', + desc= + """maximum order of spherical harmonics. must be even number. default is 4""") - odf_file = File(exists=True, argstr='-odf %s', desc="""filename that contains the reconstruction points on a HEMI-sphere. + odf_file = File( + exists=True, + argstr='-odf %s', + desc= + """filename that contains the reconstruction points on a HEMI-sphere. use the pre-set 181 points by default""") - reference_file = File(exists=True, argstr='-ref %s', desc="""provide a dicom or nifti image as the reference for the program to + reference_file = File( + exists=True, + argstr='-ref %s', + desc= + """provide a dicom or nifti image as the reference for the program to figure out the image orientation information. if no such info was found in the given image header, the next 5 options -info, etc., will be used if provided. if image orientation info can be found in the given reference, all other 5 image orientation options will be IGNORED""") - image_info = File(exists=True, argstr='-info %s', desc="""specify image information file. the image info file is generated + image_info = File( + exists=True, + argstr='-info %s', + desc="""specify image information file. the image info file is generated from original dicom image by diff_unpack program and contains image orientation and other information needed for reconstruction and tracking. by default will look into the image folder for .info file""") - image_orientation_vectors = traits.List(traits.Float(), minlen=6, maxlen=6, desc="""specify image orientation vectors. if just one argument given, + image_orientation_vectors = traits.List( + traits.Float(), + minlen=6, + maxlen=6, + desc="""specify image orientation vectors. if just one argument given, will treat it as filename and read the orientation vectors from the file. if 6 arguments are given, will treat them as 6 float numbers and construct the 1st and 2nd vector and calculate the 3rd one automatically. this information will be used to determine image orientation, - as well as to adjust gradient vectors with oblique angle when""", argstr="-iop %f") - oblique_correction = traits.Bool(desc="""when oblique angle(s) applied, some SIEMENS dti protocols do not + as well as to adjust gradient vectors with oblique angle when""", + argstr="-iop %f") + oblique_correction = traits.Bool( + desc="""when oblique angle(s) applied, some SIEMENS dti protocols do not adjust gradient accordingly, thus it requires adjustment for correct - diffusion tensor calculation""", argstr="-oc") + diffusion tensor calculation""", + argstr="-oc") class HARDIMatOutputSpec(TraitedSpec): @@ -67,7 +99,10 @@ class HARDIMat(CommandLine): def _create_gradient_matrix(self, bvecs_file, bvals_file): _gradient_matrix_file = 'gradient_matrix.txt' - bvals = [val for val in re.split('\s+', open(bvals_file).readline().strip())] + bvals = [ + val for val in re.split('\s+', + open(bvals_file).readline().strip()) + ] bvecs_f = open(bvecs_file) bvecs_x = [val for val in re.split('\s+', bvecs_f.readline().strip())] bvecs_y = [val for val in re.split('\s+', bvecs_f.readline().strip())] @@ -77,13 +112,15 @@ def _create_gradient_matrix(self, bvecs_file, bvals_file): for i in range(len(bvals)): if int(bvals[i]) == 0: continue - gradient_matrix_f.write("%s %s %s\n" % (bvecs_x[i], bvecs_y[i], bvecs_z[i])) + gradient_matrix_f.write("%s %s %s\n" % (bvecs_x[i], bvecs_y[i], + bvecs_z[i])) gradient_matrix_f.close() return _gradient_matrix_file def _format_arg(self, name, spec, value): if name == "bvecs": - new_val = self._create_gradient_matrix(self.inputs.bvecs, self.inputs.bvals) + new_val = self._create_gradient_matrix(self.inputs.bvecs, + self.inputs.bvals) return super(HARDIMat, self)._format_arg("bvecs", spec, new_val) return super(HARDIMat, self)._format_arg(name, spec, value) @@ -94,33 +131,75 @@ def _list_outputs(self): class ODFReconInputSpec(CommandLineInputSpec): - DWI = File(desc='Input raw data', argstr='%s', exists=True, mandatory=True, position=1) - n_directions = traits.Int(desc='Number of directions', argstr='%s', mandatory=True, position=2) - n_output_directions = traits.Int(desc='Number of output directions', argstr='%s', mandatory=True, position=3) - out_prefix = traits.Str("odf", desc='Output file prefix', argstr='%s', usedefault=True, position=4) - matrix = File(argstr='-mat %s', exists=True, desc="""use given file as reconstruction matrix.""", mandatory=True) - n_b0 = traits.Int(argstr='-b0 %s', desc="""number of b0 scans. by default the program gets this information + DWI = File( + desc='Input raw data', + argstr='%s', + exists=True, + mandatory=True, + position=1) + n_directions = traits.Int( + desc='Number of directions', argstr='%s', mandatory=True, position=2) + n_output_directions = traits.Int( + desc='Number of output directions', + argstr='%s', + mandatory=True, + position=3) + out_prefix = traits.Str( + "odf", + desc='Output file prefix', + argstr='%s', + usedefault=True, + position=4) + matrix = File( + argstr='-mat %s', + exists=True, + desc="""use given file as reconstruction matrix.""", + mandatory=True) + n_b0 = traits.Int( + argstr='-b0 %s', + desc="""number of b0 scans. by default the program gets this information from the number of directions and number of volumes in the raw data. useful when dealing with incomplete raw - data set or only using part of raw data set to reconstruct""", mandatory=True) - output_type = traits.Enum('nii', 'analyze', 'ni1', 'nii.gz', argstr='-ot %s', desc='output file type', usedefault=True) - sharpness = traits.Float(desc="""smooth or sharpen the raw data. factor > 0 is smoothing. + data set or only using part of raw data set to reconstruct""", + mandatory=True) + output_type = traits.Enum( + 'nii', + 'analyze', + 'ni1', + 'nii.gz', + argstr='-ot %s', + desc='output file type', + usedefault=True) + sharpness = traits.Float( + desc="""smooth or sharpen the raw data. factor > 0 is smoothing. factor < 0 is sharpening. default value is 0 - NOTE: this option applies to DSI study only""", argstr='-s %f') - filter = traits.Bool(desc="""apply a filter (e.g. high pass) to the raw image""", argstr='-f') - subtract_background = traits.Bool(desc="""subtract the background value before reconstruction""", argstr='-bg') + NOTE: this option applies to DSI study only""", + argstr='-s %f') + filter = traits.Bool( + desc="""apply a filter (e.g. high pass) to the raw image""", + argstr='-f') + subtract_background = traits.Bool( + desc="""subtract the background value before reconstruction""", + argstr='-bg') dsi = traits.Bool(desc="""indicates that the data is dsi""", argstr='-dsi') output_entropy = traits.Bool(desc="""output entropy map""", argstr='-oe') - image_orientation_vectors = traits.List(traits.Float(), minlen=6, maxlen=6, desc="""specify image orientation vectors. if just one argument given, + image_orientation_vectors = traits.List( + traits.Float(), + minlen=6, + maxlen=6, + desc="""specify image orientation vectors. if just one argument given, will treat it as filename and read the orientation vectors from the file. if 6 arguments are given, will treat them as 6 float numbers and construct the 1st and 2nd vector and calculate the 3rd one automatically. this information will be used to determine image orientation, - as well as to adjust gradient vectors with oblique angle when""", argstr="-iop %f") - oblique_correction = traits.Bool(desc="""when oblique angle(s) applied, some SIEMENS dti protocols do not + as well as to adjust gradient vectors with oblique angle when""", + argstr="-iop %f") + oblique_correction = traits.Bool( + desc="""when oblique angle(s) applied, some SIEMENS dti protocols do not adjust gradient accordingly, thus it requires adjustment for correct - diffusion tensor calculation""", argstr="-oc") + diffusion tensor calculation""", + argstr="-oc") class ODFReconOutputSpec(TraitedSpec): @@ -145,12 +224,22 @@ def _list_outputs(self): output_type = self.inputs.output_type outputs = self.output_spec().get() - outputs['B0'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_b0.' + output_type)) - outputs['DWI'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_dwi.' + output_type)) - outputs['max'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_max.' + output_type)) - outputs['ODF'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_odf.' + output_type)) + outputs['B0'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_b0.' + output_type)) + outputs['DWI'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_dwi.' + output_type)) + outputs['max'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_max.' + output_type)) + outputs['ODF'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_odf.' + output_type)) if isdefined(self.inputs.output_entropy): - outputs['entropy'] = os.path.abspath(fname_presuffix("", prefix=out_prefix, suffix='_entropy.' + output_type)) + outputs['entropy'] = os.path.abspath( + fname_presuffix( + "", prefix=out_prefix, suffix='_entropy.' + output_type)) return outputs @@ -158,45 +247,107 @@ def _list_outputs(self): class ODFTrackerInputSpec(CommandLineInputSpec): max = File(exists=True, mandatory=True) ODF = File(exists=True, mandatory=True) - input_data_prefix = traits.Str("odf", desc='recon data prefix', argstr='%s', usedefault=True, position=0) - out_file = File("tracks.trk", desc='output track file', argstr='%s', usedefault=True, position=1) - input_output_type = traits.Enum('nii', 'analyze', 'ni1', 'nii.gz', argstr='-it %s', desc='input and output file type', usedefault=True) - runge_kutta2 = traits.Bool(argstr='-rk2', desc="""use 2nd order runge-kutta method for tracking. + input_data_prefix = traits.Str( + "odf", + desc='recon data prefix', + argstr='%s', + usedefault=True, + position=0) + out_file = File( + "tracks.trk", + desc='output track file', + argstr='%s', + usedefault=True, + position=1) + input_output_type = traits.Enum( + 'nii', + 'analyze', + 'ni1', + 'nii.gz', + argstr='-it %s', + desc='input and output file type', + usedefault=True) + runge_kutta2 = traits.Bool( + argstr='-rk2', + desc="""use 2nd order runge-kutta method for tracking. default tracking method is non-interpolate streamline""") - step_length = traits.Float(argstr='-l %f', desc="""set step length, in the unit of minimum voxel size. + step_length = traits.Float( + argstr='-l %f', + desc="""set step length, in the unit of minimum voxel size. default value is 0.1.""") - angle_threshold = traits.Float(argstr='-at %f', desc="""set angle threshold. default value is 35 degree for + angle_threshold = traits.Float( + argstr='-at %f', + desc="""set angle threshold. default value is 35 degree for default tracking method and 25 for rk2""") - random_seed = traits.Int(argstr='-rseed %s', desc="""use random location in a voxel instead of the center of the voxel + random_seed = traits.Int( + argstr='-rseed %s', + desc="""use random location in a voxel instead of the center of the voxel to seed. can also define number of seed per voxel. default is 1""") - invert_x = traits.Bool(argstr='-ix', desc='invert x component of the vector') - invert_y = traits.Bool(argstr='-iy', desc='invert y component of the vector') - invert_z = traits.Bool(argstr='-iz', desc='invert z component of the vector') - swap_xy = traits.Bool(argstr='-sxy', desc='swap x and y vectors while tracking') - swap_yz = traits.Bool(argstr='-syz', desc='swap y and z vectors while tracking') - swap_zx = traits.Bool(argstr='-szx', desc='swap x and z vectors while tracking') + invert_x = traits.Bool( + argstr='-ix', desc='invert x component of the vector') + invert_y = traits.Bool( + argstr='-iy', desc='invert y component of the vector') + invert_z = traits.Bool( + argstr='-iz', desc='invert z component of the vector') + swap_xy = traits.Bool( + argstr='-sxy', desc='swap x and y vectors while tracking') + swap_yz = traits.Bool( + argstr='-syz', desc='swap y and z vectors while tracking') + swap_zx = traits.Bool( + argstr='-szx', desc='swap x and z vectors while tracking') disc = traits.Bool(argstr='-disc', desc='use disc tracking') - mask1_file = File(desc="first mask image", mandatory=True, argstr="-m %s", position=2) - mask1_threshold = traits.Float(desc="threshold value for the first mask image, if not given, the program will \ - try automatically find the threshold", position=3) + mask1_file = File( + desc="first mask image", mandatory=True, argstr="-m %s", position=2) + mask1_threshold = traits.Float( + desc= + "threshold value for the first mask image, if not given, the program will \ + try automatically find the threshold", + position=3) mask2_file = File(desc="second mask image", argstr="-m2 %s", position=4) - mask2_threshold = traits.Float(desc="threshold value for the second mask image, if not given, the program will \ - try automatically find the threshold", position=5) - limit = traits.Int(argstr='-limit %d', desc="""in some special case, such as heart data, some track may go into + mask2_threshold = traits.Float( + desc= + "threshold value for the second mask image, if not given, the program will \ + try automatically find the threshold", + position=5) + limit = traits.Int( + argstr='-limit %d', + desc="""in some special case, such as heart data, some track may go into infinite circle and take long time to stop. this option allows setting a limit for the longest tracking steps (voxels)""") - dsi = traits.Bool(argstr='-dsi', desc=""" specify the input odf data is dsi. because dsi recon uses fixed + dsi = traits.Bool( + argstr='-dsi', + desc=""" specify the input odf data is dsi. because dsi recon uses fixed pre-calculated matrix, some special orientation patch needs to be applied to keep dti/dsi/q-ball consistent.""") - image_orientation_vectors = traits.List(traits.Float(), minlen=6, maxlen=6, desc="""specify image orientation vectors. if just one argument given, + image_orientation_vectors = traits.List( + traits.Float(), + minlen=6, + maxlen=6, + desc="""specify image orientation vectors. if just one argument given, will treat it as filename and read the orientation vectors from the file. if 6 arguments are given, will treat them as 6 float numbers and construct the 1st and 2nd vector and calculate the 3rd one automatically. this information will be used to determine image orientation, - as well as to adjust gradient vectors with oblique angle when""", argstr="-iop %f") - slice_order = traits.Int(argstr='-sorder %d', desc='set the slice order. 1 means normal, -1 means reversed. default value is 1') - voxel_order = traits.Enum('RAS', 'RPS', 'RAI', 'RPI', 'LAI', 'LAS', 'LPS', 'LPI', argstr='-vorder %s', desc="""specify the voxel order in RL/AP/IS (human brain) reference. must be + as well as to adjust gradient vectors with oblique angle when""", + argstr="-iop %f") + slice_order = traits.Int( + argstr='-sorder %d', + desc= + 'set the slice order. 1 means normal, -1 means reversed. default value is 1' + ) + voxel_order = traits.Enum( + 'RAS', + 'RPS', + 'RAI', + 'RPI', + 'LAI', + 'LAS', + 'LPS', + 'LPI', + argstr='-vorder %s', + desc= + """specify the voxel order in RL/AP/IS (human brain) reference. must be 3 letters with no space in between. for example, RAS means the voxel row is from L->R, the column is from P->A and the slice order is from I->S. @@ -224,10 +375,16 @@ class ODFTracker(CommandLine): def _run_interface(self, runtime): _, _, ext = split_filename(self.inputs.max) - copyfile(self.inputs.max, os.path.abspath(self.inputs.input_data_prefix + "_max" + ext), copy=False) + copyfile( + self.inputs.max, + os.path.abspath(self.inputs.input_data_prefix + "_max" + ext), + copy=False) _, _, ext = split_filename(self.inputs.ODF) - copyfile(self.inputs.ODF, os.path.abspath(self.inputs.input_data_prefix + "_odf" + ext), copy=False) + copyfile( + self.inputs.ODF, + os.path.abspath(self.inputs.input_data_prefix + "_odf" + ext), + copy=False) return super(ODFTracker, self)._run_interface(runtime) diff --git a/nipype/interfaces/diffusion_toolkit/postproc.py b/nipype/interfaces/diffusion_toolkit/postproc.py index 4a14d96b90..3536cc2643 100644 --- a/nipype/interfaces/diffusion_toolkit/postproc.py +++ b/nipype/interfaces/diffusion_toolkit/postproc.py @@ -10,18 +10,34 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os -from ..base import (TraitedSpec, File, traits, CommandLine, - InputMultiPath, CommandLineInputSpec) +from ..base import (TraitedSpec, File, traits, CommandLine, InputMultiPath, + CommandLineInputSpec) __docformat__ = 'restructuredtext' + class SplineFilterInputSpec(CommandLineInputSpec): - track_file = File(exists=True, desc="file containing tracks to be filtered", position=0, argstr="%s", mandatory=True) - step_length = traits.Float(desc="in the unit of minimum voxel size", position=1, argstr="%f", mandatory=True) - output_file = File("spline_tracks.trk", desc="target file for smoothed tracks", position=2, argstr="%s", usedefault=True) + track_file = File( + exists=True, + desc="file containing tracks to be filtered", + position=0, + argstr="%s", + mandatory=True) + step_length = traits.Float( + desc="in the unit of minimum voxel size", + position=1, + argstr="%f", + mandatory=True) + output_file = File( + "spline_tracks.trk", + desc="target file for smoothed tracks", + position=2, + argstr="%s", + usedefault=True) class SplineFilterOutputSpec(TraitedSpec): @@ -53,13 +69,24 @@ class SplineFilter(CommandLine): def _list_outputs(self): outputs = self.output_spec().get() - outputs['smoothed_track_file'] = os.path.abspath(self.inputs.output_file) + outputs['smoothed_track_file'] = os.path.abspath( + self.inputs.output_file) return outputs class TrackMergeInputSpec(CommandLineInputSpec): - track_files = InputMultiPath(File(exists=True), desc="file containing tracks to be filtered", position=0, argstr="%s...", mandatory=True) - output_file = File("merged_tracks.trk", desc="target file for merged tracks", position=-1, argstr="%s", usedefault=True) + track_files = InputMultiPath( + File(exists=True), + desc="file containing tracks to be filtered", + position=0, + argstr="%s...", + mandatory=True) + output_file = File( + "merged_tracks.trk", + desc="target file for merged tracks", + position=-1, + argstr="%s", + usedefault=True) class TrackMergeOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py index 569f1ac79f..267b57fabf 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py @@ -4,63 +4,64 @@ def test_DTIRecon_inputs(): - input_map = dict(DWI=dict(argstr='%s', - mandatory=True, - position=1, - ), - args=dict(argstr='%s', - ), - b0_threshold=dict(argstr='-b0_th', - ), - bvals=dict(mandatory=True, - ), - bvecs=dict(argstr='-gm %s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_orientation_vectors=dict(argstr='-iop %f', - ), - n_averages=dict(argstr='-nex %s', - ), - oblique_correction=dict(argstr='-oc', - ), - out_prefix=dict(argstr='%s', - position=2, - usedefault=True, - ), - output_type=dict(argstr='-ot %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + DWI=dict( + argstr='%s', + mandatory=True, + position=1, + ), + args=dict(argstr='%s', ), + b0_threshold=dict(argstr='-b0_th', ), + bvals=dict(mandatory=True, ), + bvecs=dict( + argstr='-gm %s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_orientation_vectors=dict(argstr='-iop %f', ), + n_averages=dict(argstr='-nex %s', ), + oblique_correction=dict(argstr='-oc', ), + out_prefix=dict( + argstr='%s', + position=2, + usedefault=True, + ), + output_type=dict( + argstr='-ot %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DTIRecon.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTIRecon_outputs(): - output_map = dict(ADC=dict(), - B0=dict(), - FA=dict(), - FA_color=dict(), - L1=dict(), - L2=dict(), - L3=dict(), - V1=dict(), - V2=dict(), - V3=dict(), - exp=dict(), - tensor=dict(), + output_map = dict( + ADC=dict(), + B0=dict(), + FA=dict(), + FA_color=dict(), + L1=dict(), + L2=dict(), + L3=dict(), + V1=dict(), + V2=dict(), + V3=dict(), + exp=dict(), + tensor=dict(), ) outputs = DTIRecon.output_spec() diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py index 0a0a66ffb1..ded73b8372 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py @@ -4,77 +4,67 @@ def test_DTITracker_inputs(): - input_map = dict(angle_threshold=dict(argstr='-at %f', - ), - angle_threshold_weight=dict(argstr='-atw %f', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_data_prefix=dict(argstr='%s', - position=0, - usedefault=True, - ), - input_type=dict(argstr='-it %s', - ), - invert_x=dict(argstr='-ix', - ), - invert_y=dict(argstr='-iy', - ), - invert_z=dict(argstr='-iz', - ), - mask1_file=dict(argstr='-m %s', - mandatory=True, - position=2, - ), - mask1_threshold=dict(position=3, - ), - mask2_file=dict(argstr='-m2 %s', - position=4, - ), - mask2_threshold=dict(position=5, - ), - output_file=dict(argstr='%s', - position=1, - usedefault=True, - ), - output_mask=dict(argstr='-om %s', - ), - primary_vector=dict(argstr='-%s', - ), - random_seed=dict(argstr='-rseed %d', - ), - step_length=dict(argstr='-l %f', - ), - swap_xy=dict(argstr='-sxy', - ), - swap_yz=dict(argstr='-syz', - ), - swap_zx=dict(argstr='-szx', - ), - tensor_file=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracking_method=dict(argstr='-%s', - ), + input_map = dict( + angle_threshold=dict(argstr='-at %f', ), + angle_threshold_weight=dict(argstr='-atw %f', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_data_prefix=dict( + argstr='%s', + position=0, + usedefault=True, + ), + input_type=dict(argstr='-it %s', ), + invert_x=dict(argstr='-ix', ), + invert_y=dict(argstr='-iy', ), + invert_z=dict(argstr='-iz', ), + mask1_file=dict( + argstr='-m %s', + mandatory=True, + position=2, + ), + mask1_threshold=dict(position=3, ), + mask2_file=dict( + argstr='-m2 %s', + position=4, + ), + mask2_threshold=dict(position=5, ), + output_file=dict( + argstr='%s', + position=1, + usedefault=True, + ), + output_mask=dict(argstr='-om %s', ), + primary_vector=dict(argstr='-%s', ), + random_seed=dict(argstr='-rseed %d', ), + step_length=dict(argstr='-l %f', ), + swap_xy=dict(argstr='-sxy', ), + swap_yz=dict(argstr='-syz', ), + swap_zx=dict(argstr='-szx', ), + tensor_file=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracking_method=dict(argstr='-%s', ), ) inputs = DTITracker.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTITracker_outputs(): - output_map = dict(mask_file=dict(), - track_file=dict(), + output_map = dict( + mask_file=dict(), + track_file=dict(), ) outputs = DTITracker.output_spec() diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py index d85c9558de..565e606eb0 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py @@ -4,51 +4,46 @@ def test_HARDIMat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bvals=dict(mandatory=True, - ), - bvecs=dict(argstr='%s', - mandatory=True, - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_info=dict(argstr='-info %s', - ), - image_orientation_vectors=dict(argstr='-iop %f', - ), - oblique_correction=dict(argstr='-oc', - ), - odf_file=dict(argstr='-odf %s', - ), - order=dict(argstr='-order %s', - ), - out_file=dict(argstr='%s', - position=2, - usedefault=True, - ), - reference_file=dict(argstr='-ref %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bvals=dict(mandatory=True, ), + bvecs=dict( + argstr='%s', + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_info=dict(argstr='-info %s', ), + image_orientation_vectors=dict(argstr='-iop %f', ), + oblique_correction=dict(argstr='-oc', ), + odf_file=dict(argstr='-odf %s', ), + order=dict(argstr='-order %s', ), + out_file=dict( + argstr='%s', + position=2, + usedefault=True, + ), + reference_file=dict(argstr='-ref %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = HARDIMat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_HARDIMat_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = HARDIMat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py index f4d116561e..1e25ac5a75 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py @@ -4,71 +4,73 @@ def test_ODFRecon_inputs(): - input_map = dict(DWI=dict(argstr='%s', - mandatory=True, - position=1, - ), - args=dict(argstr='%s', - ), - dsi=dict(argstr='-dsi', - ), - environ=dict(nohash=True, - usedefault=True, - ), - filter=dict(argstr='-f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_orientation_vectors=dict(argstr='-iop %f', - ), - matrix=dict(argstr='-mat %s', - mandatory=True, - ), - n_b0=dict(argstr='-b0 %s', - mandatory=True, - ), - n_directions=dict(argstr='%s', - mandatory=True, - position=2, - ), - n_output_directions=dict(argstr='%s', - mandatory=True, - position=3, - ), - oblique_correction=dict(argstr='-oc', - ), - out_prefix=dict(argstr='%s', - position=4, - usedefault=True, - ), - output_entropy=dict(argstr='-oe', - ), - output_type=dict(argstr='-ot %s', - usedefault=True, - ), - sharpness=dict(argstr='-s %f', - ), - subtract_background=dict(argstr='-bg', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + DWI=dict( + argstr='%s', + mandatory=True, + position=1, + ), + args=dict(argstr='%s', ), + dsi=dict(argstr='-dsi', ), + environ=dict( + nohash=True, + usedefault=True, + ), + filter=dict(argstr='-f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_orientation_vectors=dict(argstr='-iop %f', ), + matrix=dict( + argstr='-mat %s', + mandatory=True, + ), + n_b0=dict( + argstr='-b0 %s', + mandatory=True, + ), + n_directions=dict( + argstr='%s', + mandatory=True, + position=2, + ), + n_output_directions=dict( + argstr='%s', + mandatory=True, + position=3, + ), + oblique_correction=dict(argstr='-oc', ), + out_prefix=dict( + argstr='%s', + position=4, + usedefault=True, + ), + output_entropy=dict(argstr='-oe', ), + output_type=dict( + argstr='-ot %s', + usedefault=True, + ), + sharpness=dict(argstr='-s %f', ), + subtract_background=dict(argstr='-bg', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ODFRecon.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ODFRecon_outputs(): - output_map = dict(B0=dict(), - DWI=dict(), - ODF=dict(), - entropy=dict(), - max=dict(), + output_map = dict( + B0=dict(), + DWI=dict(), + ODF=dict(), + entropy=dict(), + max=dict(), ) outputs = ODFRecon.output_spec() diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py index 931375abd1..053abd400e 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py @@ -4,87 +4,72 @@ def test_ODFTracker_inputs(): - input_map = dict(ODF=dict(mandatory=True, - ), - angle_threshold=dict(argstr='-at %f', - ), - args=dict(argstr='%s', - ), - disc=dict(argstr='-disc', - ), - dsi=dict(argstr='-dsi', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_orientation_vectors=dict(argstr='-iop %f', - ), - input_data_prefix=dict(argstr='%s', - position=0, - usedefault=True, - ), - input_output_type=dict(argstr='-it %s', - usedefault=True, - ), - invert_x=dict(argstr='-ix', - ), - invert_y=dict(argstr='-iy', - ), - invert_z=dict(argstr='-iz', - ), - limit=dict(argstr='-limit %d', - ), - mask1_file=dict(argstr='-m %s', - mandatory=True, - position=2, - ), - mask1_threshold=dict(position=3, - ), - mask2_file=dict(argstr='-m2 %s', - position=4, - ), - mask2_threshold=dict(position=5, - ), - max=dict(mandatory=True, - ), - out_file=dict(argstr='%s', - position=1, - usedefault=True, - ), - random_seed=dict(argstr='-rseed %s', - ), - runge_kutta2=dict(argstr='-rk2', - ), - slice_order=dict(argstr='-sorder %d', - ), - step_length=dict(argstr='-l %f', - ), - swap_xy=dict(argstr='-sxy', - ), - swap_yz=dict(argstr='-syz', - ), - swap_zx=dict(argstr='-szx', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel_order=dict(argstr='-vorder %s', - ), + input_map = dict( + ODF=dict(mandatory=True, ), + angle_threshold=dict(argstr='-at %f', ), + args=dict(argstr='%s', ), + disc=dict(argstr='-disc', ), + dsi=dict(argstr='-dsi', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_orientation_vectors=dict(argstr='-iop %f', ), + input_data_prefix=dict( + argstr='%s', + position=0, + usedefault=True, + ), + input_output_type=dict( + argstr='-it %s', + usedefault=True, + ), + invert_x=dict(argstr='-ix', ), + invert_y=dict(argstr='-iy', ), + invert_z=dict(argstr='-iz', ), + limit=dict(argstr='-limit %d', ), + mask1_file=dict( + argstr='-m %s', + mandatory=True, + position=2, + ), + mask1_threshold=dict(position=3, ), + mask2_file=dict( + argstr='-m2 %s', + position=4, + ), + mask2_threshold=dict(position=5, ), + max=dict(mandatory=True, ), + out_file=dict( + argstr='%s', + position=1, + usedefault=True, + ), + random_seed=dict(argstr='-rseed %s', ), + runge_kutta2=dict(argstr='-rk2', ), + slice_order=dict(argstr='-sorder %d', ), + step_length=dict(argstr='-l %f', ), + swap_xy=dict(argstr='-sxy', ), + swap_yz=dict(argstr='-syz', ), + swap_zx=dict(argstr='-szx', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel_order=dict(argstr='-vorder %s', ), ) inputs = ODFTracker.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ODFTracker_outputs(): - output_map = dict(track_file=dict(), - ) + output_map = dict(track_file=dict(), ) outputs = ODFTracker.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py index 7db4168340..0e40d997d8 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py @@ -4,41 +4,44 @@ def test_SplineFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - output_file=dict(argstr='%s', - position=2, - usedefault=True, - ), - step_length=dict(argstr='%f', - mandatory=True, - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - track_file=dict(argstr='%s', - mandatory=True, - position=0, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + output_file=dict( + argstr='%s', + position=2, + usedefault=True, + ), + step_length=dict( + argstr='%f', + mandatory=True, + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + track_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), ) inputs = SplineFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SplineFilter_outputs(): - output_map = dict(smoothed_track_file=dict(), - ) + output_map = dict(smoothed_track_file=dict(), ) outputs = SplineFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py index 8a9a0d9201..c05ea7234f 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py @@ -4,37 +4,39 @@ def test_TrackMerge_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - output_file=dict(argstr='%s', - position=-1, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - track_files=dict(argstr='%s...', - mandatory=True, - position=0, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + output_file=dict( + argstr='%s', + position=-1, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + track_files=dict( + argstr='%s...', + mandatory=True, + position=0, + ), ) inputs = TrackMerge.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackMerge_outputs(): - output_map = dict(track_file=dict(), - ) + output_map = dict(track_file=dict(), ) outputs = TrackMerge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/anisotropic_power.py b/nipype/interfaces/dipy/anisotropic_power.py index 2a678dfd1f..29b81d1ebb 100644 --- a/nipype/interfaces/dipy/anisotropic_power.py +++ b/nipype/interfaces/dipy/anisotropic_power.py @@ -6,7 +6,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import nibabel as nb @@ -18,8 +19,7 @@ class APMQballInputSpec(DipyBaseInterfaceInputSpec): - mask_file = File(exists=True, - desc='An optional brain mask') + mask_file = File(exists=True, desc='An optional brain mask') class APMQballOutputSpec(TraitedSpec): @@ -58,12 +58,15 @@ def _run_interface(self, runtime): mask = nb.load(self.inputs.mask_file).get_data() # Fit it - model = shm.QballModel(gtab,8) + model = shm.QballModel(gtab, 8) sphere = get_sphere('symmetric724') - peaks = peaks_from_model(model=model, data=data, - relative_peak_threshold=.5, - min_separation_angle=25, - sphere=sphere, mask=mask) + peaks = peaks_from_model( + model=model, + data=data, + relative_peak_threshold=.5, + min_separation_angle=25, + sphere=sphere, + mask=mask) apm = shm.anisotropic_power(peaks.shm_coeff) out_file = self._gen_filename('apm') nb.Nifti1Image(apm.astype("float32"), affine).to_filename(out_file) diff --git a/nipype/interfaces/dipy/base.py b/nipype/interfaces/dipy/base.py index d5b2e9957f..6c05da6f16 100644 --- a/nipype/interfaces/dipy/base.py +++ b/nipype/interfaces/dipy/base.py @@ -1,12 +1,13 @@ # -*- coding: utf-8 -*- """ Base interfaces for dipy """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op import numpy as np from ... import logging -from ..base import (traits, File, isdefined, - BaseInterface, BaseInterfaceInputSpec) +from ..base import (traits, File, isdefined, BaseInterface, + BaseInterfaceInputSpec) IFLOGGER = logging.getLogger('interface') @@ -32,10 +33,10 @@ def dipy_version(): class DipyBaseInterface(BaseInterface): - """ A base interface for py:mod:`dipy` computations """ + def __init__(self, **inputs): if no_dipy(): IFLOGGER.warn('dipy was not found') @@ -52,7 +53,6 @@ class DipyBaseInterfaceInputSpec(BaseInterfaceInputSpec): class DipyDiffusionInterface(DipyBaseInterface): - """ A base interface for py:mod:`dipy` computations """ diff --git a/nipype/interfaces/dipy/preprocess.py b/nipype/interfaces/dipy/preprocess.py index bfe197cae2..a5a81555b7 100644 --- a/nipype/interfaces/dipy/preprocess.py +++ b/nipype/interfaces/dipy/preprocess.py @@ -7,7 +7,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op import nibabel as nb @@ -23,15 +24,22 @@ class ResampleInputSpec(TraitedSpec): - in_file = File(exists=True, mandatory=True, - desc='The input 4D diffusion-weighted image file') - vox_size = traits.Tuple(traits.Float, traits.Float, traits.Float, - desc=('specify the new voxel zooms. If no vox_size' - ' is set, then isotropic regridding will ' - 'be performed, with spacing equal to the ' - 'smallest current zoom.')) + in_file = File( + exists=True, + mandatory=True, + desc='The input 4D diffusion-weighted image file') + vox_size = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + desc=('specify the new voxel zooms. If no vox_size' + ' is set, then isotropic regridding will ' + 'be performed, with spacing equal to the ' + 'smallest current zoom.')) interp = traits.Int( - 1, mandatory=True, usedefault=True, + 1, + mandatory=True, + usedefault=True, desc=('order of the interpolator (0 = nearest, 1 = linear, etc.')) @@ -40,7 +48,6 @@ class ResampleOutputSpec(TraitedSpec): class Resample(DipyBaseInterface): - """ An interface to reslicing diffusion datasets. See @@ -65,8 +72,11 @@ def _run_interface(self, runtime): vox_size = self.inputs.vox_size out_file = op.abspath(self._gen_outfilename()) - resample_proxy(self.inputs.in_file, order=order, - new_zooms=vox_size, out_file=out_file) + resample_proxy( + self.inputs.in_file, + order=order, + new_zooms=vox_size, + out_file=out_file) IFLOGGER.info('Resliced image saved as %s', out_file) return runtime @@ -85,16 +95,25 @@ def _gen_outfilename(self): class DenoiseInputSpec(TraitedSpec): - in_file = File(exists=True, mandatory=True, - desc='The input 4D diffusion-weighted image file') + in_file = File( + exists=True, + mandatory=True, + desc='The input 4D diffusion-weighted image file') in_mask = File(exists=True, desc='brain mask') - noise_model = traits.Enum('rician', 'gaussian', mandatory=True, - usedefault=True, - desc=('noise distribution model')) - signal_mask = File(desc=('mask in which the mean signal ' - 'will be computed'), exists=True) - noise_mask = File(desc=('mask in which the standard deviation of noise ' - 'will be computed'), exists=True) + noise_model = traits.Enum( + 'rician', + 'gaussian', + mandatory=True, + usedefault=True, + desc=('noise distribution model')) + signal_mask = File( + desc=('mask in which the mean signal ' + 'will be computed'), + exists=True) + noise_mask = File( + desc=('mask in which the standard deviation of noise ' + 'will be computed'), + exists=True) patch_radius = traits.Int(1, desc='patch radius') block_radius = traits.Int(5, desc='block_radius') snr = traits.Float(desc='manually set an SNR') @@ -105,7 +124,6 @@ class DenoiseOutputSpec(TraitedSpec): class Denoise(DipyBaseInterface): - """ An interface to denoising diffusion datasets [Coupe2008]_. See @@ -131,8 +149,8 @@ class Denoise(DipyBaseInterface): def _run_interface(self, runtime): out_file = op.abspath(self._gen_outfilename()) - settings = dict(mask=None, - rician=(self.inputs.noise_model == 'rician')) + settings = dict( + mask=None, rician=(self.inputs.noise_model == 'rician')) if isdefined(self.inputs.in_mask): settings['mask'] = nb.load(self.inputs.in_mask).get_data() @@ -154,13 +172,15 @@ def _run_interface(self, runtime): if isdefined(self.inputs.noise_mask): noise_mask = nb.load(self.inputs.noise_mask).get_data() - _, s = nlmeans_proxy(self.inputs.in_file, settings, - snr=snr, - smask=signal_mask, - nmask=noise_mask, - out_file=out_file) - IFLOGGER.info('Denoised image saved as %s, estimated SNR=%s', - out_file, str(s)) + _, s = nlmeans_proxy( + self.inputs.in_file, + settings, + snr=snr, + smask=signal_mask, + nmask=noise_mask, + out_file=out_file) + IFLOGGER.info('Denoised image saved as %s, estimated SNR=%s', out_file, + str(s)) return runtime def _list_outputs(self): @@ -197,7 +217,7 @@ def resample_proxy(in_file, order=3, new_zooms=None, out_file=None): if new_zooms is None: minzoom = np.array(im_zooms).min() - new_zooms = tuple(np.ones((3,)) * minzoom) + new_zooms = tuple(np.ones((3, )) * minzoom) if np.all(im_zooms == new_zooms): return in_file @@ -208,12 +228,13 @@ def resample_proxy(in_file, order=3, new_zooms=None, out_file=None): hdr.set_zooms(tuple(tmp_zooms)) hdr.set_data_shape(data2.shape) hdr.set_xyzt_units('mm') - nb.Nifti1Image(data2.astype(hdr.get_data_dtype()), - affine2, hdr).to_filename(out_file) + nb.Nifti1Image(data2.astype(hdr.get_data_dtype()), affine2, + hdr).to_filename(out_file) return out_file, new_zooms -def nlmeans_proxy(in_file, settings, +def nlmeans_proxy(in_file, + settings, snr=None, smask=None, nmask=None, diff --git a/nipype/interfaces/dipy/reconstruction.py b/nipype/interfaces/dipy/reconstruction.py index d10e51dede..33c0c6a3e0 100644 --- a/nipype/interfaces/dipy/reconstruction.py +++ b/nipype/interfaces/dipy/reconstruction.py @@ -3,7 +3,8 @@ Interfaces to the reconstruction algorithms in dipy """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from future import standard_library standard_library.install_aliases() from builtins import str, open @@ -28,20 +29,20 @@ class RESTOREInputSpec(DipyBaseInterfaceInputSpec): class RESTOREOutputSpec(TraitedSpec): fa = File(desc='output fractional anisotropy (FA) map computed from ' - 'the fitted DTI') + 'the fitted DTI') md = File(desc='output mean diffusivity (MD) map computed from the ' - 'fitted DTI') + 'fitted DTI') rd = File(desc='output radial diffusivity (RD) map computed from ' - 'the fitted DTI') + 'the fitted DTI') mode = File(desc=('output mode (MO) map computed from the fitted DTI')) - trace = File(desc=('output the tensor trace map computed from the ' - 'fitted DTI')) + trace = File( + desc=('output the tensor trace map computed from the ' + 'fitted DTI')) evals = File(desc=('output the eigenvalues of the fitted DTI')) evecs = File(desc=('output the eigenvectors of the fitted DTI')) class RESTORE(DipyDiffusionInterface): - """ Uses RESTORE [Chang2005]_ to perform DTI fitting with outlier detection. The interface uses :py:mod:`dipy`, as explained in `dipy's documentation`_. @@ -101,8 +102,8 @@ def _run_interface(self, runtime): dsample = data.reshape(-1, data.shape[-1]) if try_b0 and (nb0 > 1): - noise_data = dsample.take(np.where(gtab.b0s_mask), - axis=-1)[noise_msk == 0, ...] + noise_data = dsample.take( + np.where(gtab.b0s_mask), axis=-1)[noise_msk == 0, ...] n = nb0 else: nodiff = np.where(~gtab.b0s_mask) @@ -114,8 +115,8 @@ def _run_interface(self, runtime): # Estimate sigma required by RESTORE mean_std = np.median(noise_data.std(-1)) try: - bias = (1. - np.sqrt(2. / (n - 1)) * - (gamma(n / 2.) / gamma((n - 1) / 2.))) + bias = (1. - np.sqrt(2. / (n - 1)) * (gamma(n / 2.) / gamma( + (n - 1) / 2.))) except: bias = .0 pass @@ -123,9 +124,9 @@ def _run_interface(self, runtime): sigma = mean_std * (1 + bias) if sigma == 0: - IFLOGGER.warn('Noise std is 0.0, looks like data was masked and noise ' - 'cannot be estimated correctly. Using default tensor ' - 'model instead of RESTORE.') + IFLOGGER.warn('Noise std is 0.0, looks like data was masked and ' + 'noise cannot be estimated correctly. Using default ' + 'tensor model instead of RESTORE.') dti = TensorModel(gtab) else: IFLOGGER.info('Performing RESTORE with noise std=%.4f.', sigma) @@ -143,8 +144,8 @@ def _run_interface(self, runtime): for k in self._outputs().get(): scalar = getattr(fit_restore, k) hdr.set_data_shape(np.shape(scalar)) - nb.Nifti1Image(scalar.astype(np.float32), - affine, hdr).to_filename(self._gen_filename(k)) + nb.Nifti1Image(scalar.astype(np.float32), affine, hdr).to_filename( + self._gen_filename(k)) return runtime @@ -160,8 +161,7 @@ class EstimateResponseSHInputSpec(DipyBaseInterfaceInputSpec): exists=True, mandatory=True, desc=('input eigenvalues file')) in_mask = File( exists=True, desc=('input mask in which we find single fibers')) - fa_thresh = traits.Float( - 0.7, usedefault=True, desc=('FA threshold')) + fa_thresh = traits.Float(0.7, usedefault=True, desc=('FA threshold')) roi_radius = traits.Int( 10, usedefault=True, desc=('ROI radius to be used in auto_response')) auto = traits.Bool( @@ -179,7 +179,6 @@ class EstimateResponseSHOutputSpec(TraitedSpec): class EstimateResponseSH(DipyDiffusionInterface): - """ Uses dipy to compute the single fiber response to be used in spherical deconvolution methods, in a similar way to MRTrix's command @@ -228,20 +227,28 @@ def _run_interface(self, runtime): S0 = np.mean(S0s) if self.inputs.auto: - response, ratio = auto_response(gtab, data, - roi_radius=self.inputs.roi_radius, - fa_thr=self.inputs.fa_thresh) + response, ratio = auto_response( + gtab, + data, + roi_radius=self.inputs.roi_radius, + fa_thr=self.inputs.fa_thresh) response = response[0].tolist() + [S0] elif self.inputs.recursive: MD = np.nan_to_num(mean_diffusivity(evals)) * msk - indices = np.logical_or( - FA >= 0.4, (np.logical_and(FA >= 0.15, MD >= 0.0011))) + indices = np.logical_or(FA >= 0.4, + (np.logical_and(FA >= 0.15, MD >= 0.0011))) data = nb.load(self.inputs.in_file).get_data() - response = recursive_response(gtab, data, mask=indices, sh_order=8, - peak_thr=0.01, init_fa=0.08, - init_trace=0.0021, iter=8, - convergence=0.001, - parallel=True) + response = recursive_response( + gtab, + data, + mask=indices, + sh_order=8, + peak_thr=0.01, + init_fa=0.08, + init_trace=0.0021, + iter=8, + convergence=0.001, + parallel=True) ratio = abs(response[1] / response[0]) else: lambdas = evals[indices] @@ -255,7 +262,8 @@ def _run_interface(self, runtime): 'Ratio=%0.3f.', ratio) elif ratio < 1.e-5 or np.any(np.isnan(response)): response = np.array([1.8e-3, 3.6e-4, 3.6e-4, S0]) - IFLOGGER.warn('Estimated response is not valid, using a default one') + IFLOGGER.warn( + 'Estimated response is not valid, using a default one') else: IFLOGGER.info('Estimated response: %s', str(response[:3])) @@ -263,9 +271,8 @@ def _run_interface(self, runtime): wm_mask = np.zeros_like(FA) wm_mask[indices] = 1 - nb.Nifti1Image( - wm_mask.astype(np.uint8), affine, - None).to_filename(op.abspath(self.inputs.out_mask)) + nb.Nifti1Image(wm_mask.astype(np.uint8), affine, None).to_filename( + op.abspath(self.inputs.out_mask)) return runtime def _list_outputs(self): @@ -278,10 +285,9 @@ def _list_outputs(self): class CSDInputSpec(DipyBaseInterfaceInputSpec): in_mask = File(exists=True, desc=('input mask in which compute tensors')) response = File(exists=True, desc=('single fiber estimated response')) - sh_order = traits.Int(8, usedefault=True, - desc=('maximal shperical harmonics order')) - save_fods = traits.Bool(True, usedefault=True, - desc=('save fODFs in file')) + sh_order = traits.Int( + 8, usedefault=True, desc=('maximal shperical harmonics order')) + save_fods = traits.Bool(True, usedefault=True, desc=('save fODFs in file')) out_fods = File(desc=('fODFs output file name')) @@ -291,7 +297,6 @@ class CSDOutputSpec(TraitedSpec): class CSD(DipyDiffusionInterface): - """ Uses CSD [Tournier2007]_ to generate the fODF of DWIs. The interface uses :py:mod:`dipy`, as explained in `dipy's CSD example @@ -324,7 +329,6 @@ def _run_interface(self, runtime): img = nb.load(self.inputs.in_file) imref = nb.four_to_three(img)[0] - affine = img.affine if isdefined(self.inputs.in_mask): msk = nb.load(self.inputs.in_mask).get_data() @@ -332,7 +336,6 @@ def _run_interface(self, runtime): msk = np.ones(imref.shape) data = img.get_data().astype(np.float32) - hdr = imref.header.copy() gtab = self._get_gradient_table() resp_file = np.loadtxt(self.inputs.response) diff --git a/nipype/interfaces/dipy/setup.py b/nipype/interfaces/dipy/setup.py index 43dfe1156c..e6c8f000b2 100644 --- a/nipype/interfaces/dipy/setup.py +++ b/nipype/interfaces/dipy/setup.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) def configuration(parent_package='', top_path=None): @@ -12,6 +13,7 @@ def configuration(parent_package='', top_path=None): # config.add_data_dir('tests') return config + if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) diff --git a/nipype/interfaces/dipy/simulate.py b/nipype/interfaces/dipy/simulate.py index f008948c97..282f79519a 100644 --- a/nipype/interfaces/dipy/simulate.py +++ b/nipype/interfaces/dipy/simulate.py @@ -5,7 +5,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from multiprocessing import (Pool, cpu_count) import os.path as op from builtins import range @@ -15,28 +16,39 @@ from ... import logging from ...utils import NUMPY_MMAP -from ..base import (traits, TraitedSpec, BaseInterfaceInputSpec, - File, InputMultiPath, isdefined) +from ..base import (traits, TraitedSpec, BaseInterfaceInputSpec, File, + InputMultiPath, isdefined) from .base import DipyBaseInterface IFLOGGER = logging.getLogger('interface') class SimulateMultiTensorInputSpec(BaseInterfaceInputSpec): - in_dirs = InputMultiPath(File(exists=True), mandatory=True, - desc='list of fibers (principal directions)') - in_frac = InputMultiPath(File(exists=True), mandatory=True, - desc=('volume fraction of each fiber')) - in_vfms = InputMultiPath(File(exists=True), mandatory=True, - desc=('volume fractions of isotropic ' - 'compartiments')) + in_dirs = InputMultiPath( + File(exists=True), + mandatory=True, + desc='list of fibers (principal directions)') + in_frac = InputMultiPath( + File(exists=True), + mandatory=True, + desc=('volume fraction of each fiber')) + in_vfms = InputMultiPath( + File(exists=True), + mandatory=True, + desc=('volume fractions of isotropic ' + 'compartiments')) in_mask = File(exists=True, desc='mask to simulate data') diff_iso = traits.List( - [3000e-6, 960e-6, 680e-6], traits.Float, usedefault=True, + [3000e-6, 960e-6, 680e-6], + traits.Float, + usedefault=True, desc='Diffusivity of isotropic compartments') diff_sf = traits.Tuple( (1700e-6, 200e-6, 200e-6), - traits.Float, traits.Float, traits.Float, usedefault=True, + traits.Float, + traits.Float, + traits.Float, + usedefault=True, desc='Single fiber tensor') n_proc = traits.Int(0, usedefault=True, desc='number of processes') @@ -44,16 +56,23 @@ class SimulateMultiTensorInputSpec(BaseInterfaceInputSpec): gradients = File(exists=True, desc='gradients file') in_bvec = File(exists=True, desc='input bvecs file') in_bval = File(exists=True, desc='input bvals file') - num_dirs = traits.Int(32, usedefault=True, - desc=('number of gradient directions (when table ' - 'is automatically generated)')) - bvalues = traits.List(traits.Int, value=[1000, 3000], usedefault=True, - desc=('list of b-values (when table ' - 'is automatically generated)')) - out_file = File('sim_dwi.nii.gz', usedefault=True, - desc='output file with fractions to be simluated') - out_mask = File('sim_msk.nii.gz', usedefault=True, - desc='file with the mask simulated') + num_dirs = traits.Int( + 32, + usedefault=True, + desc=('number of gradient directions (when table ' + 'is automatically generated)')) + bvalues = traits.List( + traits.Int, + value=[1000, 3000], + usedefault=True, + desc=('list of b-values (when table ' + 'is automatically generated)')) + out_file = File( + 'sim_dwi.nii.gz', + usedefault=True, + desc='output file with fractions to be simluated') + out_mask = File( + 'sim_msk.nii.gz', usedefault=True, desc='file with the mask simulated') out_bvec = File('bvec.sim', usedefault=True, desc='simulated b vectors') out_bval = File('bval.sim', usedefault=True, desc='simulated b values') snr = traits.Int(0, usedefault=True, desc='signal-to-noise ratio (dB)') @@ -67,7 +86,6 @@ class SimulateMultiTensorOutputSpec(TraitedSpec): class SimulateMultiTensor(DipyBaseInterface): - """ Interface to MultiTensor model simulator in dipy http://nipy.org/dipy/examples_built/simulate_multi_tensor.html @@ -119,8 +137,10 @@ def _run_interface(self, runtime): # Volume fractions of isotropic compartments nballs = len(self.inputs.in_vfms) - vfs = np.squeeze(nb.concat_images( - [nb.load(f, mmap=NUMPY_MMAP) for f in self.inputs.in_vfms]).get_data()) + vfs = np.squeeze( + nb.concat_images([ + nb.load(f, mmap=NUMPY_MMAP) for f in self.inputs.in_vfms + ]).get_data()) if nballs == 1: vfs = vfs[..., np.newaxis] total_vf = np.sum(vfs, axis=3) @@ -138,7 +158,8 @@ def _run_interface(self, runtime): nvox = len(msk[msk > 0]) # Fiber fractions - ffsim = nb.concat_images([nb.load(f, mmap=NUMPY_MMAP) for f in self.inputs.in_frac]) + ffsim = nb.concat_images( + [nb.load(f, mmap=NUMPY_MMAP) for f in self.inputs.in_frac]) ffs = np.nan_to_num(np.squeeze(ffsim.get_data())) # fiber fractions ffs = np.clip(ffs, 0., 1.) if nsticks == 1: @@ -165,8 +186,8 @@ def _run_interface(self, runtime): fractions = np.concatenate((ffs, vfs), axis=3) nb.Nifti1Image(fractions, aff, None).to_filename('fractions.nii.gz') - nb.Nifti1Image(np.sum(fractions, axis=3), aff, None).to_filename( - 'total_vf.nii.gz') + nb.Nifti1Image(np.sum(fractions, axis=3), aff, + None).to_filename('total_vf.nii.gz') mhdr = hdr.copy() mhdr.set_data_dtype(np.uint8) @@ -208,15 +229,20 @@ def _run_interface(self, runtime): b0 = b0_im.get_data()[msk > 0] args = [] for i in range(nvox): - args.append( - {'fractions': fracs[i, ...].tolist(), - 'sticks': [tuple(dirs[i, j:j + 3]) - for j in range(nsticks + nballs)], - 'gradients': gtab, - 'mevals': mevals, - 'S0': b0[i], - 'snr': self.inputs.snr - }) + args.append({ + 'fractions': + fracs[i, ...].tolist(), + 'sticks': + [tuple(dirs[i, j:j + 3]) for j in range(nsticks + nballs)], + 'gradients': + gtab, + 'mevals': + mevals, + 'S0': + b0[i], + 'snr': + self.inputs.snr + }) n_proc = self.inputs.n_proc if n_proc == 0: @@ -228,8 +254,9 @@ def _run_interface(self, runtime): pool = Pool(processes=n_proc) # Simulate sticks using dipy - IFLOGGER.info('Starting simulation of %d voxels, %d diffusion directions.', - len(args), ndirs) + IFLOGGER.info( + 'Starting simulation of %d voxels, %d diffusion directions.', + len(args), ndirs) result = np.array(pool.map(_compute_voxel, args)) if np.shape(result)[1] != ndirs: raise RuntimeError(('Computed directions do not match number' @@ -241,8 +268,8 @@ def _run_interface(self, runtime): simhdr = hdr.copy() simhdr.set_data_dtype(np.float32) simhdr.set_xyzt_units('mm', 'sec') - nb.Nifti1Image(signal.astype(np.float32), aff, - simhdr).to_filename(op.abspath(self.inputs.out_file)) + nb.Nifti1Image(signal.astype(np.float32), aff, simhdr).to_filename( + op.abspath(self.inputs.out_file)) return runtime @@ -285,9 +312,13 @@ def _compute_voxel(args): try: signal, _ = multi_tensor( - gtab, args['mevals'], S0=args['S0'], - angles=args['sticks'], fractions=ffs, snr=snr) - except Exception as e: + gtab, + args['mevals'], + S0=args['S0'], + angles=args['sticks'], + fractions=ffs, + snr=snr) + except Exception: pass return signal.tolist() diff --git a/nipype/interfaces/dipy/tensors.py b/nipype/interfaces/dipy/tensors.py index e5518f4ea0..ee19e6cd38 100644 --- a/nipype/interfaces/dipy/tensors.py +++ b/nipype/interfaces/dipy/tensors.py @@ -5,7 +5,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import nibabel as nb @@ -17,8 +18,7 @@ class DTIInputSpec(DipyBaseInterfaceInputSpec): - mask_file = File(exists=True, - desc='An optional white matter mask') + mask_file = File(exists=True, desc='An optional white matter mask') class DTIOutputSpec(TraitedSpec): @@ -67,9 +67,9 @@ def _run_interface(self, runtime): nb.save(img, out_file) IFLOGGER.info('DTI parameters image saved as %s', out_file) - #FA MD RD and AD + # FA MD RD and AD for metric in ["fa", "md", "rd", "ad"]: - data = getattr(ten_fit,metric).astype("float32") + data = getattr(ten_fit, metric).astype("float32") out_name = self._gen_filename(metric) nb.Nifti1Image(data, affine).to_filename(out_name) IFLOGGER.info('DTI %s image saved as %s', metric, out_name) @@ -87,8 +87,7 @@ def _list_outputs(self): class TensorModeInputSpec(DipyBaseInterfaceInputSpec): - mask_file = File(exists=True, - desc='An optional white matter mask') + mask_file = File(exists=True, desc='An optional white matter mask') class TensorModeOutputSpec(TraitedSpec): @@ -96,7 +95,6 @@ class TensorModeOutputSpec(TraitedSpec): class TensorMode(DipyDiffusionInterface): - """ Creates a map of the mode of the diffusion tensors given a set of diffusion-weighted images, as well as their associated b-values and diff --git a/nipype/interfaces/dipy/tests/test_auto_APMQball.py b/nipype/interfaces/dipy/tests/test_auto_APMQball.py index 33a5a512c7..ce5ba095e2 100644 --- a/nipype/interfaces/dipy/tests/test_auto_APMQball.py +++ b/nipype/interfaces/dipy/tests/test_auto_APMQball.py @@ -4,31 +4,26 @@ def test_APMQball_inputs(): - input_map = dict(b0_thres=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(mandatory=True, - ), - in_bvec=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - mask_file=dict(), - out_prefix=dict(), + input_map = dict( + b0_thres=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(mandatory=True, ), + in_bvec=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + mask_file=dict(), + out_prefix=dict(), ) inputs = APMQball.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_APMQball_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = APMQball.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_CSD.py b/nipype/interfaces/dipy/tests/test_auto_CSD.py index bed97a5660..8df31812e3 100644 --- a/nipype/interfaces/dipy/tests/test_auto_CSD.py +++ b/nipype/interfaces/dipy/tests/test_auto_CSD.py @@ -4,37 +4,32 @@ def test_CSD_inputs(): - input_map = dict(b0_thres=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(mandatory=True, - ), - in_bvec=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - in_mask=dict(), - out_fods=dict(), - out_prefix=dict(), - response=dict(), - save_fods=dict(usedefault=True, - ), - sh_order=dict(usedefault=True, - ), + input_map = dict( + b0_thres=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(mandatory=True, ), + in_bvec=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + in_mask=dict(), + out_fods=dict(), + out_prefix=dict(), + response=dict(), + save_fods=dict(usedefault=True, ), + sh_order=dict(usedefault=True, ), ) inputs = CSD.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CSD_outputs(): - output_map = dict(model=dict(), - out_fods=dict(), + output_map = dict( + model=dict(), + out_fods=dict(), ) outputs = CSD.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_DTI.py b/nipype/interfaces/dipy/tests/test_auto_DTI.py index 524072e1e5..1c41b83e46 100644 --- a/nipype/interfaces/dipy/tests/test_auto_DTI.py +++ b/nipype/interfaces/dipy/tests/test_auto_DTI.py @@ -4,34 +4,31 @@ def test_DTI_inputs(): - input_map = dict(b0_thres=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(mandatory=True, - ), - in_bvec=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - mask_file=dict(), - out_prefix=dict(), + input_map = dict( + b0_thres=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(mandatory=True, ), + in_bvec=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + mask_file=dict(), + out_prefix=dict(), ) inputs = DTI.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTI_outputs(): - output_map = dict(ad_file=dict(), - fa_file=dict(), - md_file=dict(), - out_file=dict(), - rd_file=dict(), + output_map = dict( + ad_file=dict(), + fa_file=dict(), + md_file=dict(), + out_file=dict(), + rd_file=dict(), ) outputs = DTI.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_Denoise.py b/nipype/interfaces/dipy/tests/test_auto_Denoise.py index f678c34cd0..2f748f5074 100644 --- a/nipype/interfaces/dipy/tests/test_auto_Denoise.py +++ b/nipype/interfaces/dipy/tests/test_auto_Denoise.py @@ -4,28 +4,26 @@ def test_Denoise_inputs(): - input_map = dict(block_radius=dict(), - in_file=dict(mandatory=True, - ), - in_mask=dict(), - noise_mask=dict(), - noise_model=dict(mandatory=True, - usedefault=True, - ), - patch_radius=dict(), - signal_mask=dict(), - snr=dict(), + input_map = dict( + block_radius=dict(), + in_file=dict(mandatory=True, ), + in_mask=dict(), + noise_mask=dict(), + noise_model=dict( + mandatory=True, + usedefault=True, + ), + patch_radius=dict(), + signal_mask=dict(), + snr=dict(), ) inputs = Denoise.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Denoise_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Denoise.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_DipyBaseInterface.py b/nipype/interfaces/dipy/tests/test_auto_DipyBaseInterface.py index 3807c48139..f4ddbe6256 100644 --- a/nipype/interfaces/dipy/tests/test_auto_DipyBaseInterface.py +++ b/nipype/interfaces/dipy/tests/test_auto_DipyBaseInterface.py @@ -4,14 +4,14 @@ def test_DipyBaseInterface_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ) + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = DipyBaseInterface.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py b/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py index 63fabe8f88..f495857181 100644 --- a/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py +++ b/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py @@ -4,23 +4,20 @@ def test_DipyDiffusionInterface_inputs(): - input_map = dict(b0_thres=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(mandatory=True, - ), - in_bvec=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - out_prefix=dict(), + input_map = dict( + b0_thres=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(mandatory=True, ), + in_bvec=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + out_prefix=dict(), ) inputs = DipyDiffusionInterface.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py b/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py index 05f29f6dc3..2971b7fbc1 100644 --- a/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py +++ b/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py @@ -4,45 +4,35 @@ def test_EstimateResponseSH_inputs(): - input_map = dict(auto=dict(xor=['recursive'], - ), - b0_thres=dict(usedefault=True, - ), - fa_thresh=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(mandatory=True, - ), - in_bvec=dict(mandatory=True, - ), - in_evals=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - in_mask=dict(), - out_mask=dict(usedefault=True, - ), - out_prefix=dict(), - recursive=dict(xor=['auto'], - ), - response=dict(usedefault=True, - ), - roi_radius=dict(usedefault=True, - ), + input_map = dict( + auto=dict(xor=['recursive'], ), + b0_thres=dict(usedefault=True, ), + fa_thresh=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(mandatory=True, ), + in_bvec=dict(mandatory=True, ), + in_evals=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + in_mask=dict(), + out_mask=dict(usedefault=True, ), + out_prefix=dict(), + recursive=dict(xor=['auto'], ), + response=dict(usedefault=True, ), + roi_radius=dict(usedefault=True, ), ) inputs = EstimateResponseSH.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EstimateResponseSH_outputs(): - output_map = dict(out_mask=dict(), - response=dict(), + output_map = dict( + out_mask=dict(), + response=dict(), ) outputs = EstimateResponseSH.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_RESTORE.py b/nipype/interfaces/dipy/tests/test_auto_RESTORE.py index 61e48c856a..cee36a676e 100644 --- a/nipype/interfaces/dipy/tests/test_auto_RESTORE.py +++ b/nipype/interfaces/dipy/tests/test_auto_RESTORE.py @@ -4,37 +4,34 @@ def test_RESTORE_inputs(): - input_map = dict(b0_thres=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(mandatory=True, - ), - in_bvec=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - in_mask=dict(), - noise_mask=dict(), - out_prefix=dict(), + input_map = dict( + b0_thres=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(mandatory=True, ), + in_bvec=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + in_mask=dict(), + noise_mask=dict(), + out_prefix=dict(), ) inputs = RESTORE.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RESTORE_outputs(): - output_map = dict(evals=dict(), - evecs=dict(), - fa=dict(), - md=dict(), - mode=dict(), - rd=dict(), - trace=dict(), + output_map = dict( + evals=dict(), + evecs=dict(), + fa=dict(), + md=dict(), + mode=dict(), + rd=dict(), + trace=dict(), ) outputs = RESTORE.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_Resample.py b/nipype/interfaces/dipy/tests/test_auto_Resample.py index 83add746d8..ff51e0efe4 100644 --- a/nipype/interfaces/dipy/tests/test_auto_Resample.py +++ b/nipype/interfaces/dipy/tests/test_auto_Resample.py @@ -4,23 +4,21 @@ def test_Resample_inputs(): - input_map = dict(in_file=dict(mandatory=True, - ), - interp=dict(mandatory=True, - usedefault=True, - ), - vox_size=dict(), + input_map = dict( + in_file=dict(mandatory=True, ), + interp=dict( + mandatory=True, + usedefault=True, + ), + vox_size=dict(), ) inputs = Resample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Resample_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py b/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py index 546627441c..4cc8865e99 100644 --- a/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py +++ b/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py @@ -4,55 +4,42 @@ def test_SimulateMultiTensor_inputs(): - input_map = dict(baseline=dict(mandatory=True, - ), - bvalues=dict(usedefault=True, - ), - diff_iso=dict(usedefault=True, - ), - diff_sf=dict(usedefault=True, - ), - gradients=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(), - in_dirs=dict(mandatory=True, - ), - in_frac=dict(mandatory=True, - ), - in_mask=dict(), - in_vfms=dict(mandatory=True, - ), - n_proc=dict(usedefault=True, - ), - num_dirs=dict(usedefault=True, - ), - out_bval=dict(usedefault=True, - ), - out_bvec=dict(usedefault=True, - ), - out_file=dict(usedefault=True, - ), - out_mask=dict(usedefault=True, - ), - snr=dict(usedefault=True, - ), + input_map = dict( + baseline=dict(mandatory=True, ), + bvalues=dict(usedefault=True, ), + diff_iso=dict(usedefault=True, ), + diff_sf=dict(usedefault=True, ), + gradients=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(), + in_dirs=dict(mandatory=True, ), + in_frac=dict(mandatory=True, ), + in_mask=dict(), + in_vfms=dict(mandatory=True, ), + n_proc=dict(usedefault=True, ), + num_dirs=dict(usedefault=True, ), + out_bval=dict(usedefault=True, ), + out_bvec=dict(usedefault=True, ), + out_file=dict(usedefault=True, ), + out_mask=dict(usedefault=True, ), + snr=dict(usedefault=True, ), ) inputs = SimulateMultiTensor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SimulateMultiTensor_outputs(): - output_map = dict(out_bval=dict(), - out_bvec=dict(), - out_file=dict(), - out_mask=dict(), + output_map = dict( + out_bval=dict(), + out_bvec=dict(), + out_file=dict(), + out_mask=dict(), ) outputs = SimulateMultiTensor.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py b/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py index 09c03dafbc..579cd561a4 100644 --- a/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py +++ b/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py @@ -4,49 +4,55 @@ def test_StreamlineTractography_inputs(): - input_map = dict(gfa_thresh=dict(mandatory=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - in_model=dict(), - in_peaks=dict(), - min_angle=dict(mandatory=True, - usedefault=True, - ), - multiprocess=dict(mandatory=True, - usedefault=True, - ), - num_seeds=dict(mandatory=True, - usedefault=True, - ), - out_prefix=dict(), - peak_threshold=dict(mandatory=True, - usedefault=True, - ), - save_seeds=dict(mandatory=True, - usedefault=True, - ), - seed_coord=dict(), - seed_mask=dict(), - tracking_mask=dict(), + input_map = dict( + gfa_thresh=dict( + mandatory=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + in_model=dict(), + in_peaks=dict(), + min_angle=dict( + mandatory=True, + usedefault=True, + ), + multiprocess=dict( + mandatory=True, + usedefault=True, + ), + num_seeds=dict( + mandatory=True, + usedefault=True, + ), + out_prefix=dict(), + peak_threshold=dict( + mandatory=True, + usedefault=True, + ), + save_seeds=dict( + mandatory=True, + usedefault=True, + ), + seed_coord=dict(), + seed_mask=dict(), + tracking_mask=dict(), ) inputs = StreamlineTractography.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_StreamlineTractography_outputs(): - output_map = dict(gfa=dict(), - odf_peaks=dict(), - out_seeds=dict(), - tracks=dict(), + output_map = dict( + gfa=dict(), + odf_peaks=dict(), + out_seeds=dict(), + tracks=dict(), ) outputs = StreamlineTractography.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_TensorMode.py b/nipype/interfaces/dipy/tests/test_auto_TensorMode.py index cb807e7ef8..8e80c89d36 100644 --- a/nipype/interfaces/dipy/tests/test_auto_TensorMode.py +++ b/nipype/interfaces/dipy/tests/test_auto_TensorMode.py @@ -4,31 +4,26 @@ def test_TensorMode_inputs(): - input_map = dict(b0_thres=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(mandatory=True, - ), - in_bvec=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - mask_file=dict(), - out_prefix=dict(), + input_map = dict( + b0_thres=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(mandatory=True, ), + in_bvec=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + mask_file=dict(), + out_prefix=dict(), ) inputs = TensorMode.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TensorMode_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TensorMode.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py b/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py index 2a352d6e36..ef8a561214 100644 --- a/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py +++ b/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py @@ -4,30 +4,26 @@ def test_TrackDensityMap_inputs(): - input_map = dict(data_dims=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - out_filename=dict(usedefault=True, - ), - points_space=dict(usedefault=True, - ), - reference=dict(), - voxel_dims=dict(), + input_map = dict( + data_dims=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + out_filename=dict(usedefault=True, ), + points_space=dict(usedefault=True, ), + reference=dict(), + voxel_dims=dict(), ) inputs = TrackDensityMap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrackDensityMap_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TrackDensityMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tracks.py b/nipype/interfaces/dipy/tracks.py index bd52fe937e..a129ed043d 100644 --- a/nipype/interfaces/dipy/tracks.py +++ b/nipype/interfaces/dipy/tracks.py @@ -6,7 +6,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op import numpy as np @@ -14,26 +15,35 @@ import nibabel.trackvis as nbt from ... import logging -from ..base import (TraitedSpec, BaseInterfaceInputSpec, - File, isdefined, traits) +from ..base import (TraitedSpec, BaseInterfaceInputSpec, File, isdefined, + traits) from .base import DipyBaseInterface IFLOGGER = logging.getLogger('interface') class TrackDensityMapInputSpec(BaseInterfaceInputSpec): - in_file = File(exists=True, mandatory=True, - desc='The input TrackVis track file') - reference = File(exists=True, - desc='A reference file to define RAS coordinates space') - points_space = traits.Enum('rasmm', 'voxel', None, usedefault=True, - desc='coordinates of trk file') - voxel_dims = traits.List(traits.Float, minlen=3, maxlen=3, - desc='The size of each voxel in mm.') - data_dims = traits.List(traits.Int, minlen=3, maxlen=3, - desc='The size of the image in voxels.') - out_filename = File('tdi.nii', usedefault=True, - desc='The output filename for the tracks in TrackVis ' - '(.trk) format') + in_file = File( + exists=True, mandatory=True, desc='The input TrackVis track file') + reference = File( + exists=True, desc='A reference file to define RAS coordinates space') + points_space = traits.Enum( + 'rasmm', + 'voxel', + None, + usedefault=True, + desc='coordinates of trk file') + voxel_dims = traits.List( + traits.Float, minlen=3, maxlen=3, desc='The size of each voxel in mm.') + data_dims = traits.List( + traits.Int, + minlen=3, + maxlen=3, + desc='The size of the image in voxels.') + out_filename = File( + 'tdi.nii', + usedefault=True, + desc='The output filename for the tracks in TrackVis ' + '(.trk) format') class TrackDensityMapOutputSpec(TraitedSpec): @@ -41,7 +51,6 @@ class TrackDensityMapOutputSpec(TraitedSpec): class TrackDensityMap(DipyBaseInterface): - """ Creates a tract density image from a TrackVis track file using functions from dipy @@ -106,41 +115,57 @@ def _list_outputs(self): class StreamlineTractographyInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True, desc=('input diffusion data')) in_model = File(exists=True, desc=('input f/d-ODF model extracted from.')) - tracking_mask = File(exists=True, - desc=('input mask within which perform tracking')) - seed_mask = File(exists=True, - desc=('input mask within which perform seeding')) + tracking_mask = File( + exists=True, desc=('input mask within which perform tracking')) + seed_mask = File( + exists=True, desc=('input mask within which perform seeding')) in_peaks = File(exists=True, desc=('peaks computed from the odf')) - seed_coord = File(exists=True, - desc=('file containing the list of seed voxel ' - 'coordinates (N,3)')) - gfa_thresh = traits.Float(0.2, mandatory=True, usedefault=True, - desc=('GFA threshold to compute tracking mask')) + seed_coord = File( + exists=True, + desc=('file containing the list of seed voxel ' + 'coordinates (N,3)')) + gfa_thresh = traits.Float( + 0.2, + mandatory=True, + usedefault=True, + desc=('GFA threshold to compute tracking mask')) peak_threshold = traits.Float( - 0.5, mandatory=True, usedefault=True, + 0.5, + mandatory=True, + usedefault=True, desc=('threshold to consider peaks from model')) - min_angle = traits.Float(25.0, mandatory=True, usedefault=True, - desc=('minimum separation angle')) - multiprocess = traits.Bool(True, mandatory=True, usedefault=True, - desc=('use multiprocessing')) - save_seeds = traits.Bool(False, mandatory=True, usedefault=True, - desc=('save seeding voxels coordinates')) - num_seeds = traits.Int(10000, mandatory=True, usedefault=True, - desc=('desired number of tracks in tractography')) + min_angle = traits.Float( + 25.0, + mandatory=True, + usedefault=True, + desc=('minimum separation angle')) + multiprocess = traits.Bool( + True, mandatory=True, usedefault=True, desc=('use multiprocessing')) + save_seeds = traits.Bool( + False, + mandatory=True, + usedefault=True, + desc=('save seeding voxels coordinates')) + num_seeds = traits.Int( + 10000, + mandatory=True, + usedefault=True, + desc=('desired number of tracks in tractography')) out_prefix = traits.Str(desc=('output prefix for file names')) class StreamlineTractographyOutputSpec(TraitedSpec): tracks = File(desc='TrackVis file containing extracted streamlines') - gfa = File(desc=('The resulting GFA (generalized FA) computed using the ' - 'peaks of the ODF')) + gfa = File( + desc=('The resulting GFA (generalized FA) computed using the ' + 'peaks of the ODF')) odf_peaks = File(desc=('peaks computed from the odf')) - out_seeds = File(desc=('file containing the (N,3) *voxel* coordinates used' - ' in seeding.')) + out_seeds = File( + desc=('file containing the (N,3) *voxel* coordinates used' + ' in seeding.')) class StreamlineTractography(DipyBaseInterface): - """ Streamline tractography using EuDX [Garyfallidis12]_. @@ -168,8 +193,8 @@ def _run_interface(self, runtime): import pickle as pickle import gzip - if (not (isdefined(self.inputs.in_model) or - isdefined(self.inputs.in_peaks))): + if (not (isdefined(self.inputs.in_model) + or isdefined(self.inputs.in_peaks))): raise RuntimeError(('At least one of in_model or in_peaks should ' 'be supplied')) @@ -210,8 +235,8 @@ def _run_interface(self, runtime): f.close() hdr.set_data_shape(peaks.gfa.shape) - nb.Nifti1Image(peaks.gfa.astype(np.float32), affine, - hdr).to_filename(self._gen_filename('gfa')) + nb.Nifti1Image(peaks.gfa.astype(np.float32), affine, hdr).to_filename( + self._gen_filename('gfa')) IFLOGGER.info('Performing tractography') @@ -230,23 +255,23 @@ def _run_interface(self, runtime): elif isdefined(self.inputs.seed_mask): seedmsk = nb.load(self.inputs.seed_mask).get_data() - assert(seedmsk.shape == data.shape[:3]) + assert (seedmsk.shape == data.shape[:3]) seedmsk[seedmsk > 0] = 1 seedmsk[seedmsk < 1] = 0 seedps = np.array(np.where(seedmsk == 1), dtype=np.float32).T vseeds = seedps.shape[0] nsperv = (seeds // vseeds) + 1 IFLOGGER.info('Seed mask is provided (%d voxels inside ' - 'mask), computing seeds (%d seeds/voxel).', - vseeds, nsperv) + 'mask), computing seeds (%d seeds/voxel).', vseeds, + nsperv) if nsperv > 1: IFLOGGER.info('Needed %d seeds per selected voxel (total %d).', nsperv, vseeds) seedps = np.vstack(np.array([seedps] * nsperv)) voxcoord = seedps + np.random.uniform(-1, 1, size=seedps.shape) nseeds = voxcoord.shape[0] - seeds = affine.dot(np.vstack((voxcoord.T, - np.ones((1, nseeds)))))[:3, :].T + seeds = affine.dot( + np.vstack((voxcoord.T, np.ones((1, nseeds)))))[:3, :].T if self.inputs.save_seeds: np.savetxt(self._gen_filename('seeds', ext='.txt'), seeds) @@ -258,17 +283,20 @@ def _run_interface(self, runtime): tmask = gfa a_low = self.inputs.gfa_thresh - eu = EuDX(tmask, - peaks.peak_indices[..., 0], - seeds=seeds, - affine=affine, - odf_vertices=sphere.vertices, - a_low=a_low) + eu = EuDX( + tmask, + peaks.peak_indices[..., 0], + seeds=seeds, + affine=affine, + odf_vertices=sphere.vertices, + a_low=a_low) ss_mm = [np.array(s) for s in eu] trkfilev = nb.trackvis.TrackvisFile( - [(s, None, None) for s in ss_mm], points_space='rasmm', affine=np.eye(4)) + [(s, None, None) for s in ss_mm], + points_space='rasmm', + affine=np.eye(4)) trkfilev.to_file(self._gen_filename('tracked', ext='.trk')) return runtime @@ -282,8 +310,7 @@ def _list_outputs(self): if isdefined(self.inputs.seed_coord): outputs['out_seeds'] = self.inputs.seed_coord else: - outputs['out_seeds'] = self._gen_filename('seeds', - ext='.txt') + outputs['out_seeds'] = self._gen_filename('seeds', ext='.txt') return outputs diff --git a/nipype/interfaces/dynamic_slicer.py b/nipype/interfaces/dynamic_slicer.py index 4d1df1e136..5d3a3c1899 100644 --- a/nipype/interfaces/dynamic_slicer.py +++ b/nipype/interfaces/dynamic_slicer.py @@ -1,19 +1,20 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import warnings import xml.dom.minidom -from .base import (CommandLine, CommandLineInputSpec, - DynamicTraitedSpec, traits, Undefined, - File, isdefined) +from .base import (CommandLine, CommandLineInputSpec, DynamicTraitedSpec, + traits, Undefined, File, isdefined) class SlicerCommandLineInputSpec(DynamicTraitedSpec, CommandLineInputSpec): - module = traits.Str(desc="name of the Slicer command line module you want to use") + module = traits.Str( + desc="name of the Slicer command line module you want to use") class SlicerCommandLine(CommandLine): @@ -25,8 +26,10 @@ class SlicerCommandLine(CommandLine): output_spec = DynamicTraitedSpec def _grab_xml(self, module): - cmd = CommandLine(command="Slicer3", resource_monitor=False, - args="--launch %s --xml" % module) + cmd = CommandLine( + command="Slicer3", + resource_monitor=False, + args="--launch %s --xml" % module) ret = cmd.run() if ret.runtime.returncode == 0: return xml.dom.minidom.parseString(ret.runtime.stdout) @@ -36,7 +39,10 @@ def _grab_xml(self, module): def _outputs(self): base = super(SlicerCommandLine, self)._outputs() undefined_output_traits = {} - for key in [node.getElementsByTagName('name')[0].firstChild.nodeValue for node in self._outputs_nodes]: + for key in [ + node.getElementsByTagName('name')[0].firstChild.nodeValue + for node in self._outputs_nodes + ]: base.add_trait(key, File(exists=True)) undefined_output_traits[key] = Undefined @@ -44,9 +50,9 @@ def _outputs(self): return base def __init__(self, module, **inputs): - warnings.warn('slicer is Not fully implemented', - RuntimeWarning) - super(SlicerCommandLine, self).__init__(command="Slicer3 --launch %s " % module, name=module, **inputs) + warnings.warn('slicer is Not fully implemented', RuntimeWarning) + super(SlicerCommandLine, self).__init__( + command="Slicer3 --launch %s " % module, name=module, **inputs) dom = self._grab_xml(module) self._outputs_filenames = {} @@ -56,19 +62,33 @@ def __init__(self, module, **inputs): for paramGroup in dom.getElementsByTagName("parameters"): for param in paramGroup.childNodes: - if param.nodeName in ['label', 'description', '#text', '#comment']: + if param.nodeName in [ + 'label', 'description', '#text', '#comment' + ]: continue traitsParams = {} - name = param.getElementsByTagName('name')[0].firstChild.nodeValue + name = param.getElementsByTagName('name')[ + 0].firstChild.nodeValue longFlagNode = param.getElementsByTagName('longflag') if longFlagNode: - traitsParams["argstr"] = "--" + longFlagNode[0].firstChild.nodeValue + " " + traitsParams[ + "argstr"] = "--" + longFlagNode[0].firstChild.nodeValue + " " else: traitsParams["argstr"] = "--" + name + " " - argsDict = {'file': '%s', 'integer': "%d", 'double': "%f", 'float': "%f", 'image': "%s", 'transform': "%s", 'boolean': '', 'string-enumeration': '%s', 'string': "%s"} + argsDict = { + 'file': '%s', + 'integer': "%d", + 'double': "%f", + 'float': "%f", + 'image': "%s", + 'transform': "%s", + 'boolean': '', + 'string-enumeration': '%s', + 'string': "%s" + } if param.nodeName.endswith('-vector'): traitsParams["argstr"] += argsDict[param.nodeName[:-7]] @@ -83,13 +103,26 @@ def __init__(self, module, **inputs): if index: traitsParams["desc"] = desc[0].firstChild.nodeValue - name = param.getElementsByTagName('name')[0].firstChild.nodeValue + name = param.getElementsByTagName('name')[ + 0].firstChild.nodeValue - typesDict = {'integer': traits.Int, 'double': traits.Float, 'float': traits.Float, 'image': File, 'transform': File, 'boolean': traits.Bool, 'string': traits.Str, 'file': File} + typesDict = { + 'integer': traits.Int, + 'double': traits.Float, + 'float': traits.Float, + 'image': File, + 'transform': File, + 'boolean': traits.Bool, + 'string': traits.Str, + 'file': File + } if param.nodeName == 'string-enumeration': type = traits.Enum - values = [el.firstChild.nodeValue for el in param.getElementsByTagName('element')] + values = [ + el.firstChild.nodeValue + for el in param.getElementsByTagName('element') + ] elif param.nodeName.endswith('-vector'): type = traits.List values = [typesDict[param.nodeName[:-7]]] @@ -98,17 +131,26 @@ def __init__(self, module, **inputs): values = [] type = typesDict[param.nodeName] - if param.nodeName in ['file', 'directory', 'image', 'transform'] and param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output': - self.inputs.add_trait(name, traits.Either(traits.Bool, File, **traitsParams)) + if param.nodeName in [ + 'file', 'directory', 'image', 'transform' + ] and param.getElementsByTagName( + 'channel')[0].firstChild.nodeValue == 'output': + self.inputs.add_trait(name, + traits.Either( + traits.Bool, File, + **traitsParams)) undefined_traits[name] = Undefined # traitsParams["exists"] = True - self._outputs_filenames[name] = self._gen_filename_from_param(param) + self._outputs_filenames[ + name] = self._gen_filename_from_param(param) # undefined_output_traits[name] = Undefined # self._outputs().add_trait(name, File(*values, **traitsParams)) self._outputs_nodes.append(param) else: - if param.nodeName in ['file', 'directory', 'image', 'transform']: + if param.nodeName in [ + 'file', 'directory', 'image', 'transform' + ]: traitsParams["exists"] = True self.inputs.add_trait(name, type(*values, **traitsParams)) undefined_traits[name] = Undefined @@ -129,13 +171,18 @@ def _gen_filename_from_param(self, param): if fileExtensions: ext = fileExtensions else: - ext = {'image': '.nii', 'transform': '.txt', 'file': ''}[param.nodeName] + ext = { + 'image': '.nii', + 'transform': '.txt', + 'file': '' + }[param.nodeName] return base + ext def _list_outputs(self): outputs = self.output_spec().get() for output_node in self._outputs_nodes: - name = output_node.getElementsByTagName('name')[0].firstChild.nodeValue + name = output_node.getElementsByTagName('name')[ + 0].firstChild.nodeValue outputs[name] = getattr(self.inputs, name) if isdefined(outputs[name]) and isinstance(outputs[name], bool): if outputs[name]: @@ -145,7 +192,10 @@ def _list_outputs(self): return outputs def _format_arg(self, name, spec, value): - if name in [output_node.getElementsByTagName('name')[0].firstChild.nodeValue for output_node in self._outputs_nodes]: + if name in [ + output_node.getElementsByTagName('name')[0] + .firstChild.nodeValue for output_node in self._outputs_nodes + ]: if isinstance(value, bool): fname = self._gen_filename(name) else: @@ -153,6 +203,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % fname return super(SlicerCommandLine, self)._format_arg(name, spec, value) + # test = SlicerCommandLine(module="BRAINSFit") # test.inputs.fixedVolume = "/home/filo/workspace/fmri_tumour/data/pilot1/10_co_COR_3D_IR_PREP.nii" # test.inputs.movingVolume = "/home/filo/workspace/fmri_tumour/data/pilot1/2_line_bisection.nii" diff --git a/nipype/interfaces/elastix/__init__.py b/nipype/interfaces/elastix/__init__.py index 2a1287ed63..9dcdb88c18 100644 --- a/nipype/interfaces/elastix/__init__.py +++ b/nipype/interfaces/elastix/__init__.py @@ -2,7 +2,6 @@ # coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """Top-level namespace for elastix.""" from __future__ import absolute_import diff --git a/nipype/interfaces/elastix/base.py b/nipype/interfaces/elastix/base.py index 746e571f3f..56233c8eaa 100644 --- a/nipype/interfaces/elastix/base.py +++ b/nipype/interfaces/elastix/base.py @@ -2,7 +2,6 @@ # coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """The :py:mod:`nipype.interfaces.elastix` provides the interface to the elastix registration software. @@ -10,7 +9,8 @@ """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from ... import logging from ..base import CommandLineInputSpec, Directory, traits @@ -18,8 +18,15 @@ class ElastixBaseInputSpec(CommandLineInputSpec): - output_path = Directory('./', exists=True, mandatory=True, usedefault=True, - argstr='-out %s', desc='output directory') + output_path = Directory( + './', + exists=True, + mandatory=True, + usedefault=True, + argstr='-out %s', + desc='output directory') num_threads = traits.Int( - 1, argstr='-threads %01d', nohash=True, + 1, + argstr='-threads %01d', + nohash=True, desc='set the maximum number of threads of elastix') diff --git a/nipype/interfaces/elastix/registration.py b/nipype/interfaces/elastix/registration.py index 5038447465..a19e337eb4 100644 --- a/nipype/interfaces/elastix/registration.py +++ b/nipype/interfaces/elastix/registration.py @@ -2,13 +2,13 @@ # coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ Interfaces to perform image registrations and to apply the resulting displacement maps to images and points. """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os.path as op @@ -22,25 +22,34 @@ class RegistrationInputSpec(ElastixBaseInputSpec): - fixed_image = File(exists=True, mandatory=True, argstr='-f %s', - desc='fixed image') - moving_image = File(exists=True, mandatory=True, argstr='-m %s', - desc='moving image') - parameters = InputMultiPath(File(exists=True), mandatory=True, argstr='-p %s...', - desc='parameter file, elastix handles 1 or more -p') - fixed_mask = File(exists=True, argstr='-fMask %s', desc='mask for fixed image') - moving_mask = File(exists=True, argstr='-mMask %s', desc='mask for moving image') - initial_transform = File(exists=True, argstr='-t0 %s', - desc='parameter file for initial transform') + fixed_image = File( + exists=True, mandatory=True, argstr='-f %s', desc='fixed image') + moving_image = File( + exists=True, mandatory=True, argstr='-m %s', desc='moving image') + parameters = InputMultiPath( + File(exists=True), + mandatory=True, + argstr='-p %s...', + desc='parameter file, elastix handles 1 or more -p') + fixed_mask = File( + exists=True, argstr='-fMask %s', desc='mask for fixed image') + moving_mask = File( + exists=True, argstr='-mMask %s', desc='mask for moving image') + initial_transform = File( + exists=True, + argstr='-t0 %s', + desc='parameter file for initial transform') class RegistrationOutputSpec(TraitedSpec): transform = InputMultiPath(File(exists=True), desc='output transform') warped_file = File(desc='input moving image warped to fixed image') - warped_files = InputMultiPath(File(exists=False), - desc=('input moving image warped to fixed image at each level')) - warped_files_flags = traits.List(traits.Bool(False), - desc='flag indicating if warped image was generated') + warped_files = InputMultiPath( + File(exists=False), + desc=('input moving image warped to fixed image at each level')) + warped_files_flags = traits.List( + traits.Bool(False), + desc='flag indicating if warped image was generated') class Registration(CommandLine): @@ -70,7 +79,6 @@ def _list_outputs(self): out_dir = op.abspath(self.inputs.output_path) - opts = ['WriteResultImage', 'ResultImageFormat'] regex = re.compile(r'^\((\w+)\s(.+)\)$') outputs['transform'] = [] @@ -89,13 +97,13 @@ def _list_outputs(self): value = self._cast(m.group(2).strip()) config[m.group(1).strip()] = value - outputs['transform'].append(op.join(out_dir, - 'TransformParameters.%01d.txt' % i)) + outputs['transform'].append( + op.join(out_dir, 'TransformParameters.%01d.txt' % i)) warped_file = None if config['WriteResultImage']: - warped_file = op.join(out_dir, - 'result.%01d.%s' % (i, config['ResultImageFormat'])) + warped_file = op.join(out_dir, 'result.%01d.%s' % + (i, config['ResultImageFormat'])) outputs['warped_files'].append(warped_file) outputs['warped_files_flags'].append(config['WriteResultImage']) @@ -124,11 +132,17 @@ def _cast(self, val): class ApplyWarpInputSpec(ElastixBaseInputSpec): - transform_file = File(exists=True, mandatory=True, argstr='-tp %s', - desc='transform-parameter file, only 1') + transform_file = File( + exists=True, + mandatory=True, + argstr='-tp %s', + desc='transform-parameter file, only 1') - moving_image = File(exists=True, argstr='-in %s', mandatory=True, - desc='input image to deform') + moving_image = File( + exists=True, + argstr='-in %s', + mandatory=True, + desc='input image to deform') class ApplyWarpOutputSpec(TraitedSpec): @@ -165,8 +179,11 @@ def _list_outputs(self): class AnalyzeWarpInputSpec(ElastixBaseInputSpec): - transform_file = File(exists=True, mandatory=True, argstr='-tp %s', - desc='transform-parameter file, only 1') + transform_file = File( + exists=True, + mandatory=True, + argstr='-tp %s', + desc='transform-parameter file, only 1') class AnalyzeWarpOutputSpec(TraitedSpec): @@ -207,10 +224,16 @@ def _list_outputs(self): class PointsWarpInputSpec(ElastixBaseInputSpec): - points_file = File(exists=True, argstr='-def %s', mandatory=True, - desc='input points (accepts .vtk triangular meshes).') - transform_file = File(exists=True, mandatory=True, argstr='-tp %s', - desc='transform-parameter file, only 1') + points_file = File( + exists=True, + argstr='-def %s', + mandatory=True, + desc='input points (accepts .vtk triangular meshes).') + transform_file = File( + exists=True, + mandatory=True, + argstr='-tp %s', + desc='transform-parameter file, only 1') class PointsWarpOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py b/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py index 2f53e07c77..a9318dd8b5 100644 --- a/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py +++ b/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py @@ -4,40 +4,45 @@ def test_AnalyzeWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(argstr='-threads %01d', - nohash=True, - ), - output_path=dict(argstr='-out %s', - mandatory=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform_file=dict(argstr='-tp %s', - mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + argstr='-threads %01d', + nohash=True, + ), + output_path=dict( + argstr='-out %s', + mandatory=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform_file=dict( + argstr='-tp %s', + mandatory=True, + ), ) inputs = AnalyzeWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AnalyzeWarp_outputs(): - output_map = dict(disp_field=dict(), - jacdet_map=dict(), - jacmat_map=dict(), + output_map = dict( + disp_field=dict(), + jacdet_map=dict(), + jacmat_map=dict(), ) outputs = AnalyzeWarp.output_spec() diff --git a/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py b/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py index 7b6913f96f..1006da7807 100644 --- a/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py +++ b/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py @@ -4,42 +4,46 @@ def test_ApplyWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - moving_image=dict(argstr='-in %s', - mandatory=True, - ), - num_threads=dict(argstr='-threads %01d', - nohash=True, - ), - output_path=dict(argstr='-out %s', - mandatory=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform_file=dict(argstr='-tp %s', - mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + moving_image=dict( + argstr='-in %s', + mandatory=True, + ), + num_threads=dict( + argstr='-threads %01d', + nohash=True, + ), + output_path=dict( + argstr='-out %s', + mandatory=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform_file=dict( + argstr='-tp %s', + mandatory=True, + ), ) inputs = ApplyWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyWarp_outputs(): - output_map = dict(warped_file=dict(), - ) + output_map = dict(warped_file=dict(), ) outputs = ApplyWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/elastix/tests/test_auto_EditTransform.py b/nipype/interfaces/elastix/tests/test_auto_EditTransform.py index 58a7d72e01..5abfdbda67 100644 --- a/nipype/interfaces/elastix/tests/test_auto_EditTransform.py +++ b/nipype/interfaces/elastix/tests/test_auto_EditTransform.py @@ -4,32 +4,29 @@ def test_EditTransform_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interpolation=dict(argstr='FinalBSplineInterpolationOrder', - usedefault=True, - ), - output_file=dict(), - output_format=dict(argstr='ResultImageFormat', - ), - output_type=dict(argstr='ResultImagePixelType', - ), - reference_image=dict(), - transform_file=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interpolation=dict( + argstr='FinalBSplineInterpolationOrder', + usedefault=True, + ), + output_file=dict(), + output_format=dict(argstr='ResultImageFormat', ), + output_type=dict(argstr='ResultImagePixelType', ), + reference_image=dict(), + transform_file=dict(mandatory=True, ), ) inputs = EditTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EditTransform_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = EditTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py b/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py index 3853fe0e8c..4f98b4a037 100644 --- a/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py +++ b/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py @@ -4,42 +4,46 @@ def test_PointsWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(argstr='-threads %01d', - nohash=True, - ), - output_path=dict(argstr='-out %s', - mandatory=True, - usedefault=True, - ), - points_file=dict(argstr='-def %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform_file=dict(argstr='-tp %s', - mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict( + argstr='-threads %01d', + nohash=True, + ), + output_path=dict( + argstr='-out %s', + mandatory=True, + usedefault=True, + ), + points_file=dict( + argstr='-def %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform_file=dict( + argstr='-tp %s', + mandatory=True, + ), ) inputs = PointsWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PointsWarp_outputs(): - output_map = dict(warped_file=dict(), - ) + output_map = dict(warped_file=dict(), ) outputs = PointsWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/elastix/tests/test_auto_Registration.py b/nipype/interfaces/elastix/tests/test_auto_Registration.py index bf4c322e54..d456ee083d 100644 --- a/nipype/interfaces/elastix/tests/test_auto_Registration.py +++ b/nipype/interfaces/elastix/tests/test_auto_Registration.py @@ -4,53 +4,57 @@ def test_Registration_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_image=dict(argstr='-f %s', - mandatory=True, - ), - fixed_mask=dict(argstr='-fMask %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initial_transform=dict(argstr='-t0 %s', - ), - moving_image=dict(argstr='-m %s', - mandatory=True, - ), - moving_mask=dict(argstr='-mMask %s', - ), - num_threads=dict(argstr='-threads %01d', - nohash=True, - ), - output_path=dict(argstr='-out %s', - mandatory=True, - usedefault=True, - ), - parameters=dict(argstr='-p %s...', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + argstr='-f %s', + mandatory=True, + ), + fixed_mask=dict(argstr='-fMask %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initial_transform=dict(argstr='-t0 %s', ), + moving_image=dict( + argstr='-m %s', + mandatory=True, + ), + moving_mask=dict(argstr='-mMask %s', ), + num_threads=dict( + argstr='-threads %01d', + nohash=True, + ), + output_path=dict( + argstr='-out %s', + mandatory=True, + usedefault=True, + ), + parameters=dict( + argstr='-p %s...', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Registration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Registration_outputs(): - output_map = dict(transform=dict(), - warped_file=dict(), - warped_files=dict(), - warped_files_flags=dict(), + output_map = dict( + transform=dict(), + warped_file=dict(), + warped_files=dict(), + warped_files_flags=dict(), ) outputs = Registration.output_spec() diff --git a/nipype/interfaces/elastix/utils.py b/nipype/interfaces/elastix/utils.py index 718f5310fd..56f7b253d8 100644 --- a/nipype/interfaces/elastix/utils.py +++ b/nipype/interfaces/elastix/utils.py @@ -2,13 +2,13 @@ # coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ Generic interfaces to manipulate registration parameters files, including transform files (to configure warpings) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os.path as op @@ -20,22 +20,38 @@ class EditTransformInputSpec(BaseInterfaceInputSpec): - transform_file = File(exists=True, mandatory=True, - desc='transform-parameter file, only 1') - reference_image = File(exists=True, - desc=('set a new reference image to change the ' - 'target coordinate system.')) - interpolation = traits.Enum('cubic', 'linear', 'nearest', usedefault=True, - argstr='FinalBSplineInterpolationOrder', - desc='set a new interpolator for transformation') - - output_type = traits.Enum('float', 'unsigned char', 'unsigned short', 'short', - 'unsigned long', 'long', 'double', - argstr='ResultImagePixelType', - desc='set a new output pixel type for resampled images') - output_format = traits.Enum('nii.gz', 'nii', 'mhd', 'hdr', 'vtk', - argstr='ResultImageFormat', - desc='set a new image format for resampled images') + transform_file = File( + exists=True, mandatory=True, desc='transform-parameter file, only 1') + reference_image = File( + exists=True, + desc=('set a new reference image to change the ' + 'target coordinate system.')) + interpolation = traits.Enum( + 'cubic', + 'linear', + 'nearest', + usedefault=True, + argstr='FinalBSplineInterpolationOrder', + desc='set a new interpolator for transformation') + + output_type = traits.Enum( + 'float', + 'unsigned char', + 'unsigned short', + 'short', + 'unsigned long', + 'long', + 'double', + argstr='ResultImagePixelType', + desc='set a new output pixel type for resampled images') + output_format = traits.Enum( + 'nii.gz', + 'nii', + 'mhd', + 'hdr', + 'vtk', + argstr='ResultImageFormat', + desc='set a new image format for resampled images') output_file = File(desc='the filename for the resulting transform file') @@ -77,17 +93,21 @@ def _run_interface(self, runtime): contents = f.read() if isdefined(self.inputs.output_type): - p = re.compile((self._pattern % 'ResultImagePixelType').decode('string-escape')) + p = re.compile((self._pattern % + 'ResultImagePixelType').decode('string-escape')) rep = '(\g%s\g<3>' % self.inputs.output_type contents = p.sub(rep, contents) if isdefined(self.inputs.output_format): - p = re.compile((self._pattern % 'ResultImageFormat').decode('string-escape')) + p = re.compile( + (self._pattern % 'ResultImageFormat').decode('string-escape')) rep = '(\g%s\g<3>' % self.inputs.output_format contents = p.sub(rep, contents) if isdefined(self.inputs.interpolation): - p = re.compile((self._pattern % 'FinalBSplineInterpolationOrder').decode('string-escape')) + p = re.compile( + (self._pattern % + 'FinalBSplineInterpolationOrder').decode('string-escape')) rep = '(\g%s\g<3>' % self._interp[self.inputs.interpolation] contents = p.sub(rep, contents) @@ -117,7 +137,8 @@ def _run_interface(self, runtime): itkmat[1, 1] = -1 affine = np.dot(itkmat, im.affine) - dirs = ' '.join(['%0.4f' % f for f in affine[0:3, 0:3].reshape(-1)]) + dirs = ' '.join( + ['%0.4f' % f for f in affine[0:3, 0:3].reshape(-1)]) orig = ' '.join(['%0.4f' % f for f in affine[0:3, 3].reshape(-1)]) # p = re.compile((self._pattern % 'Direction').decode('string-escape')) diff --git a/nipype/interfaces/freesurfer/__init__.py b/nipype/interfaces/freesurfer/__init__.py index 46e2dc9c0d..44c939706e 100644 --- a/nipype/interfaces/freesurfer/__init__.py +++ b/nipype/interfaces/freesurfer/__init__.py @@ -4,24 +4,26 @@ """Top-level namespace for freesurfer.""" from .base import Info, FSCommand, no_freesurfer -from .preprocess import (ParseDICOMDir, UnpackSDICOMDir, MRIConvert, Resample, - ReconAll, BBRegister, ApplyVolTransform, Smooth, - DICOMConvert, RobustRegister, FitMSParams, - SynthesizeFLASH, MNIBiasCorrection, WatershedSkullStrip, - Normalize, CANormalize, CARegister, CALabel, MRIsCALabel, - SegmentCC, SegmentWM, EditWMwithAseg, ConcatenateLTA) -from .model import (MRISPreproc, MRISPreprocReconAll, GLMFit, OneSampleTTest, Binarize, - Concatenate, SegStats, SegStatsReconAll, Label2Vol, MS_LDA, - Label2Label, Label2Annot, SphericalAverage) -from .utils import (SampleToSurface, SurfaceSmooth, SurfaceTransform, Surface2VolTransform, - SurfaceSnapshots, ApplyMask, MRIsConvert, MRITessellate, MRIPretess, - MRIMarchingCubes, SmoothTessellation, MakeAverageSubject, - ExtractMainComponent, Tkregister2, AddXFormToHeader, - CheckTalairachAlignment, TalairachAVI, TalairachQC, RemoveNeck, - MRIFill, MRIsInflate, Sphere, FixTopology, EulerNumber, - RemoveIntersection, MakeSurfaces, Curvature, CurvatureStats, - Jacobian, MRIsCalc, VolumeMask, ParcellationStats, Contrast, - RelabelHypointensities, Aparc2Aseg, Apas2Aseg, MRIsExpand, MRIsCombine) +from .preprocess import ( + ParseDICOMDir, UnpackSDICOMDir, MRIConvert, Resample, ReconAll, BBRegister, + ApplyVolTransform, Smooth, DICOMConvert, RobustRegister, FitMSParams, + SynthesizeFLASH, MNIBiasCorrection, WatershedSkullStrip, Normalize, + CANormalize, CARegister, CALabel, MRIsCALabel, SegmentCC, SegmentWM, + EditWMwithAseg, ConcatenateLTA) +from .model import (MRISPreproc, MRISPreprocReconAll, GLMFit, OneSampleTTest, + Binarize, Concatenate, SegStats, SegStatsReconAll, + Label2Vol, MS_LDA, Label2Label, Label2Annot, + SphericalAverage) +from .utils import ( + SampleToSurface, SurfaceSmooth, SurfaceTransform, Surface2VolTransform, + SurfaceSnapshots, ApplyMask, MRIsConvert, MRITessellate, MRIPretess, + MRIMarchingCubes, SmoothTessellation, MakeAverageSubject, + ExtractMainComponent, Tkregister2, AddXFormToHeader, + CheckTalairachAlignment, TalairachAVI, TalairachQC, RemoveNeck, MRIFill, + MRIsInflate, Sphere, FixTopology, EulerNumber, RemoveIntersection, + MakeSurfaces, Curvature, CurvatureStats, Jacobian, MRIsCalc, VolumeMask, + ParcellationStats, Contrast, RelabelHypointensities, Aparc2Aseg, Apas2Aseg, + MRIsExpand, MRIsCombine) from .longitudinal import (RobustTemplate, FuseSegmentations) -from .registration import (MPRtoMNI305, RegisterAVItoTalairach, EMRegister, Register, - Paint, MRICoreg) +from .registration import (MPRtoMNI305, RegisterAVItoTalairach, EMRegister, + Register, Paint, MRICoreg) diff --git a/nipype/interfaces/freesurfer/base.py b/nipype/interfaces/freesurfer/base.py index 56a4d5df77..cda527a5ea 100644 --- a/nipype/interfaces/freesurfer/base.py +++ b/nipype/interfaces/freesurfer/base.py @@ -14,17 +14,16 @@ See the docstrings for the individual classes for 'working' examples. """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open, object, str import os from ... import LooseVersion from ...utils.filemanip import fname_presuffix -from ..base import (CommandLine, Directory, - CommandLineInputSpec, isdefined, - traits, TraitedSpec, File, - PackageInfo) +from ..base import (CommandLine, Directory, CommandLineInputSpec, isdefined, + traits, TraitedSpec, File, PackageInfo) __docformat__ = 'restructuredtext' @@ -41,8 +40,8 @@ class Info(PackageInfo): """ if os.getenv('FREESURFER_HOME'): - version_file = os.path.join(os.getenv('FREESURFER_HOME'), - 'build-stamp.txt') + version_file = os.path.join( + os.getenv('FREESURFER_HOME'), 'build-stamp.txt') @staticmethod def parse_version(raw_info): @@ -130,8 +129,9 @@ def __init__(self, **inputs): def _subjects_dir_update(self): if self.inputs.subjects_dir: - self.inputs.environ.update({'SUBJECTS_DIR': - self.inputs.subjects_dir}) + self.inputs.environ.update({ + 'SUBJECTS_DIR': self.inputs.subjects_dir + }) @classmethod def set_default_subjects_dir(cls, subjects_dir): @@ -143,7 +143,11 @@ def run(self, **inputs): self._subjects_dir_update() return super(FSCommand, self).run(**inputs) - def _gen_fname(self, basename, fname=None, cwd=None, suffix='_fs', + def _gen_fname(self, + basename, + fname=None, + cwd=None, + suffix='_fs', use_ext=True): '''Define a generic mapping for a single outfile @@ -166,8 +170,8 @@ def _gen_fname(self, basename, fname=None, cwd=None, suffix='_fs', raise ValueError(msg) if cwd is None: cwd = os.getcwd() - fname = fname_presuffix(basename, suffix=suffix, - use_ext=use_ext, newpath=cwd) + fname = fname_presuffix( + basename, suffix=suffix, use_ext=use_ext, newpath=cwd) return fname @property @@ -179,11 +183,12 @@ def version(self): class FSSurfaceCommand(FSCommand): """Support for FreeSurfer surface-related functions. - For some functions, if the output file is not specified starting with - 'lh.' or 'rh.', FreeSurfer prepends the prefix from the input file to the - output filename. Output out_file must be adjusted to accommodate this. - By including the full path in the filename, we can also avoid this behavior. + For some functions, if the output file is not specified starting with 'lh.' + or 'rh.', FreeSurfer prepends the prefix from the input file to the output + filename. Output out_file must be adjusted to accommodate this. By + including the full path in the filename, we can also avoid this behavior. """ + def _get_filecopy_info(self): self._normalize_filenames() return super(FSSurfaceCommand, self)._get_filecopy_info() @@ -226,8 +231,8 @@ def _list_outputs(self): class FSScriptOutputSpec(TraitedSpec): - log_file = File('output.nipype', usedefault=True, - exists=True, desc="The output log") + log_file = File( + 'output.nipype', usedefault=True, exists=True, desc="The output log") class FSTraitedSpecOpenMP(FSTraitedSpec): @@ -258,8 +263,10 @@ def __init__(self, **inputs): def _num_threads_update(self): if self.inputs.num_threads: - self.inputs.environ.update( - {'OMP_NUM_THREADS': str(self.inputs.num_threads)}) + self.inputs.environ.update({ + 'OMP_NUM_THREADS': + str(self.inputs.num_threads) + }) def run(self, **inputs): if 'num_threads' in inputs: diff --git a/nipype/interfaces/freesurfer/longitudinal.py b/nipype/interfaces/freesurfer/longitudinal.py index 84559c90d9..72b71adfe1 100644 --- a/nipype/interfaces/freesurfer/longitudinal.py +++ b/nipype/interfaces/freesurfer/longitudinal.py @@ -10,13 +10,14 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from ... import logging -from ..base import (TraitedSpec, File, traits, - InputMultiPath, OutputMultiPath, isdefined) +from ..base import (TraitedSpec, File, traits, InputMultiPath, OutputMultiPath, + isdefined) from .base import (FSCommand, FSTraitedSpec, FSCommandOpenMP, FSTraitedSpecOpenMP) @@ -27,51 +28,70 @@ class RobustTemplateInputSpec(FSTraitedSpecOpenMP): # required in_files = InputMultiPath( - File(exists=True), mandatory=True, argstr='--mov %s', + File(exists=True), + mandatory=True, + argstr='--mov %s', desc='input movable volumes to be aligned to common mean/median ' - 'template') - out_file = File('mri_robust_template_out.mgz', mandatory=True, - usedefault=True, argstr='--template %s', - desc='output template volume (final mean/median image)') + 'template') + out_file = File( + 'mri_robust_template_out.mgz', + mandatory=True, + usedefault=True, + argstr='--template %s', + desc='output template volume (final mean/median image)') auto_detect_sensitivity = traits.Bool( - argstr='--satit', xor=['outlier_sensitivity'], mandatory=True, + argstr='--satit', + xor=['outlier_sensitivity'], + mandatory=True, desc='auto-detect good sensitivity (recommended for head or full ' - 'brain scans)') + 'brain scans)') outlier_sensitivity = traits.Float( - argstr='--sat %.4f', xor=['auto_detect_sensitivity'], mandatory=True, + argstr='--sat %.4f', + xor=['auto_detect_sensitivity'], + mandatory=True, desc='set outlier sensitivity manually (e.g. "--sat 4.685" ). Higher ' - 'values mean less sensitivity.') + 'values mean less sensitivity.') # optional transform_outputs = traits.Either( - InputMultiPath(File(exists=False)), traits.Bool, argstr='--lta %s', + InputMultiPath(File(exists=False)), + traits.Bool, + argstr='--lta %s', desc='output xforms to template (for each input)') intensity_scaling = traits.Bool( - default_value=False, argstr='--iscale', + default_value=False, + argstr='--iscale', desc='allow also intensity scaling (default off)') scaled_intensity_outputs = traits.Either( - InputMultiPath(File(exists=False)), traits.Bool, + InputMultiPath(File(exists=False)), + traits.Bool, argstr='--iscaleout %s', desc='final intensity scales (will activate --iscale)') subsample_threshold = traits.Int( argstr='--subsample %d', desc='subsample if dim > # on all axes (default no subs.)') average_metric = traits.Enum( - 'median', 'mean', argstr='--average %d', + 'median', + 'mean', + argstr='--average %d', desc='construct template from: 0 Mean, 1 Median (default)') initial_timepoint = traits.Int( argstr='--inittp %d', desc='use TP# for spacial init (default random), 0: no init') fixed_timepoint = traits.Bool( - default_value=False, argstr='--fixtp', + default_value=False, + argstr='--fixtp', desc='map everthing to init TP# (init TP is not resampled)') no_iteration = traits.Bool( - default_value=False, argstr='--noit', + default_value=False, + argstr='--noit', desc='do not iterate, just create first template') initial_transforms = InputMultiPath( - File(exists=True), argstr='--ixforms %s', + File(exists=True), + argstr='--ixforms %s', desc='use initial transforms (lta) on source') in_intensity_scales = InputMultiPath( - File(exists=True), argstr='--iscalein %s', + File(exists=True), + argstr='--iscalein %s', desc='use initial intensity scales') @@ -144,38 +164,53 @@ def _list_outputs(self): if isdefined(self.inputs.transform_outputs): fnames = self.inputs.transform_outputs if fnames is True: - fnames = [fmt.format('tp', i + 1, 'lta') - for i in range(n_files)] + fnames = [ + fmt.format('tp', i + 1, 'lta') for i in range(n_files) + ] outputs['transform_outputs'] = [os.path.abspath(x) for x in fnames] if isdefined(self.inputs.scaled_intensity_outputs): fnames = self.inputs.scaled_intensity_outputs if fnames is True: - fnames = [fmt.format('is', i + 1, 'txt') - for i in range(n_files)] - outputs['scaled_intensity_outputs'] = [os.path.abspath(x) - for x in fnames] + fnames = [ + fmt.format('is', i + 1, 'txt') for i in range(n_files) + ] + outputs['scaled_intensity_outputs'] = [ + os.path.abspath(x) for x in fnames + ] return outputs class FuseSegmentationsInputSpec(FSTraitedSpec): # required - subject_id = traits.String(argstr='%s', position=-3, - desc="subject_id being processed") + subject_id = traits.String( + argstr='%s', position=-3, desc="subject_id being processed") timepoints = InputMultiPath( - traits.String(), mandatory=True, argstr='%s', position=-2, + traits.String(), + mandatory=True, + argstr='%s', + position=-2, desc='subject_ids or timepoints to be processed') - out_file = File(exists=False, mandatory=True, position=-1, - desc="output fused segmentation file") + out_file = File( + exists=False, + mandatory=True, + position=-1, + desc="output fused segmentation file") in_segmentations = InputMultiPath( - File(exists=True), argstr="-a %s", mandatory=True, + File(exists=True), + argstr="-a %s", + mandatory=True, desc="name of aseg file to use (default: aseg.mgz) \ must include the aseg files for all the given timepoints") in_segmentations_noCC = InputMultiPath( - File(exists=True), argstr="-c %s", mandatory=True, + File(exists=True), + argstr="-c %s", + mandatory=True, desc="name of aseg file w/o CC labels (default: aseg.auto_noCCseg.mgz) \ must include the corresponding file for all the given timepoints") in_norms = InputMultiPath( - File(exists=True), argstr="-n %s", mandatory=True, + File(exists=True), + argstr="-n %s", + mandatory=True, desc="-n - name of norm file to use (default: norm.mgs) \ must include the corresponding norm file for all given timepoints \ as well as for the current subject") @@ -186,7 +221,6 @@ class FuseSegmentationsOutputSpec(TraitedSpec): class FuseSegmentations(FSCommand): - """ fuse segmentations together from multiple timepoints Examples @@ -215,6 +249,5 @@ def _format_arg(self, name, spec, value): def _list_outputs(self): outputs = self.output_spec().get() - outputs['out_file'] = os.path.abspath( - self.inputs.out_file) + outputs['out_file'] = os.path.abspath(self.inputs.out_file) return outputs diff --git a/nipype/interfaces/freesurfer/model.py b/nipype/interfaces/freesurfer/model.py index e2eba23196..4e9a4d0352 100644 --- a/nipype/interfaces/freesurfer/model.py +++ b/nipype/interfaces/freesurfer/model.py @@ -11,67 +11,86 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from ...utils.filemanip import fname_presuffix, split_filename -from ..base import (TraitedSpec, File, traits, InputMultiPath, - OutputMultiPath, Directory, isdefined) +from ..base import (TraitedSpec, File, traits, InputMultiPath, OutputMultiPath, + Directory, isdefined) from .base import FSCommand, FSTraitedSpec from .utils import copy2subjdir __docformat__ = 'restructuredtext' + class MRISPreprocInputSpec(FSTraitedSpec): - out_file = File(argstr='--out %s', genfile=True, - desc='output filename') - target = traits.Str(argstr='--target %s', mandatory=True, - desc='target subject name') - hemi = traits.Enum('lh', 'rh', argstr='--hemi %s', - mandatory=True, - desc='hemisphere for source and target') - surf_measure = traits.Str(argstr='--meas %s', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - desc='Use subject/surf/hemi.surf_measure as input') - surf_area = traits.Str(argstr='--area %s', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - desc='Extract vertex area from subject/surf/hemi.surfname to use as input.') - subjects = traits.List(argstr='--s %s...', - xor=('subjects', 'fsgd_file', 'subject_file'), - desc='subjects from who measures are calculated') - fsgd_file = File(exists=True, argstr='--fsgd %s', - xor=('subjects', 'fsgd_file', 'subject_file'), - desc='specify subjects using fsgd file') - subject_file = File(exists=True, argstr='--f %s', - xor=('subjects', 'fsgd_file', 'subject_file'), - desc='file specifying subjects separated by white space') - surf_measure_file = InputMultiPath(File(exists=True), argstr='--is %s...', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - desc='file alternative to surfmeas, still requires list of subjects') + out_file = File(argstr='--out %s', genfile=True, desc='output filename') + target = traits.Str( + argstr='--target %s', mandatory=True, desc='target subject name') + hemi = traits.Enum( + 'lh', + 'rh', + argstr='--hemi %s', + mandatory=True, + desc='hemisphere for source and target') + surf_measure = traits.Str( + argstr='--meas %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + desc='Use subject/surf/hemi.surf_measure as input') + surf_area = traits.Str( + argstr='--area %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + desc= + 'Extract vertex area from subject/surf/hemi.surfname to use as input.') + subjects = traits.List( + argstr='--s %s...', + xor=('subjects', 'fsgd_file', 'subject_file'), + desc='subjects from who measures are calculated') + fsgd_file = File( + exists=True, + argstr='--fsgd %s', + xor=('subjects', 'fsgd_file', 'subject_file'), + desc='specify subjects using fsgd file') + subject_file = File( + exists=True, + argstr='--f %s', + xor=('subjects', 'fsgd_file', 'subject_file'), + desc='file specifying subjects separated by white space') + surf_measure_file = InputMultiPath( + File(exists=True), + argstr='--is %s...', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + desc='file alternative to surfmeas, still requires list of subjects') source_format = traits.Str(argstr='--srcfmt %s', desc='source format') - surf_dir = traits.Str(argstr='--surfdir %s', - desc='alternative directory (instead of surf)') - vol_measure_file = InputMultiPath(traits.Tuple(File(exists=True), - File(exists=True)), - argstr='--iv %s %s...', - desc='list of volume measure and reg file tuples') - proj_frac = traits.Float(argstr='--projfrac %s', - desc='projection fraction for vol2surf') - fwhm = traits.Float(argstr='--fwhm %f', - xor=['num_iters'], - desc='smooth by fwhm mm on the target surface') - num_iters = traits.Int(argstr='--niters %d', - xor=['fwhm'], - desc='niters : smooth by niters on the target surface') - fwhm_source = traits.Float(argstr='--fwhm-src %f', - xor=['num_iters_source'], - desc='smooth by fwhm mm on the source surface') - num_iters_source = traits.Int(argstr='--niterssrc %d', - xor=['fwhm_source'], - desc='niters : smooth by niters on the source surface') - smooth_cortex_only = traits.Bool(argstr='--smooth-cortex-only', - desc='only smooth cortex (ie, exclude medial wall)') + surf_dir = traits.Str( + argstr='--surfdir %s', desc='alternative directory (instead of surf)') + vol_measure_file = InputMultiPath( + traits.Tuple(File(exists=True), File(exists=True)), + argstr='--iv %s %s...', + desc='list of volume measure and reg file tuples') + proj_frac = traits.Float( + argstr='--projfrac %s', desc='projection fraction for vol2surf') + fwhm = traits.Float( + argstr='--fwhm %f', + xor=['num_iters'], + desc='smooth by fwhm mm on the target surface') + num_iters = traits.Int( + argstr='--niters %d', + xor=['fwhm'], + desc='niters : smooth by niters on the target surface') + fwhm_source = traits.Float( + argstr='--fwhm-src %f', + xor=['num_iters_source'], + desc='smooth by fwhm mm on the source surface') + num_iters_source = traits.Int( + argstr='--niterssrc %d', + xor=['fwhm_source'], + desc='niters : smooth by niters on the source surface') + smooth_cortex_only = traits.Bool( + argstr='--smooth-cortex-only', + desc='only smooth cortex (ie, exclude medial wall)') class MRISPreprocOutputSpec(TraitedSpec): @@ -105,9 +124,9 @@ def _list_outputs(self): outfile = self.inputs.out_file outputs['out_file'] = outfile if not isdefined(outfile): - outputs['out_file'] = os.path.join(os.getcwd(), - 'concat_%s_%s.mgz' % (self.inputs.hemi, - self.inputs.target)) + outputs['out_file'] = os.path.join( + os.getcwd(), 'concat_%s_%s.mgz' % (self.inputs.hemi, + self.inputs.target)) return outputs def _gen_filename(self, name): @@ -117,24 +136,31 @@ def _gen_filename(self, name): class MRISPreprocReconAllInputSpec(MRISPreprocInputSpec): - surf_measure_file = File(exists=True, argstr='--meas %s', - xor=('surf_measure', - 'surf_measure_file', 'surf_area'), - desc='file necessary for surfmeas') - surfreg_files = InputMultiPath(File(exists=True), argstr="--surfreg %s", - requires=['lh_surfreg_target', 'rh_surfreg_target'], - desc="lh and rh input surface registration files") - lh_surfreg_target = File(desc="Implicit target surface registration file", - requires=['surfreg_files']) - rh_surfreg_target = File(desc="Implicit target surface registration file", - requires=['surfreg_files']) - subject_id = traits.String('subject_id', argstr='--s %s', usedefault=True, - xor=('subjects', 'fsgd_file', - 'subject_file', 'subject_id'), - desc='subject from whom measures are calculated') - copy_inputs = traits.Bool(desc="If running as a node, set this to True " + - "this will copy some implicit inputs to the " + - "node directory.") + surf_measure_file = File( + exists=True, + argstr='--meas %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + desc='file necessary for surfmeas') + surfreg_files = InputMultiPath( + File(exists=True), + argstr="--surfreg %s", + requires=['lh_surfreg_target', 'rh_surfreg_target'], + desc="lh and rh input surface registration files") + lh_surfreg_target = File( + desc="Implicit target surface registration file", + requires=['surfreg_files']) + rh_surfreg_target = File( + desc="Implicit target surface registration file", + requires=['surfreg_files']) + subject_id = traits.String( + 'subject_id', + argstr='--s %s', + usedefault=True, + xor=('subjects', 'fsgd_file', 'subject_file', 'subject_id'), + desc='subject from whom measures are calculated') + copy_inputs = traits.Bool( + desc="If running as a node, set this to True " + + "this will copy some implicit inputs to the " + "node directory.") class MRISPreprocReconAll(MRISPreproc): @@ -168,13 +194,19 @@ def run(self, **inputs): basename = os.path.basename(surfreg) copy2subjdir(self, surfreg, folder, basename) if basename.startswith('lh.'): - copy2subjdir(self, self.inputs.lh_surfreg_target, - folder, basename, - subject_id=self.inputs.target) + copy2subjdir( + self, + self.inputs.lh_surfreg_target, + folder, + basename, + subject_id=self.inputs.target) else: - copy2subjdir(self, self.inputs.rh_surfreg_target, - folder, basename, - subject_id=self.inputs.target) + copy2subjdir( + self, + self.inputs.rh_surfreg_target, + folder, + basename, + subject_id=self.inputs.target) if isdefined(self.inputs.surf_measure_file): copy2subjdir(self, self.inputs.surf_measure_file, folder) @@ -183,132 +215,173 @@ def run(self, **inputs): def _format_arg(self, name, spec, value): # mris_preproc looks for these files in the surf dir - if name == 'surfreg_files': + if name == 'surfreg_files': basename = os.path.basename(value[0]) return spec.argstr % basename.lstrip('rh.').lstrip('lh.') - if name == "surf_measure_file": + if name == "surf_measure_file": basename = os.path.basename(value) return spec.argstr % basename.lstrip('rh.').lstrip('lh.') return super(MRISPreprocReconAll, self)._format_arg(name, spec, value) class GLMFitInputSpec(FSTraitedSpec): - glm_dir = traits.Str(argstr='--glmdir %s', desc='save outputs to dir', - genfile=True) - in_file = File(desc='input 4D file', argstr='--y %s', mandatory=True, - copyfile=False) + glm_dir = traits.Str( + argstr='--glmdir %s', desc='save outputs to dir', genfile=True) + in_file = File( + desc='input 4D file', argstr='--y %s', mandatory=True, copyfile=False) _design_xor = ('fsgd', 'design', 'one_sample') - fsgd = traits.Tuple(File(exists=True), traits.Enum('doss', 'dods'), - argstr='--fsgd %s %s', xor=_design_xor, - desc='freesurfer descriptor file') - design = File(exists=True, argstr='--X %s', xor=_design_xor, - desc='design matrix file') - contrast = InputMultiPath(File(exists=True), argstr='--C %s...', - desc='contrast file') - - one_sample = traits.Bool(argstr='--osgm', - xor=('one_sample', 'fsgd', 'design', 'contrast'), - desc='construct X and C as a one-sample group mean') - no_contrast_ok = traits.Bool(argstr='--no-contrasts-ok', - desc='do not fail if no contrasts specified') - per_voxel_reg = InputMultiPath(File(exists=True), argstr='--pvr %s...', - desc='per-voxel regressors') - self_reg = traits.Tuple(traits.Int, traits.Int, traits.Int, - argstr='--selfreg %d %d %d', - desc='self-regressor from index col row slice') - weighted_ls = File(exists=True, argstr='--wls %s', - xor=('weight_file', 'weight_inv', 'weight_sqrt'), - desc='weighted least squares') - fixed_fx_var = File(exists=True, argstr='--yffxvar %s', - desc='for fixed effects analysis') - fixed_fx_dof = traits.Int(argstr='--ffxdof %d', - xor=['fixed_fx_dof_file'], - desc='dof for fixed effects analysis') - fixed_fx_dof_file = File(argstr='--ffxdofdat %d', - xor=['fixed_fx_dof'], - desc='text file with dof for fixed effects analysis') - weight_file = File(exists=True, xor=['weighted_ls'], - desc='weight for each input at each voxel') - weight_inv = traits.Bool(argstr='--w-inv', desc='invert weights', - xor=['weighted_ls']) - weight_sqrt = traits.Bool(argstr='--w-sqrt', desc='sqrt of weights', - xor=['weighted_ls']) - fwhm = traits.Range(low=0.0, argstr='--fwhm %f', - desc='smooth input by fwhm') - var_fwhm = traits.Range(low=0.0, argstr='--var-fwhm %f', - desc='smooth variance by fwhm') - no_mask_smooth = traits.Bool(argstr='--no-mask-smooth', - desc='do not mask when smoothing') - no_est_fwhm = traits.Bool(argstr='--no-est-fwhm', - desc='turn off FWHM output estimation') + fsgd = traits.Tuple( + File(exists=True), + traits.Enum('doss', 'dods'), + argstr='--fsgd %s %s', + xor=_design_xor, + desc='freesurfer descriptor file') + design = File( + exists=True, + argstr='--X %s', + xor=_design_xor, + desc='design matrix file') + contrast = InputMultiPath( + File(exists=True), argstr='--C %s...', desc='contrast file') + + one_sample = traits.Bool( + argstr='--osgm', + xor=('one_sample', 'fsgd', 'design', 'contrast'), + desc='construct X and C as a one-sample group mean') + no_contrast_ok = traits.Bool( + argstr='--no-contrasts-ok', + desc='do not fail if no contrasts specified') + per_voxel_reg = InputMultiPath( + File(exists=True), argstr='--pvr %s...', desc='per-voxel regressors') + self_reg = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + argstr='--selfreg %d %d %d', + desc='self-regressor from index col row slice') + weighted_ls = File( + exists=True, + argstr='--wls %s', + xor=('weight_file', 'weight_inv', 'weight_sqrt'), + desc='weighted least squares') + fixed_fx_var = File( + exists=True, argstr='--yffxvar %s', desc='for fixed effects analysis') + fixed_fx_dof = traits.Int( + argstr='--ffxdof %d', + xor=['fixed_fx_dof_file'], + desc='dof for fixed effects analysis') + fixed_fx_dof_file = File( + argstr='--ffxdofdat %d', + xor=['fixed_fx_dof'], + desc='text file with dof for fixed effects analysis') + weight_file = File( + exists=True, + xor=['weighted_ls'], + desc='weight for each input at each voxel') + weight_inv = traits.Bool( + argstr='--w-inv', desc='invert weights', xor=['weighted_ls']) + weight_sqrt = traits.Bool( + argstr='--w-sqrt', desc='sqrt of weights', xor=['weighted_ls']) + fwhm = traits.Range( + low=0.0, argstr='--fwhm %f', desc='smooth input by fwhm') + var_fwhm = traits.Range( + low=0.0, argstr='--var-fwhm %f', desc='smooth variance by fwhm') + no_mask_smooth = traits.Bool( + argstr='--no-mask-smooth', desc='do not mask when smoothing') + no_est_fwhm = traits.Bool( + argstr='--no-est-fwhm', desc='turn off FWHM output estimation') mask_file = File(exists=True, argstr='--mask %s', desc='binary mask') - label_file = File(exists=True, argstr='--label %s', - xor=['cortex'], - desc='use label as mask, surfaces only') - cortex = traits.Bool(argstr='--cortex', - xor=['label_file'], - desc='use subjects ?h.cortex.label as label') - invert_mask = traits.Bool(argstr='--mask-inv', - desc='invert mask') - prune = traits.Bool(argstr='--prune', - desc='remove voxels that do not have a non-zero value at each frame (def)') - no_prune = traits.Bool(argstr='--no-prune', - xor=['prunethresh'], - desc='do not prune') - prune_thresh = traits.Float(argstr='--prune_thr %f', - xor=['noprune'], - desc='prune threshold. Default is FLT_MIN') - compute_log_y = traits.Bool(argstr='--logy', - desc='compute natural log of y prior to analysis') - save_estimate = traits.Bool(argstr='--yhat-save', - desc='save signal estimate (yhat)') - save_residual = traits.Bool(argstr='--eres-save', - desc='save residual error (eres)') - save_res_corr_mtx = traits.Bool(argstr='--eres-scm', - desc='save residual error spatial correlation matrix (eres.scm). Big!') - surf = traits.Bool(argstr="--surf %s %s %s", - requires=["subject_id", "hemi"], - desc="analysis is on a surface mesh") + label_file = File( + exists=True, + argstr='--label %s', + xor=['cortex'], + desc='use label as mask, surfaces only') + cortex = traits.Bool( + argstr='--cortex', + xor=['label_file'], + desc='use subjects ?h.cortex.label as label') + invert_mask = traits.Bool(argstr='--mask-inv', desc='invert mask') + prune = traits.Bool( + argstr='--prune', + desc= + 'remove voxels that do not have a non-zero value at each frame (def)') + no_prune = traits.Bool( + argstr='--no-prune', xor=['prunethresh'], desc='do not prune') + prune_thresh = traits.Float( + argstr='--prune_thr %f', + xor=['noprune'], + desc='prune threshold. Default is FLT_MIN') + compute_log_y = traits.Bool( + argstr='--logy', desc='compute natural log of y prior to analysis') + save_estimate = traits.Bool( + argstr='--yhat-save', desc='save signal estimate (yhat)') + save_residual = traits.Bool( + argstr='--eres-save', desc='save residual error (eres)') + save_res_corr_mtx = traits.Bool( + argstr='--eres-scm', + desc='save residual error spatial correlation matrix (eres.scm). Big!') + surf = traits.Bool( + argstr="--surf %s %s %s", + requires=["subject_id", "hemi"], + desc="analysis is on a surface mesh") subject_id = traits.Str(desc="subject id for surface geometry") hemi = traits.Enum("lh", "rh", desc="surface hemisphere") - surf_geo = traits.Str("white", usedefault=True, - desc="surface geometry name (e.g. white, pial)") - simulation = traits.Tuple(traits.Enum('perm', 'mc-full', 'mc-z'), - traits.Int(min=1), traits.Float, traits.Str, - argstr='--sim %s %d %f %s', - desc='nulltype nsim thresh csdbasename') - sim_sign = traits.Enum('abs', 'pos', 'neg', argstr='--sim-sign %s', - desc='abs, pos, or neg') - uniform = traits.Tuple(traits.Float, traits.Float, - argstr='--uniform %f %f', - desc='use uniform distribution instead of gaussian') - pca = traits.Bool(argstr='--pca', - desc='perform pca/svd analysis on residual') - calc_AR1 = traits.Bool(argstr='--tar1', - desc='compute and save temporal AR1 of residual') - save_cond = traits.Bool(argstr='--save-cond', - desc='flag to save design matrix condition at each voxel') - vox_dump = traits.Tuple(traits.Int, traits.Int, traits.Int, - argstr='--voxdump %d %d %d', - desc='dump voxel GLM and exit') + surf_geo = traits.Str( + "white", + usedefault=True, + desc="surface geometry name (e.g. white, pial)") + simulation = traits.Tuple( + traits.Enum('perm', 'mc-full', 'mc-z'), + traits.Int(min=1), + traits.Float, + traits.Str, + argstr='--sim %s %d %f %s', + desc='nulltype nsim thresh csdbasename') + sim_sign = traits.Enum( + 'abs', 'pos', 'neg', argstr='--sim-sign %s', desc='abs, pos, or neg') + uniform = traits.Tuple( + traits.Float, + traits.Float, + argstr='--uniform %f %f', + desc='use uniform distribution instead of gaussian') + pca = traits.Bool( + argstr='--pca', desc='perform pca/svd analysis on residual') + calc_AR1 = traits.Bool( + argstr='--tar1', desc='compute and save temporal AR1 of residual') + save_cond = traits.Bool( + argstr='--save-cond', + desc='flag to save design matrix condition at each voxel') + vox_dump = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + argstr='--voxdump %d %d %d', + desc='dump voxel GLM and exit') seed = traits.Int(argstr='--seed %d', desc='used for synthesizing noise') synth = traits.Bool(argstr='--synth', desc='replace input with gaussian') - resynth_test = traits.Int(argstr='--resynthtest %d', desc='test GLM by resynthsis') + resynth_test = traits.Int( + argstr='--resynthtest %d', desc='test GLM by resynthsis') profile = traits.Int(argstr='--profile %d', desc='niters : test speed') - force_perm = traits.Bool(argstr='--perm-force', - desc='force perumtation test, even when design matrix is not orthog') + force_perm = traits.Bool( + argstr='--perm-force', + desc='force perumtation test, even when design matrix is not orthog') diag = traits.Int('--diag %d', desc='Gdiag_no : set diagnositc level') - diag_cluster = traits.Bool(argstr='--diag-cluster', - desc='save sig volume and exit from first sim loop') + diag_cluster = traits.Bool( + argstr='--diag-cluster', + desc='save sig volume and exit from first sim loop') debug = traits.Bool(argstr='--debug', desc='turn on debugging') - check_opts = traits.Bool(argstr='--checkopts', - desc="don't run anything, just check options and exit") - allow_repeated_subjects = traits.Bool(argstr='--allowsubjrep', - desc='allow subject names to repeat in the fsgd file (must appear before --fsgd') - allow_ill_cond = traits.Bool(argstr='--illcond', - desc='allow ill-conditioned design matrices') - sim_done_file = File(argstr='--sim-done %s', - desc='create file when simulation finished') + check_opts = traits.Bool( + argstr='--checkopts', + desc="don't run anything, just check options and exit") + allow_repeated_subjects = traits.Bool( + argstr='--allowsubjrep', + desc= + 'allow subject names to repeat in the fsgd file (must appear before --fsgd' + ) + allow_ill_cond = traits.Bool( + argstr='--illcond', desc='allow ill-conditioned design matrices') + sim_done_file = File( + argstr='--sim-done %s', desc='create file when simulation finished') class GLMFitOutputSpec(TraitedSpec): @@ -321,13 +394,18 @@ class GLMFitOutputSpec(TraitedSpec): estimate_file = File(desc="map of the estimated Y values") mask_file = File(desc="map of the mask used in the analysis") fwhm_file = File(desc="text file with estimated smoothness") - dof_file = File(desc="text file with effective degrees-of-freedom for the analysis") - gamma_file = OutputMultiPath(desc="map of contrast of regression coefficients") - gamma_var_file = OutputMultiPath(desc="map of regression contrast variance") + dof_file = File( + desc="text file with effective degrees-of-freedom for the analysis") + gamma_file = OutputMultiPath( + desc="map of contrast of regression coefficients") + gamma_var_file = OutputMultiPath( + desc="map of regression contrast variance") sig_file = OutputMultiPath(desc="map of F-test significance (in -log10p)") ftest_file = OutputMultiPath(desc="map of test statistic values") - spatial_eigenvectors = File(desc="map of spatial eigenvectors from residual PCA") - frame_eigenvectors = File(desc="matrix of frame eigenvectors from residual PCA") + spatial_eigenvectors = File( + desc="map of spatial eigenvectors from residual PCA") + frame_eigenvectors = File( + desc="matrix of frame eigenvectors from residual PCA") singular_values = File(desc="matrix singular values from residual PCA") svd_stats_file = File(desc="text file summarizing the residual PCA") @@ -390,10 +468,18 @@ def _list_outputs(self): contrasts = ["osgm"] # Add in the contrast images - outputs["sig_file"] = [os.path.join(glmdir, c, "sig.mgh") for c in contrasts] - outputs["ftest_file"] = [os.path.join(glmdir, c, "F.mgh") for c in contrasts] - outputs["gamma_file"] = [os.path.join(glmdir, c, "gamma.mgh") for c in contrasts] - outputs["gamma_var_file"] = [os.path.join(glmdir, c, "gammavar.mgh") for c in contrasts] + outputs["sig_file"] = [ + os.path.join(glmdir, c, "sig.mgh") for c in contrasts + ] + outputs["ftest_file"] = [ + os.path.join(glmdir, c, "F.mgh") for c in contrasts + ] + outputs["gamma_file"] = [ + os.path.join(glmdir, c, "gamma.mgh") for c in contrasts + ] + outputs["gamma_var_file"] = [ + os.path.join(glmdir, c, "gammavar.mgh") for c in contrasts + ] # Add in the PCA results, if relevant if isdefined(self.inputs.pca) and self.inputs.pca: @@ -412,66 +498,79 @@ def _gen_filename(self, name): class OneSampleTTest(GLMFit): - def __init__(self, **kwargs): super(OneSampleTTest, self).__init__(**kwargs) self.inputs.one_sample = True class BinarizeInputSpec(FSTraitedSpec): - in_file = File(exists=True, argstr='--i %s', mandatory=True, - copyfile=False, desc='input volume') - min = traits.Float(argstr='--min %f', xor=['wm_ven_csf'], - desc='min thresh') - max = traits.Float(argstr='--max %f', xor=['wm_ven_csf'], - desc='max thresh') - rmin = traits.Float(argstr='--rmin %f', - desc='compute min based on rmin*globalmean') - rmax = traits.Float(argstr='--rmax %f', - desc='compute max based on rmax*globalmean') - match = traits.List(traits.Int, argstr='--match %d...', - desc='match instead of threshold') - wm = traits.Bool(argstr='--wm', - desc='set match vals to 2 and 41 (aseg for cerebral WM)') - ventricles = traits.Bool(argstr='--ventricles', - desc='set match vals those for aseg ventricles+choroid (not 4th)') - wm_ven_csf = traits.Bool(argstr='--wm+vcsf', xor=['min', 'max'], - desc='WM and ventricular CSF, including choroid (not 4th)') - binary_file = File(argstr='--o %s', genfile=True, - desc='binary output volume') - out_type = traits.Enum('nii', 'nii.gz', 'mgz', argstr='', - desc='output file type') - count_file = traits.Either(traits.Bool, File, - argstr='--count %s', - desc='save number of hits in ascii file (hits, ntotvox, pct)') - bin_val = traits.Int(argstr='--binval %d', - desc='set vox within thresh to val (default is 1)') - bin_val_not = traits.Int(argstr='--binvalnot %d', - desc='set vox outside range to val (default is 0)') - invert = traits.Bool(argstr='--inv', - desc='set binval=0, binvalnot=1') - frame_no = traits.Int(argstr='--frame %s', - desc='use 0-based frame of input (default is 0)') - merge_file = File(exists=True, argstr='--merge %s', - desc='merge with mergevol') - mask_file = File(exists=True, argstr='--mask maskvol', - desc='must be within mask') - mask_thresh = traits.Float(argstr='--mask-thresh %f', - desc='set thresh for mask') - abs = traits.Bool(argstr='--abs', - desc='take abs of invol first (ie, make unsigned)') - bin_col_num = traits.Bool(argstr='--bincol', - desc='set binarized voxel value to its column number') - zero_edges = traits.Bool(argstr='--zero-edges', - desc='zero the edge voxels') - zero_slice_edge = traits.Bool(argstr='--zero-slice-edges', - desc='zero the edge slice voxels') - dilate = traits.Int(argstr='--dilate %d', - desc='niters: dilate binarization in 3D') - erode = traits.Int(argstr='--erode %d', - desc='nerode: erode binarization in 3D (after any dilation)') - erode2d = traits.Int(argstr='--erode2d %d', - desc='nerode2d: erode binarization in 2D (after any 3D erosion)') + in_file = File( + exists=True, + argstr='--i %s', + mandatory=True, + copyfile=False, + desc='input volume') + min = traits.Float( + argstr='--min %f', xor=['wm_ven_csf'], desc='min thresh') + max = traits.Float( + argstr='--max %f', xor=['wm_ven_csf'], desc='max thresh') + rmin = traits.Float( + argstr='--rmin %f', desc='compute min based on rmin*globalmean') + rmax = traits.Float( + argstr='--rmax %f', desc='compute max based on rmax*globalmean') + match = traits.List( + traits.Int, argstr='--match %d...', desc='match instead of threshold') + wm = traits.Bool( + argstr='--wm', + desc='set match vals to 2 and 41 (aseg for cerebral WM)') + ventricles = traits.Bool( + argstr='--ventricles', + desc='set match vals those for aseg ventricles+choroid (not 4th)') + wm_ven_csf = traits.Bool( + argstr='--wm+vcsf', + xor=['min', 'max'], + desc='WM and ventricular CSF, including choroid (not 4th)') + binary_file = File( + argstr='--o %s', genfile=True, desc='binary output volume') + out_type = traits.Enum( + 'nii', 'nii.gz', 'mgz', argstr='', desc='output file type') + count_file = traits.Either( + traits.Bool, + File, + argstr='--count %s', + desc='save number of hits in ascii file (hits, ntotvox, pct)') + bin_val = traits.Int( + argstr='--binval %d', + desc='set vox within thresh to val (default is 1)') + bin_val_not = traits.Int( + argstr='--binvalnot %d', + desc='set vox outside range to val (default is 0)') + invert = traits.Bool(argstr='--inv', desc='set binval=0, binvalnot=1') + frame_no = traits.Int( + argstr='--frame %s', desc='use 0-based frame of input (default is 0)') + merge_file = File( + exists=True, argstr='--merge %s', desc='merge with mergevol') + mask_file = File( + exists=True, argstr='--mask maskvol', desc='must be within mask') + mask_thresh = traits.Float( + argstr='--mask-thresh %f', desc='set thresh for mask') + abs = traits.Bool( + argstr='--abs', desc='take abs of invol first (ie, make unsigned)') + bin_col_num = traits.Bool( + argstr='--bincol', + desc='set binarized voxel value to its column number') + zero_edges = traits.Bool( + argstr='--zero-edges', desc='zero the edge voxels') + zero_slice_edge = traits.Bool( + argstr='--zero-slice-edges', desc='zero the edge slice voxels') + dilate = traits.Int( + argstr='--dilate %d', desc='niters: dilate binarization in 3D') + erode = traits.Int( + argstr='--erode %d', + desc='nerode: erode binarization in 3D (after any dilation)') + erode2d = traits.Int( + argstr='--erode2d %d', + desc='nerode2d: erode binarization in 2D (after any 3D erosion)') class BinarizeOutputSpec(TraitedSpec): @@ -500,24 +599,24 @@ def _list_outputs(self): outfile = self.inputs.binary_file if not isdefined(outfile): if isdefined(self.inputs.out_type): - outfile = fname_presuffix(self.inputs.in_file, - newpath=os.getcwd(), - suffix='.'.join(('_thresh', - self.inputs.out_type)), - use_ext=False) + outfile = fname_presuffix( + self.inputs.in_file, + newpath=os.getcwd(), + suffix='.'.join(('_thresh', self.inputs.out_type)), + use_ext=False) else: - outfile = fname_presuffix(self.inputs.in_file, - newpath=os.getcwd(), - suffix='_thresh') + outfile = fname_presuffix( + self.inputs.in_file, newpath=os.getcwd(), suffix='_thresh') outputs['binary_file'] = os.path.abspath(outfile) value = self.inputs.count_file if isdefined(value): if isinstance(value, bool): if value: - outputs['count_file'] = fname_presuffix(self.inputs.in_file, - suffix='_count.txt', - newpath=os.getcwd(), - use_ext=False) + outputs['count_file'] = fname_presuffix( + self.inputs.in_file, + suffix='_count.txt', + newpath=os.getcwd(), + use_ext=False) else: outputs['count_file'] = value return outputs @@ -540,46 +639,75 @@ def _gen_filename(self, name): class ConcatenateInputSpec(FSTraitedSpec): - in_files = InputMultiPath(File(exists=True), - desc='Individual volumes to be concatenated', - argstr='--i %s...', mandatory=True) - concatenated_file = File(desc='Output volume', argstr='--o %s', - genfile=True) - sign = traits.Enum('abs', 'pos', 'neg', argstr='--%s', - desc='Take only pos or neg voxles from input, or take abs') - stats = traits.Enum('sum', 'var', 'std', 'max', 'min', 'mean', argstr='--%s', - desc='Compute the sum, var, std, max, min or mean of the input volumes') - paired_stats = traits.Enum('sum', 'avg', 'diff', 'diff-norm', 'diff-norm1', - 'diff-norm2', argstr='--paired-%s', - desc='Compute paired sum, avg, or diff') - gmean = traits.Int(argstr='--gmean %d', - desc='create matrix to average Ng groups, Nper=Ntot/Ng') - mean_div_n = traits.Bool(argstr='--mean-div-n', - desc='compute mean/nframes (good for var)') - multiply_by = traits.Float(argstr='--mul %f', - desc='Multiply input volume by some amount') - add_val = traits.Float(argstr='--add %f', - desc='Add some amount to the input volume') - multiply_matrix_file = File(exists=True, argstr='--mtx %s', - desc='Multiply input by an ascii matrix in file') - combine = traits.Bool(argstr='--combine', - desc='Combine non-zero values into single frame volume') - keep_dtype = traits.Bool(argstr='--keep-datatype', - desc='Keep voxelwise precision type (default is float') - max_bonfcor = traits.Bool(argstr='--max-bonfcor', - desc='Compute max and bonferroni correct (assumes -log10(ps))') - max_index = traits.Bool(argstr='--max-index', - desc='Compute the index of max voxel in concatenated volumes') - mask_file = File(exists=True, argstr='--mask %s', desc='Mask input with a volume') - vote = traits.Bool(argstr='--vote', - desc='Most frequent value at each voxel and fraction of occurances') - sort = traits.Bool(argstr='--sort', - desc='Sort each voxel by ascending frame value') + in_files = InputMultiPath( + File(exists=True), + desc='Individual volumes to be concatenated', + argstr='--i %s...', + mandatory=True) + concatenated_file = File( + desc='Output volume', argstr='--o %s', genfile=True) + sign = traits.Enum( + 'abs', + 'pos', + 'neg', + argstr='--%s', + desc='Take only pos or neg voxles from input, or take abs') + stats = traits.Enum( + 'sum', + 'var', + 'std', + 'max', + 'min', + 'mean', + argstr='--%s', + desc='Compute the sum, var, std, max, min or mean of the input volumes' + ) + paired_stats = traits.Enum( + 'sum', + 'avg', + 'diff', + 'diff-norm', + 'diff-norm1', + 'diff-norm2', + argstr='--paired-%s', + desc='Compute paired sum, avg, or diff') + gmean = traits.Int( + argstr='--gmean %d', + desc='create matrix to average Ng groups, Nper=Ntot/Ng') + mean_div_n = traits.Bool( + argstr='--mean-div-n', desc='compute mean/nframes (good for var)') + multiply_by = traits.Float( + argstr='--mul %f', desc='Multiply input volume by some amount') + add_val = traits.Float( + argstr='--add %f', desc='Add some amount to the input volume') + multiply_matrix_file = File( + exists=True, + argstr='--mtx %s', + desc='Multiply input by an ascii matrix in file') + combine = traits.Bool( + argstr='--combine', + desc='Combine non-zero values into single frame volume') + keep_dtype = traits.Bool( + argstr='--keep-datatype', + desc='Keep voxelwise precision type (default is float') + max_bonfcor = traits.Bool( + argstr='--max-bonfcor', + desc='Compute max and bonferroni correct (assumes -log10(ps))') + max_index = traits.Bool( + argstr='--max-index', + desc='Compute the index of max voxel in concatenated volumes') + mask_file = File( + exists=True, argstr='--mask %s', desc='Mask input with a volume') + vote = traits.Bool( + argstr='--vote', + desc='Most frequent value at each voxel and fraction of occurances') + sort = traits.Bool( + argstr='--sort', desc='Sort each voxel by ascending frame value') class ConcatenateOutputSpec(TraitedSpec): - concatenated_file = File(exists=True, - desc='Path/name of the output volume') + concatenated_file = File( + exists=True, desc='Path/name of the output volume') class Concatenate(FSCommand): @@ -621,89 +749,169 @@ def _gen_filename(self, name): class SegStatsInputSpec(FSTraitedSpec): _xor_inputs = ('segmentation_file', 'annot', 'surf_label') - segmentation_file = File(exists=True, argstr='--seg %s', xor=_xor_inputs, - mandatory=True, desc='segmentation volume path') - annot = traits.Tuple(traits.Str, traits.Enum('lh', 'rh'), traits.Str, - argstr='--annot %s %s %s', xor=_xor_inputs, - mandatory=True, - desc='subject hemi parc : use surface parcellation') - surf_label = traits.Tuple(traits.Str, traits.Enum('lh', 'rh'), traits.Str, - argstr='--slabel %s %s %s', xor=_xor_inputs, - mandatory=True, - desc='subject hemi label : use surface label') - summary_file = File(argstr='--sum %s', genfile=True, position=-1, - desc='Segmentation stats summary table file') - partial_volume_file = File(exists=True, argstr='--pv %s', - desc='Compensate for partial voluming') - in_file = File(exists=True, argstr='--i %s', - desc='Use the segmentation to report stats on this volume') - frame = traits.Int(argstr='--frame %d', - desc='Report stats on nth frame of input volume') + segmentation_file = File( + exists=True, + argstr='--seg %s', + xor=_xor_inputs, + mandatory=True, + desc='segmentation volume path') + annot = traits.Tuple( + traits.Str, + traits.Enum('lh', 'rh'), + traits.Str, + argstr='--annot %s %s %s', + xor=_xor_inputs, + mandatory=True, + desc='subject hemi parc : use surface parcellation') + surf_label = traits.Tuple( + traits.Str, + traits.Enum('lh', 'rh'), + traits.Str, + argstr='--slabel %s %s %s', + xor=_xor_inputs, + mandatory=True, + desc='subject hemi label : use surface label') + summary_file = File( + argstr='--sum %s', + genfile=True, + position=-1, + desc='Segmentation stats summary table file') + partial_volume_file = File( + exists=True, argstr='--pv %s', desc='Compensate for partial voluming') + in_file = File( + exists=True, + argstr='--i %s', + desc='Use the segmentation to report stats on this volume') + frame = traits.Int( + argstr='--frame %d', desc='Report stats on nth frame of input volume') multiply = traits.Float(argstr='--mul %f', desc='multiply input by val') - calc_snr = traits.Bool(argstr='--snr', desc='save mean/std as extra column in output table') - calc_power = traits.Enum('sqr', 'sqrt', argstr='--%s', - desc='Compute either the sqr or the sqrt of the input') - _ctab_inputs = ('color_table_file', 'default_color_table', 'gca_color_table') - color_table_file = File(exists=True, argstr='--ctab %s', xor=_ctab_inputs, - desc='color table file with seg id names') - default_color_table = traits.Bool(argstr='--ctab-default', xor=_ctab_inputs, - desc='use $FREESURFER_HOME/FreeSurferColorLUT.txt') - gca_color_table = File(exists=True, argstr='--ctab-gca %s', xor=_ctab_inputs, - desc='get color table from GCA (CMA)') - segment_id = traits.List(argstr='--id %s...', desc='Manually specify segmentation ids') - exclude_id = traits.Int(argstr='--excludeid %d', desc='Exclude seg id from report') - exclude_ctx_gm_wm = traits.Bool(argstr='--excl-ctxgmwm', - desc='exclude cortical gray and white matter') - wm_vol_from_surf = traits.Bool(argstr='--surf-wm-vol', desc='Compute wm volume from surf') - cortex_vol_from_surf = traits.Bool(argstr='--surf-ctx-vol', desc='Compute cortex volume from surf') - non_empty_only = traits.Bool(argstr='--nonempty', desc='Only report nonempty segmentations') - empty = traits.Bool(argstr="--empty", - desc="Report on segmentations listed in the color table") - mask_file = File(exists=True, argstr='--mask %s', - desc='Mask volume (same size as seg') - mask_thresh = traits.Float(argstr='--maskthresh %f', - desc='binarize mask with this threshold <0.5>') - mask_sign = traits.Enum('abs', 'pos', 'neg', '--masksign %s', - desc='Sign for mask threshold: pos, neg, or abs') - mask_frame = traits.Int('--maskframe %d', - requires=['mask_file'], - desc='Mask with this (0 based) frame of the mask volume') - mask_invert = traits.Bool(argstr='--maskinvert', desc='Invert binarized mask volume') - mask_erode = traits.Int(argstr='--maskerode %d', desc='Erode mask by some amount') - brain_vol = traits.Enum('brain-vol-from-seg', 'brainmask', argstr='--%s', - desc='Compute brain volume either with ``brainmask`` or ``brain-vol-from-seg``') - brainmask_file = File(argstr="--brainmask %s", exists=True, - desc="Load brain mask and compute the volume of the brain as the non-zero voxels in this volume") - etiv = traits.Bool(argstr='--etiv', desc='Compute ICV from talairach transform') - etiv_only = traits.Enum('etiv', 'old-etiv', '--%s-only', - desc='Compute etiv and exit. Use ``etiv`` or ``old-etiv``') - avgwf_txt_file = traits.Either(traits.Bool, File, argstr='--avgwf %s', - desc='Save average waveform into file (bool or filename)') - avgwf_file = traits.Either(traits.Bool, File, argstr='--avgwfvol %s', - desc='Save as binary volume (bool or filename)') - sf_avg_file = traits.Either(traits.Bool, File, argstr='--sfavg %s', - desc='Save mean across space and time') - vox = traits.List(traits.Int, argstr='--vox %s', - desc='Replace seg with all 0s except at C R S (three int inputs)') - supratent = traits.Bool(argstr="--supratent", - desc="Undocumented input flag") - subcort_gm = traits.Bool(argstr="--subcortgray", - desc="Compute volume of subcortical gray matter") - total_gray = traits.Bool(argstr="--totalgray", - desc="Compute volume of total gray matter") - euler = traits.Bool(argstr="--euler", - desc="Write out number of defect holes in orig.nofix based on the euler number") - in_intensity = File(argstr="--in %s --in-intensity-name %s", - desc="Undocumented input norm.mgz file") - intensity_units = traits.Enum('MR', argstr="--in-intensity-units %s", - requires=["in_intensity"], desc="Intensity units") + calc_snr = traits.Bool( + argstr='--snr', desc='save mean/std as extra column in output table') + calc_power = traits.Enum( + 'sqr', + 'sqrt', + argstr='--%s', + desc='Compute either the sqr or the sqrt of the input') + _ctab_inputs = ('color_table_file', 'default_color_table', + 'gca_color_table') + color_table_file = File( + exists=True, + argstr='--ctab %s', + xor=_ctab_inputs, + desc='color table file with seg id names') + default_color_table = traits.Bool( + argstr='--ctab-default', + xor=_ctab_inputs, + desc='use $FREESURFER_HOME/FreeSurferColorLUT.txt') + gca_color_table = File( + exists=True, + argstr='--ctab-gca %s', + xor=_ctab_inputs, + desc='get color table from GCA (CMA)') + segment_id = traits.List( + argstr='--id %s...', desc='Manually specify segmentation ids') + exclude_id = traits.Int( + argstr='--excludeid %d', desc='Exclude seg id from report') + exclude_ctx_gm_wm = traits.Bool( + argstr='--excl-ctxgmwm', desc='exclude cortical gray and white matter') + wm_vol_from_surf = traits.Bool( + argstr='--surf-wm-vol', desc='Compute wm volume from surf') + cortex_vol_from_surf = traits.Bool( + argstr='--surf-ctx-vol', desc='Compute cortex volume from surf') + non_empty_only = traits.Bool( + argstr='--nonempty', desc='Only report nonempty segmentations') + empty = traits.Bool( + argstr="--empty", + desc="Report on segmentations listed in the color table") + mask_file = File( + exists=True, argstr='--mask %s', desc='Mask volume (same size as seg') + mask_thresh = traits.Float( + argstr='--maskthresh %f', + desc='binarize mask with this threshold <0.5>') + mask_sign = traits.Enum( + 'abs', + 'pos', + 'neg', + '--masksign %s', + desc='Sign for mask threshold: pos, neg, or abs') + mask_frame = traits.Int( + '--maskframe %d', + requires=['mask_file'], + desc='Mask with this (0 based) frame of the mask volume') + mask_invert = traits.Bool( + argstr='--maskinvert', desc='Invert binarized mask volume') + mask_erode = traits.Int( + argstr='--maskerode %d', desc='Erode mask by some amount') + brain_vol = traits.Enum( + 'brain-vol-from-seg', + 'brainmask', + argstr='--%s', + desc= + 'Compute brain volume either with ``brainmask`` or ``brain-vol-from-seg``' + ) + brainmask_file = File( + argstr="--brainmask %s", + exists=True, + desc= + "Load brain mask and compute the volume of the brain as the non-zero voxels in this volume" + ) + etiv = traits.Bool( + argstr='--etiv', desc='Compute ICV from talairach transform') + etiv_only = traits.Enum( + 'etiv', + 'old-etiv', + '--%s-only', + desc='Compute etiv and exit. Use ``etiv`` or ``old-etiv``') + avgwf_txt_file = traits.Either( + traits.Bool, + File, + argstr='--avgwf %s', + desc='Save average waveform into file (bool or filename)') + avgwf_file = traits.Either( + traits.Bool, + File, + argstr='--avgwfvol %s', + desc='Save as binary volume (bool or filename)') + sf_avg_file = traits.Either( + traits.Bool, + File, + argstr='--sfavg %s', + desc='Save mean across space and time') + vox = traits.List( + traits.Int, + argstr='--vox %s', + desc='Replace seg with all 0s except at C R S (three int inputs)') + supratent = traits.Bool( + argstr="--supratent", desc="Undocumented input flag") + subcort_gm = traits.Bool( + argstr="--subcortgray", + desc="Compute volume of subcortical gray matter") + total_gray = traits.Bool( + argstr="--totalgray", desc="Compute volume of total gray matter") + euler = traits.Bool( + argstr="--euler", + desc= + "Write out number of defect holes in orig.nofix based on the euler number" + ) + in_intensity = File( + argstr="--in %s --in-intensity-name %s", + desc="Undocumented input norm.mgz file") + intensity_units = traits.Enum( + 'MR', + argstr="--in-intensity-units %s", + requires=["in_intensity"], + desc="Intensity units") class SegStatsOutputSpec(TraitedSpec): - summary_file = File(exists=True, desc='Segmentation summary statistics table') - avgwf_txt_file = File(desc='Text file with functional statistics averaged over segs') - avgwf_file = File(desc='Volume with functional statistics averaged over segs') - sf_avg_file = File(desc='Text file with func statistics averaged over segs and framss') + summary_file = File( + exists=True, desc='Segmentation summary statistics table') + avgwf_txt_file = File( + desc='Text file with functional statistics averaged over segs') + avgwf_file = File( + desc='Volume with functional statistics averaged over segs') + sf_avg_file = File( + desc='Text file with func statistics averaged over segs and framss') class SegStats(FSCommand): @@ -733,9 +941,12 @@ def _list_outputs(self): if isdefined(self.inputs.summary_file): outputs['summary_file'] = os.path.abspath(self.inputs.summary_file) else: - outputs['summary_file'] = os.path.join(os.getcwd(), 'summary.stats') - suffices = dict(avgwf_txt_file='_avgwf.txt', avgwf_file='_avgwf.nii.gz', - sf_avg_file='sfavg.txt') + outputs['summary_file'] = os.path.join(os.getcwd(), + 'summary.stats') + suffices = dict( + avgwf_txt_file='_avgwf.txt', + avgwf_file='_avgwf.nii.gz', + sf_avg_file='sfavg.txt') if isdefined(self.inputs.segmentation_file): _, src = os.path.split(self.inputs.segmentation_file) if isdefined(self.inputs.annot): @@ -746,9 +957,8 @@ def _list_outputs(self): value = getattr(self.inputs, name) if isdefined(value): if isinstance(value, bool): - outputs[name] = fname_presuffix(src, suffix=suffix, - newpath=os.getcwd(), - use_ext=False) + outputs[name] = fname_presuffix( + src, suffix=suffix, newpath=os.getcwd(), use_ext=False) else: outputs[name] = os.path.abspath(value) return outputs @@ -765,7 +975,8 @@ def _format_arg(self, name, spec, value): fname = value return spec.argstr % fname elif name == 'in_intensity': - intensity_name = os.path.basename(self.inputs.in_intensity).replace('.mgz', '') + intensity_name = os.path.basename( + self.inputs.in_intensity).replace('.mgz', '') return spec.argstr % (value, intensity_name) return super(SegStats, self)._format_arg(name, spec, value) @@ -777,37 +988,44 @@ def _gen_filename(self, name): class SegStatsReconAllInputSpec(SegStatsInputSpec): # recon-all input requirements - subject_id = traits.String('subject_id', usedefault=True, - argstr="--subject %s", mandatory=True, - desc="Subject id being processed") + subject_id = traits.String( + 'subject_id', + usedefault=True, + argstr="--subject %s", + mandatory=True, + desc="Subject id being processed") # implicit - ribbon = traits.File(mandatory=True, exists=True, - desc="Input file mri/ribbon.mgz") - presurf_seg = File(exists=True, - desc="Input segmentation volume") - transform = File(mandatory=True, exists=True, - desc="Input transform file") - lh_orig_nofix = File(mandatory=True, exists=True, - desc="Input lh.orig.nofix") - rh_orig_nofix = File(mandatory=True, exists=True, - desc="Input rh.orig.nofix") - lh_white = File(mandatory=True, exists=True, - desc="Input file must be /surf/lh.white") - rh_white = File(mandatory=True, exists=True, - desc="Input file must be /surf/rh.white") - lh_pial = File(mandatory=True, exists=True, - desc="Input file must be /surf/lh.pial") - rh_pial = File(mandatory=True, exists=True, - desc="Input file must be /surf/rh.pial") - aseg = File(exists=True, - desc="Mandatory implicit input in 5.3") + ribbon = traits.File( + mandatory=True, exists=True, desc="Input file mri/ribbon.mgz") + presurf_seg = File(exists=True, desc="Input segmentation volume") + transform = File(mandatory=True, exists=True, desc="Input transform file") + lh_orig_nofix = File( + mandatory=True, exists=True, desc="Input lh.orig.nofix") + rh_orig_nofix = File( + mandatory=True, exists=True, desc="Input rh.orig.nofix") + lh_white = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/lh.white") + rh_white = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/rh.white") + lh_pial = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/lh.pial") + rh_pial = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/rh.pial") + aseg = File(exists=True, desc="Mandatory implicit input in 5.3") copy_inputs = traits.Bool(desc="If running as a node, set this to True " + - "otherwise, this will copy the implicit inputs " + - "to the node directory.") + "otherwise, this will copy the implicit inputs " + + "to the node directory.") class SegStatsReconAll(SegStats): - """ This class inherits SegStats and modifies it for use in a recon-all workflow. This implementation mandates implicit inputs that SegStats. @@ -857,89 +1075,100 @@ def run(self, **inputs): self.inputs.subjects_dir = os.getcwd() if 'subjects_dir' in inputs: inputs['subjects_dir'] = self.inputs.subjects_dir - copy2subjdir(self, self.inputs.lh_orig_nofix, - 'surf', 'lh.orig.nofix') - copy2subjdir(self, self.inputs.rh_orig_nofix, - 'surf', 'rh.orig.nofix') - copy2subjdir(self, self.inputs.lh_white, - 'surf', 'lh.white') - copy2subjdir(self, self.inputs.rh_white, - 'surf', 'rh.white') - copy2subjdir(self, self.inputs.lh_pial, - 'surf', 'lh.pial') - copy2subjdir(self, self.inputs.rh_pial, - 'surf', 'rh.pial') - copy2subjdir(self, self.inputs.ribbon, - 'mri', 'ribbon.mgz') - copy2subjdir(self, self.inputs.presurf_seg, - 'mri', 'aseg.presurf.mgz') - copy2subjdir(self, self.inputs.aseg, - 'mri', 'aseg.mgz') + copy2subjdir(self, self.inputs.lh_orig_nofix, 'surf', + 'lh.orig.nofix') + copy2subjdir(self, self.inputs.rh_orig_nofix, 'surf', + 'rh.orig.nofix') + copy2subjdir(self, self.inputs.lh_white, 'surf', 'lh.white') + copy2subjdir(self, self.inputs.rh_white, 'surf', 'rh.white') + copy2subjdir(self, self.inputs.lh_pial, 'surf', 'lh.pial') + copy2subjdir(self, self.inputs.rh_pial, 'surf', 'rh.pial') + copy2subjdir(self, self.inputs.ribbon, 'mri', 'ribbon.mgz') + copy2subjdir(self, self.inputs.presurf_seg, 'mri', + 'aseg.presurf.mgz') + copy2subjdir(self, self.inputs.aseg, 'mri', 'aseg.mgz') copy2subjdir(self, self.inputs.transform, - os.path.join('mri', 'transforms'), - 'talairach.xfm') + os.path.join('mri', 'transforms'), 'talairach.xfm') copy2subjdir(self, self.inputs.in_intensity, 'mri') copy2subjdir(self, self.inputs.brainmask_file, 'mri') return super(SegStatsReconAll, self).run(**inputs) class Label2VolInputSpec(FSTraitedSpec): - label_file = InputMultiPath(File(exists=True), argstr='--label %s...', - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - copyfile=False, - mandatory=True, - desc='list of label files') - annot_file = File(exists=True, argstr='--annot %s', - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - requires=('subject_id', 'hemi'), - mandatory=True, - copyfile=False, - desc='surface annotation file') - seg_file = File(exists=True, argstr='--seg %s', - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - mandatory=True, - copyfile=False, - desc='segmentation file') - aparc_aseg = traits.Bool(argstr='--aparc+aseg', - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - mandatory=True, - desc='use aparc+aseg.mgz in subjectdir as seg') - template_file = File(exists=True, argstr='--temp %s', mandatory=True, - desc='output template volume') - reg_file = File(exists=True, argstr='--reg %s', - xor=('reg_file', 'reg_header', 'identity'), - desc='tkregister style matrix VolXYZ = R*LabelXYZ') - reg_header = File(exists=True, argstr='--regheader %s', - xor=('reg_file', 'reg_header', 'identity'), - desc='label template volume') - identity = traits.Bool(argstr='--identity', - xor=('reg_file', 'reg_header', 'identity'), - desc='set R=I') - invert_mtx = traits.Bool(argstr='--invertmtx', - desc='Invert the registration matrix') - fill_thresh = traits.Range(0., 1., argstr='--fillthresh %.f', - desc='thresh : between 0 and 1') - label_voxel_volume = traits.Float(argstr='--labvoxvol %f', - desc='volume of each label point (def 1mm3)') - proj = traits.Tuple(traits.Enum('abs', 'frac'), traits.Float, - traits.Float, traits.Float, - argstr='--proj %s %f %f %f', - requires=('subject_id', 'hemi'), - desc='project along surface normal') - subject_id = traits.Str(argstr='--subject %s', - desc='subject id') - hemi = traits.Enum('lh', 'rh', argstr='--hemi %s', - desc='hemisphere to use lh or rh') - surface = traits.Str(argstr='--surf %s', - desc='use surface instead of white') - vol_label_file = File(argstr='--o %s', genfile=True, - desc='output volume') - label_hit_file = File(argstr='--hits %s', - desc='file with each frame is nhits for a label') - map_label_stat = File(argstr='--label-stat %s', - desc='map the label stats field into the vol') - native_vox2ras = traits.Bool(argstr='--native-vox2ras', - desc='use native vox2ras xform instead of tkregister-style') + label_file = InputMultiPath( + File(exists=True), + argstr='--label %s...', + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + copyfile=False, + mandatory=True, + desc='list of label files') + annot_file = File( + exists=True, + argstr='--annot %s', + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + requires=('subject_id', 'hemi'), + mandatory=True, + copyfile=False, + desc='surface annotation file') + seg_file = File( + exists=True, + argstr='--seg %s', + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + mandatory=True, + copyfile=False, + desc='segmentation file') + aparc_aseg = traits.Bool( + argstr='--aparc+aseg', + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + mandatory=True, + desc='use aparc+aseg.mgz in subjectdir as seg') + template_file = File( + exists=True, + argstr='--temp %s', + mandatory=True, + desc='output template volume') + reg_file = File( + exists=True, + argstr='--reg %s', + xor=('reg_file', 'reg_header', 'identity'), + desc='tkregister style matrix VolXYZ = R*LabelXYZ') + reg_header = File( + exists=True, + argstr='--regheader %s', + xor=('reg_file', 'reg_header', 'identity'), + desc='label template volume') + identity = traits.Bool( + argstr='--identity', + xor=('reg_file', 'reg_header', 'identity'), + desc='set R=I') + invert_mtx = traits.Bool( + argstr='--invertmtx', desc='Invert the registration matrix') + fill_thresh = traits.Range( + 0., 1., argstr='--fillthresh %.f', desc='thresh : between 0 and 1') + label_voxel_volume = traits.Float( + argstr='--labvoxvol %f', desc='volume of each label point (def 1mm3)') + proj = traits.Tuple( + traits.Enum('abs', 'frac'), + traits.Float, + traits.Float, + traits.Float, + argstr='--proj %s %f %f %f', + requires=('subject_id', 'hemi'), + desc='project along surface normal') + subject_id = traits.Str(argstr='--subject %s', desc='subject id') + hemi = traits.Enum( + 'lh', 'rh', argstr='--hemi %s', desc='hemisphere to use lh or rh') + surface = traits.Str( + argstr='--surf %s', desc='use surface instead of white') + vol_label_file = File(argstr='--o %s', genfile=True, desc='output volume') + label_hit_file = File( + argstr='--hits %s', desc='file with each frame is nhits for a label') + map_label_stat = File( + argstr='--label-stat %s', + desc='map the label stats field into the vol') + native_vox2ras = traits.Bool( + argstr='--native-vox2ras', + desc='use native vox2ras xform instead of tkregister-style') class Label2VolOutputSpec(TraitedSpec): @@ -974,9 +1203,8 @@ def _list_outputs(self): _, src = os.path.split(path) if isdefined(self.inputs.aparc_aseg): src = 'aparc+aseg.mgz' - outfile = fname_presuffix(src, suffix='_vol.nii.gz', - newpath=os.getcwd(), - use_ext=False) + outfile = fname_presuffix( + src, suffix='_vol.nii.gz', newpath=os.getcwd(), use_ext=False) outputs['vol_label_file'] = outfile return outputs @@ -987,30 +1215,48 @@ def _gen_filename(self, name): class MS_LDAInputSpec(FSTraitedSpec): - lda_labels = traits.List(traits.Int(), argstr='-lda %s', mandatory=True, - minlen=2, maxlen=2, sep=' ', - desc='pair of class labels to optimize') - weight_file = traits.File(argstr='-weight %s', mandatory=True, - desc='filename for the LDA weights (input or output)') - vol_synth_file = traits.File(exists=False, argstr='-synth %s', - mandatory=True, - desc=('filename for the synthesized output ' - 'volume')) - label_file = traits.File(exists=True, argstr='-label %s', - desc='filename of the label volume') - mask_file = traits.File(exists=True, argstr='-mask %s', - desc='filename of the brain mask volume') - shift = traits.Int(argstr='-shift %d', - desc='shift all values equal to the given value to zero') - conform = traits.Bool(argstr='-conform', - desc=('Conform the input volumes (brain mask ' - 'typically already conformed)')) - use_weights = traits.Bool(argstr='-W', - desc=('Use the weights from a previously ' - 'generated weight file')) - images = InputMultiPath(File(exists=True), argstr='%s', mandatory=True, - copyfile=False, desc='list of input FLASH images', - position=-1) + lda_labels = traits.List( + traits.Int(), + argstr='-lda %s', + mandatory=True, + minlen=2, + maxlen=2, + sep=' ', + desc='pair of class labels to optimize') + weight_file = traits.File( + argstr='-weight %s', + mandatory=True, + desc='filename for the LDA weights (input or output)') + vol_synth_file = traits.File( + exists=False, + argstr='-synth %s', + mandatory=True, + desc=('filename for the synthesized output ' + 'volume')) + label_file = traits.File( + exists=True, argstr='-label %s', desc='filename of the label volume') + mask_file = traits.File( + exists=True, + argstr='-mask %s', + desc='filename of the brain mask volume') + shift = traits.Int( + argstr='-shift %d', + desc='shift all values equal to the given value to zero') + conform = traits.Bool( + argstr='-conform', + desc=('Conform the input volumes (brain mask ' + 'typically already conformed)')) + use_weights = traits.Bool( + argstr='-W', + desc=('Use the weights from a previously ' + 'generated weight file')) + images = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + copyfile=False, + desc='list of input FLASH images', + position=-1) class MS_LDAOutputSpec(TraitedSpec): @@ -1043,16 +1289,20 @@ class MS_LDA(FSCommand): def _list_outputs(self): outputs = self._outputs().get() if isdefined(self.inputs.output_synth): - outputs['vol_synth_file'] = os.path.abspath(self.inputs.output_synth) + outputs['vol_synth_file'] = os.path.abspath( + self.inputs.output_synth) else: - outputs['vol_synth_file'] = os.path.abspath(self.inputs.vol_synth_file) - if not isdefined(self.inputs.use_weights) or self.inputs.use_weights is False: + outputs['vol_synth_file'] = os.path.abspath( + self.inputs.vol_synth_file) + if not isdefined( + self.inputs.use_weights) or self.inputs.use_weights is False: outputs['weight_file'] = os.path.abspath(self.inputs.weight_file) return outputs def _verify_weights_file_exists(self): if not os.path.exists(os.path.abspath(self.inputs.weight_file)): - raise traits.TraitError("MS_LDA: use_weights must accompany an existing weights file") + raise traits.TraitError( + "MS_LDA: use_weights must accompany an existing weights file") def _format_arg(self, name, spec, value): if name == 'use_weights': @@ -1068,33 +1318,55 @@ def _gen_filename(self, name): class Label2LabelInputSpec(FSTraitedSpec): - hemisphere = traits.Enum('lh', 'rh', argstr="--hemi %s", mandatory=True, - desc="Input hemisphere") - subject_id = traits.String('subject_id', usedefault=True, - argstr="--trgsubject %s", mandatory=True, - desc="Target subject") - sphere_reg = File(mandatory=True, exists=True, - desc="Implicit input .sphere.reg") - white = File(mandatory=True, exists=True, - desc="Implicit input .white") - source_sphere_reg = File(mandatory=True, exists=True, - desc="Implicit input .sphere.reg") - source_white = File(mandatory=True, exists=True, - desc="Implicit input .white") - source_label = File(argstr="--srclabel %s", mandatory=True, exists=True, - desc="Source label") - source_subject = traits.String(argstr="--srcsubject %s", mandatory=True, - desc="Source subject name") + hemisphere = traits.Enum( + 'lh', + 'rh', + argstr="--hemi %s", + mandatory=True, + desc="Input hemisphere") + subject_id = traits.String( + 'subject_id', + usedefault=True, + argstr="--trgsubject %s", + mandatory=True, + desc="Target subject") + sphere_reg = File( + mandatory=True, + exists=True, + desc="Implicit input .sphere.reg") + white = File( + mandatory=True, exists=True, desc="Implicit input .white") + source_sphere_reg = File( + mandatory=True, + exists=True, + desc="Implicit input .sphere.reg") + source_white = File( + mandatory=True, exists=True, desc="Implicit input .white") + source_label = File( + argstr="--srclabel %s", + mandatory=True, + exists=True, + desc="Source label") + source_subject = traits.String( + argstr="--srcsubject %s", mandatory=True, desc="Source subject name") # optional - out_file = File(argstr="--trglabel %s", - name_source=['source_label'], name_template='%s_converted', - hash_files=False, keep_extension=True, - desc="Target label") - registration_method = traits.Enum('surface', 'volume', usedefault=True, - argstr="--regmethod %s", desc="Registration method") - copy_inputs = traits.Bool(desc="If running as a node, set this to True." + - "This will copy the input files to the node " + - "directory.") + out_file = File( + argstr="--trglabel %s", + name_source=['source_label'], + name_template='%s_converted', + hash_files=False, + keep_extension=True, + desc="Target label") + registration_method = traits.Enum( + 'surface', + 'volume', + usedefault=True, + argstr="--regmethod %s", + desc="Registration method") + copy_inputs = traits.Bool( + desc="If running as a node, set this to True." + + "This will copy the input files to the node " + "directory.") + class Label2LabelOutputSpec(TraitedSpec): out_file = File(exists=True, desc='Output label') @@ -1135,8 +1407,7 @@ class Label2Label(FSCommand): def _list_outputs(self): outputs = self._outputs().get() outputs['out_file'] = os.path.join(self.inputs.subjects_dir, - self.inputs.subject_id, - 'label', + self.inputs.subject_id, 'label', self.inputs.out_file) return outputs @@ -1150,17 +1421,22 @@ def run(self, **inputs): '{0}.sphere.reg'.format(hemi)) copy2subjdir(self, self.inputs.white, 'surf', '{0}.white'.format(hemi)) - copy2subjdir(self, self.inputs.source_sphere_reg, 'surf', - '{0}.sphere.reg'.format(hemi), - subject_id=self.inputs.source_subject) - copy2subjdir(self, self.inputs.source_white, 'surf', - '{0}.white'.format(hemi), - subject_id=self.inputs.source_subject) + copy2subjdir( + self, + self.inputs.source_sphere_reg, + 'surf', + '{0}.sphere.reg'.format(hemi), + subject_id=self.inputs.source_subject) + copy2subjdir( + self, + self.inputs.source_white, + 'surf', + '{0}.white'.format(hemi), + subject_id=self.inputs.source_subject) # label dir must exist in order for output file to be written label_dir = os.path.join(self.inputs.subjects_dir, - self.inputs.subject_id, - 'label') + self.inputs.subject_id, 'label') if not os.path.isdir(label_dir): os.makedirs(label_dir) @@ -1169,26 +1445,39 @@ def run(self, **inputs): class Label2AnnotInputSpec(FSTraitedSpec): # required - hemisphere = traits.Enum('lh', 'rh', - argstr="--hemi %s", mandatory=True, - desc="Input hemisphere") - subject_id = traits.String('subject_id', usedefault=True, - argstr="--s %s", mandatory=True, - desc="Subject name/ID") - in_labels = traits.List(argstr="--l %s...", mandatory=True, - desc="List of input label files") - out_annot = traits.String(argstr="--a %s", mandatory=True, - desc="Name of the annotation to create") - orig = File(exists=True, mandatory=True, - desc="implicit {hemisphere}.orig") + hemisphere = traits.Enum( + 'lh', + 'rh', + argstr="--hemi %s", + mandatory=True, + desc="Input hemisphere") + subject_id = traits.String( + 'subject_id', + usedefault=True, + argstr="--s %s", + mandatory=True, + desc="Subject name/ID") + in_labels = traits.List( + argstr="--l %s...", mandatory=True, desc="List of input label files") + out_annot = traits.String( + argstr="--a %s", + mandatory=True, + desc="Name of the annotation to create") + orig = File(exists=True, mandatory=True, desc="implicit {hemisphere}.orig") # optional - keep_max = traits.Bool(argstr="--maxstatwinner", - desc="Keep label with highest 'stat' value") - verbose_off = traits.Bool(argstr="--noverbose", - desc="Turn off overlap and stat override messages") - color_table = File(argstr="--ctab %s", exists=True, - desc="File that defines the structure names, their indices, and their color") - copy_inputs = traits.Bool(desc="copy implicit inputs and create a temp subjects_dir") + keep_max = traits.Bool( + argstr="--maxstatwinner", desc="Keep label with highest 'stat' value") + verbose_off = traits.Bool( + argstr="--noverbose", + desc="Turn off overlap and stat override messages") + color_table = File( + argstr="--ctab %s", + exists=True, + desc= + "File that defines the structure names, their indices, and their color" + ) + copy_inputs = traits.Bool( + desc="copy implicit inputs and create a temp subjects_dir") class Label2AnnotOutputSpec(TraitedSpec): @@ -1221,50 +1510,80 @@ def run(self, **inputs): self.inputs.subjects_dir = os.getcwd() if 'subjects_dir' in inputs: inputs['subjects_dir'] = self.inputs.subjects_dir - copy2subjdir(self, self.inputs.orig, - folder='surf', - basename='{0}.orig'.format(self.inputs.hemisphere)) + copy2subjdir( + self, + self.inputs.orig, + folder='surf', + basename='{0}.orig'.format(self.inputs.hemisphere)) # label dir must exist in order for output file to be written label_dir = os.path.join(self.inputs.subjects_dir, - self.inputs.subject_id, - 'label') + self.inputs.subject_id, 'label') if not os.path.isdir(label_dir): os.makedirs(label_dir) return super(Label2Annot, self).run(**inputs) def _list_outputs(self): outputs = self._outputs().get() - outputs["out_file"] = os.path.join(str(self.inputs.subjects_dir), - str(self.inputs.subject_id), - 'label', - str(self.inputs.hemisphere) + '.' + str(self.inputs.out_annot) + '.annot') + outputs["out_file"] = os.path.join( + str(self.inputs.subjects_dir), str(self.inputs.subject_id), + 'label', + str(self.inputs.hemisphere) + '.' + str(self.inputs.out_annot) + + '.annot') return outputs class SphericalAverageInputSpec(FSTraitedSpec): - out_file = File(argstr="%s", genfile=True, exists=False, - position=-1, desc="Output filename") - in_average = traits.Directory(argstr="%s", exists=True, genfile=True, - position=-2, desc="Average subject") - in_surf = File(argstr="%s", mandatory=True, exists=True, - position=-3, desc="Input surface file") - hemisphere = traits.Enum('lh', 'rh', argstr="%s", mandatory=True, - position=-4, desc="Input hemisphere") - fname = traits.String(argstr="%s", mandatory=True, position=-5, - desc="""Filename from the average subject directory. + out_file = File( + argstr="%s", + genfile=True, + exists=False, + position=-1, + desc="Output filename") + in_average = traits.Directory( + argstr="%s", + exists=True, + genfile=True, + position=-2, + desc="Average subject") + in_surf = File( + argstr="%s", + mandatory=True, + exists=True, + position=-3, + desc="Input surface file") + hemisphere = traits.Enum( + 'lh', + 'rh', + argstr="%s", + mandatory=True, + position=-4, + desc="Input hemisphere") + fname = traits.String( + argstr="%s", + mandatory=True, + position=-5, + desc="""Filename from the average subject directory. Example: to use rh.entorhinal.label as the input label filename, set fname to 'rh.entorhinal' and which to 'label'. The program will then search for '{in_average}/label/rh.entorhinal.label' """) - which = traits.Enum('coords', 'label', 'vals', 'curv', 'area', - argstr="%s", mandatory=True, position=-6, desc="No documentation") + which = traits.Enum( + 'coords', + 'label', + 'vals', + 'curv', + 'area', + argstr="%s", + mandatory=True, + position=-6, + desc="No documentation") subject_id = traits.String( argstr="-o %s", mandatory=True, desc="Output subject id") # optional erode = traits.Int(argstr="-erode %d", desc="Undocumented") - in_orig = File(argstr="-orig %s", exists=True, - desc="Original surface filename") + in_orig = File( + argstr="-orig %s", exists=True, desc="Original surface filename") threshold = traits.Float(argstr="-t %.1f", desc="Undocumented") @@ -1311,7 +1630,6 @@ def _gen_filename(self, name): avg_directory = os.path.join(self.inputs.subjects_dir, avg_subject) if not os.path.isdir(avg_directory): fs_home = os.path.abspath(os.environ.get('FREESURFER_HOME')) - avg_home = os.path.join(fs_home, 'subjects', 'fsaverage') return avg_subject elif name == 'out_file': return self._list_outputs()[name] @@ -1323,12 +1641,13 @@ def _list_outputs(self): if isdefined(self.inputs.out_file): outputs['out_file'] = os.path.abspath(self.inputs.out_file) else: - out_dir = os.path.join( - self.inputs.subjects_dir, self.inputs.subject_id, 'label') + out_dir = os.path.join(self.inputs.subjects_dir, + self.inputs.subject_id, 'label') if isdefined(self.inputs.in_average): basename = os.path.basename(self.inputs.in_average) basename = basename.replace('_', '_exvivo_') + '.label' else: - basename = str(self.inputs.hemisphere) + '.EC_exvivo_average.label' + basename = str( + self.inputs.hemisphere) + '.EC_exvivo_average.label' outputs['out_file'] = os.path.join(out_dir, basename) return outputs diff --git a/nipype/interfaces/freesurfer/preprocess.py b/nipype/interfaces/freesurfer/preprocess.py index 1d209c3022..3e70200ad3 100644 --- a/nipype/interfaces/freesurfer/preprocess.py +++ b/nipype/interfaces/freesurfer/preprocess.py @@ -10,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range import os @@ -24,12 +25,10 @@ from ... import logging, LooseVersion from ...utils.filemanip import fname_presuffix, check_depends from ..io import FreeSurferSource -from ..base import (TraitedSpec, File, traits, - Directory, InputMultiPath, - OutputMultiPath, CommandLine, - CommandLineInputSpec, isdefined) -from .base import (FSCommand, FSTraitedSpec, - FSTraitedSpecOpenMP, +from ..base import (TraitedSpec, File, traits, Directory, InputMultiPath, + OutputMultiPath, CommandLine, CommandLineInputSpec, + isdefined) +from .base import (FSCommand, FSTraitedSpec, FSTraitedSpecOpenMP, FSCommandOpenMP, Info) from .utils import copy2subjdir @@ -42,18 +41,24 @@ class ParseDICOMDirInputSpec(FSTraitedSpec): - dicom_dir = Directory(exists=True, argstr='--d %s', mandatory=True, - desc='path to siemens dicom directory') - dicom_info_file = File('dicominfo.txt', argstr='--o %s', usedefault=True, - desc='file to which results are written') + dicom_dir = Directory( + exists=True, + argstr='--d %s', + mandatory=True, + desc='path to siemens dicom directory') + dicom_info_file = File( + 'dicominfo.txt', + argstr='--o %s', + usedefault=True, + desc='file to which results are written') sortbyrun = traits.Bool(argstr='--sortbyrun', desc='assign run numbers') - summarize = traits.Bool(argstr='--summarize', - desc='only print out info for run leaders') + summarize = traits.Bool( + argstr='--summarize', desc='only print out info for run leaders') class ParseDICOMDirOutputSpec(TraitedSpec): - dicom_info_file = File(exists=True, - desc='text file containing dicom information') + dicom_info_file = File( + exists=True, desc='text file containing dicom information') class ParseDICOMDir(FSCommand): @@ -79,41 +84,59 @@ class ParseDICOMDir(FSCommand): def _list_outputs(self): outputs = self.output_spec().get() if isdefined(self.inputs.dicom_info_file): - outputs['dicom_info_file'] = os.path.join(os.getcwd(), self.inputs.dicom_info_file) + outputs['dicom_info_file'] = os.path.join( + os.getcwd(), self.inputs.dicom_info_file) return outputs class UnpackSDICOMDirInputSpec(FSTraitedSpec): - source_dir = Directory(exists=True, argstr='-src %s', - mandatory=True, - desc='directory with the DICOM files') - output_dir = Directory(argstr='-targ %s', - desc='top directory into which the files will be unpacked') - run_info = traits.Tuple(traits.Int, traits.Str, traits.Str, traits.Str, - mandatory=True, - argstr='-run %d %s %s %s', - xor=('run_info', 'config', 'seq_config'), - desc='runno subdir format name : spec unpacking rules on cmdline') - config = File(exists=True, argstr='-cfg %s', - mandatory=True, - xor=('run_info', 'config', 'seq_config'), - desc='specify unpacking rules in file') - seq_config = File(exists=True, argstr='-seqcfg %s', - mandatory=True, - xor=('run_info', 'config', 'seq_config'), - desc='specify unpacking rules based on sequence') - dir_structure = traits.Enum('fsfast', 'generic', argstr='-%s', - desc='unpack to specified directory structures') - no_info_dump = traits.Bool(argstr='-noinfodump', - desc='do not create infodump file') - scan_only = File(exists=True, argstr='-scanonly %s', - desc='only scan the directory and put result in file') - log_file = File(exists=True, argstr='-log %s', - desc='explicilty set log file') - spm_zeropad = traits.Int(argstr='-nspmzeropad %d', - desc='set frame number zero padding width for SPM') - no_unpack_err = traits.Bool(argstr='-no-unpackerr', - desc='do not try to unpack runs with errors') + source_dir = Directory( + exists=True, + argstr='-src %s', + mandatory=True, + desc='directory with the DICOM files') + output_dir = Directory( + argstr='-targ %s', + desc='top directory into which the files will be unpacked') + run_info = traits.Tuple( + traits.Int, + traits.Str, + traits.Str, + traits.Str, + mandatory=True, + argstr='-run %d %s %s %s', + xor=('run_info', 'config', 'seq_config'), + desc='runno subdir format name : spec unpacking rules on cmdline') + config = File( + exists=True, + argstr='-cfg %s', + mandatory=True, + xor=('run_info', 'config', 'seq_config'), + desc='specify unpacking rules in file') + seq_config = File( + exists=True, + argstr='-seqcfg %s', + mandatory=True, + xor=('run_info', 'config', 'seq_config'), + desc='specify unpacking rules based on sequence') + dir_structure = traits.Enum( + 'fsfast', + 'generic', + argstr='-%s', + desc='unpack to specified directory structures') + no_info_dump = traits.Bool( + argstr='-noinfodump', desc='do not create infodump file') + scan_only = File( + exists=True, + argstr='-scanonly %s', + desc='only scan the directory and put result in file') + log_file = File( + exists=True, argstr='-log %s', desc='explicilty set log file') + spm_zeropad = traits.Int( + argstr='-nspmzeropad %d', + desc='set frame number zero padding width for SPM') + no_unpack_err = traits.Bool( + argstr='-no-unpackerr', desc='do not try to unpack runs with errors') class UnpackSDICOMDir(FSCommand): @@ -139,201 +162,263 @@ class UnpackSDICOMDir(FSCommand): class MRIConvertInputSpec(FSTraitedSpec): - read_only = traits.Bool(argstr='--read_only', - desc='read the input volume') - no_write = traits.Bool(argstr='--no_write', - desc='do not write output') - in_info = traits.Bool(argstr='--in_info', - desc='display input info') - out_info = traits.Bool(argstr='--out_info', - desc='display output info') - in_stats = traits.Bool(argstr='--in_stats', - desc='display input stats') - out_stats = traits.Bool(argstr='--out_stats', - desc='display output stats') - in_matrix = traits.Bool(argstr='--in_matrix', - desc='display input matrix') - out_matrix = traits.Bool(argstr='--out_matrix', - desc='display output matrix') - in_i_size = traits.Int(argstr='--in_i_size %d', - desc='input i size') - in_j_size = traits.Int(argstr='--in_j_size %d', - desc='input j size') - in_k_size = traits.Int(argstr='--in_k_size %d', - desc='input k size') - force_ras = traits.Bool(argstr='--force_ras_good', - desc='use default when orientation info absent') - in_i_dir = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='--in_i_direction %f %f %f', - desc=' ') - in_j_dir = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='--in_j_direction %f %f %f', - desc=' ') - in_k_dir = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='--in_k_direction %f %f %f', - desc=' ') - _orientations = ['LAI', 'LIA', 'ALI', 'AIL', 'ILA', 'IAL', 'LAS', 'LSA', 'ALS', 'ASL', 'SLA', 'SAL', 'LPI', 'LIP', 'PLI', 'PIL', 'ILP', 'IPL', 'LPS', 'LSP', 'PLS', 'PSL', 'SLP', 'SPL', 'RAI', 'RIA', 'ARI', 'AIR', 'IRA', 'IAR', 'RAS', 'RSA', 'ARS', 'ASR', 'SRA', 'SAR', 'RPI', 'RIP', 'PRI', 'PIR', 'IRP', 'IPR', 'RPS', 'RSP', 'PRS', 'PSR', 'SRP', 'SPR'] + read_only = traits.Bool(argstr='--read_only', desc='read the input volume') + no_write = traits.Bool(argstr='--no_write', desc='do not write output') + in_info = traits.Bool(argstr='--in_info', desc='display input info') + out_info = traits.Bool(argstr='--out_info', desc='display output info') + in_stats = traits.Bool(argstr='--in_stats', desc='display input stats') + out_stats = traits.Bool(argstr='--out_stats', desc='display output stats') + in_matrix = traits.Bool(argstr='--in_matrix', desc='display input matrix') + out_matrix = traits.Bool( + argstr='--out_matrix', desc='display output matrix') + in_i_size = traits.Int(argstr='--in_i_size %d', desc='input i size') + in_j_size = traits.Int(argstr='--in_j_size %d', desc='input j size') + in_k_size = traits.Int(argstr='--in_k_size %d', desc='input k size') + force_ras = traits.Bool( + argstr='--force_ras_good', + desc='use default when orientation info absent') + in_i_dir = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='--in_i_direction %f %f %f', + desc=' ') + in_j_dir = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='--in_j_direction %f %f %f', + desc=' ') + in_k_dir = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='--in_k_direction %f %f %f', + desc=' ') + _orientations = [ + 'LAI', 'LIA', 'ALI', 'AIL', 'ILA', 'IAL', 'LAS', 'LSA', 'ALS', 'ASL', + 'SLA', 'SAL', 'LPI', 'LIP', 'PLI', 'PIL', 'ILP', 'IPL', 'LPS', 'LSP', + 'PLS', 'PSL', 'SLP', 'SPL', 'RAI', 'RIA', 'ARI', 'AIR', 'IRA', 'IAR', + 'RAS', 'RSA', 'ARS', 'ASR', 'SRA', 'SAR', 'RPI', 'RIP', 'PRI', 'PIR', + 'IRP', 'IPR', 'RPS', 'RSP', 'PRS', 'PSR', 'SRP', 'SPR' + ] # _orientations = [comb for comb in itertools.chain(*[[''.join(c) for c in itertools.permutations(s)] for s in [a+b+c for a in 'LR' for b in 'AP' for c in 'IS']])] - in_orientation = traits.Enum(_orientations, - argstr='--in_orientation %s', - desc='specify the input orientation') - in_center = traits.List(traits.Float, maxlen=3, - argstr='--in_center %s', - desc=' ') - sphinx = traits.Bool(argstr='--sphinx', - desc='change orientation info to sphinx') - out_i_count = traits.Int(argstr='--out_i_count %d', - desc='some count ?? in i direction') - out_j_count = traits.Int(argstr='--out_j_count %d', - desc='some count ?? in j direction') - out_k_count = traits.Int(argstr='--out_k_count %d', - desc='some count ?? in k direction') - vox_size = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='-voxsize %f %f %f', - desc=' specify the size (mm) - useful for upsampling or downsampling') - out_i_size = traits.Int(argstr='--out_i_size %d', - desc='output i size') - out_j_size = traits.Int(argstr='--out_j_size %d', - desc='output j size') - out_k_size = traits.Int(argstr='--out_k_size %d', - desc='output k size') - out_i_dir = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='--out_i_direction %f %f %f', - desc=' ') - out_j_dir = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='--out_j_direction %f %f %f', - desc=' ') - out_k_dir = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='--out_k_direction %f %f %f', - desc=' ') - out_orientation = traits.Enum(_orientations, - argstr='--out_orientation %s', - desc='specify the output orientation') - out_center = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='--out_center %f %f %f', - desc=' ') - out_datatype = traits.Enum('uchar', 'short', 'int', 'float', - argstr='--out_data_type %s', - desc='output data type ') - resample_type = traits.Enum('interpolate', 'weighted', 'nearest', 'sinc', 'cubic', - argstr='--resample_type %s', - desc=' (default is interpolate)') - no_scale = traits.Bool(argstr='--no_scale 1', - desc='dont rescale values for COR') - no_change = traits.Bool(argstr='--nochange', - desc="don't change type of input to that of template") - tr = traits.Int(argstr='-tr %d', - desc='TR in msec') - te = traits.Int(argstr='-te %d', - desc='TE in msec') - ti = traits.Int(argstr='-ti %d', - desc='TI in msec (note upper case flag)') - autoalign_matrix = File(exists=True, argstr='--autoalign %s', - desc='text file with autoalign matrix') - unwarp_gradient = traits.Bool(argstr='--unwarp_gradient_nonlinearity', - desc='unwarp gradient nonlinearity') - apply_transform = File(exists=True, argstr='--apply_transform %s', - desc='apply xfm file') - apply_inv_transform = File(exists=True, argstr='--apply_inverse_transform %s', - desc='apply inverse transformation xfm file') - devolve_transform = traits.Str(argstr='--devolvexfm %s', - desc='subject id') - crop_center = traits.Tuple(traits.Int, traits.Int, traits.Int, - argstr='--crop %d %d %d', - desc=' crop to 256 around center (x, y, z)') - crop_size = traits.Tuple(traits.Int, traits.Int, traits.Int, - argstr='--cropsize %d %d %d', - desc=' crop to size ') - cut_ends = traits.Int(argstr='--cutends %d', - desc='remove ncut slices from the ends') - slice_crop = traits.Tuple(traits.Int, traits.Int, - argstr='--slice-crop %d %d', - desc='s_start s_end : keep slices s_start to s_end') - slice_reverse = traits.Bool(argstr='--slice-reverse', - desc='reverse order of slices, update vox2ras') - slice_bias = traits.Float(argstr='--slice-bias %f', - desc='apply half-cosine bias field') - fwhm = traits.Float(argstr='--fwhm %f', - desc='smooth input volume by fwhm mm') - _filetypes = ['cor', 'mgh', 'mgz', 'minc', 'analyze', - 'analyze4d', 'spm', 'afni', 'brik', 'bshort', - 'bfloat', 'sdt', 'outline', 'otl', 'gdf', - 'nifti1', 'nii', 'niigz'] - _infiletypes = ['ge', 'gelx', 'lx', 'ximg', 'siemens', 'dicom', 'siemens_dicom'] - in_type = traits.Enum(_filetypes + _infiletypes, argstr='--in_type %s', - desc='input file type') - out_type = traits.Enum(_filetypes, argstr='--out_type %s', - desc='output file type') - ascii = traits.Bool(argstr='--ascii', - desc='save output as ascii col>row>slice>frame') - reorder = traits.Tuple(traits.Int, traits.Int, traits.Int, - argstr='--reorder %d %d %d', - desc='olddim1 olddim2 olddim3') - invert_contrast = traits.Float(argstr='--invert_contrast %f', - desc='threshold for inversting contrast') - in_file = File(exists=True, mandatory=True, - position=-2, - argstr='--input_volume %s', - desc='File to read/convert') - out_file = File(argstr='--output_volume %s', - position=-1, genfile=True, - desc='output filename or True to generate one') - conform = traits.Bool(argstr='--conform', - desc='conform to 1mm voxel size in coronal slice direction with 256^3 or more') - conform_min = traits.Bool(argstr='--conform_min', - desc='conform to smallest size') - conform_size = traits.Float(argstr='--conform_size %s', - desc='conform to size_in_mm') - cw256 = traits.Bool(argstr='--cw256', - desc='confrom to dimensions of 256^3') - parse_only = traits.Bool(argstr='--parse_only', - desc='parse input only') - subject_name = traits.Str(argstr='--subject_name %s', - desc='subject name ???') - reslice_like = File(exists=True, argstr='--reslice_like %s', - desc='reslice output to match file') - template_type = traits.Enum(_filetypes + _infiletypes, - argstr='--template_type %s', - desc='template file type') - split = traits.Bool(argstr='--split', - desc='split output frames into separate output files.') - frame = traits.Int(argstr='--frame %d', - desc='keep only 0-based frame number') - midframe = traits.Bool(argstr='--mid-frame', - desc='keep only the middle frame') - skip_n = traits.Int(argstr='--nskip %d', - desc='skip the first n frames') - drop_n = traits.Int(argstr='--ndrop %d', - desc='drop the last n frames') - frame_subsample = traits.Tuple(traits.Int, traits.Int, traits.Int, - argstr='--fsubsample %d %d %d', - desc='start delta end : frame subsampling (end = -1 for end)') - in_scale = traits.Float(argstr='--scale %f', - desc='input intensity scale factor') - out_scale = traits.Float(argstr='--out-scale %d', - desc='output intensity scale factor') - in_like = File(exists=True, argstr='--in_like %s', - desc='input looks like') - fill_parcellation = traits.Bool(argstr='--fill_parcellation', - desc='fill parcellation') - smooth_parcellation = traits.Bool(argstr='--smooth_parcellation', - desc='smooth parcellation') - zero_outlines = traits.Bool(argstr='--zero_outlines', - desc='zero outlines') - color_file = File(exists=True, argstr='--color_file %s', - desc='color file') - no_translate = traits.Bool(argstr='--no_translate', - desc='???') - status_file = File(argstr='--status %s', - desc='status file for DICOM conversion') - sdcm_list = File(exists=True, argstr='--sdcmlist %s', - desc='list of DICOM files for conversion') - template_info = traits.Bool('--template_info', - desc='dump info about template') - crop_gdf = traits.Bool(argstr='--crop_gdf', - desc='apply GDF cropping') - zero_ge_z_offset = traits.Bool(argstr='--zero_ge_z_offset', - desc='zero ge z offset ???') + in_orientation = traits.Enum( + _orientations, + argstr='--in_orientation %s', + desc='specify the input orientation') + in_center = traits.List( + traits.Float, + maxlen=3, + argstr='--in_center %s', + desc=' ') + sphinx = traits.Bool( + argstr='--sphinx', desc='change orientation info to sphinx') + out_i_count = traits.Int( + argstr='--out_i_count %d', desc='some count ?? in i direction') + out_j_count = traits.Int( + argstr='--out_j_count %d', desc='some count ?? in j direction') + out_k_count = traits.Int( + argstr='--out_k_count %d', desc='some count ?? in k direction') + vox_size = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='-voxsize %f %f %f', + desc= + ' specify the size (mm) - useful for upsampling or downsampling' + ) + out_i_size = traits.Int(argstr='--out_i_size %d', desc='output i size') + out_j_size = traits.Int(argstr='--out_j_size %d', desc='output j size') + out_k_size = traits.Int(argstr='--out_k_size %d', desc='output k size') + out_i_dir = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='--out_i_direction %f %f %f', + desc=' ') + out_j_dir = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='--out_j_direction %f %f %f', + desc=' ') + out_k_dir = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='--out_k_direction %f %f %f', + desc=' ') + out_orientation = traits.Enum( + _orientations, + argstr='--out_orientation %s', + desc='specify the output orientation') + out_center = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='--out_center %f %f %f', + desc=' ') + out_datatype = traits.Enum( + 'uchar', + 'short', + 'int', + 'float', + argstr='--out_data_type %s', + desc='output data type ') + resample_type = traits.Enum( + 'interpolate', + 'weighted', + 'nearest', + 'sinc', + 'cubic', + argstr='--resample_type %s', + desc= + ' (default is interpolate)') + no_scale = traits.Bool( + argstr='--no_scale 1', desc='dont rescale values for COR') + no_change = traits.Bool( + argstr='--nochange', + desc="don't change type of input to that of template") + tr = traits.Int(argstr='-tr %d', desc='TR in msec') + te = traits.Int(argstr='-te %d', desc='TE in msec') + ti = traits.Int(argstr='-ti %d', desc='TI in msec (note upper case flag)') + autoalign_matrix = File( + exists=True, + argstr='--autoalign %s', + desc='text file with autoalign matrix') + unwarp_gradient = traits.Bool( + argstr='--unwarp_gradient_nonlinearity', + desc='unwarp gradient nonlinearity') + apply_transform = File( + exists=True, argstr='--apply_transform %s', desc='apply xfm file') + apply_inv_transform = File( + exists=True, + argstr='--apply_inverse_transform %s', + desc='apply inverse transformation xfm file') + devolve_transform = traits.Str(argstr='--devolvexfm %s', desc='subject id') + crop_center = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + argstr='--crop %d %d %d', + desc=' crop to 256 around center (x, y, z)') + crop_size = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + argstr='--cropsize %d %d %d', + desc=' crop to size ') + cut_ends = traits.Int( + argstr='--cutends %d', desc='remove ncut slices from the ends') + slice_crop = traits.Tuple( + traits.Int, + traits.Int, + argstr='--slice-crop %d %d', + desc='s_start s_end : keep slices s_start to s_end') + slice_reverse = traits.Bool( + argstr='--slice-reverse', + desc='reverse order of slices, update vox2ras') + slice_bias = traits.Float( + argstr='--slice-bias %f', desc='apply half-cosine bias field') + fwhm = traits.Float( + argstr='--fwhm %f', desc='smooth input volume by fwhm mm') + _filetypes = [ + 'cor', 'mgh', 'mgz', 'minc', 'analyze', 'analyze4d', 'spm', 'afni', + 'brik', 'bshort', 'bfloat', 'sdt', 'outline', 'otl', 'gdf', 'nifti1', + 'nii', 'niigz' + ] + _infiletypes = [ + 'ge', 'gelx', 'lx', 'ximg', 'siemens', 'dicom', 'siemens_dicom' + ] + in_type = traits.Enum( + _filetypes + _infiletypes, + argstr='--in_type %s', + desc='input file type') + out_type = traits.Enum( + _filetypes, argstr='--out_type %s', desc='output file type') + ascii = traits.Bool( + argstr='--ascii', desc='save output as ascii col>row>slice>frame') + reorder = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + argstr='--reorder %d %d %d', + desc='olddim1 olddim2 olddim3') + invert_contrast = traits.Float( + argstr='--invert_contrast %f', + desc='threshold for inversting contrast') + in_file = File( + exists=True, + mandatory=True, + position=-2, + argstr='--input_volume %s', + desc='File to read/convert') + out_file = File( + argstr='--output_volume %s', + position=-1, + genfile=True, + desc='output filename or True to generate one') + conform = traits.Bool( + argstr='--conform', + desc= + 'conform to 1mm voxel size in coronal slice direction with 256^3 or more' + ) + conform_min = traits.Bool( + argstr='--conform_min', desc='conform to smallest size') + conform_size = traits.Float( + argstr='--conform_size %s', desc='conform to size_in_mm') + cw256 = traits.Bool( + argstr='--cw256', desc='confrom to dimensions of 256^3') + parse_only = traits.Bool(argstr='--parse_only', desc='parse input only') + subject_name = traits.Str( + argstr='--subject_name %s', desc='subject name ???') + reslice_like = File( + exists=True, + argstr='--reslice_like %s', + desc='reslice output to match file') + template_type = traits.Enum( + _filetypes + _infiletypes, + argstr='--template_type %s', + desc='template file type') + split = traits.Bool( + argstr='--split', + desc='split output frames into separate output files.') + frame = traits.Int( + argstr='--frame %d', desc='keep only 0-based frame number') + midframe = traits.Bool( + argstr='--mid-frame', desc='keep only the middle frame') + skip_n = traits.Int(argstr='--nskip %d', desc='skip the first n frames') + drop_n = traits.Int(argstr='--ndrop %d', desc='drop the last n frames') + frame_subsample = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + argstr='--fsubsample %d %d %d', + desc='start delta end : frame subsampling (end = -1 for end)') + in_scale = traits.Float( + argstr='--scale %f', desc='input intensity scale factor') + out_scale = traits.Float( + argstr='--out-scale %d', desc='output intensity scale factor') + in_like = File(exists=True, argstr='--in_like %s', desc='input looks like') + fill_parcellation = traits.Bool( + argstr='--fill_parcellation', desc='fill parcellation') + smooth_parcellation = traits.Bool( + argstr='--smooth_parcellation', desc='smooth parcellation') + zero_outlines = traits.Bool(argstr='--zero_outlines', desc='zero outlines') + color_file = File(exists=True, argstr='--color_file %s', desc='color file') + no_translate = traits.Bool(argstr='--no_translate', desc='???') + status_file = File( + argstr='--status %s', desc='status file for DICOM conversion') + sdcm_list = File( + exists=True, + argstr='--sdcmlist %s', + desc='list of DICOM files for conversion') + template_info = traits.Bool( + '--template_info', desc='dump info about template') + crop_gdf = traits.Bool(argstr='--crop_gdf', desc='apply GDF cropping') + zero_ge_z_offset = traits.Bool( + argstr='--zero_ge_z_offset', desc='zero ge z offset ???') class MRIConvertOutputSpec(TraitedSpec): @@ -361,11 +446,21 @@ class MRIConvert(FSCommand): input_spec = MRIConvertInputSpec output_spec = MRIConvertOutputSpec - filemap = dict(cor='cor', mgh='mgh', mgz='mgz', minc='mnc', - afni='brik', brik='brik', bshort='bshort', - spm='img', analyze='img', analyze4d='img', - bfloat='bfloat', nifti1='img', nii='nii', - niigz='nii.gz') + filemap = dict( + cor='cor', + mgh='mgh', + mgz='mgz', + minc='mnc', + afni='brik', + brik='brik', + bshort='bshort', + spm='img', + analyze='img', + analyze4d='img', + bfloat='bfloat', + nifti1='img', + nii='nii', + niigz='nii.gz') def _format_arg(self, name, spec, value): if name in ['in_type', 'out_type', 'template_type']: @@ -380,10 +475,11 @@ def _get_outfilename(self): suffix = '_out.' + self.filemap[self.inputs.out_type] else: suffix = '_out.nii.gz' - outfile = fname_presuffix(self.inputs.in_file, - newpath=os.getcwd(), - suffix=suffix, - use_ext=False) + outfile = fname_presuffix( + self.inputs.in_file, + newpath=os.getcwd(), + suffix=suffix, + use_ext=False) return os.path.abspath(outfile) def _list_outputs(self): @@ -416,12 +512,14 @@ def _list_outputs(self): else: tp = size[-1] # have to take care of all the frame manipulations - raise Exception('Not taking frame manipulations into account- please warn the developers') + raise Exception( + 'Not taking frame manipulations into account- please warn the developers' + ) outfiles = [] outfile = self._get_outfilename() for i in range(tp): - outfiles.append(fname_presuffix(outfile, - suffix='%03d' % (i + 1))) + outfiles.append( + fname_presuffix(outfile, suffix='%03d' % (i + 1))) outfile = outfiles outputs['out_file'] = outfile return outputs @@ -433,25 +531,34 @@ def _gen_filename(self, name): class DICOMConvertInputSpec(FSTraitedSpec): - dicom_dir = Directory(exists=True, mandatory=True, - desc='dicom directory from which to convert dicom files') - base_output_dir = Directory(mandatory=True, - desc='directory in which subject directories are created') - subject_dir_template = traits.Str('S.%04d', usedefault=True, - desc='template for subject directory name') + dicom_dir = Directory( + exists=True, + mandatory=True, + desc='dicom directory from which to convert dicom files') + base_output_dir = Directory( + mandatory=True, + desc='directory in which subject directories are created') + subject_dir_template = traits.Str( + 'S.%04d', usedefault=True, desc='template for subject directory name') subject_id = traits.Any(desc='subject identifier to insert into template') - file_mapping = traits.List(traits.Tuple(traits.Str, traits.Str), - desc='defines the output fields of interface') - out_type = traits.Enum('niigz', MRIConvertInputSpec._filetypes, - usedefault=True, - desc='defines the type of output file produced') - dicom_info = File(exists=True, - desc='File containing summary information from mri_parse_sdcmdir') - seq_list = traits.List(traits.Str, - requires=['dicom_info'], - desc='list of pulse sequence names to be converted.') - ignore_single_slice = traits.Bool(requires=['dicom_info'], - desc='ignore volumes containing a single slice') + file_mapping = traits.List( + traits.Tuple(traits.Str, traits.Str), + desc='defines the output fields of interface') + out_type = traits.Enum( + 'niigz', + MRIConvertInputSpec._filetypes, + usedefault=True, + desc='defines the type of output file produced') + dicom_info = File( + exists=True, + desc='File containing summary information from mri_parse_sdcmdir') + seq_list = traits.List( + traits.Str, + requires=['dicom_info'], + desc='list of pulse sequence names to be converted.') + ignore_single_slice = traits.Bool( + requires=['dicom_info'], + desc='ignore volumes containing a single slice') class DICOMConvert(FSCommand): @@ -473,8 +580,8 @@ def _get_dicomfiles(self): """validate fsl bet options if set to None ignore """ - return glob(os.path.abspath(os.path.join(self.inputs.dicom_dir, - '*-1.dcm'))) + return glob( + os.path.abspath(os.path.join(self.inputs.dicom_dir, '*-1.dcm'))) def _get_outdir(self): """returns output directory""" @@ -501,10 +608,12 @@ def _get_runs(self): for s in seq: if self.inputs.seq_list: if self.inputs.ignore_single_slice: - if (int(s[8]) > 1) and any([s[12].startswith(sn) for sn in self.inputs.seq_list]): + if (int(s[8]) > 1) and any( + [s[12].startswith(sn) for sn in self.inputs.seq_list]): runs.append(int(s[2])) else: - if any([s[12].startswith(sn) for sn in self.inputs.seq_list]): + if any( + [s[12].startswith(sn) for sn in self.inputs.seq_list]): runs.append(int(s[2])) else: runs.append(int(s[2])) @@ -519,9 +628,8 @@ def _get_filelist(self, outdir): fileparts = fname.split('-') runno = int(fileparts[1]) out_type = MRIConvert.filemap[self.inputs.out_type] - outfile = os.path.join(outdir, '.'.join(('%s-%02d' % (fileparts[0], - runno), - out_type))) + outfile = os.path.join(outdir, '.'.join( + ('%s-%02d' % (fileparts[0], runno), out_type))) filemap[runno] = (f, outfile) if self.inputs.dicom_info: files = [filemap[r] for r in self._get_runs()] @@ -554,18 +662,25 @@ def cmdline(self): class ResampleInputSpec(FSTraitedSpec): - in_file = File(exists=True, argstr='-i %s', mandatory=True, - desc='file to resample', position=-2) - resampled_file = File(argstr='-o %s', desc='output filename', genfile=True, - position=-1) - voxel_size = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr='-vs %.2f %.2f %.2f', desc='triplet of output voxel sizes', - mandatory=True) + in_file = File( + exists=True, + argstr='-i %s', + mandatory=True, + desc='file to resample', + position=-2) + resampled_file = File( + argstr='-o %s', desc='output filename', genfile=True, position=-1) + voxel_size = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr='-vs %.2f %.2f %.2f', + desc='triplet of output voxel sizes', + mandatory=True) class ResampleOutputSpec(TraitedSpec): - resampled_file = File(exists=True, - desc='output filename') + resampled_file = File(exists=True, desc='output filename') class Resample(FSCommand): @@ -592,9 +707,8 @@ def _get_outfilename(self): if isdefined(self.inputs.resampled_file): outfile = self.inputs.resampled_file else: - outfile = fname_presuffix(self.inputs.in_file, - newpath=os.getcwd(), - suffix='_resample') + outfile = fname_presuffix( + self.inputs.in_file, newpath=os.getcwd(), suffix='_resample') return outfile def _list_outputs(self): @@ -609,97 +723,163 @@ def _gen_filename(self, name): class ReconAllInputSpec(CommandLineInputSpec): - subject_id = traits.Str("recon_all", argstr='-subjid %s', - desc='subject name', usedefault=True) - directive = traits.Enum('all', 'autorecon1', - # autorecon2 variants - 'autorecon2', 'autorecon2-volonly', - 'autorecon2-perhemi', 'autorecon2-inflate1', - 'autorecon2-cp', 'autorecon2-wm', - # autorecon3 variants - 'autorecon3', 'autorecon3-T2pial', - # Mix of autorecon2 and autorecon3 steps - 'autorecon-pial', 'autorecon-hemi', - # Not "multi-stage flags" - 'localGI', 'qcache', - argstr='-%s', desc='process directive', - usedefault=True, position=0) - hemi = traits.Enum('lh', 'rh', desc='hemisphere to process', - argstr="-hemi %s") - T1_files = InputMultiPath(File(exists=True), argstr='-i %s...', - desc='name of T1 file to process') - T2_file = File(exists=True, argstr="-T2 %s", - min_ver='5.3.0', - desc='Convert T2 image to orig directory') - FLAIR_file = File(exists=True, argstr="-FLAIR %s", - min_ver='5.3.0', - desc='Convert FLAIR image to orig directory') - use_T2 = traits.Bool(argstr="-T2pial", min_ver='5.3.0', xor=['use_FLAIR'], - desc='Use T2 image to refine the pial surface') - use_FLAIR = traits.Bool(argstr="-FLAIRpial", - min_ver='5.3.0', xor=['use_T2'], - desc='Use FLAIR image to refine the pial surface') - openmp = traits.Int(argstr="-openmp %d", - desc="Number of processors to use in parallel") - parallel = traits.Bool(argstr="-parallel", - desc="Enable parallel execution") - hires = traits.Bool(argstr="-hires", min_ver='6.0.0', - desc="Conform to minimum voxel size (for voxels < 1mm)") - mprage = traits.Bool(argstr='-mprage', - desc=('Assume scan parameters are MGH MP-RAGE ' - 'protocol, which produces darker gray matter')) - big_ventricles = traits.Bool(argstr='-bigventricles', - desc=('For use in subjects with enlarged ' - 'ventricles')) - brainstem = traits.Bool(argstr='-brainstem-structures', - desc='Segment brainstem structures') + subject_id = traits.Str( + "recon_all", argstr='-subjid %s', desc='subject name', usedefault=True) + directive = traits.Enum( + 'all', + 'autorecon1', + # autorecon2 variants + 'autorecon2', + 'autorecon2-volonly', + 'autorecon2-perhemi', + 'autorecon2-inflate1', + 'autorecon2-cp', + 'autorecon2-wm', + # autorecon3 variants + 'autorecon3', + 'autorecon3-T2pial', + # Mix of autorecon2 and autorecon3 steps + 'autorecon-pial', + 'autorecon-hemi', + # Not "multi-stage flags" + 'localGI', + 'qcache', + argstr='-%s', + desc='process directive', + usedefault=True, + position=0) + hemi = traits.Enum( + 'lh', 'rh', desc='hemisphere to process', argstr="-hemi %s") + T1_files = InputMultiPath( + File(exists=True), + argstr='-i %s...', + desc='name of T1 file to process') + T2_file = File( + exists=True, + argstr="-T2 %s", + min_ver='5.3.0', + desc='Convert T2 image to orig directory') + FLAIR_file = File( + exists=True, + argstr="-FLAIR %s", + min_ver='5.3.0', + desc='Convert FLAIR image to orig directory') + use_T2 = traits.Bool( + argstr="-T2pial", + min_ver='5.3.0', + xor=['use_FLAIR'], + desc='Use T2 image to refine the pial surface') + use_FLAIR = traits.Bool( + argstr="-FLAIRpial", + min_ver='5.3.0', + xor=['use_T2'], + desc='Use FLAIR image to refine the pial surface') + openmp = traits.Int( + argstr="-openmp %d", desc="Number of processors to use in parallel") + parallel = traits.Bool( + argstr="-parallel", desc="Enable parallel execution") + hires = traits.Bool( + argstr="-hires", + min_ver='6.0.0', + desc="Conform to minimum voxel size (for voxels < 1mm)") + mprage = traits.Bool( + argstr='-mprage', + desc=('Assume scan parameters are MGH MP-RAGE ' + 'protocol, which produces darker gray matter')) + big_ventricles = traits.Bool( + argstr='-bigventricles', + desc=('For use in subjects with enlarged ' + 'ventricles')) + brainstem = traits.Bool( + argstr='-brainstem-structures', desc='Segment brainstem structures') hippocampal_subfields_T1 = traits.Bool( - argstr='-hippocampal-subfields-T1', min_ver='6.0.0', + argstr='-hippocampal-subfields-T1', + min_ver='6.0.0', desc='segment hippocampal subfields using input T1 scan') hippocampal_subfields_T2 = traits.Tuple( - File(exists=True), traits.Str(), - argstr='-hippocampal-subfields-T2 %s %s', min_ver='6.0.0', + File(exists=True), + traits.Str(), + argstr='-hippocampal-subfields-T2 %s %s', + min_ver='6.0.0', desc=('segment hippocampal subfields using T2 scan, identified by ' 'ID (may be combined with hippocampal_subfields_T1)')) - expert = File(exists=True, argstr='-expert %s', - desc="Set parameters using expert file") - xopts = traits.Enum("use", "clean", "overwrite", argstr='-xopts-%s', - desc="Use, delete or overwrite existing expert options file") - subjects_dir = Directory(exists=True, argstr='-sd %s', hash_files=False, - desc='path to subjects directory', genfile=True) - flags = InputMultiPath(traits.Str, argstr='%s', desc='additional parameters') + expert = File( + exists=True, + argstr='-expert %s', + desc="Set parameters using expert file") + xopts = traits.Enum( + "use", + "clean", + "overwrite", + argstr='-xopts-%s', + desc="Use, delete or overwrite existing expert options file") + subjects_dir = Directory( + exists=True, + argstr='-sd %s', + hash_files=False, + desc='path to subjects directory', + genfile=True) + flags = InputMultiPath( + traits.Str, argstr='%s', desc='additional parameters') # Expert options - talairach = traits.Str(desc="Flags to pass to talairach commands", xor=['expert']) - mri_normalize = traits.Str(desc="Flags to pass to mri_normalize commands", xor=['expert']) - mri_watershed = traits.Str(desc="Flags to pass to mri_watershed commands", xor=['expert']) - mri_em_register = traits.Str(desc="Flags to pass to mri_em_register commands", xor=['expert']) - mri_ca_normalize = traits.Str(desc="Flags to pass to mri_ca_normalize commands", xor=['expert']) - mri_ca_register = traits.Str(desc="Flags to pass to mri_ca_register commands", xor=['expert']) - mri_remove_neck = traits.Str(desc="Flags to pass to mri_remove_neck commands", xor=['expert']) - mri_ca_label = traits.Str(desc="Flags to pass to mri_ca_label commands", xor=['expert']) - mri_segstats = traits.Str(desc="Flags to pass to mri_segstats commands", xor=['expert']) - mri_mask = traits.Str(desc="Flags to pass to mri_mask commands", xor=['expert']) - mri_segment = traits.Str(desc="Flags to pass to mri_segment commands", xor=['expert']) - mri_edit_wm_with_aseg = traits.Str(desc="Flags to pass to mri_edit_wm_with_aseg commands", xor=['expert']) - mri_pretess = traits.Str(desc="Flags to pass to mri_pretess commands", xor=['expert']) - mri_fill = traits.Str(desc="Flags to pass to mri_fill commands", xor=['expert']) - mri_tessellate = traits.Str(desc="Flags to pass to mri_tessellate commands", xor=['expert']) - mris_smooth = traits.Str(desc="Flags to pass to mri_smooth commands", xor=['expert']) - mris_inflate = traits.Str(desc="Flags to pass to mri_inflate commands", xor=['expert']) - mris_sphere = traits.Str(desc="Flags to pass to mris_sphere commands", xor=['expert']) - mris_fix_topology = traits.Str(desc="Flags to pass to mris_fix_topology commands", xor=['expert']) - mris_make_surfaces = traits.Str(desc="Flags to pass to mris_make_surfaces commands", xor=['expert']) - mris_surf2vol = traits.Str(desc="Flags to pass to mris_surf2vol commands", xor=['expert']) - mris_register = traits.Str(desc="Flags to pass to mris_register commands", xor=['expert']) - mrisp_paint = traits.Str(desc="Flags to pass to mrisp_paint commands", xor=['expert']) - mris_ca_label = traits.Str(desc="Flags to pass to mris_ca_label commands", xor=['expert']) - mris_anatomical_stats = traits.Str(desc="Flags to pass to mris_anatomical_stats commands", xor=['expert']) - mri_aparc2aseg = traits.Str(desc="Flags to pass to mri_aparc2aseg commands", xor=['expert']) + talairach = traits.Str( + desc="Flags to pass to talairach commands", xor=['expert']) + mri_normalize = traits.Str( + desc="Flags to pass to mri_normalize commands", xor=['expert']) + mri_watershed = traits.Str( + desc="Flags to pass to mri_watershed commands", xor=['expert']) + mri_em_register = traits.Str( + desc="Flags to pass to mri_em_register commands", xor=['expert']) + mri_ca_normalize = traits.Str( + desc="Flags to pass to mri_ca_normalize commands", xor=['expert']) + mri_ca_register = traits.Str( + desc="Flags to pass to mri_ca_register commands", xor=['expert']) + mri_remove_neck = traits.Str( + desc="Flags to pass to mri_remove_neck commands", xor=['expert']) + mri_ca_label = traits.Str( + desc="Flags to pass to mri_ca_label commands", xor=['expert']) + mri_segstats = traits.Str( + desc="Flags to pass to mri_segstats commands", xor=['expert']) + mri_mask = traits.Str( + desc="Flags to pass to mri_mask commands", xor=['expert']) + mri_segment = traits.Str( + desc="Flags to pass to mri_segment commands", xor=['expert']) + mri_edit_wm_with_aseg = traits.Str( + desc="Flags to pass to mri_edit_wm_with_aseg commands", xor=['expert']) + mri_pretess = traits.Str( + desc="Flags to pass to mri_pretess commands", xor=['expert']) + mri_fill = traits.Str( + desc="Flags to pass to mri_fill commands", xor=['expert']) + mri_tessellate = traits.Str( + desc="Flags to pass to mri_tessellate commands", xor=['expert']) + mris_smooth = traits.Str( + desc="Flags to pass to mri_smooth commands", xor=['expert']) + mris_inflate = traits.Str( + desc="Flags to pass to mri_inflate commands", xor=['expert']) + mris_sphere = traits.Str( + desc="Flags to pass to mris_sphere commands", xor=['expert']) + mris_fix_topology = traits.Str( + desc="Flags to pass to mris_fix_topology commands", xor=['expert']) + mris_make_surfaces = traits.Str( + desc="Flags to pass to mris_make_surfaces commands", xor=['expert']) + mris_surf2vol = traits.Str( + desc="Flags to pass to mris_surf2vol commands", xor=['expert']) + mris_register = traits.Str( + desc="Flags to pass to mris_register commands", xor=['expert']) + mrisp_paint = traits.Str( + desc="Flags to pass to mrisp_paint commands", xor=['expert']) + mris_ca_label = traits.Str( + desc="Flags to pass to mris_ca_label commands", xor=['expert']) + mris_anatomical_stats = traits.Str( + desc="Flags to pass to mris_anatomical_stats commands", xor=['expert']) + mri_aparc2aseg = traits.Str( + desc="Flags to pass to mri_aparc2aseg commands", xor=['expert']) class ReconAllOutputSpec(FreeSurferSource.output_spec): - subjects_dir = Directory(exists=True, desc='Freesurfer subjects directory.') + subjects_dir = Directory( + exists=True, desc='Freesurfer subjects directory.') subject_id = traits.Str(desc='Subject name for whom to retrieve data') @@ -779,62 +959,78 @@ class ReconAll(CommandLine): # [1] https://surfer.nmr.mgh.harvard.edu/fswiki/ReconAllTableStableV6.0 _autorecon1_steps = [ ('motioncor', ['mri/rawavg.mgz', 'mri/orig.mgz'], []), - ('talairach', ['mri/orig_nu.mgz', - 'mri/transforms/talairach.auto.xfm', - 'mri/transforms/talairach.xfm', - # 'mri/transforms/talairach_avi.log', - ], []), + ( + 'talairach', + [ + 'mri/orig_nu.mgz', + 'mri/transforms/talairach.auto.xfm', + 'mri/transforms/talairach.xfm', + # 'mri/transforms/talairach_avi.log', + ], + []), ('nuintensitycor', ['mri/nu.mgz'], []), ('normalization', ['mri/T1.mgz'], []), - ('skullstrip', ['mri/transforms/talairach_with_skull.lta', - 'mri/brainmask.auto.mgz', - 'mri/brainmask.mgz'], []), - ] + ('skullstrip', [ + 'mri/transforms/talairach_with_skull.lta', + 'mri/brainmask.auto.mgz', 'mri/brainmask.mgz' + ], []), + ] if Info.looseversion() < LooseVersion("6.0.0"): _autorecon2_volonly_steps = [ ('gcareg', ['mri/transforms/talairach.lta'], []), ('canorm', ['mri/norm.mgz'], []), ('careg', ['mri/transforms/talairach.m3z'], []), - ('careginv', ['mri/transforms/talairach.m3z.inv.x.mgz', - 'mri/transforms/talairach.m3z.inv.y.mgz', - 'mri/transforms/talairach.m3z.inv.z.mgz', - ], []), + ('careginv', [ + 'mri/transforms/talairach.m3z.inv.x.mgz', + 'mri/transforms/talairach.m3z.inv.y.mgz', + 'mri/transforms/talairach.m3z.inv.z.mgz', + ], []), ('rmneck', ['mri/nu_noneck.mgz'], []), ('skull-lta', ['mri/transforms/talairach_with_skull_2.lta'], []), - ('calabel', ['mri/aseg.auto_noCCseg.mgz', - 'mri/aseg.auto.mgz', - 'mri/aseg.mgz'], []), + ('calabel', [ + 'mri/aseg.auto_noCCseg.mgz', 'mri/aseg.auto.mgz', + 'mri/aseg.mgz' + ], []), ('normalization2', ['mri/brain.mgz'], []), ('maskbfs', ['mri/brain.finalsurfs.mgz'], []), - ('segmentation', ['mri/wm.seg.mgz', - 'mri/wm.asegedit.mgz', - 'mri/wm.mgz'], []), - ('fill', ['mri/filled.mgz', - # 'scripts/ponscc.cut.log', - ], []), - ] + ('segmentation', + ['mri/wm.seg.mgz', 'mri/wm.asegedit.mgz', 'mri/wm.mgz'], []), + ( + 'fill', + [ + 'mri/filled.mgz', + # 'scripts/ponscc.cut.log', + ], + []), + ] _autorecon2_lh_steps = [ ('tessellate', ['surf/lh.orig.nofix'], []), ('smooth1', ['surf/lh.smoothwm.nofix'], []), ('inflate1', ['surf/lh.inflated.nofix'], []), ('qsphere', ['surf/lh.qsphere.nofix'], []), ('fix', ['surf/lh.orig'], []), - ('white', ['surf/lh.white', 'surf/lh.curv', 'surf/lh.area', - 'label/lh.cortex.label'], []), + ('white', [ + 'surf/lh.white', 'surf/lh.curv', 'surf/lh.area', + 'label/lh.cortex.label' + ], []), ('smooth2', ['surf/lh.smoothwm'], []), - ('inflate2', ['surf/lh.inflated', 'surf/lh.sulc', - 'surf/lh.inflated.H', 'surf/lh.inflated.K'], []), + ('inflate2', [ + 'surf/lh.inflated', 'surf/lh.sulc', 'surf/lh.inflated.H', + 'surf/lh.inflated.K' + ], []), # Undocumented in ReconAllTableStableV5.3 ('curvstats', ['stats/lh.curv.stats'], []), - ] + ] _autorecon3_lh_steps = [ ('sphere', ['surf/lh.sphere'], []), ('surfreg', ['surf/lh.sphere.reg'], []), ('jacobian_white', ['surf/lh.jacobian_white'], []), ('avgcurv', ['surf/lh.avg_curv'], []), ('cortparc', ['label/lh.aparc.annot'], []), - ('pial', ['surf/lh.pial', 'surf/lh.curv.pial', 'surf/lh.area.pial', - 'surf/lh.thickness'], []), + ('pial', [ + 'surf/lh.pial', 'surf/lh.curv.pial', 'surf/lh.area.pial', + 'surf/lh.thickness' + ], []), # Misnamed outputs in ReconAllTableStableV5.3: ?h.w-c.pct.mgz ('pctsurfcon', ['surf/lh.w-g.pct.mgh'], []), ('parcstats', ['stats/lh.aparc.stats'], []), @@ -845,99 +1041,108 @@ class ReconAll(CommandLine): # Undocumented in ReconAllTableStableV5.3 ('parcstats3', ['stats/lh.aparc.a2009s.stats'], []), ('label-exvivo-ec', ['label/lh.entorhinal_exvivo.label'], []), - ] + ] _autorecon3_added_steps = [ - ('cortribbon', ['mri/lh.ribbon.mgz', 'mri/rh.ribbon.mgz', - 'mri/ribbon.mgz'], []), + ('cortribbon', + ['mri/lh.ribbon.mgz', 'mri/rh.ribbon.mgz', 'mri/ribbon.mgz'], []), ('segstats', ['stats/aseg.stats'], []), - ('aparc2aseg', ['mri/aparc+aseg.mgz', - 'mri/aparc.a2009s+aseg.mgz'], []), + ('aparc2aseg', ['mri/aparc+aseg.mgz', 'mri/aparc.a2009s+aseg.mgz'], + []), ('wmparc', ['mri/wmparc.mgz', 'stats/wmparc.stats'], []), ('balabels', ['label/BA.ctab', 'label/BA.thresh.ctab'], []), - ] + ] else: _autorecon2_volonly_steps = [ ('gcareg', ['mri/transforms/talairach.lta'], []), ('canorm', ['mri/norm.mgz'], []), ('careg', ['mri/transforms/talairach.m3z'], []), - ('calabel', ['mri/aseg.auto_noCCseg.mgz', - 'mri/aseg.auto.mgz', - 'mri/aseg.mgz'], []), + ('calabel', [ + 'mri/aseg.auto_noCCseg.mgz', 'mri/aseg.auto.mgz', + 'mri/aseg.mgz' + ], []), ('normalization2', ['mri/brain.mgz'], []), ('maskbfs', ['mri/brain.finalsurfs.mgz'], []), - ('segmentation', ['mri/wm.seg.mgz', - 'mri/wm.asegedit.mgz', - 'mri/wm.mgz'], []), - ('fill', ['mri/filled.mgz', - # 'scripts/ponscc.cut.log', - ], []), - ] + ('segmentation', + ['mri/wm.seg.mgz', 'mri/wm.asegedit.mgz', 'mri/wm.mgz'], []), + ( + 'fill', + [ + 'mri/filled.mgz', + # 'scripts/ponscc.cut.log', + ], + []), + ] _autorecon2_lh_steps = [ ('tessellate', ['surf/lh.orig.nofix'], []), ('smooth1', ['surf/lh.smoothwm.nofix'], []), ('inflate1', ['surf/lh.inflated.nofix'], []), ('qsphere', ['surf/lh.qsphere.nofix'], []), ('fix', ['surf/lh.orig'], []), - ('white', ['surf/lh.white.preaparc', 'surf/lh.curv', - 'surf/lh.area', 'label/lh.cortex.label'], []), + ('white', [ + 'surf/lh.white.preaparc', 'surf/lh.curv', 'surf/lh.area', + 'label/lh.cortex.label' + ], []), ('smooth2', ['surf/lh.smoothwm'], []), ('inflate2', ['surf/lh.inflated', 'surf/lh.sulc'], []), - ('curvHK', ['surf/lh.white.H', 'surf/lh.white.K', - 'surf/lh.inflated.H', 'surf/lh.inflated.K'], []), + ('curvHK', [ + 'surf/lh.white.H', 'surf/lh.white.K', 'surf/lh.inflated.H', + 'surf/lh.inflated.K' + ], []), ('curvstats', ['stats/lh.curv.stats'], []), - ] + ] _autorecon3_lh_steps = [ ('sphere', ['surf/lh.sphere'], []), ('surfreg', ['surf/lh.sphere.reg'], []), ('jacobian_white', ['surf/lh.jacobian_white'], []), ('avgcurv', ['surf/lh.avg_curv'], []), ('cortparc', ['label/lh.aparc.annot'], []), - ('pial', ['surf/lh.pial', 'surf/lh.curv.pial', - 'surf/lh.area.pial', 'surf/lh.thickness', - 'surf/lh.white'], []), + ('pial', [ + 'surf/lh.pial', 'surf/lh.curv.pial', 'surf/lh.area.pial', + 'surf/lh.thickness', 'surf/lh.white' + ], []), ('parcstats', ['stats/lh.aparc.stats'], []), ('cortparc2', ['label/lh.aparc.a2009s.annot'], []), ('parcstats2', ['stats/lh.aparc.a2009s.stats'], []), ('cortparc3', ['label/lh.aparc.DKTatlas.annot'], []), ('parcstats3', ['stats/lh.aparc.DKTatlas.stats'], []), ('pctsurfcon', ['surf/lh.w-g.pct.mgh'], []), - ] + ] _autorecon3_added_steps = [ - ('cortribbon', ['mri/lh.ribbon.mgz', 'mri/rh.ribbon.mgz', - 'mri/ribbon.mgz'], []), + ('cortribbon', + ['mri/lh.ribbon.mgz', 'mri/rh.ribbon.mgz', 'mri/ribbon.mgz'], []), ('hyporelabel', ['mri/aseg.presurf.hypos.mgz'], []), - ('aparc2aseg', ['mri/aparc+aseg.mgz', - 'mri/aparc.a2009s+aseg.mgz', - 'mri/aparc.DKTatlas+aseg.mgz'], []), + ('aparc2aseg', [ + 'mri/aparc+aseg.mgz', 'mri/aparc.a2009s+aseg.mgz', + 'mri/aparc.DKTatlas+aseg.mgz' + ], []), ('apas2aseg', ['mri/aseg.mgz'], ['mri/aparc+aseg.mgz']), ('segstats', ['stats/aseg.stats'], []), ('wmparc', ['mri/wmparc.mgz', 'stats/wmparc.stats'], []), # Note that this is a very incomplete list; however the ctab # files are last to be touched, so this should be reasonable - ('balabels', ['label/BA_exvivo.ctab', - 'label/BA_exvivo.thresh.ctab', - 'label/lh.entorhinal_exvivo.label', - 'label/rh.entorhinal_exvivo.label'], []), - ] + ('balabels', [ + 'label/BA_exvivo.ctab', 'label/BA_exvivo.thresh.ctab', + 'label/lh.entorhinal_exvivo.label', + 'label/rh.entorhinal_exvivo.label' + ], []), + ] # Fill out autorecon2 steps - _autorecon2_rh_steps = [ - (step, [out.replace('lh', 'rh') for out in outs], ins) - for step, outs, ins in _autorecon2_lh_steps] - _autorecon2_perhemi_steps = [ - (step, [of for out in outs - for of in (out, out.replace('lh', 'rh'))], ins) - for step, outs, ins in _autorecon2_lh_steps] + _autorecon2_rh_steps = [(step, [out.replace('lh', 'rh') + for out in outs], ins) + for step, outs, ins in _autorecon2_lh_steps] + _autorecon2_perhemi_steps = [(step, [ + of for out in outs for of in (out, out.replace('lh', 'rh')) + ], ins) for step, outs, ins in _autorecon2_lh_steps] _autorecon2_steps = _autorecon2_volonly_steps + _autorecon2_perhemi_steps # Fill out autorecon3 steps - _autorecon3_rh_steps = [ - (step, [out.replace('lh', 'rh') for out in outs], ins) - for step, outs, ins in _autorecon3_lh_steps] - _autorecon3_perhemi_steps = [ - (step, [of for out in outs - for of in (out, out.replace('lh', 'rh'))], ins) - for step, outs, ins in _autorecon3_lh_steps] + _autorecon3_rh_steps = [(step, [out.replace('lh', 'rh') + for out in outs], ins) + for step, outs, ins in _autorecon3_lh_steps] + _autorecon3_perhemi_steps = [(step, [ + of for out in outs for of in (out, out.replace('lh', 'rh')) + ], ins) for step, outs, ins in _autorecon3_lh_steps] _autorecon3_steps = _autorecon3_perhemi_steps + _autorecon3_added_steps # Fill out autorecon-hemi lh/rh steps @@ -946,15 +1151,15 @@ class ReconAll(CommandLine): _steps = _autorecon1_steps + _autorecon2_steps + _autorecon3_steps - _binaries = ['talairach', 'mri_normalize', 'mri_watershed', - 'mri_em_register', 'mri_ca_normalize', 'mri_ca_register', - 'mri_remove_neck', 'mri_ca_label', 'mri_segstats', - 'mri_mask', 'mri_segment', 'mri_edit_wm_with_aseg', - 'mri_pretess', 'mri_fill', 'mri_tessellate', 'mris_smooth', - 'mris_inflate', 'mris_sphere', 'mris_fix_topology', - 'mris_make_surfaces', 'mris_surf2vol', 'mris_register', - 'mrisp_paint', 'mris_ca_label', 'mris_anatomical_stats', - 'mri_aparc2aseg'] + _binaries = [ + 'talairach', 'mri_normalize', 'mri_watershed', 'mri_em_register', + 'mri_ca_normalize', 'mri_ca_register', 'mri_remove_neck', + 'mri_ca_label', 'mri_segstats', 'mri_mask', 'mri_segment', + 'mri_edit_wm_with_aseg', 'mri_pretess', 'mri_fill', 'mri_tessellate', + 'mris_smooth', 'mris_inflate', 'mris_sphere', 'mris_fix_topology', + 'mris_make_surfaces', 'mris_surf2vol', 'mris_register', 'mrisp_paint', + 'mris_ca_label', 'mris_anatomical_stats', 'mri_aparc2aseg' + ] def _gen_subjects_dir(self): return os.getcwd() @@ -980,9 +1185,11 @@ def _list_outputs(self): outputs = self._outputs().get() - outputs.update(FreeSurferSource(subject_id=self.inputs.subject_id, - subjects_dir=subjects_dir, - hemi=hemi)._list_outputs()) + outputs.update( + FreeSurferSource( + subject_id=self.inputs.subject_id, + subjects_dir=subjects_dir, + hemi=hemi)._list_outputs()) outputs['subject_id'] = self.inputs.subject_id outputs['subjects_dir'] = subjects_dir return outputs @@ -991,8 +1198,8 @@ def _is_resuming(self): subjects_dir = self.inputs.subjects_dir if not isdefined(subjects_dir): subjects_dir = self._gen_subjects_dir() - if os.path.isdir(os.path.join(subjects_dir, self.inputs.subject_id, - 'mri')): + if os.path.isdir( + os.path.join(subjects_dir, self.inputs.subject_id, 'mri')): return True return False @@ -1004,8 +1211,8 @@ def _format_arg(self, name, trait_spec, value): isdefined(self.inputs.hippocampal_subfields_T2): return None if all((name == 'hippocampal_subfields_T2', - isdefined(self.inputs.hippocampal_subfields_T1) and - self.inputs.hippocampal_subfields_T1)): + isdefined(self.inputs.hippocampal_subfields_T1) + and self.inputs.hippocampal_subfields_T1)): argstr = trait_spec.argstr.replace('T2', 'T1T2') return argstr % value if name == 'directive' and value == 'autorecon-hemi': @@ -1013,9 +1220,8 @@ def _format_arg(self, name, trait_spec, value): raise ValueError("Directive 'autorecon-hemi' requires hemi " "input to be set") value += ' ' + self.inputs.hemi - if all((name == 'hemi', - isdefined(self.inputs.directive) and - self.inputs.directive == 'autorecon-hemi')): + if all((name == 'hemi', isdefined(self.inputs.directive) + and self.inputs.directive == 'autorecon-hemi')): return None return super(ReconAll, self)._format_arg(name, trait_spec, value) @@ -1128,64 +1334,111 @@ def _get_expert_file(self): class BBRegisterInputSpec(FSTraitedSpec): - subject_id = traits.Str(argstr='--s %s', - desc='freesurfer subject id', - mandatory=True) - source_file = File(argstr='--mov %s', - desc='source file to be registered', - mandatory=True, copyfile=False) - init = traits.Enum('spm', 'fsl', 'header', argstr='--init-%s', - mandatory=True, xor=['init_reg_file'], - desc='initialize registration spm, fsl, header') - init_reg_file = File(exists=True, argstr='--init-reg %s', - desc='existing registration file', - xor=['init'], mandatory=True) - contrast_type = traits.Enum('t1', 't2', 'bold', 'dti', argstr='--%s', - desc='contrast type of image', - mandatory=True) - intermediate_file = File(exists=True, argstr="--int %s", - desc="Intermediate image, e.g. in case of partial FOV") - reg_frame = traits.Int(argstr="--frame %d", xor=["reg_middle_frame"], - desc="0-based frame index for 4D source file") - reg_middle_frame = traits.Bool(argstr="--mid-frame", xor=["reg_frame"], - desc="Register middle frame of 4D source file") - out_reg_file = File(argstr='--reg %s', - desc='output registration file', - genfile=True) - spm_nifti = traits.Bool(argstr="--spm-nii", - desc="force use of nifti rather than analyze with SPM") - epi_mask = traits.Bool(argstr="--epi-mask", - desc="mask out B0 regions in stages 1 and 2") - dof = traits.Enum(6, 9, 12, argstr='--%d', - desc='number of transform degrees of freedom') - fsldof = traits.Int(argstr='--fsl-dof %d', - desc='degrees of freedom for initial registration (FSL)') - out_fsl_file = traits.Either(traits.Bool, File, argstr="--fslmat %s", - desc="write the transformation matrix in FSL FLIRT format") - out_lta_file = traits.Either(traits.Bool, File, argstr="--lta %s", min_ver='5.2.0', - desc="write the transformation matrix in LTA format") - registered_file = traits.Either(traits.Bool, File, argstr='--o %s', - desc='output warped sourcefile either True or filename') - init_cost_file = traits.Either(traits.Bool, File, argstr='--initcost %s', - desc='output initial registration cost file') + subject_id = traits.Str( + argstr='--s %s', desc='freesurfer subject id', mandatory=True) + source_file = File( + argstr='--mov %s', + desc='source file to be registered', + mandatory=True, + copyfile=False) + init = traits.Enum( + 'spm', + 'fsl', + 'header', + argstr='--init-%s', + mandatory=True, + xor=['init_reg_file'], + desc='initialize registration spm, fsl, header') + init_reg_file = File( + exists=True, + argstr='--init-reg %s', + desc='existing registration file', + xor=['init'], + mandatory=True) + contrast_type = traits.Enum( + 't1', + 't2', + 'bold', + 'dti', + argstr='--%s', + desc='contrast type of image', + mandatory=True) + intermediate_file = File( + exists=True, + argstr="--int %s", + desc="Intermediate image, e.g. in case of partial FOV") + reg_frame = traits.Int( + argstr="--frame %d", + xor=["reg_middle_frame"], + desc="0-based frame index for 4D source file") + reg_middle_frame = traits.Bool( + argstr="--mid-frame", + xor=["reg_frame"], + desc="Register middle frame of 4D source file") + out_reg_file = File( + argstr='--reg %s', desc='output registration file', genfile=True) + spm_nifti = traits.Bool( + argstr="--spm-nii", + desc="force use of nifti rather than analyze with SPM") + epi_mask = traits.Bool( + argstr="--epi-mask", desc="mask out B0 regions in stages 1 and 2") + dof = traits.Enum( + 6, 9, 12, argstr='--%d', desc='number of transform degrees of freedom') + fsldof = traits.Int( + argstr='--fsl-dof %d', + desc='degrees of freedom for initial registration (FSL)') + out_fsl_file = traits.Either( + traits.Bool, + File, + argstr="--fslmat %s", + desc="write the transformation matrix in FSL FLIRT format") + out_lta_file = traits.Either( + traits.Bool, + File, + argstr="--lta %s", + min_ver='5.2.0', + desc="write the transformation matrix in LTA format") + registered_file = traits.Either( + traits.Bool, + File, + argstr='--o %s', + desc='output warped sourcefile either True or filename') + init_cost_file = traits.Either( + traits.Bool, + File, + argstr='--initcost %s', + desc='output initial registration cost file') class BBRegisterInputSpec6(BBRegisterInputSpec): - init = traits.Enum('coreg', 'rr', 'spm', 'fsl', 'header', 'best', argstr='--init-%s', - xor=['init_reg_file'], - desc='initialize registration with mri_coreg, spm, fsl, or header') - init_reg_file = File(exists=True, argstr='--init-reg %s', - desc='existing registration file', - xor=['init']) + init = traits.Enum( + 'coreg', + 'rr', + 'spm', + 'fsl', + 'header', + 'best', + argstr='--init-%s', + xor=['init_reg_file'], + desc='initialize registration with mri_coreg, spm, fsl, or header') + init_reg_file = File( + exists=True, + argstr='--init-reg %s', + desc='existing registration file', + xor=['init']) class BBRegisterOutputSpec(TraitedSpec): out_reg_file = File(exists=True, desc='Output registration file') - out_fsl_file = File(exists=True, desc='Output FLIRT-style registration file') + out_fsl_file = File( + exists=True, desc='Output FLIRT-style registration file') out_lta_file = File(exists=True, desc='Output LTA-style registration file') - min_cost_file = File(exists=True, desc='Output registration minimum cost file') - init_cost_file = File(exists=True, desc='Output initial registration cost file') - registered_file = File(exists=True, desc='Registered and resampled source file') + min_cost_file = File( + exists=True, desc='Output registration minimum cost file') + init_cost_file = File( + exists=True, desc='Output initial registration cost file') + registered_file = File( + exists=True, desc='Registered and resampled source file') class BBRegister(FSCommand): @@ -1221,23 +1474,21 @@ def _list_outputs(self): outputs['out_reg_file'] = op.abspath(_in.out_reg_file) elif _in.source_file: suffix = '_bbreg_%s.dat' % _in.subject_id - outputs['out_reg_file'] = fname_presuffix(_in.source_file, - suffix=suffix, - use_ext=False) + outputs['out_reg_file'] = fname_presuffix( + _in.source_file, suffix=suffix, use_ext=False) if isdefined(_in.registered_file): if isinstance(_in.registered_file, bool): - outputs['registered_file'] = fname_presuffix(_in.source_file, - suffix='_bbreg') + outputs['registered_file'] = fname_presuffix( + _in.source_file, suffix='_bbreg') else: outputs['registered_file'] = op.abspath(_in.registered_file) if isdefined(_in.out_lta_file): if isinstance(_in.out_lta_file, bool): suffix = '_bbreg_%s.lta' % _in.subject_id - out_lta_file = fname_presuffix(_in.source_file, - suffix=suffix, - use_ext=False) + out_lta_file = fname_presuffix( + _in.source_file, suffix=suffix, use_ext=False) outputs['out_lta_file'] = out_lta_file else: outputs['out_lta_file'] = op.abspath(_in.out_lta_file) @@ -1245,16 +1496,16 @@ def _list_outputs(self): if isdefined(_in.out_fsl_file): if isinstance(_in.out_fsl_file, bool): suffix = '_bbreg_%s.mat' % _in.subject_id - out_fsl_file = fname_presuffix(_in.source_file, - suffix=suffix, - use_ext=False) + out_fsl_file = fname_presuffix( + _in.source_file, suffix=suffix, use_ext=False) outputs['out_fsl_file'] = out_fsl_file else: outputs['out_fsl_file'] = op.abspath(_in.out_fsl_file) if isdefined(_in.init_cost_file): if isinstance(_in.out_fsl_file, bool): - outputs['init_cost_file'] = outputs['out_reg_file'] + '.initcost' + outputs[ + 'init_cost_file'] = outputs['out_reg_file'] + '.initcost' else: outputs['init_cost_file'] = op.abspath(_in.init_cost_file) @@ -1275,75 +1526,125 @@ def _gen_filename(self, name): class ApplyVolTransformInputSpec(FSTraitedSpec): - source_file = File(exists=True, argstr='--mov %s', - copyfile=False, mandatory=True, - desc='Input volume you wish to transform') - transformed_file = File(desc='Output volume', argstr='--o %s', genfile=True) + source_file = File( + exists=True, + argstr='--mov %s', + copyfile=False, + mandatory=True, + desc='Input volume you wish to transform') + transformed_file = File( + desc='Output volume', argstr='--o %s', genfile=True) _targ_xor = ('target_file', 'tal', 'fs_target') - target_file = File(exists=True, argstr='--targ %s', xor=_targ_xor, - desc='Output template volume', mandatory=True) - tal = traits.Bool(argstr='--tal', xor=_targ_xor, mandatory=True, - desc='map to a sub FOV of MNI305 (with --reg only)') - tal_resolution = traits.Float(argstr="--talres %.10f", - desc="Resolution to sample when using tal") - fs_target = traits.Bool(argstr='--fstarg', xor=_targ_xor, mandatory=True, - requires=['reg_file'], - desc='use orig.mgz from subject in regfile as target') - _reg_xor = ('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', - 'reg_header', 'mni_152_reg', 'subject') - reg_file = File(exists=True, xor=_reg_xor, argstr='--reg %s', - mandatory=True, - desc='tkRAS-to-tkRAS matrix (tkregister2 format)') - lta_file = File(exists=True, xor=_reg_xor, argstr='--lta %s', - mandatory=True, desc='Linear Transform Array file') - lta_inv_file = File(exists=True, xor=_reg_xor, argstr='--lta-inv %s', - mandatory=True, desc='LTA, invert') - reg_file = File(exists=True, xor=_reg_xor, argstr='--reg %s', - mandatory=True, - desc='tkRAS-to-tkRAS matrix (tkregister2 format)') - fsl_reg_file = File(exists=True, xor=_reg_xor, argstr='--fsl %s', - mandatory=True, - desc='fslRAS-to-fslRAS matrix (FSL format)') - xfm_reg_file = File(exists=True, xor=_reg_xor, argstr='--xfm %s', - mandatory=True, - desc='ScannerRAS-to-ScannerRAS matrix (MNI format)') - reg_header = traits.Bool(xor=_reg_xor, argstr='--regheader', - mandatory=True, - desc='ScannerRAS-to-ScannerRAS matrix = identity') - mni_152_reg = traits.Bool(xor=_reg_xor, argstr='--regheader', mandatory=True, - desc='target MNI152 space') - subject = traits.Str(xor=_reg_xor, argstr='--s %s', mandatory=True, - desc='set matrix = identity and use subject for any templates') - inverse = traits.Bool(desc='sample from target to source', - argstr='--inv') - interp = traits.Enum('trilin', 'nearest', 'cubic', argstr='--interp %s', - desc='Interpolation method ( or nearest)') - no_resample = traits.Bool(desc='Do not resample; just change vox2ras matrix', - argstr='--no-resample') - m3z_file = File(argstr="--m3z %s", - desc=('This is the morph to be applied to the volume. ' - 'Unless the morph is in mri/transforms (eg.: for ' - 'talairach.m3z computed by reconall), you will need ' - 'to specify the full path to this morph and use the ' - '--noDefM3zPath flag.')) - no_ded_m3z_path = traits.Bool(argstr="--noDefM3zPath", - requires=['m3z_file'], - desc=('To be used with the m3z flag. ' - 'Instructs the code not to look for the' - 'm3z morph in the default location ' - '(SUBJECTS_DIR/subj/mri/transforms), ' - 'but instead just use the path ' - 'indicated in --m3z.')) - - invert_morph = traits.Bool(argstr="--inv-morph", - requires=['m3z_file'], - desc=('Compute and use the inverse of the ' - 'non-linear morph to resample the input ' - 'volume. To be used by --m3z.')) + target_file = File( + exists=True, + argstr='--targ %s', + xor=_targ_xor, + desc='Output template volume', + mandatory=True) + tal = traits.Bool( + argstr='--tal', + xor=_targ_xor, + mandatory=True, + desc='map to a sub FOV of MNI305 (with --reg only)') + tal_resolution = traits.Float( + argstr="--talres %.10f", desc="Resolution to sample when using tal") + fs_target = traits.Bool( + argstr='--fstarg', + xor=_targ_xor, + mandatory=True, + requires=['reg_file'], + desc='use orig.mgz from subject in regfile as target') + _reg_xor = ('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject') + reg_file = File( + exists=True, + xor=_reg_xor, + argstr='--reg %s', + mandatory=True, + desc='tkRAS-to-tkRAS matrix (tkregister2 format)') + lta_file = File( + exists=True, + xor=_reg_xor, + argstr='--lta %s', + mandatory=True, + desc='Linear Transform Array file') + lta_inv_file = File( + exists=True, + xor=_reg_xor, + argstr='--lta-inv %s', + mandatory=True, + desc='LTA, invert') + reg_file = File( + exists=True, + xor=_reg_xor, + argstr='--reg %s', + mandatory=True, + desc='tkRAS-to-tkRAS matrix (tkregister2 format)') + fsl_reg_file = File( + exists=True, + xor=_reg_xor, + argstr='--fsl %s', + mandatory=True, + desc='fslRAS-to-fslRAS matrix (FSL format)') + xfm_reg_file = File( + exists=True, + xor=_reg_xor, + argstr='--xfm %s', + mandatory=True, + desc='ScannerRAS-to-ScannerRAS matrix (MNI format)') + reg_header = traits.Bool( + xor=_reg_xor, + argstr='--regheader', + mandatory=True, + desc='ScannerRAS-to-ScannerRAS matrix = identity') + mni_152_reg = traits.Bool( + xor=_reg_xor, + argstr='--regheader', + mandatory=True, + desc='target MNI152 space') + subject = traits.Str( + xor=_reg_xor, + argstr='--s %s', + mandatory=True, + desc='set matrix = identity and use subject for any templates') + inverse = traits.Bool(desc='sample from target to source', argstr='--inv') + interp = traits.Enum( + 'trilin', + 'nearest', + 'cubic', + argstr='--interp %s', + desc='Interpolation method ( or nearest)') + no_resample = traits.Bool( + desc='Do not resample; just change vox2ras matrix', + argstr='--no-resample') + m3z_file = File( + argstr="--m3z %s", + desc=('This is the morph to be applied to the volume. ' + 'Unless the morph is in mri/transforms (eg.: for ' + 'talairach.m3z computed by reconall), you will need ' + 'to specify the full path to this morph and use the ' + '--noDefM3zPath flag.')) + no_ded_m3z_path = traits.Bool( + argstr="--noDefM3zPath", + requires=['m3z_file'], + desc=('To be used with the m3z flag. ' + 'Instructs the code not to look for the' + 'm3z morph in the default location ' + '(SUBJECTS_DIR/subj/mri/transforms), ' + 'but instead just use the path ' + 'indicated in --m3z.')) + + invert_morph = traits.Bool( + argstr="--inv-morph", + requires=['m3z_file'], + desc=('Compute and use the inverse of the ' + 'non-linear morph to resample the input ' + 'volume. To be used by --m3z.')) class ApplyVolTransformOutputSpec(TraitedSpec): - transformed_file = File(exists=True, desc='Path to output file if used normally') + transformed_file = File( + exists=True, desc='Path to output file if used normally') class ApplyVolTransform(FSCommand): @@ -1377,9 +1678,8 @@ def _get_outfile(self): src = self.inputs.target_file else: src = self.inputs.source_file - outfile = fname_presuffix(src, - newpath=os.getcwd(), - suffix='_warped') + outfile = fname_presuffix( + src, newpath=os.getcwd(), suffix='_warped') return outfile def _list_outputs(self): @@ -1394,27 +1694,42 @@ def _gen_filename(self, name): class SmoothInputSpec(FSTraitedSpec): - in_file = File(exists=True, desc='source volume', - argstr='--i %s', mandatory=True) - reg_file = File(desc='registers volume to surface anatomical ', - argstr='--reg %s', mandatory=True, - exists=True) + in_file = File( + exists=True, desc='source volume', argstr='--i %s', mandatory=True) + reg_file = File( + desc='registers volume to surface anatomical ', + argstr='--reg %s', + mandatory=True, + exists=True) smoothed_file = File(desc='output volume', argstr='--o %s', genfile=True) - proj_frac_avg = traits.Tuple(traits.Float, traits.Float, traits.Float, - xor=['proj_frac'], - desc='average a long normal min max delta', - argstr='--projfrac-avg %.2f %.2f %.2f') - proj_frac = traits.Float(desc='project frac of thickness a long surface normal', - xor=['proj_frac_avg'], - argstr='--projfrac %s') - surface_fwhm = traits.Range(low=0.0, requires=['reg_file'], - mandatory=True, xor=['num_iters'], - desc='surface FWHM in mm', argstr='--fwhm %f') - num_iters = traits.Range(low=1, xor=['surface_fwhm'], - mandatory=True, argstr='--niters %d', - desc='number of iterations instead of fwhm') - vol_fwhm = traits.Range(low=0.0, argstr='--vol-fwhm %f', - desc='volume smoothing outside of surface') + proj_frac_avg = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + xor=['proj_frac'], + desc='average a long normal min max delta', + argstr='--projfrac-avg %.2f %.2f %.2f') + proj_frac = traits.Float( + desc='project frac of thickness a long surface normal', + xor=['proj_frac_avg'], + argstr='--projfrac %s') + surface_fwhm = traits.Range( + low=0.0, + requires=['reg_file'], + mandatory=True, + xor=['num_iters'], + desc='surface FWHM in mm', + argstr='--fwhm %f') + num_iters = traits.Range( + low=1, + xor=['surface_fwhm'], + mandatory=True, + argstr='--niters %d', + desc='number of iterations instead of fwhm') + vol_fwhm = traits.Range( + low=0.0, + argstr='--vol-fwhm %f', + desc='volume smoothing outside of surface') class SmoothOutputSpec(TraitedSpec): @@ -1451,8 +1766,7 @@ def _list_outputs(self): outputs = self.output_spec().get() outfile = self.inputs.smoothed_file if not isdefined(outfile): - outfile = self._gen_fname(self.inputs.in_file, - suffix='_smooth') + outfile = self._gen_fname(self.inputs.in_file, suffix='_smooth') outputs['smoothed_file'] = outfile return outputs @@ -1464,46 +1778,76 @@ def _gen_filename(self, name): class RobustRegisterInputSpec(FSTraitedSpec): - source_file = File(exists=True, mandatory=True, argstr='--mov %s', - desc='volume to be registered') - target_file = File(exists=True, mandatory=True, argstr='--dst %s', - desc='target volume for the registration') + source_file = File( + exists=True, + mandatory=True, + argstr='--mov %s', + desc='volume to be registered') + target_file = File( + exists=True, + mandatory=True, + argstr='--dst %s', + desc='target volume for the registration') out_reg_file = traits.Either( - True, File, default=True, usedefault=True, argstr='--lta %s', + True, + File, + default=True, + usedefault=True, + argstr='--lta %s', desc='registration file; either True or filename') registered_file = traits.Either( - traits.Bool, File, argstr='--warp %s', + traits.Bool, + File, + argstr='--warp %s', desc='registered image; either True or filename') weights_file = traits.Either( - traits.Bool, File, argstr='--weights %s', + traits.Bool, + File, + argstr='--weights %s', desc='weights image to write; either True or filename') est_int_scale = traits.Bool( argstr='--iscale', desc='estimate intensity scale (recommended for unnormalized images)') - trans_only = traits.Bool(argstr='--transonly', - desc='find 3 parameter translation only') - in_xfm_file = File(exists=True, argstr='--transform', - desc='use initial transform on source') + trans_only = traits.Bool( + argstr='--transonly', desc='find 3 parameter translation only') + in_xfm_file = File( + exists=True, + argstr='--transform', + desc='use initial transform on source') half_source = traits.Either( - traits.Bool, File, argstr='--halfmov %s', + traits.Bool, + File, + argstr='--halfmov %s', desc="write source volume mapped to halfway space") half_targ = traits.Either( - traits.Bool, File, argstr="--halfdst %s", + traits.Bool, + File, + argstr="--halfdst %s", desc="write target volume mapped to halfway space") half_weights = traits.Either( - traits.Bool, File, argstr="--halfweights %s", + traits.Bool, + File, + argstr="--halfweights %s", desc="write weights volume mapped to halfway space") half_source_xfm = traits.Either( - traits.Bool, File, argstr="--halfmovlta %s", + traits.Bool, + File, + argstr="--halfmovlta %s", desc="write transform from source to halfway space") half_targ_xfm = traits.Either( - traits.Bool, File, argstr="--halfdstlta %s", + traits.Bool, + File, + argstr="--halfdstlta %s", desc="write transform from target to halfway space") auto_sens = traits.Bool( - argstr='--satit', xor=['outlier_sens'], mandatory=True, + argstr='--satit', + xor=['outlier_sens'], + mandatory=True, desc='auto-detect good sensitivity') outlier_sens = traits.Float( - argstr='--sat %.4f', xor=['auto_sens'], mandatory=True, + argstr='--sat %.4f', + xor=['auto_sens'], + mandatory=True, desc='set outlier sensitivity explicitly') least_squares = traits.Bool( argstr='--leastsquares', @@ -1512,43 +1856,47 @@ class RobustRegisterInputSpec(FSTraitedSpec): init_orient = traits.Bool( argstr='--initorient', desc='use moments for initial orient (recommended for stripped brains)' - ) - max_iterations = traits.Int(argstr='--maxit %d', - desc='maximum # of times on each resolution') - high_iterations = traits.Int(argstr='--highit %d', - desc='max # of times on highest resolution') + ) + max_iterations = traits.Int( + argstr='--maxit %d', desc='maximum # of times on each resolution') + high_iterations = traits.Int( + argstr='--highit %d', desc='max # of times on highest resolution') iteration_thresh = traits.Float( argstr='--epsit %.3f', desc='stop iterations when below threshold') subsample_thresh = traits.Int( argstr='--subsample %d', desc='subsample if dimension is above threshold size') - outlier_limit = traits.Float(argstr='--wlimit %.3f', - desc='set maximal outlier limit in satit') + outlier_limit = traits.Float( + argstr='--wlimit %.3f', desc='set maximal outlier limit in satit') write_vo2vox = traits.Bool( argstr='--vox2vox', desc='output vox2vox matrix (default is RAS2RAS)') - no_multi = traits.Bool(argstr='--nomulti', - desc='work on highest resolution') - mask_source = File(exists=True, argstr='--maskmov %s', - desc='image to mask source volume with') - mask_target = File(exists=True, argstr='--maskdst %s', - desc='image to mask target volume with') - force_double = traits.Bool(argstr='--doubleprec', - desc='use double-precision intensities') - force_float = traits.Bool(argstr='--floattype', - desc='use float intensities') + no_multi = traits.Bool( + argstr='--nomulti', desc='work on highest resolution') + mask_source = File( + exists=True, + argstr='--maskmov %s', + desc='image to mask source volume with') + mask_target = File( + exists=True, + argstr='--maskdst %s', + desc='image to mask target volume with') + force_double = traits.Bool( + argstr='--doubleprec', desc='use double-precision intensities') + force_float = traits.Bool( + argstr='--floattype', desc='use float intensities') class RobustRegisterOutputSpec(TraitedSpec): out_reg_file = File(exists=True, desc="output registration file") - registered_file = File(exists=True, - desc="output image with registration applied") + registered_file = File( + exists=True, desc="output image with registration applied") weights_file = File(exists=True, desc="image of weights used") - half_source = File(exists=True, - desc="source image mapped to halfway space") + half_source = File( + exists=True, desc="source image mapped to halfway space") half_targ = File(exists=True, desc="target image mapped to halfway space") - half_weights = File(exists=True, - desc="weights image mapped to halfway space") + half_weights = File( + exists=True, desc="weights image mapped to halfway space") half_source_xfm = File( exists=True, desc="transform file to map source image to halfway space") @@ -1594,24 +1942,26 @@ def _format_arg(self, name, spec, value): def _list_outputs(self): outputs = self.output_spec().get() cwd = os.getcwd() - prefices = dict(src=self.inputs.source_file, - trg=self.inputs.target_file) - suffices = dict(out_reg_file=("src", "_robustreg.lta", False), - registered_file=("src", "_robustreg", True), - weights_file=("src", "_robustweights", True), - half_source=("src", "_halfway", True), - half_targ=("trg", "_halfway", True), - half_weights=("src", "_halfweights", True), - half_source_xfm=("src", "_robustxfm.lta", False), - half_targ_xfm=("trg", "_robustxfm.lta", False)) + prefices = dict( + src=self.inputs.source_file, trg=self.inputs.target_file) + suffices = dict( + out_reg_file=("src", "_robustreg.lta", False), + registered_file=("src", "_robustreg", True), + weights_file=("src", "_robustweights", True), + half_source=("src", "_halfway", True), + half_targ=("trg", "_halfway", True), + half_weights=("src", "_halfweights", True), + half_source_xfm=("src", "_robustxfm.lta", False), + half_targ_xfm=("trg", "_robustxfm.lta", False)) for name, sufftup in list(suffices.items()): value = getattr(self.inputs, name) if value: if value is True: - outputs[name] = fname_presuffix(prefices[sufftup[0]], - suffix=sufftup[1], - newpath=cwd, - use_ext=sufftup[2]) + outputs[name] = fname_presuffix( + prefices[sufftup[0]], + suffix=sufftup[1], + newpath=cwd, + use_ext=sufftup[2]) else: outputs[name] = os.path.abspath(value) return outputs @@ -1619,21 +1969,34 @@ def _list_outputs(self): class FitMSParamsInputSpec(FSTraitedSpec): - in_files = traits.List(File(exists=True), argstr="%s", position=-2, mandatory=True, - desc="list of FLASH images (must be in mgh format)") - tr_list = traits.List(traits.Int, desc="list of TRs of the input files (in msec)") - te_list = traits.List(traits.Float, desc="list of TEs of the input files (in msec)") - flip_list = traits.List(traits.Int, desc="list of flip angles of the input files") - xfm_list = traits.List(File(exists=True), - desc="list of transform files to apply to each FLASH image") - out_dir = Directory(argstr="%s", position=-1, genfile=True, - desc="directory to store output in") + in_files = traits.List( + File(exists=True), + argstr="%s", + position=-2, + mandatory=True, + desc="list of FLASH images (must be in mgh format)") + tr_list = traits.List( + traits.Int, desc="list of TRs of the input files (in msec)") + te_list = traits.List( + traits.Float, desc="list of TEs of the input files (in msec)") + flip_list = traits.List( + traits.Int, desc="list of flip angles of the input files") + xfm_list = traits.List( + File(exists=True), + desc="list of transform files to apply to each FLASH image") + out_dir = Directory( + argstr="%s", + position=-1, + genfile=True, + desc="directory to store output in") class FitMSParamsOutputSpec(TraitedSpec): - t1_image = File(exists=True, desc="image of estimated T1 relaxation values") - pd_image = File(exists=True, desc="image of estimated proton density values") + t1_image = File( + exists=True, desc="image of estimated T1 relaxation values") + pd_image = File( + exists=True, desc="image of estimated proton density values") t2star_image = File(exists=True, desc="image of estimated T2* values") @@ -1663,7 +2026,8 @@ def _format_arg(self, name, spec, value): if isdefined(self.inputs.te_list): cmd = " ".join((cmd, "-te %.3f" % self.inputs.te_list[i])) if isdefined(self.inputs.flip_list): - cmd = " ".join((cmd, "-fa %.1f" % self.inputs.flip_list[i])) + cmd = " ".join((cmd, + "-fa %.1f" % self.inputs.flip_list[i])) if isdefined(self.inputs.xfm_list): cmd = " ".join((cmd, "-at %s" % self.inputs.xfm_list[i])) cmd = " ".join((cmd, file)) @@ -1689,18 +2053,34 @@ def _gen_filename(self, name): class SynthesizeFLASHInputSpec(FSTraitedSpec): - fixed_weighting = traits.Bool(position=1, argstr="-w", - desc="use a fixed weighting to generate optimal gray/white contrast") - tr = traits.Float(mandatory=True, position=2, argstr="%.2f", - desc="repetition time (in msec)") - flip_angle = traits.Float(mandatory=True, position=3, argstr="%.2f", - desc="flip angle (in degrees)") - te = traits.Float(mandatory=True, position=4, argstr="%.3f", - desc="echo time (in msec)") - t1_image = File(exists=True, mandatory=True, position=5, argstr="%s", - desc="image of T1 values") - pd_image = File(exists=True, mandatory=True, position=6, argstr="%s", - desc="image of proton density values") + fixed_weighting = traits.Bool( + position=1, + argstr="-w", + desc="use a fixed weighting to generate optimal gray/white contrast") + tr = traits.Float( + mandatory=True, + position=2, + argstr="%.2f", + desc="repetition time (in msec)") + flip_angle = traits.Float( + mandatory=True, + position=3, + argstr="%.2f", + desc="flip angle (in degrees)") + te = traits.Float( + mandatory=True, position=4, argstr="%.3f", desc="echo time (in msec)") + t1_image = File( + exists=True, + mandatory=True, + position=5, + argstr="%s", + desc="image of T1 values") + pd_image = File( + exists=True, + mandatory=True, + position=6, + argstr="%s", + desc="image of proton density values") out_file = File(genfile=True, argstr="%s", desc="image to write") @@ -1732,8 +2112,8 @@ def _list_outputs(self): if isdefined(self.inputs.out_file): outputs["out_file"] = self.inputs.out_file else: - outputs["out_file"] = self._gen_fname("synth-flash_%02d.mgz" % self.inputs.flip_angle, - suffix="") + outputs["out_file"] = self._gen_fname( + "synth-flash_%02d.mgz" % self.inputs.flip_angle, suffix="") return outputs def _gen_filename(self, name): @@ -1744,31 +2124,60 @@ def _gen_filename(self, name): class MNIBiasCorrectionInputSpec(FSTraitedSpec): # mandatory - in_file = File(exists=True, mandatory=True, argstr="--i %s", - desc="input volume. Input can be any format accepted by mri_convert.") + in_file = File( + exists=True, + mandatory=True, + argstr="--i %s", + desc="input volume. Input can be any format accepted by mri_convert.") # optional - out_file = File(argstr="--o %s", name_source=['in_file'], - name_template='%s_output', hash_files=False, keep_extension=True, - desc="output volume. Output can be any format accepted by mri_convert. " + - "If the output format is COR, then the directory must exist.") - iterations = traits.Int(4, argstr="--n %d", - desc="Number of iterations to run nu_correct. Default is 4. This is the number of times " + - "that nu_correct is repeated (ie, using the output from the previous run as the input for " + - "the next). This is different than the -iterations option to nu_correct.") - protocol_iterations = traits.Int(argstr="--proto-iters %d", - desc="Passes Np as argument of the -iterations flag of nu_correct. This is different " + - "than the --n flag above. Default is not to pass nu_correct the -iterations flag.") + out_file = File( + argstr="--o %s", + name_source=['in_file'], + name_template='%s_output', + hash_files=False, + keep_extension=True, + desc="output volume. Output can be any format accepted by mri_convert. " + + "If the output format is COR, then the directory must exist.") + iterations = traits.Int( + 4, + argstr="--n %d", + desc= + "Number of iterations to run nu_correct. Default is 4. This is the number of times " + + + "that nu_correct is repeated (ie, using the output from the previous run as the input for " + + + "the next). This is different than the -iterations option to nu_correct." + ) + protocol_iterations = traits.Int( + argstr="--proto-iters %d", + desc= + "Passes Np as argument of the -iterations flag of nu_correct. This is different " + + + "than the --n flag above. Default is not to pass nu_correct the -iterations flag." + ) distance = traits.Int(argstr="--distance %d", desc="N3 -distance option") - no_rescale = traits.Bool(argstr="--no-rescale", - desc="do not rescale so that global mean of output == input global mean") - mask = File(exists=True, argstr="--mask %s", - desc="brainmask volume. Input can be any format accepted by mri_convert.") - transform = File(exists=True, argstr="--uchar %s", - desc="tal.xfm. Use mri_make_uchar instead of conforming") - stop = traits.Float(argstr="--stop %f", - desc="Convergence threshold below which iteration stops (suggest 0.01 to 0.0001)") - shrink = traits.Int(argstr="--shrink %d", - desc="Shrink parameter for finer sampling (default is 4)") + no_rescale = traits.Bool( + argstr="--no-rescale", + desc="do not rescale so that global mean of output == input global mean" + ) + mask = File( + exists=True, + argstr="--mask %s", + desc= + "brainmask volume. Input can be any format accepted by mri_convert.") + transform = File( + exists=True, + argstr="--uchar %s", + desc="tal.xfm. Use mri_make_uchar instead of conforming") + stop = traits.Float( + argstr="--stop %f", + desc= + "Convergence threshold below which iteration stops (suggest 0.01 to 0.0001)" + ) + shrink = traits.Int( + argstr="--shrink %d", + desc="Shrink parameter for finer sampling (default is 4)") + class MNIBiasCorrectionOutputSpec(TraitedSpec): out_file = File(exists=True, desc="output volume") @@ -1809,18 +2218,27 @@ class MNIBiasCorrection(FSCommand): class WatershedSkullStripInputSpec(FSTraitedSpec): # required - in_file = File(argstr="%s", exists=True, mandatory=True, - position=-2, desc="input volume") - out_file = File('brainmask.auto.mgz', argstr="%s", exists=False, - mandatory=True, position=-1, usedefault=True, - desc="output volume") + in_file = File( + argstr="%s", + exists=True, + mandatory=True, + position=-2, + desc="input volume") + out_file = File( + 'brainmask.auto.mgz', + argstr="%s", + exists=False, + mandatory=True, + position=-1, + usedefault=True, + desc="output volume") # optional t1 = traits.Bool( argstr="-T1", desc="specify T1 input volume (T1 grey value = 110)") - brain_atlas = File(argstr="-brain_atlas %s", - exists=True, position=-4, desc="") - transform = File(argstr="%s", exists=False, - position=-3, desc="undocumented") + brain_atlas = File( + argstr="-brain_atlas %s", exists=True, position=-4, desc="") + transform = File( + argstr="%s", exists=False, position=-3, desc="undocumented") class WatershedSkullStripOutputSpec(TraitedSpec): @@ -1864,21 +2282,36 @@ def _list_outputs(self): class NormalizeInputSpec(FSTraitedSpec): # required - in_file = File(argstr='%s', exists=True, mandatory=True, - position=-2, desc="The input file for Normalize") - out_file = File(argstr='%s', position=-1, - name_source=['in_file'], name_template='%s_norm', - hash_files=False, keep_extension=True, - desc="The output file for Normalize") + in_file = File( + argstr='%s', + exists=True, + mandatory=True, + position=-2, + desc="The input file for Normalize") + out_file = File( + argstr='%s', + position=-1, + name_source=['in_file'], + name_template='%s_norm', + hash_files=False, + keep_extension=True, + desc="The output file for Normalize") # optional - gradient = traits.Int(1, argstr="-g %d", usedefault=False, - desc="use max intensity/mm gradient g (default=1)") - mask = File(argstr="-mask %s", exists=True, - desc="The input mask file for Normalize") - segmentation = File(argstr="-aseg %s", - exists=True, desc="The input segmentation for Normalize") - transform = File(exists=True, - desc="Tranform file from the header of the input file") + gradient = traits.Int( + 1, + argstr="-g %d", + usedefault=False, + desc="use max intensity/mm gradient g (default=1)") + mask = File( + argstr="-mask %s", + exists=True, + desc="The input mask file for Normalize") + segmentation = File( + argstr="-aseg %s", + exists=True, + desc="The input segmentation for Normalize") + transform = File( + exists=True, desc="Tranform file from the header of the input file") class NormalizeOutputSpec(TraitedSpec): @@ -1911,23 +2344,41 @@ def _list_outputs(self): class CANormalizeInputSpec(FSTraitedSpec): - in_file = File(argstr='%s', exists=True, mandatory=True, - position=-4, desc="The input file for CANormalize") - out_file = File(argstr='%s', position=-1, - name_source=['in_file'], name_template='%s_norm', - hash_files=False, keep_extension=True, - desc="The output file for CANormalize") - atlas = File(argstr='%s', exists=True, mandatory=True, - position=-3, desc="The atlas file in gca format") - transform = File(argstr='%s', exists=True, mandatory=True, - position=-2, desc="The tranform file in lta format") + in_file = File( + argstr='%s', + exists=True, + mandatory=True, + position=-4, + desc="The input file for CANormalize") + out_file = File( + argstr='%s', + position=-1, + name_source=['in_file'], + name_template='%s_norm', + hash_files=False, + keep_extension=True, + desc="The output file for CANormalize") + atlas = File( + argstr='%s', + exists=True, + mandatory=True, + position=-3, + desc="The atlas file in gca format") + transform = File( + argstr='%s', + exists=True, + mandatory=True, + position=-2, + desc="The tranform file in lta format") # optional - mask = File(argstr='-mask %s', exists=True, - desc="Specifies volume to use as mask") - control_points = File(argstr='-c %s', - desc="File name for the output control points") - long_file = File(argstr='-long %s', - desc='undocumented flag used in longitudinal processing') + mask = File( + argstr='-mask %s', exists=True, desc="Specifies volume to use as mask") + control_points = File( + argstr='-c %s', desc="File name for the output control points") + long_file = File( + argstr='-long %s', + desc='undocumented flag used in longitudinal processing') + class CANormalizeOutputSpec(TraitedSpec): out_file = traits.File(exists=False, desc="The output file for Normalize") @@ -1964,31 +2415,49 @@ def _list_outputs(self): class CARegisterInputSpec(FSTraitedSpecOpenMP): - #required - in_file = File(argstr='%s', exists=True, mandatory=True, - position=-3, desc="The input volume for CARegister") - out_file = File(argstr='%s', position=-1, - genfile=True, desc="The output volume for CARegister") - template = File(argstr='%s', exists=True, - position=-2, desc="The template file in gca format") + # required + in_file = File( + argstr='%s', + exists=True, + mandatory=True, + position=-3, + desc="The input volume for CARegister") + out_file = File( + argstr='%s', + position=-1, + genfile=True, + desc="The output volume for CARegister") + template = File( + argstr='%s', + exists=True, + position=-2, + desc="The template file in gca format") # optional - mask = File(argstr='-mask %s', exists=True, - desc="Specifies volume to use as mask") - invert_and_save = traits.Bool(argstr='-invert-and-save', position=-4, - desc="Invert and save the .m3z multi-dimensional talaraich transform to x, y, and z .mgz files") + mask = File( + argstr='-mask %s', exists=True, desc="Specifies volume to use as mask") + invert_and_save = traits.Bool( + argstr='-invert-and-save', + position=-4, + desc= + "Invert and save the .m3z multi-dimensional talaraich transform to x, y, and z .mgz files" + ) no_big_ventricles = traits.Bool( - argstr='-nobigventricles', desc="No big ventricles") - transform = File(argstr='-T %s', exists=True, - desc="Specifies transform in lta format") - align = traits.String(argstr='-align-%s', - desc="Specifies when to perform alignment") + argstr='-nobigventricles', desc="No big ventricles") + transform = File( + argstr='-T %s', exists=True, desc="Specifies transform in lta format") + align = traits.String( + argstr='-align-%s', desc="Specifies when to perform alignment") levels = traits.Int( argstr='-levels %d', - desc="defines how many surrounding voxels will be used in interpolations, default is 6") + desc= + "defines how many surrounding voxels will be used in interpolations, default is 6" + ) A = traits.Int( - argstr='-A %d', desc='undocumented flag used in longitudinal processing') + argstr='-A %d', + desc='undocumented flag used in longitudinal processing') l_files = InputMultiPath( - File(exists=False), argstr='-l %s', + File(exists=False), + argstr='-l %s', desc='undocumented flag used in longitudinal processing') @@ -2031,34 +2500,60 @@ def _list_outputs(self): class CALabelInputSpec(FSTraitedSpecOpenMP): - #required - in_file = File(argstr="%s", position=-4, mandatory=True, - exists=True, desc="Input volume for CALabel") - out_file = File(argstr="%s", position=-1, mandatory=True, exists=False, - desc="Output file for CALabel") - transform = File(argstr="%s", position=-3, mandatory=True, - exists=True, desc="Input transform for CALabel") - template = File(argstr="%s", position=-2, mandatory=True, - exists=True, desc="Input template for CALabel") + # required + in_file = File( + argstr="%s", + position=-4, + mandatory=True, + exists=True, + desc="Input volume for CALabel") + out_file = File( + argstr="%s", + position=-1, + mandatory=True, + exists=False, + desc="Output file for CALabel") + transform = File( + argstr="%s", + position=-3, + mandatory=True, + exists=True, + desc="Input transform for CALabel") + template = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + desc="Input template for CALabel") # optional - in_vol = File(argstr="-r %s", exists=True, - desc="set input volume") - intensities = File(argstr="-r %s", exists=True, - desc="input label intensities file(used in longitudinal processing)") + in_vol = File(argstr="-r %s", exists=True, desc="set input volume") + intensities = File( + argstr="-r %s", + exists=True, + desc="input label intensities file(used in longitudinal processing)") no_big_ventricles = traits.Bool( - argstr="-nobigventricles", desc="No big ventricles") - align = traits.Bool(argstr="-align", desc="Align CALabel") - prior = traits.Float(argstr="-prior %.1f", - desc="Prior for CALabel") - relabel_unlikely = traits.Tuple(traits.Int, traits.Float, - argstr="-relabel_unlikely %d %.1f", - desc=("Reclassify voxels at least some std" - " devs from the mean using some size" - " Gaussian window")) - label = traits.File(argstr="-l %s", exists=True, - desc="Undocumented flag. Autorecon3 uses ../label/{hemisphere}.cortex.label as input file") - aseg = traits.File(argstr="-aseg %s", exists=True, - desc="Undocumented flag. Autorecon3 uses ../mri/aseg.presurf.mgz as input file") + argstr="-nobigventricles", desc="No big ventricles") + align = traits.Bool(argstr="-align", desc="Align CALabel") + prior = traits.Float(argstr="-prior %.1f", desc="Prior for CALabel") + relabel_unlikely = traits.Tuple( + traits.Int, + traits.Float, + argstr="-relabel_unlikely %d %.1f", + desc=("Reclassify voxels at least some std" + " devs from the mean using some size" + " Gaussian window")) + label = traits.File( + argstr="-l %s", + exists=True, + desc= + "Undocumented flag. Autorecon3 uses ../label/{hemisphere}.cortex.label as input file" + ) + aseg = traits.File( + argstr="-aseg %s", + exists=True, + desc= + "Undocumented flag. Autorecon3 uses ../mri/aseg.presurf.mgz as input file" + ) class CALabelOutputSpec(TraitedSpec): @@ -2093,35 +2588,65 @@ def _list_outputs(self): class MRIsCALabelInputSpec(FSTraitedSpecOpenMP): # required - subject_id = traits.String('subject_id', argstr="%s", position=-5, - usedefault=True, mandatory=True, - desc="Subject name or ID") - hemisphere = traits.Enum('lh', 'rh', - argstr="%s", position=-4, mandatory=True, - desc="Hemisphere ('lh' or 'rh')") - canonsurf = File(argstr="%s", position=-3, mandatory=True, exists=True, - desc="Input canonical surface file") - classifier = File(argstr="%s", position=-2, mandatory=True, exists=True, - desc="Classifier array input file") - smoothwm = File(mandatory=True, exists=True, - desc="implicit input {hemisphere}.smoothwm") - curv = File(mandatory=True, exists=True, - desc="implicit input {hemisphere}.curv") - sulc = File(mandatory=True, exists=True, - desc="implicit input {hemisphere}.sulc") - out_file = File(argstr="%s", position=-1, exists=False, - name_source=['hemisphere'], keep_extension=True, - hash_files=False, name_template="%s.aparc.annot", - desc="Annotated surface output file") + subject_id = traits.String( + 'subject_id', + argstr="%s", + position=-5, + usedefault=True, + mandatory=True, + desc="Subject name or ID") + hemisphere = traits.Enum( + 'lh', + 'rh', + argstr="%s", + position=-4, + mandatory=True, + desc="Hemisphere ('lh' or 'rh')") + canonsurf = File( + argstr="%s", + position=-3, + mandatory=True, + exists=True, + desc="Input canonical surface file") + classifier = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + desc="Classifier array input file") + smoothwm = File( + mandatory=True, + exists=True, + desc="implicit input {hemisphere}.smoothwm") + curv = File( + mandatory=True, exists=True, desc="implicit input {hemisphere}.curv") + sulc = File( + mandatory=True, exists=True, desc="implicit input {hemisphere}.sulc") + out_file = File( + argstr="%s", + position=-1, + exists=False, + name_source=['hemisphere'], + keep_extension=True, + hash_files=False, + name_template="%s.aparc.annot", + desc="Annotated surface output file") # optional - label = traits.File(argstr="-l %s", exists=True, - desc="Undocumented flag. Autorecon3 uses ../label/{hemisphere}.cortex.label as input file") - aseg = traits.File(argstr="-aseg %s", exists=True, - desc="Undocumented flag. Autorecon3 uses ../mri/aseg.presurf.mgz as input file") - seed = traits.Int(argstr="-seed %d", - desc="") - copy_inputs = traits.Bool(desc="Copies implicit inputs to node directory " + - "and creates a temp subjects_directory. " + + label = traits.File( + argstr="-l %s", + exists=True, + desc= + "Undocumented flag. Autorecon3 uses ../label/{hemisphere}.cortex.label as input file" + ) + aseg = traits.File( + argstr="-aseg %s", + exists=True, + desc= + "Undocumented flag. Autorecon3 uses ../mri/aseg.presurf.mgz as input file" + ) + seed = traits.Int(argstr="-seed %d", desc="") + copy_inputs = traits.Bool(desc="Copies implicit inputs to node directory " + + "and creates a temp subjects_directory. " + "Use this when running as a node") @@ -2165,20 +2690,25 @@ def run(self, **inputs): if 'subjects_dir' in inputs: inputs['subjects_dir'] = self.inputs.subjects_dir copy2subjdir(self, self.inputs.canonsurf, folder='surf') - copy2subjdir(self, self.inputs.smoothwm, - folder='surf', - basename='{0}.smoothwm'.format(self.inputs.hemisphere)) - copy2subjdir(self, self.inputs.curv, - folder='surf', - basename='{0}.curv'.format(self.inputs.hemisphere)) - copy2subjdir(self, self.inputs.sulc, - folder='surf', - basename='{0}.sulc'.format(self.inputs.hemisphere)) + copy2subjdir( + self, + self.inputs.smoothwm, + folder='surf', + basename='{0}.smoothwm'.format(self.inputs.hemisphere)) + copy2subjdir( + self, + self.inputs.curv, + folder='surf', + basename='{0}.curv'.format(self.inputs.hemisphere)) + copy2subjdir( + self, + self.inputs.sulc, + folder='surf', + basename='{0}.sulc'.format(self.inputs.hemisphere)) # The label directory must exist in order for an output to be written label_dir = os.path.join(self.inputs.subjects_dir, - self.inputs.subject_id, - 'label') + self.inputs.subject_id, 'label') if not os.path.isdir(label_dir): os.makedirs(label_dir) @@ -2188,35 +2718,50 @@ def _list_outputs(self): outputs = self.output_spec().get() out_basename = os.path.basename(self.inputs.out_file) outputs['out_file'] = os.path.join(self.inputs.subjects_dir, - self.inputs.subject_id, - 'label', out_basename) + self.inputs.subject_id, 'label', + out_basename) return outputs class SegmentCCInputSpec(FSTraitedSpec): - in_file = File(argstr="-aseg %s", mandatory=True, exists=True, - desc="Input aseg file to read from subjects directory") - in_norm = File(mandatory=True, exists=True, - desc="Required undocumented input {subject}/mri/norm.mgz") - out_file = File(argstr="-o %s", exists=False, - name_source=['in_file'], name_template='%s.auto.mgz', - hash_files=False, keep_extension=False, - desc="Filename to write aseg including CC") - out_rotation = File(argstr="-lta %s", mandatory=True, exists=False, - desc="Global filepath for writing rotation lta") - subject_id = traits.String('subject_id', argstr="%s", mandatory=True, - position=-1, usedefault=True, - desc="Subject name") - copy_inputs = traits.Bool(desc="If running as a node, set this to True." + - "This will copy the input files to the node " + - "directory.") + in_file = File( + argstr="-aseg %s", + mandatory=True, + exists=True, + desc="Input aseg file to read from subjects directory") + in_norm = File( + mandatory=True, + exists=True, + desc="Required undocumented input {subject}/mri/norm.mgz") + out_file = File( + argstr="-o %s", + exists=False, + name_source=['in_file'], + name_template='%s.auto.mgz', + hash_files=False, + keep_extension=False, + desc="Filename to write aseg including CC") + out_rotation = File( + argstr="-lta %s", + mandatory=True, + exists=False, + desc="Global filepath for writing rotation lta") + subject_id = traits.String( + 'subject_id', + argstr="%s", + mandatory=True, + position=-1, + usedefault=True, + desc="Subject name") + copy_inputs = traits.Bool( + desc="If running as a node, set this to True." + + "This will copy the input files to the node " + "directory.") class SegmentCCOutputSpec(TraitedSpec): - out_file = File(exists=False, - desc="Output segmentation uncluding corpus collosum") - out_rotation = File(exists=False, - desc="Output lta rotation file") + out_file = File( + exists=False, desc="Output segmentation uncluding corpus collosum") + out_rotation = File(exists=False, desc="Output lta rotation file") class SegmentCC(FSCommand): @@ -2287,13 +2832,9 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): subj_dir = os.path.join(os.getcwd(), self.inputs.subject_id) if name == 'out_file': - out_tmp = os.path.join(subj_dir, - 'mri', - out_base) + out_tmp = os.path.join(subj_dir, 'mri', out_base) elif name == 'out_rotation': - out_tmp = os.path.join(subj_dir, - 'mri', - 'transforms', + out_tmp = os.path.join(subj_dir, 'mri', 'transforms', out_base) else: out_tmp = None @@ -2302,14 +2843,23 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): if not os.path.isdir(os.path.dirname(out_tmp)): os.makedirs(os.path.dirname(out_tmp)) shutil.move(out_tmp, out_file) - return super(SegmentCC, self).aggregate_outputs(runtime, needed_outputs) + return super(SegmentCC, self).aggregate_outputs( + runtime, needed_outputs) class SegmentWMInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", exists=True, mandatory=True, - position=-2, desc="Input file for SegmentWM") - out_file = File(argstr="%s", exists=False, mandatory=True, - position=-1, desc="File to be written as output for SegmentWM") + in_file = File( + argstr="%s", + exists=True, + mandatory=True, + position=-2, + desc="Input file for SegmentWM") + out_file = File( + argstr="%s", + exists=False, + mandatory=True, + position=-1, + desc="File to be written as output for SegmentWM") class SegmentWMOutputSpec(TraitedSpec): @@ -2344,17 +2894,34 @@ def _list_outputs(self): class EditWMwithAsegInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", position=-4, mandatory=True, exists=True, - desc="Input white matter segmentation file") - brain_file = File(argstr="%s", position=-3, mandatory=True, exists=True, - desc="Input brain/T1 file") - seg_file = File(argstr="%s", position=-2, mandatory=True, exists=True, - desc="Input presurf segmentation file") - out_file = File(argstr="%s", position=-1, mandatory=True, exists=False, - desc="File to be written as output") + in_file = File( + argstr="%s", + position=-4, + mandatory=True, + exists=True, + desc="Input white matter segmentation file") + brain_file = File( + argstr="%s", + position=-3, + mandatory=True, + exists=True, + desc="Input brain/T1 file") + seg_file = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + desc="Input presurf segmentation file") + out_file = File( + argstr="%s", + position=-1, + mandatory=True, + exists=False, + desc="File to be written as output") # optional - keep_in = traits.Bool(argstr="-keep-in", - desc="Keep edits as found in input volume") + keep_in = traits.Bool( + argstr="-keep-in", desc="Keep edits as found in input volume") + class EditWMwithAsegOutputSpec(TraitedSpec): out_file = File(exists=False, desc="Output edited WM file") @@ -2388,37 +2955,53 @@ def _list_outputs(self): class ConcatenateLTAInputSpec(FSTraitedSpec): # required - in_lta1 = File(exists=True, mandatory=True, argstr='%s', position=-3, - desc='maps some src1 to dst1') + in_lta1 = File( + exists=True, + mandatory=True, + argstr='%s', + position=-3, + desc='maps some src1 to dst1') in_lta2 = traits.Either( - File(exists=True), 'identity.nofile', argstr='%s', position=-2, - mandatory=True, desc='maps dst1(src2) to dst2') + File(exists=True), + 'identity.nofile', + argstr='%s', + position=-2, + mandatory=True, + desc='maps dst1(src2) to dst2') out_file = File( - position=-1, argstr='%s', hash_files=False, name_source=['in_lta1'], - name_template='%s_concat', keep_extension=True, + position=-1, + argstr='%s', + hash_files=False, + name_source=['in_lta1'], + name_template='%s_concat', + keep_extension=True, desc='the combined LTA maps: src1 to dst2 = LTA2*LTA1') # Inversion and transform type - invert_1 = traits.Bool(argstr='-invert1', - desc='invert in_lta1 before applying it') - invert_2 = traits.Bool(argstr='-invert2', - desc='invert in_lta2 before applying it') - invert_out = traits.Bool(argstr='-invertout', - desc='invert output LTA') - out_type = traits.Enum('VOX2VOX', 'RAS2RAS', argstr='-out_type %d', - desc='set final LTA type') + invert_1 = traits.Bool( + argstr='-invert1', desc='invert in_lta1 before applying it') + invert_2 = traits.Bool( + argstr='-invert2', desc='invert in_lta2 before applying it') + invert_out = traits.Bool(argstr='-invertout', desc='invert output LTA') + out_type = traits.Enum( + 'VOX2VOX', 'RAS2RAS', argstr='-out_type %d', desc='set final LTA type') # Talairach options tal_source_file = traits.File( - exists=True, argstr='-tal %s', position=-5, + exists=True, + argstr='-tal %s', + position=-5, requires=['tal_template_file'], desc='if in_lta2 is talairach.xfm, specify source for talairach') tal_template_file = traits.File( - exists=True, argstr='%s', position=-4, requires=['tal_source_file'], + exists=True, + argstr='%s', + position=-4, + requires=['tal_source_file'], desc='if in_lta2 is talairach.xfm, specify template for talairach') - subject = traits.Str(argstr='-subject %s', - desc='set subject in output LTA') + subject = traits.Str( + argstr='-subject %s', desc='set subject in output LTA') # Note rmsdiff would be xor out_file, and would be most easily dealt with # in a new interface. -CJM 2017.10.05 diff --git a/nipype/interfaces/freesurfer/registration.py b/nipype/interfaces/freesurfer/registration.py index 60a10b4c11..ccc03f9103 100644 --- a/nipype/interfaces/freesurfer/registration.py +++ b/nipype/interfaces/freesurfer/registration.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """Provides interfaces to various longitudinal commands provided by freesurfer Change directory to provide relative paths for doctests @@ -11,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import os.path @@ -19,11 +19,8 @@ from ... import logging from ...utils.filemanip import split_filename, copyfile -from .base import (FSCommand, FSTraitedSpec, - FSScriptCommand, - FSScriptOutputSpec, - FSCommandOpenMP, - FSTraitedSpecOpenMP) +from .base import (FSCommand, FSTraitedSpec, FSScriptCommand, + FSScriptOutputSpec, FSCommandOpenMP, FSTraitedSpecOpenMP) from ..base import (isdefined, TraitedSpec, File, traits, Directory) __docformat__ = 'restructuredtext' @@ -38,13 +35,16 @@ class MPRtoMNI305InputSpec(FSTraitedSpec): target = traits.String( "", mandatory=True, usedefault=True, desc="input atlas file") # required - in_file = File(argstr='%s', usedefault=True, - desc="the input file prefix for MPRtoMNI305") + in_file = File( + argstr='%s', + usedefault=True, + desc="the input file prefix for MPRtoMNI305") class MPRtoMNI305OutputSpec(FSScriptOutputSpec): out_file = File( - exists=False, desc="The output file '_to__t4_vox2vox.txt'") + exists=False, + desc="The output file '_to__t4_vox2vox.txt'") class MPRtoMNI305(FSScriptCommand): @@ -85,8 +85,11 @@ def _format_arg(self, opt, spec, val): elif opt == 'in_file': _, retval, ext = split_filename(val) # Need to copy file to working cache directory! - copyfile(val, os.path.abspath(retval + ext), - copy=True, hashmethod='content') + copyfile( + val, + os.path.abspath(retval + ext), + copy=True, + hashmethod='content') return retval return super(MPRtoMNI305, self)._format_arg(opt, spec, val) @@ -102,22 +105,39 @@ def _get_fname(self, fname): def _list_outputs(self): outputs = super(MPRtoMNI305, self)._list_outputs() - fullname = "_".join([self._get_fname(self.inputs.in_file), "to", - self.inputs.target, "t4", "vox2vox.txt"]) + fullname = "_".join([ + self._get_fname(self.inputs.in_file), "to", self.inputs.target, + "t4", "vox2vox.txt" + ]) outputs['out_file'] = os.path.abspath(fullname) return outputs class RegisterAVItoTalairachInputSpec(FSTraitedSpec): - in_file = File(argstr='%s', exists=True, mandatory=True, - position=0, desc="The input file") - target = File(argstr='%s', exists=True, mandatory=True, - position=1, desc="The target file") - vox2vox = File(argstr='%s', exists=True, mandatory=True, - position=2, desc="The vox2vox file") - out_file = File('talairach.auto.xfm', usedefault=True, - argstr='%s', - position=3, desc="The transform output") + in_file = File( + argstr='%s', + exists=True, + mandatory=True, + position=0, + desc="The input file") + target = File( + argstr='%s', + exists=True, + mandatory=True, + position=1, + desc="The target file") + vox2vox = File( + argstr='%s', + exists=True, + mandatory=True, + position=2, + desc="The vox2vox file") + out_file = File( + 'talairach.auto.xfm', + usedefault=True, + argstr='%s', + position=3, + desc="The transform output") class RegisterAVItoTalairachOutputSpec(FSScriptOutputSpec): @@ -169,23 +189,38 @@ def _list_outputs(self): class EMRegisterInputSpec(FSTraitedSpecOpenMP): # required - in_file = File(argstr="%s", exists=True, mandatory=True, - position=-3, desc="in brain volume") - template = File(argstr="%s", exists=True, mandatory=True, - position=-2, desc="template gca") - out_file = File(argstr="%s", exists=False, - name_source=['in_file'], name_template="%s_transform.lta", - hash_files=False, keep_extension=False, - position=-1, desc="output transform") + in_file = File( + argstr="%s", + exists=True, + mandatory=True, + position=-3, + desc="in brain volume") + template = File( + argstr="%s", + exists=True, + mandatory=True, + position=-2, + desc="template gca") + out_file = File( + argstr="%s", + exists=False, + name_source=['in_file'], + name_template="%s_transform.lta", + hash_files=False, + keep_extension=False, + position=-1, + desc="output transform") # optional skull = traits.Bool( argstr="-skull", desc="align to atlas containing skull (uns=5)") - mask = File(argstr="-mask %s", exists=True, - desc="use volume as a mask") - nbrspacing = traits.Int(argstr="-uns %d", - desc="align to atlas containing skull setting unknown_nbr_spacing = nbrspacing") - transform = File(argstr="-t %s", exists=True, - desc="Previously computed transform") + mask = File(argstr="-mask %s", exists=True, desc="use volume as a mask") + nbrspacing = traits.Int( + argstr="-uns %d", + desc= + "align to atlas containing skull setting unknown_nbr_spacing = nbrspacing" + ) + transform = File( + argstr="-t %s", exists=True, desc="Previously computed transform") class EMRegisterOutputSpec(TraitedSpec): @@ -219,21 +254,43 @@ def _list_outputs(self): class RegisterInputSpec(FSTraitedSpec): # required - in_surf = File(argstr="%s", exists=True, mandatory=True, position=-3, - copyfile=True, - desc="Surface to register, often {hemi}.sphere") - target = File(argstr="%s", exists=True, mandatory=True, position=-2, - desc="The data to register to. In normal recon-all usage, " + - "this is a template file for average surface.") - in_sulc = File(exists=True, mandatory=True, copyfile=True, - desc="Undocumented mandatory input file ${SUBJECTS_DIR}/surf/{hemisphere}.sulc ") - out_file = File(argstr="%s", exists=False, position=-1, genfile=True, - desc="Output surface file to capture registration") + in_surf = File( + argstr="%s", + exists=True, + mandatory=True, + position=-3, + copyfile=True, + desc="Surface to register, often {hemi}.sphere") + target = File( + argstr="%s", + exists=True, + mandatory=True, + position=-2, + desc="The data to register to. In normal recon-all usage, " + + "this is a template file for average surface.") + in_sulc = File( + exists=True, + mandatory=True, + copyfile=True, + desc= + "Undocumented mandatory input file ${SUBJECTS_DIR}/surf/{hemisphere}.sulc " + ) + out_file = File( + argstr="%s", + exists=False, + position=-1, + genfile=True, + desc="Output surface file to capture registration") # optional - curv = traits.Bool(argstr="-curv", requires=['in_smoothwm'], - desc="Use smoothwm curvature for final alignment") - in_smoothwm = File(exists=True, copyfile=True, - desc="Undocumented input file ${SUBJECTS_DIR}/surf/{hemisphere}.smoothwm ") + curv = traits.Bool( + argstr="-curv", + requires=['in_smoothwm'], + desc="Use smoothwm curvature for final alignment") + in_smoothwm = File( + exists=True, + copyfile=True, + desc= + "Undocumented input file ${SUBJECTS_DIR}/surf/{hemisphere}.smoothwm ") class RegisterOutputSpec(TraitedSpec): @@ -283,25 +340,40 @@ def _list_outputs(self): class PaintInputSpec(FSTraitedSpec): # required - in_surf = File(argstr="%s", exists=True, mandatory=True, position=-2, - desc="Surface file with grid (vertices) onto which the " + - "template data is to be sampled or 'painted'") - template = File(argstr="%s", exists=True, mandatory=True, position=-3, - desc="Template file") + in_surf = File( + argstr="%s", + exists=True, + mandatory=True, + position=-2, + desc="Surface file with grid (vertices) onto which the " + + "template data is to be sampled or 'painted'") + template = File( + argstr="%s", + exists=True, + mandatory=True, + position=-3, + desc="Template file") # optional template_param = traits.Int(desc="Frame number of the input template") - averages = traits.Int(argstr="-a %d", - desc="Average curvature patterns") - out_file = File(argstr="%s", exists=False, position=-1, - name_template="%s.avg_curv", hash_files=False, - name_source=['in_surf'], keep_extension=False, - desc="File containing a surface-worth of per-vertex values, " + - "saved in 'curvature' format.") + averages = traits.Int(argstr="-a %d", desc="Average curvature patterns") + out_file = File( + argstr="%s", + exists=False, + position=-1, + name_template="%s.avg_curv", + hash_files=False, + name_source=['in_surf'], + keep_extension=False, + desc="File containing a surface-worth of per-vertex values, " + + "saved in 'curvature' format.") class PaintOutputSpec(TraitedSpec): - out_file = File(exists=False, - desc="File containing a surface-worth of per-vertex values, saved in 'curvature' format.") + out_file = File( + exists=False, + desc= + "File containing a surface-worth of per-vertex values, saved in 'curvature' format." + ) class Paint(FSCommand): @@ -331,7 +403,8 @@ class Paint(FSCommand): def _format_arg(self, opt, spec, val): if opt == 'template': if isdefined(self.inputs.template_param): - return spec.argstr % (val + '#' + str(self.inputs.template_param)) + return spec.argstr % ( + val + '#' + str(self.inputs.template_param)) return super(Paint, self)._format_arg(opt, spec, val) def _list_outputs(self): @@ -341,78 +414,122 @@ def _list_outputs(self): class MRICoregInputSpec(FSTraitedSpec): - source_file = File(argstr='--mov %s', desc='source file to be registered', - mandatory=True, copyfile=False) - reference_file = File(argstr='--ref %s', desc='reference (target) file', - mandatory=True, copyfile=False, xor=['subject_id']) - out_lta_file = traits.Either(True, File, argstr='--lta %s', default=True, - usedefault=True, - desc='output registration file (LTA format)') - out_reg_file = traits.Either(True, File, argstr='--regdat %s', - desc='output registration file (REG format)') - out_params_file = traits.Either(True, File, argstr='--params %s', - desc='output parameters file') - - subjects_dir = Directory(exists=True, argstr='--sd %s', - desc='FreeSurfer SUBJECTS_DIR') + source_file = File( + argstr='--mov %s', + desc='source file to be registered', + mandatory=True, + copyfile=False) + reference_file = File( + argstr='--ref %s', + desc='reference (target) file', + mandatory=True, + copyfile=False, + xor=['subject_id']) + out_lta_file = traits.Either( + True, + File, + argstr='--lta %s', + default=True, + usedefault=True, + desc='output registration file (LTA format)') + out_reg_file = traits.Either( + True, + File, + argstr='--regdat %s', + desc='output registration file (REG format)') + out_params_file = traits.Either( + True, File, argstr='--params %s', desc='output parameters file') + + subjects_dir = Directory( + exists=True, argstr='--sd %s', desc='FreeSurfer SUBJECTS_DIR') subject_id = traits.Str( - argstr='--s %s', position=1, mandatory=True, xor=['reference_file'], + argstr='--s %s', + position=1, + mandatory=True, + xor=['reference_file'], requires=['subjects_dir'], desc='freesurfer subject ID (implies ``reference_mask == ' - 'aparc+aseg.mgz`` unless otherwise specified)') - dof = traits.Enum(6, 9, 12, argstr='--dof %d', - desc='number of transform degrees of freedom') + 'aparc+aseg.mgz`` unless otherwise specified)') + dof = traits.Enum( + 6, + 9, + 12, + argstr='--dof %d', + desc='number of transform degrees of freedom') reference_mask = traits.Either( - False, traits.Str, argstr='--ref-mask %s', position=2, + False, + traits.Str, + argstr='--ref-mask %s', + position=2, desc='mask reference volume with given mask, or None if ``False``') - source_mask = traits.Str(argstr='--mov-mask', - desc='mask source file with given mask') - num_threads = traits.Int(argstr='--threads %d', - desc='number of OpenMP threads') - no_coord_dithering = traits.Bool(argstr='--no-coord-dither', - desc='turn off coordinate dithering') - no_intensity_dithering = traits.Bool(argstr='--no-intensity-dither', - desc='turn off intensity dithering') - sep = traits.List(argstr='--sep %s...', minlen=1, maxlen=2, - desc='set spatial scales, in voxels (default [2, 4])') + source_mask = traits.Str( + argstr='--mov-mask', desc='mask source file with given mask') + num_threads = traits.Int( + argstr='--threads %d', desc='number of OpenMP threads') + no_coord_dithering = traits.Bool( + argstr='--no-coord-dither', desc='turn off coordinate dithering') + no_intensity_dithering = traits.Bool( + argstr='--no-intensity-dither', desc='turn off intensity dithering') + sep = traits.List( + argstr='--sep %s...', + minlen=1, + maxlen=2, + desc='set spatial scales, in voxels (default [2, 4])') initial_translation = traits.Tuple( - traits.Float, traits.Float, traits.Float, argstr='--trans %g %g %g', + traits.Float, + traits.Float, + traits.Float, + argstr='--trans %g %g %g', desc='initial translation in mm (implies no_cras0)') initial_rotation = traits.Tuple( - traits.Float, traits.Float, traits.Float, argstr='--rot %g %g %g', + traits.Float, + traits.Float, + traits.Float, + argstr='--rot %g %g %g', desc='initial rotation in degrees') initial_scale = traits.Tuple( - traits.Float, traits.Float, traits.Float, argstr='--scale %g %g %g', + traits.Float, + traits.Float, + traits.Float, + argstr='--scale %g %g %g', desc='initial scale') initial_shear = traits.Tuple( - traits.Float, traits.Float, traits.Float, argstr='--shear %g %g %g', + traits.Float, + traits.Float, + traits.Float, + argstr='--shear %g %g %g', desc='initial shear (Hxy, Hxz, Hyz)') - no_cras0 = traits.Bool(argstr='--no-cras0', - desc='do not set translation parameters to align ' - 'centers of source and reference files') - max_iters = traits.Range(low=1, argstr='--nitersmax %d', - desc='maximum iterations (default: 4)') - ftol = traits.Float(argstr='--ftol %e', - desc='floating-point tolerance (default=1e-7)') + no_cras0 = traits.Bool( + argstr='--no-cras0', + desc='do not set translation parameters to align ' + 'centers of source and reference files') + max_iters = traits.Range( + low=1, argstr='--nitersmax %d', desc='maximum iterations (default: 4)') + ftol = traits.Float( + argstr='--ftol %e', desc='floating-point tolerance (default=1e-7)') linmintol = traits.Float(argstr='--linmintol %e') saturation_threshold = traits.Range( - low=0.0, high=100.0, argstr='--sat %g', + low=0.0, + high=100.0, + argstr='--sat %g', desc='saturation threshold (default=9.999)') - conform_reference = traits.Bool(argstr='--conf-ref', - desc='conform reference without rescaling') - no_brute_force = traits.Bool(argstr='--no-bf', - desc='do not brute force search') + conform_reference = traits.Bool( + argstr='--conf-ref', desc='conform reference without rescaling') + no_brute_force = traits.Bool( + argstr='--no-bf', desc='do not brute force search') brute_force_limit = traits.Float( - argstr='--bf-lim %g', xor=['no_brute_force'], + argstr='--bf-lim %g', + xor=['no_brute_force'], desc='constrain brute force search to +/- lim') brute_force_samples = traits.Int( - argstr='--bf-nsamp %d', xor=['no_brute_force'], + argstr='--bf-nsamp %d', + xor=['no_brute_force'], desc='number of samples in brute force search') no_smooth = traits.Bool( argstr='--no-smooth', desc='do not apply smoothing to either reference or source file') - ref_fwhm = traits.Float(argstr='--ref-fwhm', - desc='apply smoothing to reference file') + ref_fwhm = traits.Float( + argstr='--ref-fwhm', desc='apply smoothing to reference file') source_oob = traits.Bool( argstr='--mov-oob', desc='count source voxels that are out-of-bounds as 0') diff --git a/nipype/interfaces/freesurfer/tests/test_BBRegister.py b/nipype/interfaces/freesurfer/tests/test_BBRegister.py index 9725065fef..dd022e0db7 100644 --- a/nipype/interfaces/freesurfer/tests/test_BBRegister.py +++ b/nipype/interfaces/freesurfer/tests/test_BBRegister.py @@ -4,53 +4,123 @@ def test_BBRegister_inputs(): input_map_5_3 = dict( - args=dict(argstr='%s',), - contrast_type=dict(argstr='--%s', mandatory=True,), - dof=dict(argstr='--%d',), - environ=dict(nohash=True, usedefault=True,), - epi_mask=dict(argstr='--epi-mask',), - fsldof=dict(argstr='--fsl-dof %d',), - ignore_exception=dict(nohash=True, usedefault=True,), - init=dict(argstr='--init-%s', mandatory=True, xor=['init_reg_file'],), - init_cost_file=dict(argstr='--initcost %s',), - init_reg_file=dict(argstr='--init-reg %s', mandatory=True, xor=['init'],), - intermediate_file=dict(argstr='--int %s',), - out_fsl_file=dict(argstr='--fslmat %s',), - out_lta_file=dict(argstr='--lta %s', min_ver='5.2.0',), - out_reg_file=dict(argstr='--reg %s', genfile=True,), - reg_frame=dict(argstr='--frame %d', xor=['reg_middle_frame'],), - reg_middle_frame=dict(argstr='--mid-frame', xor=['reg_frame'],), - registered_file=dict(argstr='--o %s',), - source_file=dict(argstr='--mov %s', copyfile=False, mandatory=True,), - spm_nifti=dict(argstr='--spm-nii',), - subject_id=dict(argstr='--s %s', mandatory=True,), + args=dict(argstr='%s', ), + contrast_type=dict( + argstr='--%s', + mandatory=True, + ), + dof=dict(argstr='--%d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi_mask=dict(argstr='--epi-mask', ), + fsldof=dict(argstr='--fsl-dof %d', ), + ignore_exception=dict( + nohash=True, + usedefault=True, + ), + init=dict( + argstr='--init-%s', + mandatory=True, + xor=['init_reg_file'], + ), + init_cost_file=dict(argstr='--initcost %s', ), + init_reg_file=dict( + argstr='--init-reg %s', + mandatory=True, + xor=['init'], + ), + intermediate_file=dict(argstr='--int %s', ), + out_fsl_file=dict(argstr='--fslmat %s', ), + out_lta_file=dict( + argstr='--lta %s', + min_ver='5.2.0', + ), + out_reg_file=dict( + argstr='--reg %s', + genfile=True, + ), + reg_frame=dict( + argstr='--frame %d', + xor=['reg_middle_frame'], + ), + reg_middle_frame=dict( + argstr='--mid-frame', + xor=['reg_frame'], + ), + registered_file=dict(argstr='--o %s', ), + source_file=dict( + argstr='--mov %s', + copyfile=False, + mandatory=True, + ), + spm_nifti=dict(argstr='--spm-nii', ), + subject_id=dict( + argstr='--s %s', + mandatory=True, + ), subjects_dir=dict(), - terminal_output=dict(nohash=True,), - ) + terminal_output=dict(nohash=True, ), + ) input_map_6_0 = dict( - args=dict(argstr='%s',), - contrast_type=dict(argstr='--%s', mandatory=True,), - dof=dict(argstr='--%d',), - environ=dict(nohash=True, usedefault=True,), - epi_mask=dict(argstr='--epi-mask',), - fsldof=dict(argstr='--fsl-dof %d',), - ignore_exception=dict(nohash=True, usedefault=True,), - init=dict(argstr='--init-%s', xor=['init_reg_file'],), - init_reg_file=dict(argstr='--init-reg %s', xor=['init'],), - init_cost_file=dict(argstr='--initcost %s',), - intermediate_file=dict(argstr='--int %s',), - out_fsl_file=dict(argstr='--fslmat %s',), - out_lta_file=dict(argstr='--lta %s', min_ver='5.2.0',), - out_reg_file=dict(argstr='--reg %s', genfile=True,), - reg_frame=dict(argstr='--frame %d', xor=['reg_middle_frame'],), - reg_middle_frame=dict(argstr='--mid-frame', xor=['reg_frame'],), - registered_file=dict(argstr='--o %s',), - source_file=dict(argstr='--mov %s', copyfile=False, mandatory=True,), - spm_nifti=dict(argstr='--spm-nii',), - subject_id=dict(argstr='--s %s', mandatory=True,), + args=dict(argstr='%s', ), + contrast_type=dict( + argstr='--%s', + mandatory=True, + ), + dof=dict(argstr='--%d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi_mask=dict(argstr='--epi-mask', ), + fsldof=dict(argstr='--fsl-dof %d', ), + ignore_exception=dict( + nohash=True, + usedefault=True, + ), + init=dict( + argstr='--init-%s', + xor=['init_reg_file'], + ), + init_reg_file=dict( + argstr='--init-reg %s', + xor=['init'], + ), + init_cost_file=dict(argstr='--initcost %s', ), + intermediate_file=dict(argstr='--int %s', ), + out_fsl_file=dict(argstr='--fslmat %s', ), + out_lta_file=dict( + argstr='--lta %s', + min_ver='5.2.0', + ), + out_reg_file=dict( + argstr='--reg %s', + genfile=True, + ), + reg_frame=dict( + argstr='--frame %d', + xor=['reg_middle_frame'], + ), + reg_middle_frame=dict( + argstr='--mid-frame', + xor=['reg_frame'], + ), + registered_file=dict(argstr='--o %s', ), + source_file=dict( + argstr='--mov %s', + copyfile=False, + mandatory=True, + ), + spm_nifti=dict(argstr='--spm-nii', ), + subject_id=dict( + argstr='--s %s', + mandatory=True, + ), subjects_dir=dict(), - terminal_output=dict(nohash=True,), - ) + terminal_output=dict(nohash=True, ), + ) instance = BBRegister() if isinstance(instance.inputs, BBRegisterInputSpec6): @@ -64,13 +134,14 @@ def test_BBRegister_inputs(): def test_BBRegister_outputs(): - output_map = dict(init_cost_file=dict(), - min_cost_file=dict(), - out_fsl_file=dict(), - out_lta_file=dict(), - out_reg_file=dict(), - registered_file=dict(), - ) + output_map = dict( + init_cost_file=dict(), + min_cost_file=dict(), + out_fsl_file=dict(), + out_lta_file=dict(), + out_reg_file=dict(), + registered_file=dict(), + ) outputs = BBRegister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py b/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py index 70701e5f57..529acd6632 100644 --- a/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py +++ b/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py @@ -1,4 +1,3 @@ -# AUTO-GENERATED by tools/checkspecs.py on 2017.04.21 # Modified 2017.04.21 by Chris Markiewicz from __future__ import unicode_literals import pytest @@ -9,17 +8,12 @@ def test_FSSurfaceCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(nohash=True, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(nohash=True, - ), + input_map = dict( + args=dict(argstr='%s'), + environ=dict(nohash=True, usedefault=True), + ignore_exception=dict(nohash=True, usedefault=True), + subjects_dir=dict(), + terminal_output=dict(nohash=True), ) inputs = FSSurfaceCommand.input_spec() @@ -30,16 +24,15 @@ def test_FSSurfaceCommand_inputs(): @pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") def test_associated_file(tmpdir): - fssrc = FreeSurferSource(subjects_dir=fs.Info.subjectsdir(), - subject_id='fsaverage', hemi='lh') + fssrc = FreeSurferSource( + subjects_dir=fs.Info.subjectsdir(), subject_id='fsaverage', hemi='lh') fssrc.base_dir = tmpdir.strpath fssrc.resource_monitor = False fsavginfo = fssrc.run().outputs.get() # Pairs of white/pial files in the same directories - for white, pial in [('lh.white', 'lh.pial'), - ('./lh.white', './lh.pial'), + for white, pial in [('lh.white', 'lh.pial'), ('./lh.white', './lh.pial'), (fsavginfo['white'], fsavginfo['pial'])]: # Unspecified paths, possibly with missing hemisphere information, diff --git a/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py b/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py index c2d0989c6f..b966a32c4f 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py @@ -4,46 +4,47 @@ def test_AddXFormToHeader_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - copy_name=dict(argstr='-c', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - position=-1, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='%s', - mandatory=True, - position=-3, - ), - verbose=dict(argstr='-v', - ), + input_map = dict( + args=dict(argstr='%s', ), + copy_name=dict(argstr='-c', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + position=-1, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + verbose=dict(argstr='-v', ), ) inputs = AddXFormToHeader.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AddXFormToHeader_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = AddXFormToHeader.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py b/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py index 140efd6227..4c285b4cf4 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py @@ -4,72 +4,57 @@ def test_Aparc2Aseg_inputs(): - input_map = dict(a2009s=dict(argstr='--a2009s', - ), - args=dict(argstr='%s', - ), - aseg=dict(argstr='--aseg %s', - ), - copy_inputs=dict(), - ctxseg=dict(argstr='--ctxseg %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - filled=dict(), - hypo_wm=dict(argstr='--hypo-as-wm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - label_wm=dict(argstr='--labelwm', - ), - lh_annotation=dict(mandatory=True, - ), - lh_pial=dict(mandatory=True, - ), - lh_ribbon=dict(mandatory=True, - ), - lh_white=dict(mandatory=True, - ), - out_file=dict(argstr='--o %s', - mandatory=True, - ), - rh_annotation=dict(mandatory=True, - ), - rh_pial=dict(mandatory=True, - ), - rh_ribbon=dict(mandatory=True, - ), - rh_white=dict(mandatory=True, - ), - ribbon=dict(mandatory=True, - ), - rip_unknown=dict(argstr='--rip-unknown', - ), - subject_id=dict(argstr='--s %s', - mandatory=True, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - volmask=dict(argstr='--volmask', - ), + input_map = dict( + a2009s=dict(argstr='--a2009s', ), + args=dict(argstr='%s', ), + aseg=dict(argstr='--aseg %s', ), + copy_inputs=dict(), + ctxseg=dict(argstr='--ctxseg %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + filled=dict(), + hypo_wm=dict(argstr='--hypo-as-wm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + label_wm=dict(argstr='--labelwm', ), + lh_annotation=dict(mandatory=True, ), + lh_pial=dict(mandatory=True, ), + lh_ribbon=dict(mandatory=True, ), + lh_white=dict(mandatory=True, ), + out_file=dict( + argstr='--o %s', + mandatory=True, + ), + rh_annotation=dict(mandatory=True, ), + rh_pial=dict(mandatory=True, ), + rh_ribbon=dict(mandatory=True, ), + rh_white=dict(mandatory=True, ), + ribbon=dict(mandatory=True, ), + rip_unknown=dict(argstr='--rip-unknown', ), + subject_id=dict( + argstr='--s %s', + mandatory=True, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + volmask=dict(argstr='--volmask', ), ) inputs = Aparc2Aseg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Aparc2Aseg_outputs(): - output_map = dict(out_file=dict(argstr='%s', - ), - ) + output_map = dict(out_file=dict(argstr='%s', ), ) outputs = Aparc2Aseg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py b/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py index 3ee51e0398..ecbac701b6 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py @@ -4,37 +4,38 @@ def test_Apas2Aseg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--i %s', - mandatory=True, - ), - out_file=dict(argstr='--o %s', - mandatory=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--i %s', + mandatory=True, + ), + out_file=dict( + argstr='--o %s', + mandatory=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Apas2Aseg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Apas2Aseg_outputs(): - output_map = dict(out_file=dict(argstr='%s', - ), - ) + output_map = dict(out_file=dict(argstr='%s', ), ) outputs = Apas2Aseg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py b/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py index cd10358bcf..52043c3828 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py @@ -4,61 +4,56 @@ def test_ApplyMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - invert_xfm=dict(argstr='-invert', - ), - keep_mask_deletion_edits=dict(argstr='-keep_mask_deletion_edits', - ), - mask_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - mask_thresh=dict(argstr='-T %.4f', - ), - out_file=dict(argstr='%s', - hash_files=True, - keep_extension=True, - name_source=['in_file'], - name_template='%s_masked', - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transfer=dict(argstr='-transfer %d', - ), - use_abs=dict(argstr='-abs', - ), - xfm_file=dict(argstr='-xform %s', - ), - xfm_source=dict(argstr='-lta_src %s', - ), - xfm_target=dict(argstr='-lta_dst %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + invert_xfm=dict(argstr='-invert', ), + keep_mask_deletion_edits=dict(argstr='-keep_mask_deletion_edits', ), + mask_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + mask_thresh=dict(argstr='-T %.4f', ), + out_file=dict( + argstr='%s', + hash_files=True, + keep_extension=True, + name_source=['in_file'], + name_template='%s_masked', + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transfer=dict(argstr='-transfer %d', ), + use_abs=dict(argstr='-abs', ), + xfm_file=dict(argstr='-xform %s', ), + xfm_source=dict(argstr='-lta_src %s', ), + xfm_target=dict(argstr='-lta_dst %s', ), ) inputs = ApplyMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyMask_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ApplyMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py b/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py index a96bf413f5..9752161454 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py @@ -4,98 +4,116 @@ def test_ApplyVolTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fs_target=dict(argstr='--fstarg', - mandatory=True, - requires=['reg_file'], - xor=('target_file', 'tal', 'fs_target'), - ), - fsl_reg_file=dict(argstr='--fsl %s', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interp=dict(argstr='--interp %s', - ), - inverse=dict(argstr='--inv', - ), - invert_morph=dict(argstr='--inv-morph', - requires=['m3z_file'], - ), - lta_file=dict(argstr='--lta %s', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), - lta_inv_file=dict(argstr='--lta-inv %s', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), - m3z_file=dict(argstr='--m3z %s', - ), - mni_152_reg=dict(argstr='--regheader', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), - no_ded_m3z_path=dict(argstr='--noDefM3zPath', - requires=['m3z_file'], - ), - no_resample=dict(argstr='--no-resample', - ), - reg_file=dict(argstr='--reg %s', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), - reg_header=dict(argstr='--regheader', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), - source_file=dict(argstr='--mov %s', - copyfile=False, - mandatory=True, - ), - subject=dict(argstr='--s %s', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), - subjects_dir=dict(), - tal=dict(argstr='--tal', - mandatory=True, - xor=('target_file', 'tal', 'fs_target'), - ), - tal_resolution=dict(argstr='--talres %.10f', - ), - target_file=dict(argstr='--targ %s', - mandatory=True, - xor=('target_file', 'tal', 'fs_target'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformed_file=dict(argstr='--o %s', - genfile=True, - ), - xfm_reg_file=dict(argstr='--xfm %s', - mandatory=True, - xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fs_target=dict( + argstr='--fstarg', + mandatory=True, + requires=['reg_file'], + xor=('target_file', 'tal', 'fs_target'), + ), + fsl_reg_file=dict( + argstr='--fsl %s', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interp=dict(argstr='--interp %s', ), + inverse=dict(argstr='--inv', ), + invert_morph=dict( + argstr='--inv-morph', + requires=['m3z_file'], + ), + lta_file=dict( + argstr='--lta %s', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), + lta_inv_file=dict( + argstr='--lta-inv %s', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), + m3z_file=dict(argstr='--m3z %s', ), + mni_152_reg=dict( + argstr='--regheader', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), + no_ded_m3z_path=dict( + argstr='--noDefM3zPath', + requires=['m3z_file'], + ), + no_resample=dict(argstr='--no-resample', ), + reg_file=dict( + argstr='--reg %s', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), + reg_header=dict( + argstr='--regheader', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), + source_file=dict( + argstr='--mov %s', + copyfile=False, + mandatory=True, + ), + subject=dict( + argstr='--s %s', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), + subjects_dir=dict(), + tal=dict( + argstr='--tal', + mandatory=True, + xor=('target_file', 'tal', 'fs_target'), + ), + tal_resolution=dict(argstr='--talres %.10f', ), + target_file=dict( + argstr='--targ %s', + mandatory=True, + xor=('target_file', 'tal', 'fs_target'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformed_file=dict( + argstr='--o %s', + genfile=True, + ), + xfm_reg_file=dict( + argstr='--xfm %s', + mandatory=True, + xor=('reg_file', 'lta_file', 'lta_inv_file', 'fsl_reg_file', + 'xfm_reg_file', 'reg_header', 'mni_152_reg', 'subject'), + ), ) inputs = ApplyVolTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyVolTransform_outputs(): - output_map = dict(transformed_file=dict(), - ) + output_map = dict(transformed_file=dict(), ) outputs = ApplyVolTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py b/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py index f0f1d8ba9d..adac7e5ad8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py @@ -4,88 +4,74 @@ def test_Binarize_inputs(): - input_map = dict(abs=dict(argstr='--abs', - ), - args=dict(argstr='%s', - ), - bin_col_num=dict(argstr='--bincol', - ), - bin_val=dict(argstr='--binval %d', - ), - bin_val_not=dict(argstr='--binvalnot %d', - ), - binary_file=dict(argstr='--o %s', - genfile=True, - ), - count_file=dict(argstr='--count %s', - ), - dilate=dict(argstr='--dilate %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - erode=dict(argstr='--erode %d', - ), - erode2d=dict(argstr='--erode2d %d', - ), - frame_no=dict(argstr='--frame %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--i %s', - copyfile=False, - mandatory=True, - ), - invert=dict(argstr='--inv', - ), - mask_file=dict(argstr='--mask maskvol', - ), - mask_thresh=dict(argstr='--mask-thresh %f', - ), - match=dict(argstr='--match %d...', - ), - max=dict(argstr='--max %f', - xor=['wm_ven_csf'], - ), - merge_file=dict(argstr='--merge %s', - ), - min=dict(argstr='--min %f', - xor=['wm_ven_csf'], - ), - out_type=dict(argstr='', - ), - rmax=dict(argstr='--rmax %f', - ), - rmin=dict(argstr='--rmin %f', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - ventricles=dict(argstr='--ventricles', - ), - wm=dict(argstr='--wm', - ), - wm_ven_csf=dict(argstr='--wm+vcsf', - xor=['min', 'max'], - ), - zero_edges=dict(argstr='--zero-edges', - ), - zero_slice_edge=dict(argstr='--zero-slice-edges', - ), + input_map = dict( + abs=dict(argstr='--abs', ), + args=dict(argstr='%s', ), + bin_col_num=dict(argstr='--bincol', ), + bin_val=dict(argstr='--binval %d', ), + bin_val_not=dict(argstr='--binvalnot %d', ), + binary_file=dict( + argstr='--o %s', + genfile=True, + ), + count_file=dict(argstr='--count %s', ), + dilate=dict(argstr='--dilate %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + erode=dict(argstr='--erode %d', ), + erode2d=dict(argstr='--erode2d %d', ), + frame_no=dict(argstr='--frame %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--i %s', + copyfile=False, + mandatory=True, + ), + invert=dict(argstr='--inv', ), + mask_file=dict(argstr='--mask maskvol', ), + mask_thresh=dict(argstr='--mask-thresh %f', ), + match=dict(argstr='--match %d...', ), + max=dict( + argstr='--max %f', + xor=['wm_ven_csf'], + ), + merge_file=dict(argstr='--merge %s', ), + min=dict( + argstr='--min %f', + xor=['wm_ven_csf'], + ), + out_type=dict(argstr='', ), + rmax=dict(argstr='--rmax %f', ), + rmin=dict(argstr='--rmin %f', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + ventricles=dict(argstr='--ventricles', ), + wm=dict(argstr='--wm', ), + wm_ven_csf=dict( + argstr='--wm+vcsf', + xor=['min', 'max'], + ), + zero_edges=dict(argstr='--zero-edges', ), + zero_slice_edge=dict(argstr='--zero-slice-edges', ), ) inputs = Binarize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Binarize_outputs(): - output_map = dict(binary_file=dict(), - count_file=dict(), + output_map = dict( + binary_file=dict(), + count_file=dict(), ) outputs = Binarize.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py b/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py index 00dc73eb06..7ee5f891b9 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py @@ -4,63 +4,59 @@ def test_CALabel_inputs(): - input_map = dict(align=dict(argstr='-align', - ), - args=dict(argstr='%s', - ), - aseg=dict(argstr='-aseg %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-4, - ), - in_vol=dict(argstr='-r %s', - ), - intensities=dict(argstr='-r %s', - ), - label=dict(argstr='-l %s', - ), - no_big_ventricles=dict(argstr='-nobigventricles', - ), - num_threads=dict(), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - prior=dict(argstr='-prior %.1f', - ), - relabel_unlikely=dict(argstr='-relabel_unlikely %d %.1f', - ), - subjects_dir=dict(), - template=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='%s', - mandatory=True, - position=-3, - ), + input_map = dict( + align=dict(argstr='-align', ), + args=dict(argstr='%s', ), + aseg=dict(argstr='-aseg %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + in_vol=dict(argstr='-r %s', ), + intensities=dict(argstr='-r %s', ), + label=dict(argstr='-l %s', ), + no_big_ventricles=dict(argstr='-nobigventricles', ), + num_threads=dict(), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + prior=dict(argstr='-prior %.1f', ), + relabel_unlikely=dict(argstr='-relabel_unlikely %d %.1f', ), + subjects_dir=dict(), + template=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict( + argstr='%s', + mandatory=True, + position=-3, + ), ) inputs = CALabel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CALabel_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = CALabel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py b/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py index bf4bdd612a..cefb659df0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py @@ -4,55 +4,58 @@ def test_CANormalize_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - atlas=dict(argstr='%s', - mandatory=True, - position=-3, - ), - control_points=dict(argstr='-c %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-4, - ), - long_file=dict(argstr='-long %s', - ), - mask=dict(argstr='-mask %s', - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s_norm', - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='%s', - mandatory=True, - position=-2, - ), + input_map = dict( + args=dict(argstr='%s', ), + atlas=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + control_points=dict(argstr='-c %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + long_file=dict(argstr='-long %s', ), + mask=dict(argstr='-mask %s', ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s_norm', + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict( + argstr='%s', + mandatory=True, + position=-2, + ), ) inputs = CANormalize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CANormalize_outputs(): - output_map = dict(control_points=dict(), - out_file=dict(), + output_map = dict( + control_points=dict(), + out_file=dict(), ) outputs = CANormalize.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py b/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py index d50d9d8e6b..94a87ced9a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py @@ -4,59 +4,56 @@ def test_CARegister_inputs(): - input_map = dict(A=dict(argstr='-A %d', - ), - align=dict(argstr='-align-%s', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - invert_and_save=dict(argstr='-invert-and-save', - position=-4, - ), - l_files=dict(argstr='-l %s', - ), - levels=dict(argstr='-levels %d', - ), - mask=dict(argstr='-mask %s', - ), - no_big_ventricles=dict(argstr='-nobigventricles', - ), - num_threads=dict(), - out_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - subjects_dir=dict(), - template=dict(argstr='%s', - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='-T %s', - ), + input_map = dict( + A=dict(argstr='-A %d', ), + align=dict(argstr='-align-%s', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + invert_and_save=dict( + argstr='-invert-and-save', + position=-4, + ), + l_files=dict(argstr='-l %s', ), + levels=dict(argstr='-levels %d', ), + mask=dict(argstr='-mask %s', ), + no_big_ventricles=dict(argstr='-nobigventricles', ), + num_threads=dict(), + out_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + subjects_dir=dict(), + template=dict( + argstr='%s', + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict(argstr='-T %s', ), ) inputs = CARegister.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CARegister_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = CARegister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py b/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py index d59e369b33..2fe3e13da7 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py @@ -4,42 +4,43 @@ def test_CheckTalairachAlignment_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-xfm %s', - mandatory=True, - position=-1, - xor=['subject'], - ), - subject=dict(argstr='-subj %s', - mandatory=True, - position=-1, - xor=['in_file'], - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='-T %.3f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-xfm %s', + mandatory=True, + position=-1, + xor=['subject'], + ), + subject=dict( + argstr='-subj %s', + mandatory=True, + position=-1, + xor=['in_file'], + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='-T %.3f', ), ) inputs = CheckTalairachAlignment.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CheckTalairachAlignment_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = CheckTalairachAlignment.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py b/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py index ea3dc4b1bb..efa08400f3 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py @@ -4,66 +4,53 @@ def test_Concatenate_inputs(): - input_map = dict(add_val=dict(argstr='--add %f', - ), - args=dict(argstr='%s', - ), - combine=dict(argstr='--combine', - ), - concatenated_file=dict(argstr='--o %s', - genfile=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - gmean=dict(argstr='--gmean %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='--i %s...', - mandatory=True, - ), - keep_dtype=dict(argstr='--keep-datatype', - ), - mask_file=dict(argstr='--mask %s', - ), - max_bonfcor=dict(argstr='--max-bonfcor', - ), - max_index=dict(argstr='--max-index', - ), - mean_div_n=dict(argstr='--mean-div-n', - ), - multiply_by=dict(argstr='--mul %f', - ), - multiply_matrix_file=dict(argstr='--mtx %s', - ), - paired_stats=dict(argstr='--paired-%s', - ), - sign=dict(argstr='--%s', - ), - sort=dict(argstr='--sort', - ), - stats=dict(argstr='--%s', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vote=dict(argstr='--vote', - ), + input_map = dict( + add_val=dict(argstr='--add %f', ), + args=dict(argstr='%s', ), + combine=dict(argstr='--combine', ), + concatenated_file=dict( + argstr='--o %s', + genfile=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gmean=dict(argstr='--gmean %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='--i %s...', + mandatory=True, + ), + keep_dtype=dict(argstr='--keep-datatype', ), + mask_file=dict(argstr='--mask %s', ), + max_bonfcor=dict(argstr='--max-bonfcor', ), + max_index=dict(argstr='--max-index', ), + mean_div_n=dict(argstr='--mean-div-n', ), + multiply_by=dict(argstr='--mul %f', ), + multiply_matrix_file=dict(argstr='--mtx %s', ), + paired_stats=dict(argstr='--paired-%s', ), + sign=dict(argstr='--%s', ), + sort=dict(argstr='--sort', ), + stats=dict(argstr='--%s', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vote=dict(argstr='--vote', ), ) inputs = Concatenate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Concatenate_outputs(): - output_map = dict(concatenated_file=dict(), - ) + output_map = dict(concatenated_file=dict(), ) outputs = Concatenate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py b/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py index 8dd0b1cb9e..60472d7876 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py @@ -4,63 +4,63 @@ def test_ConcatenateLTA_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_lta1=dict(argstr='%s', - mandatory=True, - position=-3, - ), - in_lta2=dict(argstr='%s', - mandatory=True, - position=-2, - ), - invert_1=dict(argstr='-invert1', - ), - invert_2=dict(argstr='-invert2', - ), - invert_out=dict(argstr='-invertout', - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=True, - name_source=['in_lta1'], - name_template='%s_concat', - position=-1, - ), - out_type=dict(argstr='-out_type %d', - ), - subject=dict(argstr='-subject %s', - ), - subjects_dir=dict(), - tal_source_file=dict(argstr='-tal %s', - position=-5, - requires=['tal_template_file'], - ), - tal_template_file=dict(argstr='%s', - position=-4, - requires=['tal_source_file'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_lta1=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + in_lta2=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + invert_1=dict(argstr='-invert1', ), + invert_2=dict(argstr='-invert2', ), + invert_out=dict(argstr='-invertout', ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=True, + name_source=['in_lta1'], + name_template='%s_concat', + position=-1, + ), + out_type=dict(argstr='-out_type %d', ), + subject=dict(argstr='-subject %s', ), + subjects_dir=dict(), + tal_source_file=dict( + argstr='-tal %s', + position=-5, + requires=['tal_template_file'], + ), + tal_template_file=dict( + argstr='%s', + position=-4, + requires=['tal_source_file'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ConcatenateLTA.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ConcatenateLTA_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ConcatenateLTA.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py b/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py index 1cdec290b2..e87bbf5f0f 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py @@ -4,51 +4,49 @@ def test_Contrast_inputs(): - input_map = dict(annotation=dict(mandatory=True, - ), - args=dict(argstr='%s', - ), - copy_inputs=dict(), - cortex=dict(mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - hemisphere=dict(argstr='--%s-only', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - orig=dict(mandatory=True, - ), - rawavg=dict(mandatory=True, - ), - subject_id=dict(argstr='--s %s', - mandatory=True, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thickness=dict(mandatory=True, - ), - white=dict(mandatory=True, - ), + input_map = dict( + annotation=dict(mandatory=True, ), + args=dict(argstr='%s', ), + copy_inputs=dict(), + cortex=dict(mandatory=True, ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr='--%s-only', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + orig=dict(mandatory=True, ), + rawavg=dict(mandatory=True, ), + subject_id=dict( + argstr='--s %s', + mandatory=True, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thickness=dict(mandatory=True, ), + white=dict(mandatory=True, ), ) inputs = Contrast.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Contrast_outputs(): - output_map = dict(out_contrast=dict(), - out_log=dict(), - out_stats=dict(), + output_map = dict( + out_contrast=dict(), + out_log=dict(), + out_stats=dict(), ) outputs = Contrast.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py b/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py index 3c6d0d91a3..3d1c3d0afe 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py @@ -4,46 +4,44 @@ def test_Curvature_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - averages=dict(argstr='-a %d', - ), - copy_input=dict(), - distances=dict(argstr='-distances %d %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-2, - ), - n=dict(argstr='-n', - ), - save=dict(argstr='-w', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='-thresh %.3f', - ), + input_map = dict( + args=dict(argstr='%s', ), + averages=dict(argstr='-a %d', ), + copy_input=dict(), + distances=dict(argstr='-distances %d %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-2, + ), + n=dict(argstr='-n', ), + save=dict(argstr='-w', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='-thresh %.3f', ), ) inputs = Curvature.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Curvature_outputs(): - output_map = dict(out_gauss=dict(), - out_mean=dict(), + output_map = dict( + out_gauss=dict(), + out_mean=dict(), ) outputs = Curvature.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py b/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py index 06385fc361..b3d27043e9 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py @@ -4,61 +4,62 @@ def test_CurvatureStats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - copy_inputs=dict(), - curvfile1=dict(argstr='%s', - mandatory=True, - position=-2, - ), - curvfile2=dict(argstr='%s', - mandatory=True, - position=-1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - hemisphere=dict(argstr='%s', - mandatory=True, - position=-3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - min_max=dict(argstr='-m', - ), - out_file=dict(argstr='-o %s', - hash_files=False, - name_source=['hemisphere'], - name_template='%s.curv.stats', - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=-4, - usedefault=True, - ), - subjects_dir=dict(), - surface=dict(argstr='-F %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - values=dict(argstr='-G', - ), - write=dict(argstr='--writeCurvatureFiles', - ), + input_map = dict( + args=dict(argstr='%s', ), + copy_inputs=dict(), + curvfile1=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + curvfile2=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + min_max=dict(argstr='-m', ), + out_file=dict( + argstr='-o %s', + hash_files=False, + name_source=['hemisphere'], + name_template='%s.curv.stats', + ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=-4, + usedefault=True, + ), + subjects_dir=dict(), + surface=dict(argstr='-F %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + values=dict(argstr='-G', ), + write=dict(argstr='--writeCurvatureFiles', ), ) inputs = CurvatureStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CurvatureStats_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = CurvatureStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py index f517b74200..f49611b9ce 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py @@ -4,38 +4,34 @@ def test_DICOMConvert_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - base_output_dir=dict(mandatory=True, - ), - dicom_dir=dict(mandatory=True, - ), - dicom_info=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - file_mapping=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_single_slice=dict(requires=['dicom_info'], - ), - out_type=dict(usedefault=True, - ), - seq_list=dict(requires=['dicom_info'], - ), - subject_dir_template=dict(usedefault=True, - ), - subject_id=dict(), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + base_output_dir=dict(mandatory=True, ), + dicom_dir=dict(mandatory=True, ), + dicom_info=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + file_mapping=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_single_slice=dict(requires=['dicom_info'], ), + out_type=dict(usedefault=True, ), + seq_list=dict(requires=['dicom_info'], ), + subject_dir_template=dict(usedefault=True, ), + subject_id=dict(), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DICOMConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py b/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py index f0aa686853..fb05a8319d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py @@ -4,54 +4,53 @@ def test_EMRegister_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - mask=dict(argstr='-mask %s', - ), - nbrspacing=dict(argstr='-uns %d', - ), - num_threads=dict(), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=False, - name_source=['in_file'], - name_template='%s_transform.lta', - position=-1, - ), - skull=dict(argstr='-skull', - ), - subjects_dir=dict(), - template=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='-t %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + mask=dict(argstr='-mask %s', ), + nbrspacing=dict(argstr='-uns %d', ), + num_threads=dict(), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=False, + name_source=['in_file'], + name_template='%s_transform.lta', + position=-1, + ), + skull=dict(argstr='-skull', ), + subjects_dir=dict(), + template=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict(argstr='-t %s', ), ) inputs = EMRegister.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EMRegister_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = EMRegister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py b/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py index aa23199671..d641b82923 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py @@ -4,48 +4,51 @@ def test_EditWMwithAseg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - brain_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-4, - ), - keep_in=dict(argstr='-keep-in', - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - seg_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + brain_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + keep_in=dict(argstr='-keep-in', ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + seg_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = EditWMwithAseg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EditWMwithAseg_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = EditWMwithAseg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py b/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py index 910e415852..08ba898ba2 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py @@ -4,34 +4,35 @@ def test_EulerNumber_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = EulerNumber.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EulerNumber_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = EulerNumber.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py b/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py index 439378afe4..ae84d516d1 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py @@ -4,38 +4,40 @@ def test_ExtractMainComponent_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - out_file=dict(argstr='%s', - name_source='in_file', - name_template='%s.maincmp', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + out_file=dict( + argstr='%s', + name_source='in_file', + name_template='%s.maincmp', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ExtractMainComponent.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ExtractMainComponent_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ExtractMainComponent.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py b/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py index bd9d6e0e0f..8f7c7db082 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py @@ -4,23 +4,25 @@ def test_FSCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FSCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py b/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py index d9a7a8c6f6..93e59f9a12 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py @@ -4,24 +4,26 @@ def test_FSCommandOpenMP_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_threads=dict(), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_threads=dict(), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FSCommandOpenMP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py b/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py index 6bbb0ed0d7..f2c4605c86 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py @@ -4,23 +4,25 @@ def test_FSScriptCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FSScriptCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py b/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py index 22280e25a9..299cbd5023 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py @@ -4,43 +4,47 @@ def test_FitMSParams_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - flip_list=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_dir=dict(argstr='%s', - genfile=True, - position=-1, - ), - subjects_dir=dict(), - te_list=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tr_list=dict(), - xfm_list=dict(), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip_list=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_dir=dict( + argstr='%s', + genfile=True, + position=-1, + ), + subjects_dir=dict(), + te_list=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tr_list=dict(), + xfm_list=dict(), ) inputs = FitMSParams.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FitMSParams_outputs(): - output_map = dict(pd_image=dict(), - t1_image=dict(), - t2star_image=dict(), + output_map = dict( + pd_image=dict(), + t1_image=dict(), + t2star_image=dict(), ) outputs = FitMSParams.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py b/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py index 2176d18d54..7a0f0b80ed 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py @@ -4,57 +4,50 @@ def test_FixTopology_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - copy_inputs=dict(mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ga=dict(argstr='-ga', - ), - hemisphere=dict(argstr='%s', - mandatory=True, - position=-1, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_brain=dict(mandatory=True, - ), - in_inflated=dict(mandatory=True, - ), - in_orig=dict(mandatory=True, - ), - in_wm=dict(mandatory=True, - ), - mgz=dict(argstr='-mgz', - ), - seed=dict(argstr='-seed %d', - ), - sphere=dict(argstr='-sphere %s', - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=-2, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + copy_inputs=dict(mandatory=True, ), + environ=dict( + nohash=True, + usedefault=True, + ), + ga=dict(argstr='-ga', ), + hemisphere=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_brain=dict(mandatory=True, ), + in_inflated=dict(mandatory=True, ), + in_orig=dict(mandatory=True, ), + in_wm=dict(mandatory=True, ), + mgz=dict(argstr='-mgz', ), + seed=dict(argstr='-seed %d', ), + sphere=dict(argstr='-sphere %s', ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=-2, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FixTopology.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FixTopology_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = FixTopology.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py b/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py index f2d4e53fa6..909490bbfc 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py @@ -4,49 +4,55 @@ def test_FuseSegmentations_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_norms=dict(argstr='-n %s', - mandatory=True, - ), - in_segmentations=dict(argstr='-a %s', - mandatory=True, - ), - in_segmentations_noCC=dict(argstr='-c %s', - mandatory=True, - ), - out_file=dict(mandatory=True, - position=-1, - ), - subject_id=dict(argstr='%s', - position=-3, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timepoints=dict(argstr='%s', - mandatory=True, - position=-2, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_norms=dict( + argstr='-n %s', + mandatory=True, + ), + in_segmentations=dict( + argstr='-a %s', + mandatory=True, + ), + in_segmentations_noCC=dict( + argstr='-c %s', + mandatory=True, + ), + out_file=dict( + mandatory=True, + position=-1, + ), + subject_id=dict( + argstr='%s', + position=-3, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timepoints=dict( + argstr='%s', + mandatory=True, + position=-2, + ), ) inputs = FuseSegmentations.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FuseSegmentations_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = FuseSegmentations.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py b/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py index 7b81fee22b..b310eded87 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py @@ -4,166 +4,147 @@ def test_GLMFit_inputs(): - input_map = dict(allow_ill_cond=dict(argstr='--illcond', - ), - allow_repeated_subjects=dict(argstr='--allowsubjrep', - ), - args=dict(argstr='%s', - ), - calc_AR1=dict(argstr='--tar1', - ), - check_opts=dict(argstr='--checkopts', - ), - compute_log_y=dict(argstr='--logy', - ), - contrast=dict(argstr='--C %s...', - ), - cortex=dict(argstr='--cortex', - xor=['label_file'], - ), - debug=dict(argstr='--debug', - ), - design=dict(argstr='--X %s', - xor=('fsgd', 'design', 'one_sample'), - ), - diag=dict(), - diag_cluster=dict(argstr='--diag-cluster', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_fx_dof=dict(argstr='--ffxdof %d', - xor=['fixed_fx_dof_file'], - ), - fixed_fx_dof_file=dict(argstr='--ffxdofdat %d', - xor=['fixed_fx_dof'], - ), - fixed_fx_var=dict(argstr='--yffxvar %s', - ), - force_perm=dict(argstr='--perm-force', - ), - fsgd=dict(argstr='--fsgd %s %s', - xor=('fsgd', 'design', 'one_sample'), - ), - fwhm=dict(argstr='--fwhm %f', - ), - glm_dir=dict(argstr='--glmdir %s', - genfile=True, - ), - hemi=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--y %s', - copyfile=False, - mandatory=True, - ), - invert_mask=dict(argstr='--mask-inv', - ), - label_file=dict(argstr='--label %s', - xor=['cortex'], - ), - mask_file=dict(argstr='--mask %s', - ), - no_contrast_ok=dict(argstr='--no-contrasts-ok', - ), - no_est_fwhm=dict(argstr='--no-est-fwhm', - ), - no_mask_smooth=dict(argstr='--no-mask-smooth', - ), - no_prune=dict(argstr='--no-prune', - xor=['prunethresh'], - ), - one_sample=dict(argstr='--osgm', - xor=('one_sample', 'fsgd', 'design', 'contrast'), - ), - pca=dict(argstr='--pca', - ), - per_voxel_reg=dict(argstr='--pvr %s...', - ), - profile=dict(argstr='--profile %d', - ), - prune=dict(argstr='--prune', - ), - prune_thresh=dict(argstr='--prune_thr %f', - xor=['noprune'], - ), - resynth_test=dict(argstr='--resynthtest %d', - ), - save_cond=dict(argstr='--save-cond', - ), - save_estimate=dict(argstr='--yhat-save', - ), - save_res_corr_mtx=dict(argstr='--eres-scm', - ), - save_residual=dict(argstr='--eres-save', - ), - seed=dict(argstr='--seed %d', - ), - self_reg=dict(argstr='--selfreg %d %d %d', - ), - sim_done_file=dict(argstr='--sim-done %s', - ), - sim_sign=dict(argstr='--sim-sign %s', - ), - simulation=dict(argstr='--sim %s %d %f %s', - ), - subject_id=dict(), - subjects_dir=dict(), - surf=dict(argstr='--surf %s %s %s', - requires=['subject_id', 'hemi'], - ), - surf_geo=dict(usedefault=True, - ), - synth=dict(argstr='--synth', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uniform=dict(argstr='--uniform %f %f', - ), - var_fwhm=dict(argstr='--var-fwhm %f', - ), - vox_dump=dict(argstr='--voxdump %d %d %d', - ), - weight_file=dict(xor=['weighted_ls'], - ), - weight_inv=dict(argstr='--w-inv', - xor=['weighted_ls'], - ), - weight_sqrt=dict(argstr='--w-sqrt', - xor=['weighted_ls'], - ), - weighted_ls=dict(argstr='--wls %s', - xor=('weight_file', 'weight_inv', 'weight_sqrt'), - ), + input_map = dict( + allow_ill_cond=dict(argstr='--illcond', ), + allow_repeated_subjects=dict(argstr='--allowsubjrep', ), + args=dict(argstr='%s', ), + calc_AR1=dict(argstr='--tar1', ), + check_opts=dict(argstr='--checkopts', ), + compute_log_y=dict(argstr='--logy', ), + contrast=dict(argstr='--C %s...', ), + cortex=dict( + argstr='--cortex', + xor=['label_file'], + ), + debug=dict(argstr='--debug', ), + design=dict( + argstr='--X %s', + xor=('fsgd', 'design', 'one_sample'), + ), + diag=dict(), + diag_cluster=dict(argstr='--diag-cluster', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_fx_dof=dict( + argstr='--ffxdof %d', + xor=['fixed_fx_dof_file'], + ), + fixed_fx_dof_file=dict( + argstr='--ffxdofdat %d', + xor=['fixed_fx_dof'], + ), + fixed_fx_var=dict(argstr='--yffxvar %s', ), + force_perm=dict(argstr='--perm-force', ), + fsgd=dict( + argstr='--fsgd %s %s', + xor=('fsgd', 'design', 'one_sample'), + ), + fwhm=dict(argstr='--fwhm %f', ), + glm_dir=dict( + argstr='--glmdir %s', + genfile=True, + ), + hemi=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--y %s', + copyfile=False, + mandatory=True, + ), + invert_mask=dict(argstr='--mask-inv', ), + label_file=dict( + argstr='--label %s', + xor=['cortex'], + ), + mask_file=dict(argstr='--mask %s', ), + no_contrast_ok=dict(argstr='--no-contrasts-ok', ), + no_est_fwhm=dict(argstr='--no-est-fwhm', ), + no_mask_smooth=dict(argstr='--no-mask-smooth', ), + no_prune=dict( + argstr='--no-prune', + xor=['prunethresh'], + ), + one_sample=dict( + argstr='--osgm', + xor=('one_sample', 'fsgd', 'design', 'contrast'), + ), + pca=dict(argstr='--pca', ), + per_voxel_reg=dict(argstr='--pvr %s...', ), + profile=dict(argstr='--profile %d', ), + prune=dict(argstr='--prune', ), + prune_thresh=dict( + argstr='--prune_thr %f', + xor=['noprune'], + ), + resynth_test=dict(argstr='--resynthtest %d', ), + save_cond=dict(argstr='--save-cond', ), + save_estimate=dict(argstr='--yhat-save', ), + save_res_corr_mtx=dict(argstr='--eres-scm', ), + save_residual=dict(argstr='--eres-save', ), + seed=dict(argstr='--seed %d', ), + self_reg=dict(argstr='--selfreg %d %d %d', ), + sim_done_file=dict(argstr='--sim-done %s', ), + sim_sign=dict(argstr='--sim-sign %s', ), + simulation=dict(argstr='--sim %s %d %f %s', ), + subject_id=dict(), + subjects_dir=dict(), + surf=dict( + argstr='--surf %s %s %s', + requires=['subject_id', 'hemi'], + ), + surf_geo=dict(usedefault=True, ), + synth=dict(argstr='--synth', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uniform=dict(argstr='--uniform %f %f', ), + var_fwhm=dict(argstr='--var-fwhm %f', ), + vox_dump=dict(argstr='--voxdump %d %d %d', ), + weight_file=dict(xor=['weighted_ls'], ), + weight_inv=dict( + argstr='--w-inv', + xor=['weighted_ls'], + ), + weight_sqrt=dict( + argstr='--w-sqrt', + xor=['weighted_ls'], + ), + weighted_ls=dict( + argstr='--wls %s', + xor=('weight_file', 'weight_inv', 'weight_sqrt'), + ), ) inputs = GLMFit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GLMFit_outputs(): - output_map = dict(beta_file=dict(), - dof_file=dict(), - error_file=dict(), - error_stddev_file=dict(), - error_var_file=dict(), - estimate_file=dict(), - frame_eigenvectors=dict(), - ftest_file=dict(), - fwhm_file=dict(), - gamma_file=dict(), - gamma_var_file=dict(), - glm_dir=dict(), - mask_file=dict(), - sig_file=dict(), - singular_values=dict(), - spatial_eigenvectors=dict(), - svd_stats_file=dict(), + output_map = dict( + beta_file=dict(), + dof_file=dict(), + error_file=dict(), + error_stddev_file=dict(), + error_var_file=dict(), + estimate_file=dict(), + frame_eigenvectors=dict(), + ftest_file=dict(), + fwhm_file=dict(), + gamma_file=dict(), + gamma_var_file=dict(), + glm_dir=dict(), + mask_file=dict(), + sig_file=dict(), + singular_values=dict(), + spatial_eigenvectors=dict(), + svd_stats_file=dict(), ) outputs = GLMFit.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py b/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py index f49055a47e..38c22ec2c9 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py @@ -4,42 +4,45 @@ def test_ImageInfo_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - position=1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + position=1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ImageInfo.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ImageInfo_outputs(): - output_map = dict(TE=dict(), - TI=dict(), - TR=dict(), - data_type=dict(), - dimensions=dict(), - file_format=dict(), - info=dict(), - orientation=dict(), - out_file=dict(), - ph_enc_dir=dict(), - vox_sizes=dict(), + output_map = dict( + TE=dict(), + TI=dict(), + TR=dict(), + data_type=dict(), + dimensions=dict(), + file_format=dict(), + info=dict(), + orientation=dict(), + out_file=dict(), + ph_enc_dir=dict(), + vox_sizes=dict(), ) outputs = ImageInfo.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py b/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py index fe6998874f..a7bc1dfa14 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py @@ -4,45 +4,48 @@ def test_Jacobian_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_mappedsurf=dict(argstr='%s', - mandatory=True, - position=-2, - ), - in_origsurf=dict(argstr='%s', - mandatory=True, - position=-3, - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=False, - name_source=['in_origsurf'], - name_template='%s.jacobian', - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_mappedsurf=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + in_origsurf=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=False, + name_source=['in_origsurf'], + name_template='%s.jacobian', + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Jacobian.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Jacobian_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Jacobian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py index 867e01e00d..13024587b0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py @@ -4,77 +4,83 @@ def test_LTAConvert_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_fsl=dict(argstr='--infsl %s', - mandatory=True, - xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', 'in_itk'), - ), - in_itk=dict(argstr='--initk %s', - mandatory=True, - xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', 'in_itk'), - ), - in_lta=dict(argstr='--inlta %s', - mandatory=True, - xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', 'in_itk'), - ), - in_mni=dict(argstr='--inmni %s', - mandatory=True, - xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', 'in_itk'), - ), - in_niftyreg=dict(argstr='--inniftyreg %s', - mandatory=True, - xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', 'in_itk'), - ), - in_reg=dict(argstr='--inreg %s', - mandatory=True, - xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', 'in_itk'), - ), - invert=dict(argstr='--invert', - ), - ltavox2vox=dict(argstr='--ltavox2vox', - requires=['out_lta'], - ), - out_fsl=dict(argstr='--outfsl %s', - ), - out_itk=dict(argstr='--outitk %s', - ), - out_lta=dict(argstr='--outlta %s', - ), - out_mni=dict(argstr='--outmni %s', - ), - out_reg=dict(argstr='--outreg %s', - ), - source_file=dict(argstr='--src %s', - ), - target_conform=dict(argstr='--trgconform', - ), - target_file=dict(argstr='--trg %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_fsl=dict( + argstr='--infsl %s', + mandatory=True, + xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', + 'in_itk'), + ), + in_itk=dict( + argstr='--initk %s', + mandatory=True, + xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', + 'in_itk'), + ), + in_lta=dict( + argstr='--inlta %s', + mandatory=True, + xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', + 'in_itk'), + ), + in_mni=dict( + argstr='--inmni %s', + mandatory=True, + xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', + 'in_itk'), + ), + in_niftyreg=dict( + argstr='--inniftyreg %s', + mandatory=True, + xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', + 'in_itk'), + ), + in_reg=dict( + argstr='--inreg %s', + mandatory=True, + xor=('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', + 'in_itk'), + ), + invert=dict(argstr='--invert', ), + ltavox2vox=dict( + argstr='--ltavox2vox', + requires=['out_lta'], + ), + out_fsl=dict(argstr='--outfsl %s', ), + out_itk=dict(argstr='--outitk %s', ), + out_lta=dict(argstr='--outlta %s', ), + out_mni=dict(argstr='--outmni %s', ), + out_reg=dict(argstr='--outreg %s', ), + source_file=dict(argstr='--src %s', ), + target_conform=dict(argstr='--trgconform', ), + target_file=dict(argstr='--trg %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = LTAConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LTAConvert_outputs(): - output_map = dict(out_fsl=dict(), - out_itk=dict(), - out_lta=dict(), - out_mni=dict(), - out_reg=dict(), + output_map = dict( + out_fsl=dict(), + out_itk=dict(), + out_lta=dict(), + out_mni=dict(), + out_reg=dict(), ) outputs = LTAConvert.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py b/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py index beece1b6d3..1e94061567 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py @@ -4,52 +4,52 @@ def test_Label2Annot_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - color_table=dict(argstr='--ctab %s', - ), - copy_inputs=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - hemisphere=dict(argstr='--hemi %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_labels=dict(argstr='--l %s...', - mandatory=True, - ), - keep_max=dict(argstr='--maxstatwinner', - ), - orig=dict(mandatory=True, - ), - out_annot=dict(argstr='--a %s', - mandatory=True, - ), - subject_id=dict(argstr='--s %s', - mandatory=True, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose_off=dict(argstr='--noverbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + color_table=dict(argstr='--ctab %s', ), + copy_inputs=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr='--hemi %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_labels=dict( + argstr='--l %s...', + mandatory=True, + ), + keep_max=dict(argstr='--maxstatwinner', ), + orig=dict(mandatory=True, ), + out_annot=dict( + argstr='--a %s', + mandatory=True, + ), + subject_id=dict( + argstr='--s %s', + mandatory=True, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose_off=dict(argstr='--noverbose', ), ) inputs = Label2Annot.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Label2Annot_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Label2Annot.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py b/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py index 55ed8f026c..581a5d8898 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py @@ -4,61 +4,63 @@ def test_Label2Label_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - copy_inputs=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - hemisphere=dict(argstr='--hemi %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_file=dict(argstr='--trglabel %s', - hash_files=False, - keep_extension=True, - name_source=['source_label'], - name_template='%s_converted', - ), - registration_method=dict(argstr='--regmethod %s', - usedefault=True, - ), - source_label=dict(argstr='--srclabel %s', - mandatory=True, - ), - source_sphere_reg=dict(mandatory=True, - ), - source_subject=dict(argstr='--srcsubject %s', - mandatory=True, - ), - source_white=dict(mandatory=True, - ), - sphere_reg=dict(mandatory=True, - ), - subject_id=dict(argstr='--trgsubject %s', - mandatory=True, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - white=dict(mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + copy_inputs=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr='--hemi %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='--trglabel %s', + hash_files=False, + keep_extension=True, + name_source=['source_label'], + name_template='%s_converted', + ), + registration_method=dict( + argstr='--regmethod %s', + usedefault=True, + ), + source_label=dict( + argstr='--srclabel %s', + mandatory=True, + ), + source_sphere_reg=dict(mandatory=True, ), + source_subject=dict( + argstr='--srcsubject %s', + mandatory=True, + ), + source_white=dict(mandatory=True, ), + sphere_reg=dict(mandatory=True, ), + subject_id=dict( + argstr='--trgsubject %s', + mandatory=True, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + white=dict(mandatory=True, ), ) inputs = Label2Label.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Label2Label_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Label2Label.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py b/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py index 25b680036e..971bc20062 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py @@ -4,86 +4,87 @@ def test_Label2Vol_inputs(): - input_map = dict(annot_file=dict(argstr='--annot %s', - copyfile=False, - mandatory=True, - requires=('subject_id', 'hemi'), - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - ), - aparc_aseg=dict(argstr='--aparc+aseg', - mandatory=True, - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fill_thresh=dict(argstr='--fillthresh %.f', - ), - hemi=dict(argstr='--hemi %s', - ), - identity=dict(argstr='--identity', - xor=('reg_file', 'reg_header', 'identity'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - invert_mtx=dict(argstr='--invertmtx', - ), - label_file=dict(argstr='--label %s...', - copyfile=False, - mandatory=True, - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - ), - label_hit_file=dict(argstr='--hits %s', - ), - label_voxel_volume=dict(argstr='--labvoxvol %f', - ), - map_label_stat=dict(argstr='--label-stat %s', - ), - native_vox2ras=dict(argstr='--native-vox2ras', - ), - proj=dict(argstr='--proj %s %f %f %f', - requires=('subject_id', 'hemi'), - ), - reg_file=dict(argstr='--reg %s', - xor=('reg_file', 'reg_header', 'identity'), - ), - reg_header=dict(argstr='--regheader %s', - xor=('reg_file', 'reg_header', 'identity'), - ), - seg_file=dict(argstr='--seg %s', - copyfile=False, - mandatory=True, - xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), - ), - subject_id=dict(argstr='--subject %s', - ), - subjects_dir=dict(), - surface=dict(argstr='--surf %s', - ), - template_file=dict(argstr='--temp %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vol_label_file=dict(argstr='--o %s', - genfile=True, - ), + input_map = dict( + annot_file=dict( + argstr='--annot %s', + copyfile=False, + mandatory=True, + requires=('subject_id', 'hemi'), + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + ), + aparc_aseg=dict( + argstr='--aparc+aseg', + mandatory=True, + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_thresh=dict(argstr='--fillthresh %.f', ), + hemi=dict(argstr='--hemi %s', ), + identity=dict( + argstr='--identity', + xor=('reg_file', 'reg_header', 'identity'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + invert_mtx=dict(argstr='--invertmtx', ), + label_file=dict( + argstr='--label %s...', + copyfile=False, + mandatory=True, + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + ), + label_hit_file=dict(argstr='--hits %s', ), + label_voxel_volume=dict(argstr='--labvoxvol %f', ), + map_label_stat=dict(argstr='--label-stat %s', ), + native_vox2ras=dict(argstr='--native-vox2ras', ), + proj=dict( + argstr='--proj %s %f %f %f', + requires=('subject_id', 'hemi'), + ), + reg_file=dict( + argstr='--reg %s', + xor=('reg_file', 'reg_header', 'identity'), + ), + reg_header=dict( + argstr='--regheader %s', + xor=('reg_file', 'reg_header', 'identity'), + ), + seg_file=dict( + argstr='--seg %s', + copyfile=False, + mandatory=True, + xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'), + ), + subject_id=dict(argstr='--subject %s', ), + subjects_dir=dict(), + surface=dict(argstr='--surf %s', ), + template_file=dict( + argstr='--temp %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vol_label_file=dict( + argstr='--o %s', + genfile=True, + ), ) inputs = Label2Vol.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Label2Vol_outputs(): - output_map = dict(vol_label_file=dict(), - ) + output_map = dict(vol_label_file=dict(), ) outputs = Label2Vol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py b/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py index 1cd0eacc4d..fcbf7c0ffa 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py @@ -4,55 +4,49 @@ def test_MNIBiasCorrection_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - distance=dict(argstr='--distance %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--i %s', - mandatory=True, - ), - iterations=dict(argstr='--n %d', - ), - mask=dict(argstr='--mask %s', - ), - no_rescale=dict(argstr='--no-rescale', - ), - out_file=dict(argstr='--o %s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s_output', - ), - protocol_iterations=dict(argstr='--proto-iters %d', - ), - shrink=dict(argstr='--shrink %d', - ), - stop=dict(argstr='--stop %f', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='--uchar %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + distance=dict(argstr='--distance %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--i %s', + mandatory=True, + ), + iterations=dict(argstr='--n %d', ), + mask=dict(argstr='--mask %s', ), + no_rescale=dict(argstr='--no-rescale', ), + out_file=dict( + argstr='--o %s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s_output', + ), + protocol_iterations=dict(argstr='--proto-iters %d', ), + shrink=dict(argstr='--shrink %d', ), + stop=dict(argstr='--stop %f', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict(argstr='--uchar %s', ), ) inputs = MNIBiasCorrection.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MNIBiasCorrection_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MNIBiasCorrection.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py b/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py index 1f64be215d..94aef97aff 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py @@ -4,40 +4,44 @@ def test_MPRtoMNI305_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - usedefault=True, - ), - reference_dir=dict(mandatory=True, - usedefault=True, - ), - subjects_dir=dict(), - target=dict(mandatory=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + usedefault=True, + ), + reference_dir=dict( + mandatory=True, + usedefault=True, + ), + subjects_dir=dict(), + target=dict( + mandatory=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MPRtoMNI305.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MPRtoMNI305_outputs(): - output_map = dict(log_file=dict(usedefault=True, - ), - out_file=dict(), + output_map = dict( + log_file=dict(usedefault=True, ), + out_file=dict(), ) outputs = MPRtoMNI305.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py index 8b5bc1135d..cd27862330 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py @@ -4,199 +4,121 @@ def test_MRIConvert_inputs(): - input_map = dict(apply_inv_transform=dict(argstr='--apply_inverse_transform %s', - ), - apply_transform=dict(argstr='--apply_transform %s', - ), - args=dict(argstr='%s', - ), - ascii=dict(argstr='--ascii', - ), - autoalign_matrix=dict(argstr='--autoalign %s', - ), - color_file=dict(argstr='--color_file %s', - ), - conform=dict(argstr='--conform', - ), - conform_min=dict(argstr='--conform_min', - ), - conform_size=dict(argstr='--conform_size %s', - ), - crop_center=dict(argstr='--crop %d %d %d', - ), - crop_gdf=dict(argstr='--crop_gdf', - ), - crop_size=dict(argstr='--cropsize %d %d %d', - ), - cut_ends=dict(argstr='--cutends %d', - ), - cw256=dict(argstr='--cw256', - ), - devolve_transform=dict(argstr='--devolvexfm %s', - ), - drop_n=dict(argstr='--ndrop %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fill_parcellation=dict(argstr='--fill_parcellation', - ), - force_ras=dict(argstr='--force_ras_good', - ), - frame=dict(argstr='--frame %d', - ), - frame_subsample=dict(argstr='--fsubsample %d %d %d', - ), - fwhm=dict(argstr='--fwhm %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_center=dict(argstr='--in_center %s', - ), - in_file=dict(argstr='--input_volume %s', - mandatory=True, - position=-2, - ), - in_i_dir=dict(argstr='--in_i_direction %f %f %f', - ), - in_i_size=dict(argstr='--in_i_size %d', - ), - in_info=dict(argstr='--in_info', - ), - in_j_dir=dict(argstr='--in_j_direction %f %f %f', - ), - in_j_size=dict(argstr='--in_j_size %d', - ), - in_k_dir=dict(argstr='--in_k_direction %f %f %f', - ), - in_k_size=dict(argstr='--in_k_size %d', - ), - in_like=dict(argstr='--in_like %s', - ), - in_matrix=dict(argstr='--in_matrix', - ), - in_orientation=dict(argstr='--in_orientation %s', - ), - in_scale=dict(argstr='--scale %f', - ), - in_stats=dict(argstr='--in_stats', - ), - in_type=dict(argstr='--in_type %s', - ), - invert_contrast=dict(argstr='--invert_contrast %f', - ), - midframe=dict(argstr='--mid-frame', - ), - no_change=dict(argstr='--nochange', - ), - no_scale=dict(argstr='--no_scale 1', - ), - no_translate=dict(argstr='--no_translate', - ), - no_write=dict(argstr='--no_write', - ), - out_center=dict(argstr='--out_center %f %f %f', - ), - out_datatype=dict(argstr='--out_data_type %s', - ), - out_file=dict(argstr='--output_volume %s', - genfile=True, - position=-1, - ), - out_i_count=dict(argstr='--out_i_count %d', - ), - out_i_dir=dict(argstr='--out_i_direction %f %f %f', - ), - out_i_size=dict(argstr='--out_i_size %d', - ), - out_info=dict(argstr='--out_info', - ), - out_j_count=dict(argstr='--out_j_count %d', - ), - out_j_dir=dict(argstr='--out_j_direction %f %f %f', - ), - out_j_size=dict(argstr='--out_j_size %d', - ), - out_k_count=dict(argstr='--out_k_count %d', - ), - out_k_dir=dict(argstr='--out_k_direction %f %f %f', - ), - out_k_size=dict(argstr='--out_k_size %d', - ), - out_matrix=dict(argstr='--out_matrix', - ), - out_orientation=dict(argstr='--out_orientation %s', - ), - out_scale=dict(argstr='--out-scale %d', - ), - out_stats=dict(argstr='--out_stats', - ), - out_type=dict(argstr='--out_type %s', - ), - parse_only=dict(argstr='--parse_only', - ), - read_only=dict(argstr='--read_only', - ), - reorder=dict(argstr='--reorder %d %d %d', - ), - resample_type=dict(argstr='--resample_type %s', - ), - reslice_like=dict(argstr='--reslice_like %s', - ), - sdcm_list=dict(argstr='--sdcmlist %s', - ), - skip_n=dict(argstr='--nskip %d', - ), - slice_bias=dict(argstr='--slice-bias %f', - ), - slice_crop=dict(argstr='--slice-crop %d %d', - ), - slice_reverse=dict(argstr='--slice-reverse', - ), - smooth_parcellation=dict(argstr='--smooth_parcellation', - ), - sphinx=dict(argstr='--sphinx', - ), - split=dict(argstr='--split', - ), - status_file=dict(argstr='--status %s', - ), - subject_name=dict(argstr='--subject_name %s', - ), - subjects_dir=dict(), - te=dict(argstr='-te %d', - ), - template_info=dict(), - template_type=dict(argstr='--template_type %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - ti=dict(argstr='-ti %d', - ), - tr=dict(argstr='-tr %d', - ), - unwarp_gradient=dict(argstr='--unwarp_gradient_nonlinearity', - ), - vox_size=dict(argstr='-voxsize %f %f %f', - ), - zero_ge_z_offset=dict(argstr='--zero_ge_z_offset', - ), - zero_outlines=dict(argstr='--zero_outlines', - ), + input_map = dict( + apply_inv_transform=dict(argstr='--apply_inverse_transform %s', ), + apply_transform=dict(argstr='--apply_transform %s', ), + args=dict(argstr='%s', ), + ascii=dict(argstr='--ascii', ), + autoalign_matrix=dict(argstr='--autoalign %s', ), + color_file=dict(argstr='--color_file %s', ), + conform=dict(argstr='--conform', ), + conform_min=dict(argstr='--conform_min', ), + conform_size=dict(argstr='--conform_size %s', ), + crop_center=dict(argstr='--crop %d %d %d', ), + crop_gdf=dict(argstr='--crop_gdf', ), + crop_size=dict(argstr='--cropsize %d %d %d', ), + cut_ends=dict(argstr='--cutends %d', ), + cw256=dict(argstr='--cw256', ), + devolve_transform=dict(argstr='--devolvexfm %s', ), + drop_n=dict(argstr='--ndrop %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_parcellation=dict(argstr='--fill_parcellation', ), + force_ras=dict(argstr='--force_ras_good', ), + frame=dict(argstr='--frame %d', ), + frame_subsample=dict(argstr='--fsubsample %d %d %d', ), + fwhm=dict(argstr='--fwhm %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_center=dict(argstr='--in_center %s', ), + in_file=dict( + argstr='--input_volume %s', + mandatory=True, + position=-2, + ), + in_i_dir=dict(argstr='--in_i_direction %f %f %f', ), + in_i_size=dict(argstr='--in_i_size %d', ), + in_info=dict(argstr='--in_info', ), + in_j_dir=dict(argstr='--in_j_direction %f %f %f', ), + in_j_size=dict(argstr='--in_j_size %d', ), + in_k_dir=dict(argstr='--in_k_direction %f %f %f', ), + in_k_size=dict(argstr='--in_k_size %d', ), + in_like=dict(argstr='--in_like %s', ), + in_matrix=dict(argstr='--in_matrix', ), + in_orientation=dict(argstr='--in_orientation %s', ), + in_scale=dict(argstr='--scale %f', ), + in_stats=dict(argstr='--in_stats', ), + in_type=dict(argstr='--in_type %s', ), + invert_contrast=dict(argstr='--invert_contrast %f', ), + midframe=dict(argstr='--mid-frame', ), + no_change=dict(argstr='--nochange', ), + no_scale=dict(argstr='--no_scale 1', ), + no_translate=dict(argstr='--no_translate', ), + no_write=dict(argstr='--no_write', ), + out_center=dict(argstr='--out_center %f %f %f', ), + out_datatype=dict(argstr='--out_data_type %s', ), + out_file=dict( + argstr='--output_volume %s', + genfile=True, + position=-1, + ), + out_i_count=dict(argstr='--out_i_count %d', ), + out_i_dir=dict(argstr='--out_i_direction %f %f %f', ), + out_i_size=dict(argstr='--out_i_size %d', ), + out_info=dict(argstr='--out_info', ), + out_j_count=dict(argstr='--out_j_count %d', ), + out_j_dir=dict(argstr='--out_j_direction %f %f %f', ), + out_j_size=dict(argstr='--out_j_size %d', ), + out_k_count=dict(argstr='--out_k_count %d', ), + out_k_dir=dict(argstr='--out_k_direction %f %f %f', ), + out_k_size=dict(argstr='--out_k_size %d', ), + out_matrix=dict(argstr='--out_matrix', ), + out_orientation=dict(argstr='--out_orientation %s', ), + out_scale=dict(argstr='--out-scale %d', ), + out_stats=dict(argstr='--out_stats', ), + out_type=dict(argstr='--out_type %s', ), + parse_only=dict(argstr='--parse_only', ), + read_only=dict(argstr='--read_only', ), + reorder=dict(argstr='--reorder %d %d %d', ), + resample_type=dict(argstr='--resample_type %s', ), + reslice_like=dict(argstr='--reslice_like %s', ), + sdcm_list=dict(argstr='--sdcmlist %s', ), + skip_n=dict(argstr='--nskip %d', ), + slice_bias=dict(argstr='--slice-bias %f', ), + slice_crop=dict(argstr='--slice-crop %d %d', ), + slice_reverse=dict(argstr='--slice-reverse', ), + smooth_parcellation=dict(argstr='--smooth_parcellation', ), + sphinx=dict(argstr='--sphinx', ), + split=dict(argstr='--split', ), + status_file=dict(argstr='--status %s', ), + subject_name=dict(argstr='--subject_name %s', ), + subjects_dir=dict(), + te=dict(argstr='-te %d', ), + template_info=dict(), + template_type=dict(argstr='--template_type %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + ti=dict(argstr='-ti %d', ), + tr=dict(argstr='-tr %d', ), + unwarp_gradient=dict(argstr='--unwarp_gradient_nonlinearity', ), + vox_size=dict(argstr='-voxsize %f %f %f', ), + zero_ge_z_offset=dict(argstr='--zero_ge_z_offset', ), + zero_outlines=dict(argstr='--zero_outlines', ), ) inputs = MRIConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIConvert_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRIConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py b/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py index e04b306c69..abfa091eb2 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py @@ -4,103 +4,89 @@ def test_MRICoreg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - brute_force_limit=dict(argstr='--bf-lim %g', - xor=['no_brute_force'], - ), - brute_force_samples=dict(argstr='--bf-nsamp %d', - xor=['no_brute_force'], - ), - conform_reference=dict(argstr='--conf-ref', - ), - dof=dict(argstr='--dof %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ftol=dict(argstr='--ftol %e', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initial_rotation=dict(argstr='--rot %g %g %g', - ), - initial_scale=dict(argstr='--scale %g %g %g', - ), - initial_shear=dict(argstr='--shear %g %g %g', - ), - initial_translation=dict(argstr='--trans %g %g %g', - ), - linmintol=dict(argstr='--linmintol %e', - ), - max_iters=dict(argstr='--nitersmax %d', - ), - no_brute_force=dict(argstr='--no-bf', - ), - no_coord_dithering=dict(argstr='--no-coord-dither', - ), - no_cras0=dict(argstr='--no-cras0', - ), - no_intensity_dithering=dict(argstr='--no-intensity-dither', - ), - no_smooth=dict(argstr='--no-smooth', - ), - num_threads=dict(argstr='--threads %d', - ), - out_lta_file=dict(argstr='--lta %s', - usedefault=True, - ), - out_params_file=dict(argstr='--params %s', - ), - out_reg_file=dict(argstr='--regdat %s', - ), - ref_fwhm=dict(argstr='--ref-fwhm', - ), - reference_file=dict(argstr='--ref %s', - copyfile=False, - mandatory=True, - xor=['subject_id'], - ), - reference_mask=dict(argstr='--ref-mask %s', - position=2, - ), - saturation_threshold=dict(argstr='--sat %g', - ), - sep=dict(argstr='--sep %s...', - ), - source_file=dict(argstr='--mov %s', - copyfile=False, - mandatory=True, - ), - source_mask=dict(argstr='--mov-mask', - ), - source_oob=dict(argstr='--mov-oob', - ), - subject_id=dict(argstr='--s %s', - mandatory=True, - position=1, - requires=['subjects_dir'], - xor=['reference_file'], - ), - subjects_dir=dict(argstr='--sd %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + brute_force_limit=dict( + argstr='--bf-lim %g', + xor=['no_brute_force'], + ), + brute_force_samples=dict( + argstr='--bf-nsamp %d', + xor=['no_brute_force'], + ), + conform_reference=dict(argstr='--conf-ref', ), + dof=dict(argstr='--dof %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ftol=dict(argstr='--ftol %e', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initial_rotation=dict(argstr='--rot %g %g %g', ), + initial_scale=dict(argstr='--scale %g %g %g', ), + initial_shear=dict(argstr='--shear %g %g %g', ), + initial_translation=dict(argstr='--trans %g %g %g', ), + linmintol=dict(argstr='--linmintol %e', ), + max_iters=dict(argstr='--nitersmax %d', ), + no_brute_force=dict(argstr='--no-bf', ), + no_coord_dithering=dict(argstr='--no-coord-dither', ), + no_cras0=dict(argstr='--no-cras0', ), + no_intensity_dithering=dict(argstr='--no-intensity-dither', ), + no_smooth=dict(argstr='--no-smooth', ), + num_threads=dict(argstr='--threads %d', ), + out_lta_file=dict( + argstr='--lta %s', + usedefault=True, + ), + out_params_file=dict(argstr='--params %s', ), + out_reg_file=dict(argstr='--regdat %s', ), + ref_fwhm=dict(argstr='--ref-fwhm', ), + reference_file=dict( + argstr='--ref %s', + copyfile=False, + mandatory=True, + xor=['subject_id'], + ), + reference_mask=dict( + argstr='--ref-mask %s', + position=2, + ), + saturation_threshold=dict(argstr='--sat %g', ), + sep=dict(argstr='--sep %s...', ), + source_file=dict( + argstr='--mov %s', + copyfile=False, + mandatory=True, + ), + source_mask=dict(argstr='--mov-mask', ), + source_oob=dict(argstr='--mov-oob', ), + subject_id=dict( + argstr='--s %s', + mandatory=True, + position=1, + requires=['subjects_dir'], + xor=['reference_file'], + ), + subjects_dir=dict(argstr='--sd %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRICoreg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRICoreg_outputs(): - output_map = dict(out_lta_file=dict(), - out_params_file=dict(), - out_reg_file=dict(), + output_map = dict( + out_lta_file=dict(), + out_params_file=dict(), + out_reg_file=dict(), ) outputs = MRICoreg.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py index f45165af12..b6cfafb2d7 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py @@ -4,44 +4,45 @@ def test_MRIFill_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - log_file=dict(argstr='-a %s', - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - segmentation=dict(argstr='-segmentation %s', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='-xform %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + log_file=dict(argstr='-a %s', ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + segmentation=dict(argstr='-segmentation %s', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict(argstr='-xform %s', ), ) inputs = MRIFill.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIFill_outputs(): - output_map = dict(log_file=dict(), - out_file=dict(), + output_map = dict( + log_file=dict(), + out_file=dict(), ) outputs = MRIFill.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py index 9f333c2643..38d9606c38 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py @@ -4,46 +4,50 @@ def test_MRIMarchingCubes_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - connectivity_value=dict(argstr='%d', - position=-1, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - label_value=dict(argstr='%d', - mandatory=True, - position=2, - ), - out_file=dict(argstr='./%s', - genfile=True, - position=-2, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + connectivity_value=dict( + argstr='%d', + position=-1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + label_value=dict( + argstr='%d', + mandatory=True, + position=2, + ), + out_file=dict( + argstr='./%s', + genfile=True, + position=-2, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRIMarchingCubes.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIMarchingCubes_outputs(): - output_map = dict(surface=dict(), - ) + output_map = dict(surface=dict(), ) outputs = MRIMarchingCubes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py index 87dc5ce59f..bd34227714 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py @@ -4,55 +4,56 @@ def test_MRIPretess_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_filled=dict(argstr='%s', - mandatory=True, - position=-4, - ), - in_norm=dict(argstr='%s', - mandatory=True, - position=-2, - ), - keep=dict(argstr='-keep', - ), - label=dict(argstr='%s', - mandatory=True, - position=-3, - usedefault=True, - ), - nocorners=dict(argstr='-nocorners', - ), - out_file=dict(argstr='%s', - keep_extension=True, - name_source=['in_filled'], - name_template='%s_pretesswm', - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - test=dict(argstr='-test', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_filled=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + in_norm=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + keep=dict(argstr='-keep', ), + label=dict( + argstr='%s', + mandatory=True, + position=-3, + usedefault=True, + ), + nocorners=dict(argstr='-nocorners', ), + out_file=dict( + argstr='%s', + keep_extension=True, + name_source=['in_filled'], + name_template='%s_pretesswm', + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + test=dict(argstr='-test', ), ) inputs = MRIPretess.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIPretess_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRIPretess.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py index 2e0d137668..ce68c41056 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py @@ -4,79 +4,87 @@ def test_MRISPreproc_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fsgd_file=dict(argstr='--fsgd %s', - xor=('subjects', 'fsgd_file', 'subject_file'), - ), - fwhm=dict(argstr='--fwhm %f', - xor=['num_iters'], - ), - fwhm_source=dict(argstr='--fwhm-src %f', - xor=['num_iters_source'], - ), - hemi=dict(argstr='--hemi %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_iters=dict(argstr='--niters %d', - xor=['fwhm'], - ), - num_iters_source=dict(argstr='--niterssrc %d', - xor=['fwhm_source'], - ), - out_file=dict(argstr='--out %s', - genfile=True, - ), - proj_frac=dict(argstr='--projfrac %s', - ), - smooth_cortex_only=dict(argstr='--smooth-cortex-only', - ), - source_format=dict(argstr='--srcfmt %s', - ), - subject_file=dict(argstr='--f %s', - xor=('subjects', 'fsgd_file', 'subject_file'), - ), - subjects=dict(argstr='--s %s...', - xor=('subjects', 'fsgd_file', 'subject_file'), - ), - subjects_dir=dict(), - surf_area=dict(argstr='--area %s', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - ), - surf_dir=dict(argstr='--surfdir %s', - ), - surf_measure=dict(argstr='--meas %s', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - ), - surf_measure_file=dict(argstr='--is %s...', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - ), - target=dict(argstr='--target %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vol_measure_file=dict(argstr='--iv %s %s...', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fsgd_file=dict( + argstr='--fsgd %s', + xor=('subjects', 'fsgd_file', 'subject_file'), + ), + fwhm=dict( + argstr='--fwhm %f', + xor=['num_iters'], + ), + fwhm_source=dict( + argstr='--fwhm-src %f', + xor=['num_iters_source'], + ), + hemi=dict( + argstr='--hemi %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_iters=dict( + argstr='--niters %d', + xor=['fwhm'], + ), + num_iters_source=dict( + argstr='--niterssrc %d', + xor=['fwhm_source'], + ), + out_file=dict( + argstr='--out %s', + genfile=True, + ), + proj_frac=dict(argstr='--projfrac %s', ), + smooth_cortex_only=dict(argstr='--smooth-cortex-only', ), + source_format=dict(argstr='--srcfmt %s', ), + subject_file=dict( + argstr='--f %s', + xor=('subjects', 'fsgd_file', 'subject_file'), + ), + subjects=dict( + argstr='--s %s...', + xor=('subjects', 'fsgd_file', 'subject_file'), + ), + subjects_dir=dict(), + surf_area=dict( + argstr='--area %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + ), + surf_dir=dict(argstr='--surfdir %s', ), + surf_measure=dict( + argstr='--meas %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + ), + surf_measure_file=dict( + argstr='--is %s...', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + ), + target=dict( + argstr='--target %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vol_measure_file=dict(argstr='--iv %s %s...', ), ) inputs = MRISPreproc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRISPreproc_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRISPreproc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py index 56860ed6d3..677d9dda5a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py @@ -4,91 +4,99 @@ def test_MRISPreprocReconAll_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - copy_inputs=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - fsgd_file=dict(argstr='--fsgd %s', - xor=('subjects', 'fsgd_file', 'subject_file'), - ), - fwhm=dict(argstr='--fwhm %f', - xor=['num_iters'], - ), - fwhm_source=dict(argstr='--fwhm-src %f', - xor=['num_iters_source'], - ), - hemi=dict(argstr='--hemi %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - lh_surfreg_target=dict(requires=['surfreg_files'], - ), - num_iters=dict(argstr='--niters %d', - xor=['fwhm'], - ), - num_iters_source=dict(argstr='--niterssrc %d', - xor=['fwhm_source'], - ), - out_file=dict(argstr='--out %s', - genfile=True, - ), - proj_frac=dict(argstr='--projfrac %s', - ), - rh_surfreg_target=dict(requires=['surfreg_files'], - ), - smooth_cortex_only=dict(argstr='--smooth-cortex-only', - ), - source_format=dict(argstr='--srcfmt %s', - ), - subject_file=dict(argstr='--f %s', - xor=('subjects', 'fsgd_file', 'subject_file'), - ), - subject_id=dict(argstr='--s %s', - usedefault=True, - xor=('subjects', 'fsgd_file', 'subject_file', 'subject_id'), - ), - subjects=dict(argstr='--s %s...', - xor=('subjects', 'fsgd_file', 'subject_file'), - ), - subjects_dir=dict(), - surf_area=dict(argstr='--area %s', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - ), - surf_dir=dict(argstr='--surfdir %s', - ), - surf_measure=dict(argstr='--meas %s', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - ), - surf_measure_file=dict(argstr='--meas %s', - xor=('surf_measure', 'surf_measure_file', 'surf_area'), - ), - surfreg_files=dict(argstr='--surfreg %s', - requires=['lh_surfreg_target', 'rh_surfreg_target'], - ), - target=dict(argstr='--target %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vol_measure_file=dict(argstr='--iv %s %s...', - ), + input_map = dict( + args=dict(argstr='%s', ), + copy_inputs=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + fsgd_file=dict( + argstr='--fsgd %s', + xor=('subjects', 'fsgd_file', 'subject_file'), + ), + fwhm=dict( + argstr='--fwhm %f', + xor=['num_iters'], + ), + fwhm_source=dict( + argstr='--fwhm-src %f', + xor=['num_iters_source'], + ), + hemi=dict( + argstr='--hemi %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + lh_surfreg_target=dict(requires=['surfreg_files'], ), + num_iters=dict( + argstr='--niters %d', + xor=['fwhm'], + ), + num_iters_source=dict( + argstr='--niterssrc %d', + xor=['fwhm_source'], + ), + out_file=dict( + argstr='--out %s', + genfile=True, + ), + proj_frac=dict(argstr='--projfrac %s', ), + rh_surfreg_target=dict(requires=['surfreg_files'], ), + smooth_cortex_only=dict(argstr='--smooth-cortex-only', ), + source_format=dict(argstr='--srcfmt %s', ), + subject_file=dict( + argstr='--f %s', + xor=('subjects', 'fsgd_file', 'subject_file'), + ), + subject_id=dict( + argstr='--s %s', + usedefault=True, + xor=('subjects', 'fsgd_file', 'subject_file', 'subject_id'), + ), + subjects=dict( + argstr='--s %s...', + xor=('subjects', 'fsgd_file', 'subject_file'), + ), + subjects_dir=dict(), + surf_area=dict( + argstr='--area %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + ), + surf_dir=dict(argstr='--surfdir %s', ), + surf_measure=dict( + argstr='--meas %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + ), + surf_measure_file=dict( + argstr='--meas %s', + xor=('surf_measure', 'surf_measure_file', 'surf_area'), + ), + surfreg_files=dict( + argstr='--surfreg %s', + requires=['lh_surfreg_target', 'rh_surfreg_target'], + ), + target=dict( + argstr='--target %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vol_measure_file=dict(argstr='--iv %s %s...', ), ) inputs = MRISPreprocReconAll.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRISPreprocReconAll_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRISPreprocReconAll.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py b/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py index 9829b19326..25a8a4b301 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py @@ -4,46 +4,47 @@ def test_MRITessellate_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - label_value=dict(argstr='%d', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tesselate_all_voxels=dict(argstr='-a', - ), - use_real_RAS_coordinates=dict(argstr='-n', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + label_value=dict( + argstr='%d', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tesselate_all_voxels=dict(argstr='-a', ), + use_real_RAS_coordinates=dict(argstr='-n', ), ) inputs = MRITessellate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRITessellate_outputs(): - output_map = dict(surface=dict(), - ) + output_map = dict(surface=dict(), ) outputs = MRITessellate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py index 9c70889d59..6f13ea5e75 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py @@ -4,68 +4,67 @@ def test_MRIsCALabel_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - aseg=dict(argstr='-aseg %s', - ), - canonsurf=dict(argstr='%s', - mandatory=True, - position=-3, - ), - classifier=dict(argstr='%s', - mandatory=True, - position=-2, - ), - copy_inputs=dict(), - curv=dict(mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - hemisphere=dict(argstr='%s', - mandatory=True, - position=-4, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - label=dict(argstr='-l %s', - ), - num_threads=dict(), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=True, - name_source=['hemisphere'], - name_template='%s.aparc.annot', - position=-1, - ), - seed=dict(argstr='-seed %d', - ), - smoothwm=dict(mandatory=True, - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=-5, - usedefault=True, - ), - subjects_dir=dict(), - sulc=dict(mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + aseg=dict(argstr='-aseg %s', ), + canonsurf=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + classifier=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + copy_inputs=dict(), + curv=dict(mandatory=True, ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + label=dict(argstr='-l %s', ), + num_threads=dict(), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=True, + name_source=['hemisphere'], + name_template='%s.aparc.annot', + position=-1, + ), + seed=dict(argstr='-seed %d', ), + smoothwm=dict(mandatory=True, ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=-5, + usedefault=True, + ), + subjects_dir=dict(), + sulc=dict(mandatory=True, ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRIsCALabel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIsCALabel_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRIsCALabel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py index 0844523ac8..e85a44fcea 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py @@ -4,53 +4,59 @@ def test_MRIsCalc_inputs(): - input_map = dict(action=dict(argstr='%s', - mandatory=True, - position=-2, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file1=dict(argstr='%s', - mandatory=True, - position=-3, - ), - in_file2=dict(argstr='%s', - position=-1, - xor=['in_float', 'in_int'], - ), - in_float=dict(argstr='%f', - position=-1, - xor=['in_file2', 'in_int'], - ), - in_int=dict(argstr='%d', - position=-1, - xor=['in_file2', 'in_float'], - ), - out_file=dict(argstr='-o %s', - mandatory=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + action=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file1=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + in_file2=dict( + argstr='%s', + position=-1, + xor=['in_float', 'in_int'], + ), + in_float=dict( + argstr='%f', + position=-1, + xor=['in_file2', 'in_int'], + ), + in_int=dict( + argstr='%d', + position=-1, + xor=['in_file2', 'in_float'], + ), + out_file=dict( + argstr='-o %s', + mandatory=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRIsCalc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIsCalc_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRIsCalc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py index 8ac919ad65..93c37acf7d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py @@ -4,39 +4,41 @@ def test_MRIsCombine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='--combinesurfs %s', - mandatory=True, - position=1, - ), - out_file=dict(argstr='%s', - genfile=True, - mandatory=True, - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='--combinesurfs %s', + mandatory=True, + position=1, + ), + out_file=dict( + argstr='%s', + genfile=True, + mandatory=True, + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRIsCombine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIsCombine_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRIsCombine.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py index 5fda94dd63..45205baf3a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py @@ -4,77 +4,63 @@ def test_MRIsConvert_inputs(): - input_map = dict(annot_file=dict(argstr='--annot %s', - ), - args=dict(argstr='%s', - ), - dataarray_num=dict(argstr='--da_num %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - functional_file=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - label_file=dict(argstr='--label %s', - ), - labelstats_outfile=dict(argstr='--labelstats %s', - ), - normal=dict(argstr='-n', - ), - origname=dict(argstr='-o %s', - ), - out_datatype=dict(mandatory=True, - xor=['out_file'], - ), - out_file=dict(argstr='%s', - genfile=True, - mandatory=True, - position=-1, - xor=['out_datatype'], - ), - parcstats_file=dict(argstr='--parcstats %s', - ), - patch=dict(argstr='-p', - ), - rescale=dict(argstr='-r', - ), - scalarcurv_file=dict(argstr='-c %s', - ), - scale=dict(argstr='-s %.3f', - ), - subjects_dir=dict(), - talairachxfm_subjid=dict(argstr='-t %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - to_scanner=dict(argstr='--to-scanner', - ), - to_tkr=dict(argstr='--to-tkr', - ), - vertex=dict(argstr='-v', - ), - xyz_ascii=dict(argstr='-a', - ), + input_map = dict( + annot_file=dict(argstr='--annot %s', ), + args=dict(argstr='%s', ), + dataarray_num=dict(argstr='--da_num %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + functional_file=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + label_file=dict(argstr='--label %s', ), + labelstats_outfile=dict(argstr='--labelstats %s', ), + normal=dict(argstr='-n', ), + origname=dict(argstr='-o %s', ), + out_datatype=dict( + mandatory=True, + xor=['out_file'], + ), + out_file=dict( + argstr='%s', + genfile=True, + mandatory=True, + position=-1, + xor=['out_datatype'], + ), + parcstats_file=dict(argstr='--parcstats %s', ), + patch=dict(argstr='-p', ), + rescale=dict(argstr='-r', ), + scalarcurv_file=dict(argstr='-c %s', ), + scale=dict(argstr='-s %.3f', ), + subjects_dir=dict(), + talairachxfm_subjid=dict(argstr='-t %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + to_scanner=dict(argstr='--to-scanner', ), + to_tkr=dict(argstr='--to-tkr', ), + vertex=dict(argstr='-v', ), + xyz_ascii=dict(argstr='-a', ), ) inputs = MRIsConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIsConvert_outputs(): - output_map = dict(converted=dict(), - ) + output_map = dict(converted=dict(), ) outputs = MRIsConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py index e292a2b2c5..d9b352c453 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py @@ -4,64 +4,64 @@ def test_MRIsExpand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - distance=dict(argstr='%g', - mandatory=True, - position=-2, - ), - dt=dict(argstr='-T %g', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-3, - ), - nsurfaces=dict(argstr='-N %d', - ), - out_name=dict(argstr='%s', - position=-1, - usedefault=True, - ), - pial=dict(argstr='-pial %s', - copyfile=False, - ), - smooth_averages=dict(argstr='-A %d', - ), - sphere=dict(copyfile=False, - usedefault=True, - ), - spring=dict(argstr='-S %g', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thickness=dict(argstr='-thickness', - ), - thickness_name=dict(argstr='-thickness_name %s', - copyfile=False, - ), - write_iterations=dict(argstr='-W %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + distance=dict( + argstr='%g', + mandatory=True, + position=-2, + ), + dt=dict(argstr='-T %g', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-3, + ), + nsurfaces=dict(argstr='-N %d', ), + out_name=dict( + argstr='%s', + position=-1, + usedefault=True, + ), + pial=dict( + argstr='-pial %s', + copyfile=False, + ), + smooth_averages=dict(argstr='-A %d', ), + sphere=dict( + copyfile=False, + usedefault=True, + ), + spring=dict(argstr='-S %g', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thickness=dict(argstr='-thickness', ), + thickness_name=dict( + argstr='-thickness_name %s', + copyfile=False, + ), + write_iterations=dict(argstr='-W %d', ), ) inputs = MRIsExpand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIsExpand_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRIsExpand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py index 3a93d5f1e1..ff857f3b44 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py @@ -4,47 +4,51 @@ def test_MRIsInflate_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-2, - ), - no_save_sulc=dict(argstr='-no-save-sulc', - xor=['out_sulc'], - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s.inflated', - position=-1, - ), - out_sulc=dict(xor=['no_save_sulc'], - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-2, + ), + no_save_sulc=dict( + argstr='-no-save-sulc', + xor=['out_sulc'], + ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s.inflated', + position=-1, + ), + out_sulc=dict(xor=['no_save_sulc'], ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRIsInflate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRIsInflate_outputs(): - output_map = dict(out_file=dict(), - out_sulc=dict(), + output_map = dict( + out_file=dict(), + out_sulc=dict(), ) outputs = MRIsInflate.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py b/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py index 97321adec8..6c978254a5 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py @@ -4,55 +4,56 @@ def test_MS_LDA_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - conform=dict(argstr='-conform', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - images=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - label_file=dict(argstr='-label %s', - ), - lda_labels=dict(argstr='-lda %s', - mandatory=True, - sep=' ', - ), - mask_file=dict(argstr='-mask %s', - ), - shift=dict(argstr='-shift %d', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_weights=dict(argstr='-W', - ), - vol_synth_file=dict(argstr='-synth %s', - mandatory=True, - ), - weight_file=dict(argstr='-weight %s', - mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + conform=dict(argstr='-conform', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + images=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + label_file=dict(argstr='-label %s', ), + lda_labels=dict( + argstr='-lda %s', + mandatory=True, + sep=' ', + ), + mask_file=dict(argstr='-mask %s', ), + shift=dict(argstr='-shift %d', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_weights=dict(argstr='-W', ), + vol_synth_file=dict( + argstr='-synth %s', + mandatory=True, + ), + weight_file=dict( + argstr='-weight %s', + mandatory=True, + ), ) inputs = MS_LDA.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MS_LDA_outputs(): - output_map = dict(vol_synth_file=dict(), - weight_file=dict(), + output_map = dict( + vol_synth_file=dict(), + weight_file=dict(), ) outputs = MS_LDA.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py b/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py index d0fec86806..bb102a7df7 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py @@ -4,37 +4,39 @@ def test_MakeAverageSubject_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_name=dict(argstr='--out %s', - usedefault=True, - ), - subjects_dir=dict(), - subjects_ids=dict(argstr='--subjects %s', - mandatory=True, - sep=' ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_name=dict( + argstr='--out %s', + usedefault=True, + ), + subjects_dir=dict(), + subjects_ids=dict( + argstr='--subjects %s', + mandatory=True, + sep=' ', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MakeAverageSubject.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MakeAverageSubject_outputs(): - output_map = dict(average_subject_name=dict(), - ) + output_map = dict(average_subject_name=dict(), ) outputs = MakeAverageSubject.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py b/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py index ed5c9021ab..36c4c1bf90 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py @@ -4,80 +4,74 @@ def test_MakeSurfaces_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - copy_inputs=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - fix_mtl=dict(argstr='-fix_mtl', - ), - hemisphere=dict(argstr='%s', - mandatory=True, - position=-1, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_T1=dict(argstr='-T1 %s', - ), - in_aseg=dict(argstr='-aseg %s', - ), - in_filled=dict(mandatory=True, - ), - in_label=dict(xor=['noaparc'], - ), - in_orig=dict(argstr='-orig %s', - mandatory=True, - ), - in_white=dict(), - in_wm=dict(mandatory=True, - ), - longitudinal=dict(argstr='-long', - ), - maximum=dict(argstr='-max %.1f', - ), - mgz=dict(argstr='-mgz', - ), - no_white=dict(argstr='-nowhite', - ), - noaparc=dict(argstr='-noaparc', - xor=['in_label'], - ), - orig_pial=dict(argstr='-orig_pial %s', - requires=['in_label'], - ), - orig_white=dict(argstr='-orig_white %s', - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=-2, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - white=dict(argstr='-white %s', - ), - white_only=dict(argstr='-whiteonly', - ), + input_map = dict( + args=dict(argstr='%s', ), + copy_inputs=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + fix_mtl=dict(argstr='-fix_mtl', ), + hemisphere=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_T1=dict(argstr='-T1 %s', ), + in_aseg=dict(argstr='-aseg %s', ), + in_filled=dict(mandatory=True, ), + in_label=dict(xor=['noaparc'], ), + in_orig=dict( + argstr='-orig %s', + mandatory=True, + ), + in_white=dict(), + in_wm=dict(mandatory=True, ), + longitudinal=dict(argstr='-long', ), + maximum=dict(argstr='-max %.1f', ), + mgz=dict(argstr='-mgz', ), + no_white=dict(argstr='-nowhite', ), + noaparc=dict( + argstr='-noaparc', + xor=['in_label'], + ), + orig_pial=dict( + argstr='-orig_pial %s', + requires=['in_label'], + ), + orig_white=dict(argstr='-orig_white %s', ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=-2, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + white=dict(argstr='-white %s', ), + white_only=dict(argstr='-whiteonly', ), ) inputs = MakeSurfaces.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MakeSurfaces_outputs(): - output_map = dict(out_area=dict(), - out_cortex=dict(), - out_curv=dict(), - out_pial=dict(), - out_thickness=dict(), - out_white=dict(), + output_map = dict( + out_area=dict(), + out_cortex=dict(), + out_curv=dict(), + out_pial=dict(), + out_thickness=dict(), + out_white=dict(), ) outputs = MakeSurfaces.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py b/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py index 33319e77ed..9d907403f2 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py @@ -4,49 +4,50 @@ def test_Normalize_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gradient=dict(argstr='-g %d', - usedefault=False, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - mask=dict(argstr='-mask %s', - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s_norm', - position=-1, - ), - segmentation=dict(argstr='-aseg %s', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradient=dict( + argstr='-g %d', + usedefault=False, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + mask=dict(argstr='-mask %s', ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s_norm', + position=-1, + ), + segmentation=dict(argstr='-aseg %s', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict(), ) inputs = Normalize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Normalize_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Normalize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py b/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py index a1bb43f9c5..c8b6422dd0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py @@ -4,166 +4,147 @@ def test_OneSampleTTest_inputs(): - input_map = dict(allow_ill_cond=dict(argstr='--illcond', - ), - allow_repeated_subjects=dict(argstr='--allowsubjrep', - ), - args=dict(argstr='%s', - ), - calc_AR1=dict(argstr='--tar1', - ), - check_opts=dict(argstr='--checkopts', - ), - compute_log_y=dict(argstr='--logy', - ), - contrast=dict(argstr='--C %s...', - ), - cortex=dict(argstr='--cortex', - xor=['label_file'], - ), - debug=dict(argstr='--debug', - ), - design=dict(argstr='--X %s', - xor=('fsgd', 'design', 'one_sample'), - ), - diag=dict(), - diag_cluster=dict(argstr='--diag-cluster', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_fx_dof=dict(argstr='--ffxdof %d', - xor=['fixed_fx_dof_file'], - ), - fixed_fx_dof_file=dict(argstr='--ffxdofdat %d', - xor=['fixed_fx_dof'], - ), - fixed_fx_var=dict(argstr='--yffxvar %s', - ), - force_perm=dict(argstr='--perm-force', - ), - fsgd=dict(argstr='--fsgd %s %s', - xor=('fsgd', 'design', 'one_sample'), - ), - fwhm=dict(argstr='--fwhm %f', - ), - glm_dir=dict(argstr='--glmdir %s', - genfile=True, - ), - hemi=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--y %s', - copyfile=False, - mandatory=True, - ), - invert_mask=dict(argstr='--mask-inv', - ), - label_file=dict(argstr='--label %s', - xor=['cortex'], - ), - mask_file=dict(argstr='--mask %s', - ), - no_contrast_ok=dict(argstr='--no-contrasts-ok', - ), - no_est_fwhm=dict(argstr='--no-est-fwhm', - ), - no_mask_smooth=dict(argstr='--no-mask-smooth', - ), - no_prune=dict(argstr='--no-prune', - xor=['prunethresh'], - ), - one_sample=dict(argstr='--osgm', - xor=('one_sample', 'fsgd', 'design', 'contrast'), - ), - pca=dict(argstr='--pca', - ), - per_voxel_reg=dict(argstr='--pvr %s...', - ), - profile=dict(argstr='--profile %d', - ), - prune=dict(argstr='--prune', - ), - prune_thresh=dict(argstr='--prune_thr %f', - xor=['noprune'], - ), - resynth_test=dict(argstr='--resynthtest %d', - ), - save_cond=dict(argstr='--save-cond', - ), - save_estimate=dict(argstr='--yhat-save', - ), - save_res_corr_mtx=dict(argstr='--eres-scm', - ), - save_residual=dict(argstr='--eres-save', - ), - seed=dict(argstr='--seed %d', - ), - self_reg=dict(argstr='--selfreg %d %d %d', - ), - sim_done_file=dict(argstr='--sim-done %s', - ), - sim_sign=dict(argstr='--sim-sign %s', - ), - simulation=dict(argstr='--sim %s %d %f %s', - ), - subject_id=dict(), - subjects_dir=dict(), - surf=dict(argstr='--surf %s %s %s', - requires=['subject_id', 'hemi'], - ), - surf_geo=dict(usedefault=True, - ), - synth=dict(argstr='--synth', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uniform=dict(argstr='--uniform %f %f', - ), - var_fwhm=dict(argstr='--var-fwhm %f', - ), - vox_dump=dict(argstr='--voxdump %d %d %d', - ), - weight_file=dict(xor=['weighted_ls'], - ), - weight_inv=dict(argstr='--w-inv', - xor=['weighted_ls'], - ), - weight_sqrt=dict(argstr='--w-sqrt', - xor=['weighted_ls'], - ), - weighted_ls=dict(argstr='--wls %s', - xor=('weight_file', 'weight_inv', 'weight_sqrt'), - ), + input_map = dict( + allow_ill_cond=dict(argstr='--illcond', ), + allow_repeated_subjects=dict(argstr='--allowsubjrep', ), + args=dict(argstr='%s', ), + calc_AR1=dict(argstr='--tar1', ), + check_opts=dict(argstr='--checkopts', ), + compute_log_y=dict(argstr='--logy', ), + contrast=dict(argstr='--C %s...', ), + cortex=dict( + argstr='--cortex', + xor=['label_file'], + ), + debug=dict(argstr='--debug', ), + design=dict( + argstr='--X %s', + xor=('fsgd', 'design', 'one_sample'), + ), + diag=dict(), + diag_cluster=dict(argstr='--diag-cluster', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_fx_dof=dict( + argstr='--ffxdof %d', + xor=['fixed_fx_dof_file'], + ), + fixed_fx_dof_file=dict( + argstr='--ffxdofdat %d', + xor=['fixed_fx_dof'], + ), + fixed_fx_var=dict(argstr='--yffxvar %s', ), + force_perm=dict(argstr='--perm-force', ), + fsgd=dict( + argstr='--fsgd %s %s', + xor=('fsgd', 'design', 'one_sample'), + ), + fwhm=dict(argstr='--fwhm %f', ), + glm_dir=dict( + argstr='--glmdir %s', + genfile=True, + ), + hemi=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--y %s', + copyfile=False, + mandatory=True, + ), + invert_mask=dict(argstr='--mask-inv', ), + label_file=dict( + argstr='--label %s', + xor=['cortex'], + ), + mask_file=dict(argstr='--mask %s', ), + no_contrast_ok=dict(argstr='--no-contrasts-ok', ), + no_est_fwhm=dict(argstr='--no-est-fwhm', ), + no_mask_smooth=dict(argstr='--no-mask-smooth', ), + no_prune=dict( + argstr='--no-prune', + xor=['prunethresh'], + ), + one_sample=dict( + argstr='--osgm', + xor=('one_sample', 'fsgd', 'design', 'contrast'), + ), + pca=dict(argstr='--pca', ), + per_voxel_reg=dict(argstr='--pvr %s...', ), + profile=dict(argstr='--profile %d', ), + prune=dict(argstr='--prune', ), + prune_thresh=dict( + argstr='--prune_thr %f', + xor=['noprune'], + ), + resynth_test=dict(argstr='--resynthtest %d', ), + save_cond=dict(argstr='--save-cond', ), + save_estimate=dict(argstr='--yhat-save', ), + save_res_corr_mtx=dict(argstr='--eres-scm', ), + save_residual=dict(argstr='--eres-save', ), + seed=dict(argstr='--seed %d', ), + self_reg=dict(argstr='--selfreg %d %d %d', ), + sim_done_file=dict(argstr='--sim-done %s', ), + sim_sign=dict(argstr='--sim-sign %s', ), + simulation=dict(argstr='--sim %s %d %f %s', ), + subject_id=dict(), + subjects_dir=dict(), + surf=dict( + argstr='--surf %s %s %s', + requires=['subject_id', 'hemi'], + ), + surf_geo=dict(usedefault=True, ), + synth=dict(argstr='--synth', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uniform=dict(argstr='--uniform %f %f', ), + var_fwhm=dict(argstr='--var-fwhm %f', ), + vox_dump=dict(argstr='--voxdump %d %d %d', ), + weight_file=dict(xor=['weighted_ls'], ), + weight_inv=dict( + argstr='--w-inv', + xor=['weighted_ls'], + ), + weight_sqrt=dict( + argstr='--w-sqrt', + xor=['weighted_ls'], + ), + weighted_ls=dict( + argstr='--wls %s', + xor=('weight_file', 'weight_inv', 'weight_sqrt'), + ), ) inputs = OneSampleTTest.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_OneSampleTTest_outputs(): - output_map = dict(beta_file=dict(), - dof_file=dict(), - error_file=dict(), - error_stddev_file=dict(), - error_var_file=dict(), - estimate_file=dict(), - frame_eigenvectors=dict(), - ftest_file=dict(), - fwhm_file=dict(), - gamma_file=dict(), - gamma_var_file=dict(), - glm_dir=dict(), - mask_file=dict(), - sig_file=dict(), - singular_values=dict(), - spatial_eigenvectors=dict(), - svd_stats_file=dict(), + output_map = dict( + beta_file=dict(), + dof_file=dict(), + error_file=dict(), + error_stddev_file=dict(), + error_var_file=dict(), + estimate_file=dict(), + frame_eigenvectors=dict(), + ftest_file=dict(), + fwhm_file=dict(), + gamma_file=dict(), + gamma_var_file=dict(), + glm_dir=dict(), + mask_file=dict(), + sig_file=dict(), + singular_values=dict(), + spatial_eigenvectors=dict(), + svd_stats_file=dict(), ) outputs = OneSampleTTest.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Paint.py b/nipype/interfaces/freesurfer/tests/test_auto_Paint.py index 27d836b4f7..5a4ba970f0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Paint.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Paint.py @@ -4,48 +4,50 @@ def test_Paint_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - averages=dict(argstr='-a %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_surf=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=False, - name_source=['in_surf'], - name_template='%s.avg_curv', - position=-1, - ), - subjects_dir=dict(), - template=dict(argstr='%s', - mandatory=True, - position=-3, - ), - template_param=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + averages=dict(argstr='-a %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_surf=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=False, + name_source=['in_surf'], + name_template='%s.avg_curv', + position=-1, + ), + subjects_dir=dict(), + template=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + template_param=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Paint.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Paint_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Paint.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py b/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py index 57034c4367..14a1651a1c 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py @@ -4,87 +4,84 @@ def test_ParcellationStats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - aseg=dict(mandatory=True, - ), - brainmask=dict(mandatory=True, - ), - copy_inputs=dict(), - cortex_label=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - hemisphere=dict(argstr='%s', - mandatory=True, - position=-2, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_annotation=dict(argstr='-a %s', - xor=['in_label'], - ), - in_cortex=dict(argstr='-cortex %s', - ), - in_label=dict(argstr='-l %s', - xor=['in_annotatoin', 'out_color'], - ), - lh_pial=dict(mandatory=True, - ), - lh_white=dict(mandatory=True, - ), - mgz=dict(argstr='-mgz', - ), - out_color=dict(argstr='-c %s', - genfile=True, - xor=['in_label'], - ), - out_table=dict(argstr='-f %s', - genfile=True, - requires=['tabular_output'], - ), - rh_pial=dict(mandatory=True, - ), - rh_white=dict(mandatory=True, - ), - ribbon=dict(mandatory=True, - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=-3, - usedefault=True, - ), - subjects_dir=dict(), - surface=dict(argstr='%s', - position=-1, - ), - tabular_output=dict(argstr='-b', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - th3=dict(argstr='-th3', - requires=['cortex_label'], - ), - thickness=dict(mandatory=True, - ), - transform=dict(mandatory=True, - ), - wm=dict(mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + aseg=dict(mandatory=True, ), + brainmask=dict(mandatory=True, ), + copy_inputs=dict(), + cortex_label=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_annotation=dict( + argstr='-a %s', + xor=['in_label'], + ), + in_cortex=dict(argstr='-cortex %s', ), + in_label=dict( + argstr='-l %s', + xor=['in_annotatoin', 'out_color'], + ), + lh_pial=dict(mandatory=True, ), + lh_white=dict(mandatory=True, ), + mgz=dict(argstr='-mgz', ), + out_color=dict( + argstr='-c %s', + genfile=True, + xor=['in_label'], + ), + out_table=dict( + argstr='-f %s', + genfile=True, + requires=['tabular_output'], + ), + rh_pial=dict(mandatory=True, ), + rh_white=dict(mandatory=True, ), + ribbon=dict(mandatory=True, ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=-3, + usedefault=True, + ), + subjects_dir=dict(), + surface=dict( + argstr='%s', + position=-1, + ), + tabular_output=dict(argstr='-b', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + th3=dict( + argstr='-th3', + requires=['cortex_label'], + ), + thickness=dict(mandatory=True, ), + transform=dict(mandatory=True, ), + wm=dict(mandatory=True, ), ) inputs = ParcellationStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ParcellationStats_outputs(): - output_map = dict(out_color=dict(), - out_table=dict(), + output_map = dict( + out_color=dict(), + out_table=dict(), ) outputs = ParcellationStats.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py b/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py index 59c1d931d9..c9f3ddce39 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py @@ -4,40 +4,40 @@ def test_ParseDICOMDir_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dicom_dir=dict(argstr='--d %s', - mandatory=True, - ), - dicom_info_file=dict(argstr='--o %s', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - sortbyrun=dict(argstr='--sortbyrun', - ), - subjects_dir=dict(), - summarize=dict(argstr='--summarize', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dicom_dir=dict( + argstr='--d %s', + mandatory=True, + ), + dicom_info_file=dict( + argstr='--o %s', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + sortbyrun=dict(argstr='--sortbyrun', ), + subjects_dir=dict(), + summarize=dict(argstr='--summarize', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ParseDICOMDir.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ParseDICOMDir_outputs(): - output_map = dict(dicom_info_file=dict(), - ) + output_map = dict(dicom_info_file=dict(), ) outputs = ParseDICOMDir.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py b/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py index b28d035254..e82f26bff5 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py @@ -4,224 +4,193 @@ def test_ReconAll_inputs(): - input_map = dict(FLAIR_file=dict(argstr='-FLAIR %s', - min_ver='5.3.0', - ), - T1_files=dict(argstr='-i %s...', - ), - T2_file=dict(argstr='-T2 %s', - min_ver='5.3.0', - ), - args=dict(argstr='%s', - ), - big_ventricles=dict(argstr='-bigventricles', - ), - brainstem=dict(argstr='-brainstem-structures', - ), - directive=dict(argstr='-%s', - position=0, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - expert=dict(argstr='-expert %s', - ), - flags=dict(argstr='%s', - ), - hemi=dict(argstr='-hemi %s', - ), - hippocampal_subfields_T1=dict(argstr='-hippocampal-subfields-T1', - min_ver='6.0.0', - ), - hippocampal_subfields_T2=dict(argstr='-hippocampal-subfields-T2 %s %s', - min_ver='6.0.0', - ), - hires=dict(argstr='-hires', - min_ver='6.0.0', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mprage=dict(argstr='-mprage', - ), - mri_aparc2aseg=dict(xor=['expert'], - ), - mri_ca_label=dict(xor=['expert'], - ), - mri_ca_normalize=dict(xor=['expert'], - ), - mri_ca_register=dict(xor=['expert'], - ), - mri_edit_wm_with_aseg=dict(xor=['expert'], - ), - mri_em_register=dict(xor=['expert'], - ), - mri_fill=dict(xor=['expert'], - ), - mri_mask=dict(xor=['expert'], - ), - mri_normalize=dict(xor=['expert'], - ), - mri_pretess=dict(xor=['expert'], - ), - mri_remove_neck=dict(xor=['expert'], - ), - mri_segment=dict(xor=['expert'], - ), - mri_segstats=dict(xor=['expert'], - ), - mri_tessellate=dict(xor=['expert'], - ), - mri_watershed=dict(xor=['expert'], - ), - mris_anatomical_stats=dict(xor=['expert'], - ), - mris_ca_label=dict(xor=['expert'], - ), - mris_fix_topology=dict(xor=['expert'], - ), - mris_inflate=dict(xor=['expert'], - ), - mris_make_surfaces=dict(xor=['expert'], - ), - mris_register=dict(xor=['expert'], - ), - mris_smooth=dict(xor=['expert'], - ), - mris_sphere=dict(xor=['expert'], - ), - mris_surf2vol=dict(xor=['expert'], - ), - mrisp_paint=dict(xor=['expert'], - ), - openmp=dict(argstr='-openmp %d', - ), - parallel=dict(argstr='-parallel', - ), - subject_id=dict(argstr='-subjid %s', - usedefault=True, - ), - subjects_dir=dict(argstr='-sd %s', - genfile=True, - hash_files=False, - ), - talairach=dict(xor=['expert'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_FLAIR=dict(argstr='-FLAIRpial', - min_ver='5.3.0', - xor=['use_T2'], - ), - use_T2=dict(argstr='-T2pial', - min_ver='5.3.0', - xor=['use_FLAIR'], - ), - xopts=dict(argstr='-xopts-%s', - ), + input_map = dict( + FLAIR_file=dict( + argstr='-FLAIR %s', + min_ver='5.3.0', + ), + T1_files=dict(argstr='-i %s...', ), + T2_file=dict( + argstr='-T2 %s', + min_ver='5.3.0', + ), + args=dict(argstr='%s', ), + big_ventricles=dict(argstr='-bigventricles', ), + brainstem=dict(argstr='-brainstem-structures', ), + directive=dict( + argstr='-%s', + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expert=dict(argstr='-expert %s', ), + flags=dict(argstr='%s', ), + hemi=dict(argstr='-hemi %s', ), + hippocampal_subfields_T1=dict( + argstr='-hippocampal-subfields-T1', + min_ver='6.0.0', + ), + hippocampal_subfields_T2=dict( + argstr='-hippocampal-subfields-T2 %s %s', + min_ver='6.0.0', + ), + hires=dict( + argstr='-hires', + min_ver='6.0.0', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mprage=dict(argstr='-mprage', ), + mri_aparc2aseg=dict(xor=['expert'], ), + mri_ca_label=dict(xor=['expert'], ), + mri_ca_normalize=dict(xor=['expert'], ), + mri_ca_register=dict(xor=['expert'], ), + mri_edit_wm_with_aseg=dict(xor=['expert'], ), + mri_em_register=dict(xor=['expert'], ), + mri_fill=dict(xor=['expert'], ), + mri_mask=dict(xor=['expert'], ), + mri_normalize=dict(xor=['expert'], ), + mri_pretess=dict(xor=['expert'], ), + mri_remove_neck=dict(xor=['expert'], ), + mri_segment=dict(xor=['expert'], ), + mri_segstats=dict(xor=['expert'], ), + mri_tessellate=dict(xor=['expert'], ), + mri_watershed=dict(xor=['expert'], ), + mris_anatomical_stats=dict(xor=['expert'], ), + mris_ca_label=dict(xor=['expert'], ), + mris_fix_topology=dict(xor=['expert'], ), + mris_inflate=dict(xor=['expert'], ), + mris_make_surfaces=dict(xor=['expert'], ), + mris_register=dict(xor=['expert'], ), + mris_smooth=dict(xor=['expert'], ), + mris_sphere=dict(xor=['expert'], ), + mris_surf2vol=dict(xor=['expert'], ), + mrisp_paint=dict(xor=['expert'], ), + openmp=dict(argstr='-openmp %d', ), + parallel=dict(argstr='-parallel', ), + subject_id=dict( + argstr='-subjid %s', + usedefault=True, + ), + subjects_dir=dict( + argstr='-sd %s', + genfile=True, + hash_files=False, + ), + talairach=dict(xor=['expert'], ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_FLAIR=dict( + argstr='-FLAIRpial', + min_ver='5.3.0', + xor=['use_T2'], + ), + use_T2=dict( + argstr='-T2pial', + min_ver='5.3.0', + xor=['use_FLAIR'], + ), + xopts=dict(argstr='-xopts-%s', ), ) inputs = ReconAll.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ReconAll_outputs(): - output_map = dict(BA_stats=dict(altkey='BA', - loc='stats', - ), - T1=dict(loc='mri', - ), - annot=dict(altkey='*annot', - loc='label', - ), - aparc_a2009s_stats=dict(altkey='aparc.a2009s', - loc='stats', - ), - aparc_aseg=dict(altkey='aparc*aseg', - loc='mri', - ), - aparc_stats=dict(altkey='aparc', - loc='stats', - ), - area_pial=dict(altkey='area.pial', - loc='surf', - ), - aseg=dict(loc='mri', - ), - aseg_stats=dict(altkey='aseg', - loc='stats', - ), - avg_curv=dict(loc='surf', - ), - brain=dict(loc='mri', - ), - brainmask=dict(loc='mri', - ), - curv=dict(loc='surf', - ), - curv_pial=dict(altkey='curv.pial', - loc='surf', - ), - curv_stats=dict(altkey='curv', - loc='stats', - ), - entorhinal_exvivo_stats=dict(altkey='entorhinal_exvivo', - loc='stats', - ), - filled=dict(loc='mri', - ), - graymid=dict(altkey=['graymid', 'midthickness'], - loc='surf', - ), - inflated=dict(loc='surf', - ), - jacobian_white=dict(loc='surf', - ), - label=dict(altkey='*label', - loc='label', - ), - norm=dict(loc='mri', - ), - nu=dict(loc='mri', - ), - orig=dict(loc='mri', - ), - pial=dict(loc='surf', - ), - rawavg=dict(loc='mri', - ), - ribbon=dict(altkey='*ribbon', - loc='mri', - ), - smoothwm=dict(loc='surf', - ), - sphere=dict(loc='surf', - ), - sphere_reg=dict(altkey='sphere.reg', - loc='surf', - ), - subject_id=dict(), - subjects_dir=dict(), - sulc=dict(loc='surf', - ), - thickness=dict(loc='surf', - ), - volume=dict(loc='surf', - ), - white=dict(loc='surf', - ), - wm=dict(loc='mri', - ), - wmparc=dict(loc='mri', - ), - wmparc_stats=dict(altkey='wmparc', - loc='stats', - ), + output_map = dict( + BA_stats=dict( + altkey='BA', + loc='stats', + ), + T1=dict(loc='mri', ), + annot=dict( + altkey='*annot', + loc='label', + ), + aparc_a2009s_stats=dict( + altkey='aparc.a2009s', + loc='stats', + ), + aparc_aseg=dict( + altkey='aparc*aseg', + loc='mri', + ), + aparc_stats=dict( + altkey='aparc', + loc='stats', + ), + area_pial=dict( + altkey='area.pial', + loc='surf', + ), + aseg=dict(loc='mri', ), + aseg_stats=dict( + altkey='aseg', + loc='stats', + ), + avg_curv=dict(loc='surf', ), + brain=dict(loc='mri', ), + brainmask=dict(loc='mri', ), + curv=dict(loc='surf', ), + curv_pial=dict( + altkey='curv.pial', + loc='surf', + ), + curv_stats=dict( + altkey='curv', + loc='stats', + ), + entorhinal_exvivo_stats=dict( + altkey='entorhinal_exvivo', + loc='stats', + ), + filled=dict(loc='mri', ), + graymid=dict( + altkey=['graymid', 'midthickness'], + loc='surf', + ), + inflated=dict(loc='surf', ), + jacobian_white=dict(loc='surf', ), + label=dict( + altkey='*label', + loc='label', + ), + norm=dict(loc='mri', ), + nu=dict(loc='mri', ), + orig=dict(loc='mri', ), + pial=dict(loc='surf', ), + rawavg=dict(loc='mri', ), + ribbon=dict( + altkey='*ribbon', + loc='mri', + ), + smoothwm=dict(loc='surf', ), + sphere=dict(loc='surf', ), + sphere_reg=dict( + altkey='sphere.reg', + loc='surf', + ), + subject_id=dict(), + subjects_dir=dict(), + sulc=dict(loc='surf', ), + thickness=dict(loc='surf', ), + volume=dict(loc='surf', ), + white=dict(loc='surf', ), + wm=dict(loc='mri', ), + wmparc=dict(loc='mri', ), + wmparc_stats=dict( + altkey='wmparc', + loc='stats', + ), ) outputs = ReconAll.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Register.py b/nipype/interfaces/freesurfer/tests/test_auto_Register.py index fca0812be4..b8d16473e4 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Register.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Register.py @@ -4,51 +4,55 @@ def test_Register_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - curv=dict(argstr='-curv', - requires=['in_smoothwm'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_smoothwm=dict(copyfile=True, - ), - in_sulc=dict(copyfile=True, - mandatory=True, - ), - in_surf=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-3, - ), - out_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - subjects_dir=dict(), - target=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + curv=dict( + argstr='-curv', + requires=['in_smoothwm'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_smoothwm=dict(copyfile=True, ), + in_sulc=dict( + copyfile=True, + mandatory=True, + ), + in_surf=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-3, + ), + out_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + subjects_dir=dict(), + target=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Register.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Register_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Register.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py b/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py index 452cbb0cea..e124b3fdf3 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py @@ -4,47 +4,52 @@ def test_RegisterAVItoTalairach_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - out_file=dict(argstr='%s', - position=3, - usedefault=True, - ), - subjects_dir=dict(), - target=dict(argstr='%s', - mandatory=True, - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vox2vox=dict(argstr='%s', - mandatory=True, - position=2, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + out_file=dict( + argstr='%s', + position=3, + usedefault=True, + ), + subjects_dir=dict(), + target=dict( + argstr='%s', + mandatory=True, + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vox2vox=dict( + argstr='%s', + mandatory=True, + position=2, + ), ) inputs = RegisterAVItoTalairach.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegisterAVItoTalairach_outputs(): - output_map = dict(log_file=dict(usedefault=True, - ), - out_file=dict(), + output_map = dict( + log_file=dict(usedefault=True, ), + out_file=dict(), ) outputs = RegisterAVItoTalairach.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py b/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py index 7e8aa0a3a7..894377fd42 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py @@ -4,52 +4,56 @@ def test_RelabelHypointensities_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - aseg=dict(argstr='%s', - mandatory=True, - position=-3, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - lh_white=dict(copyfile=True, - mandatory=True, - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=False, - name_source=['aseg'], - name_template='%s.hypos.mgz', - position=-1, - ), - rh_white=dict(copyfile=True, - mandatory=True, - ), - subjects_dir=dict(), - surf_directory=dict(argstr='%s', - position=-2, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + aseg=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + lh_white=dict( + copyfile=True, + mandatory=True, + ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=False, + name_source=['aseg'], + name_template='%s.hypos.mgz', + position=-1, + ), + rh_white=dict( + copyfile=True, + mandatory=True, + ), + subjects_dir=dict(), + surf_directory=dict( + argstr='%s', + position=-2, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = RelabelHypointensities.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RelabelHypointensities_outputs(): - output_map = dict(out_file=dict(argstr='%s', - ), - ) + output_map = dict(out_file=dict(argstr='%s', ), ) outputs = RelabelHypointensities.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py b/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py index d3b9719662..19dc15e93c 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py @@ -4,42 +4,44 @@ def test_RemoveIntersection_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s', - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s', + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = RemoveIntersection.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RemoveIntersection_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RemoveIntersection.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py b/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py index ae697ecaab..abada8f119 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py @@ -4,51 +4,54 @@ def test_RemoveNeck_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-4, - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s_noneck', - position=-1, - ), - radius=dict(argstr='-radius %d', - ), - subjects_dir=dict(), - template=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='%s', - mandatory=True, - position=-3, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s_noneck', + position=-1, + ), + radius=dict(argstr='-radius %d', ), + subjects_dir=dict(), + template=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict( + argstr='%s', + mandatory=True, + position=-3, + ), ) inputs = RemoveNeck.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RemoveNeck_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RemoveNeck.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Resample.py b/nipype/interfaces/freesurfer/tests/test_auto_Resample.py index eea61f7cbf..6e019e7a19 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Resample.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Resample.py @@ -4,41 +4,44 @@ def test_Resample_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=-2, - ), - resampled_file=dict(argstr='-o %s', - genfile=True, - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel_size=dict(argstr='-vs %.2f %.2f %.2f', - mandatory=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=-2, + ), + resampled_file=dict( + argstr='-o %s', + genfile=True, + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel_size=dict( + argstr='-vs %.2f %.2f %.2f', + mandatory=True, + ), ) inputs = Resample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Resample_outputs(): - output_map = dict(resampled_file=dict(), - ) + output_map = dict(resampled_file=dict(), ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py b/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py index 48f121cd70..b1681aaab0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py @@ -4,101 +4,84 @@ def test_RobustRegister_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - auto_sens=dict(argstr='--satit', - mandatory=True, - xor=['outlier_sens'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - est_int_scale=dict(argstr='--iscale', - ), - force_double=dict(argstr='--doubleprec', - ), - force_float=dict(argstr='--floattype', - ), - half_source=dict(argstr='--halfmov %s', - ), - half_source_xfm=dict(argstr='--halfmovlta %s', - ), - half_targ=dict(argstr='--halfdst %s', - ), - half_targ_xfm=dict(argstr='--halfdstlta %s', - ), - half_weights=dict(argstr='--halfweights %s', - ), - high_iterations=dict(argstr='--highit %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_xfm_file=dict(argstr='--transform', - ), - init_orient=dict(argstr='--initorient', - ), - iteration_thresh=dict(argstr='--epsit %.3f', - ), - least_squares=dict(argstr='--leastsquares', - ), - mask_source=dict(argstr='--maskmov %s', - ), - mask_target=dict(argstr='--maskdst %s', - ), - max_iterations=dict(argstr='--maxit %d', - ), - no_init=dict(argstr='--noinit', - ), - no_multi=dict(argstr='--nomulti', - ), - out_reg_file=dict(argstr='--lta %s', - usedefault=True, - ), - outlier_limit=dict(argstr='--wlimit %.3f', - ), - outlier_sens=dict(argstr='--sat %.4f', - mandatory=True, - xor=['auto_sens'], - ), - registered_file=dict(argstr='--warp %s', - ), - source_file=dict(argstr='--mov %s', - mandatory=True, - ), - subjects_dir=dict(), - subsample_thresh=dict(argstr='--subsample %d', - ), - target_file=dict(argstr='--dst %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trans_only=dict(argstr='--transonly', - ), - weights_file=dict(argstr='--weights %s', - ), - write_vo2vox=dict(argstr='--vox2vox', - ), + input_map = dict( + args=dict(argstr='%s', ), + auto_sens=dict( + argstr='--satit', + mandatory=True, + xor=['outlier_sens'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + est_int_scale=dict(argstr='--iscale', ), + force_double=dict(argstr='--doubleprec', ), + force_float=dict(argstr='--floattype', ), + half_source=dict(argstr='--halfmov %s', ), + half_source_xfm=dict(argstr='--halfmovlta %s', ), + half_targ=dict(argstr='--halfdst %s', ), + half_targ_xfm=dict(argstr='--halfdstlta %s', ), + half_weights=dict(argstr='--halfweights %s', ), + high_iterations=dict(argstr='--highit %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_xfm_file=dict(argstr='--transform', ), + init_orient=dict(argstr='--initorient', ), + iteration_thresh=dict(argstr='--epsit %.3f', ), + least_squares=dict(argstr='--leastsquares', ), + mask_source=dict(argstr='--maskmov %s', ), + mask_target=dict(argstr='--maskdst %s', ), + max_iterations=dict(argstr='--maxit %d', ), + no_init=dict(argstr='--noinit', ), + no_multi=dict(argstr='--nomulti', ), + out_reg_file=dict( + argstr='--lta %s', + usedefault=True, + ), + outlier_limit=dict(argstr='--wlimit %.3f', ), + outlier_sens=dict( + argstr='--sat %.4f', + mandatory=True, + xor=['auto_sens'], + ), + registered_file=dict(argstr='--warp %s', ), + source_file=dict( + argstr='--mov %s', + mandatory=True, + ), + subjects_dir=dict(), + subsample_thresh=dict(argstr='--subsample %d', ), + target_file=dict( + argstr='--dst %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trans_only=dict(argstr='--transonly', ), + weights_file=dict(argstr='--weights %s', ), + write_vo2vox=dict(argstr='--vox2vox', ), ) inputs = RobustRegister.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RobustRegister_outputs(): - output_map = dict(half_source=dict(), - half_source_xfm=dict(), - half_targ=dict(), - half_targ_xfm=dict(), - half_weights=dict(), - out_reg_file=dict(), - registered_file=dict(), - weights_file=dict(), + output_map = dict( + half_source=dict(), + half_source_xfm=dict(), + half_targ=dict(), + half_targ_xfm=dict(), + half_weights=dict(), + out_reg_file=dict(), + registered_file=dict(), + weights_file=dict(), ) outputs = RobustRegister.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py b/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py index c4fa30271b..bde671c699 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py @@ -4,67 +4,63 @@ def test_RobustTemplate_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - auto_detect_sensitivity=dict(argstr='--satit', - mandatory=True, - xor=['outlier_sensitivity'], - ), - average_metric=dict(argstr='--average %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_timepoint=dict(argstr='--fixtp', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='--mov %s', - mandatory=True, - ), - in_intensity_scales=dict(argstr='--iscalein %s', - ), - initial_timepoint=dict(argstr='--inittp %d', - ), - initial_transforms=dict(argstr='--ixforms %s', - ), - intensity_scaling=dict(argstr='--iscale', - ), - no_iteration=dict(argstr='--noit', - ), - num_threads=dict(), - out_file=dict(argstr='--template %s', - mandatory=True, - usedefault=True, - ), - outlier_sensitivity=dict(argstr='--sat %.4f', - mandatory=True, - xor=['auto_detect_sensitivity'], - ), - scaled_intensity_outputs=dict(argstr='--iscaleout %s', - ), - subjects_dir=dict(), - subsample_threshold=dict(argstr='--subsample %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform_outputs=dict(argstr='--lta %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + auto_detect_sensitivity=dict( + argstr='--satit', + mandatory=True, + xor=['outlier_sensitivity'], + ), + average_metric=dict(argstr='--average %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_timepoint=dict(argstr='--fixtp', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='--mov %s', + mandatory=True, + ), + in_intensity_scales=dict(argstr='--iscalein %s', ), + initial_timepoint=dict(argstr='--inittp %d', ), + initial_transforms=dict(argstr='--ixforms %s', ), + intensity_scaling=dict(argstr='--iscale', ), + no_iteration=dict(argstr='--noit', ), + num_threads=dict(), + out_file=dict( + argstr='--template %s', + mandatory=True, + usedefault=True, + ), + outlier_sensitivity=dict( + argstr='--sat %.4f', + mandatory=True, + xor=['auto_detect_sensitivity'], + ), + scaled_intensity_outputs=dict(argstr='--iscaleout %s', ), + subjects_dir=dict(), + subsample_threshold=dict(argstr='--subsample %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform_outputs=dict(argstr='--lta %s', ), ) inputs = RobustTemplate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RobustTemplate_outputs(): - output_map = dict(out_file=dict(), - scaled_intensity_outputs=dict(), - transform_outputs=dict(), + output_map = dict( + out_file=dict(), + scaled_intensity_outputs=dict(), + transform_outputs=dict(), ) outputs = RobustTemplate.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py b/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py index e479518cf3..beb143068b 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py @@ -4,119 +4,119 @@ def test_SampleToSurface_inputs(): - input_map = dict(apply_rot=dict(argstr='--rot %.3f %.3f %.3f', - ), - apply_trans=dict(argstr='--trans %.3f %.3f %.3f', - ), - args=dict(argstr='%s', - ), - cortex_mask=dict(argstr='--cortex', - xor=['mask_label'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - fix_tk_reg=dict(argstr='--fixtkreg', - ), - float2int_method=dict(argstr='--float2int %s', - ), - frame=dict(argstr='--frame %d', - ), - hemi=dict(argstr='--hemi %s', - mandatory=True, - ), - hits_file=dict(argstr='--srchit %s', - ), - hits_type=dict(argstr='--srchit_type', - ), - ico_order=dict(argstr='--icoorder %d', - requires=['target_subject'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interp_method=dict(argstr='--interp %s', - ), - mask_label=dict(argstr='--mask %s', - xor=['cortex_mask'], - ), - mni152reg=dict(argstr='--mni152reg', - mandatory=True, - xor=['reg_file', 'reg_header', 'mni152reg'], - ), - no_reshape=dict(argstr='--noreshape', - xor=['reshape'], - ), - out_file=dict(argstr='--o %s', - genfile=True, - ), - out_type=dict(argstr='--out_type %s', - ), - override_reg_subj=dict(argstr='--srcsubject %s', - requires=['subject_id'], - ), - projection_stem=dict(mandatory=True, - xor=['sampling_method'], - ), - reference_file=dict(argstr='--ref %s', - ), - reg_file=dict(argstr='--reg %s', - mandatory=True, - xor=['reg_file', 'reg_header', 'mni152reg'], - ), - reg_header=dict(argstr='--regheader %s', - mandatory=True, - requires=['subject_id'], - xor=['reg_file', 'reg_header', 'mni152reg'], - ), - reshape=dict(argstr='--reshape', - xor=['no_reshape'], - ), - reshape_slices=dict(argstr='--rf %d', - ), - sampling_method=dict(argstr='%s', - mandatory=True, - requires=['sampling_range', 'sampling_units'], - xor=['projection_stem'], - ), - sampling_range=dict(), - sampling_units=dict(), - scale_input=dict(argstr='--scale %.3f', - ), - smooth_surf=dict(argstr='--surf-fwhm %.3f', - ), - smooth_vol=dict(argstr='--fwhm %.3f', - ), - source_file=dict(argstr='--mov %s', - mandatory=True, - ), - subject_id=dict(), - subjects_dir=dict(), - surf_reg=dict(argstr='--surfreg %s', - requires=['target_subject'], - ), - surface=dict(argstr='--surf %s', - ), - target_subject=dict(argstr='--trgsubject %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vox_file=dict(argstr='--nvox %s', - ), + input_map = dict( + apply_rot=dict(argstr='--rot %.3f %.3f %.3f', ), + apply_trans=dict(argstr='--trans %.3f %.3f %.3f', ), + args=dict(argstr='%s', ), + cortex_mask=dict( + argstr='--cortex', + xor=['mask_label'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fix_tk_reg=dict(argstr='--fixtkreg', ), + float2int_method=dict(argstr='--float2int %s', ), + frame=dict(argstr='--frame %d', ), + hemi=dict( + argstr='--hemi %s', + mandatory=True, + ), + hits_file=dict(argstr='--srchit %s', ), + hits_type=dict(argstr='--srchit_type', ), + ico_order=dict( + argstr='--icoorder %d', + requires=['target_subject'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interp_method=dict(argstr='--interp %s', ), + mask_label=dict( + argstr='--mask %s', + xor=['cortex_mask'], + ), + mni152reg=dict( + argstr='--mni152reg', + mandatory=True, + xor=['reg_file', 'reg_header', 'mni152reg'], + ), + no_reshape=dict( + argstr='--noreshape', + xor=['reshape'], + ), + out_file=dict( + argstr='--o %s', + genfile=True, + ), + out_type=dict(argstr='--out_type %s', ), + override_reg_subj=dict( + argstr='--srcsubject %s', + requires=['subject_id'], + ), + projection_stem=dict( + mandatory=True, + xor=['sampling_method'], + ), + reference_file=dict(argstr='--ref %s', ), + reg_file=dict( + argstr='--reg %s', + mandatory=True, + xor=['reg_file', 'reg_header', 'mni152reg'], + ), + reg_header=dict( + argstr='--regheader %s', + mandatory=True, + requires=['subject_id'], + xor=['reg_file', 'reg_header', 'mni152reg'], + ), + reshape=dict( + argstr='--reshape', + xor=['no_reshape'], + ), + reshape_slices=dict(argstr='--rf %d', ), + sampling_method=dict( + argstr='%s', + mandatory=True, + requires=['sampling_range', 'sampling_units'], + xor=['projection_stem'], + ), + sampling_range=dict(), + sampling_units=dict(), + scale_input=dict(argstr='--scale %.3f', ), + smooth_surf=dict(argstr='--surf-fwhm %.3f', ), + smooth_vol=dict(argstr='--fwhm %.3f', ), + source_file=dict( + argstr='--mov %s', + mandatory=True, + ), + subject_id=dict(), + subjects_dir=dict(), + surf_reg=dict( + argstr='--surfreg %s', + requires=['target_subject'], + ), + surface=dict(argstr='--surf %s', ), + target_subject=dict(argstr='--trgsubject %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vox_file=dict(argstr='--nvox %s', ), ) inputs = SampleToSurface.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SampleToSurface_outputs(): - output_map = dict(hits_file=dict(), - out_file=dict(), - vox_file=dict(), + output_map = dict( + hits_file=dict(), + out_file=dict(), + vox_file=dict(), ) outputs = SampleToSurface.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py b/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py index 1f329ac491..4dbbf24d3a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py @@ -4,122 +4,102 @@ def test_SegStats_inputs(): - input_map = dict(annot=dict(argstr='--annot %s %s %s', - mandatory=True, - xor=('segmentation_file', 'annot', 'surf_label'), - ), - args=dict(argstr='%s', - ), - avgwf_file=dict(argstr='--avgwfvol %s', - ), - avgwf_txt_file=dict(argstr='--avgwf %s', - ), - brain_vol=dict(argstr='--%s', - ), - brainmask_file=dict(argstr='--brainmask %s', - ), - calc_power=dict(argstr='--%s', - ), - calc_snr=dict(argstr='--snr', - ), - color_table_file=dict(argstr='--ctab %s', - xor=('color_table_file', 'default_color_table', 'gca_color_table'), - ), - cortex_vol_from_surf=dict(argstr='--surf-ctx-vol', - ), - default_color_table=dict(argstr='--ctab-default', - xor=('color_table_file', 'default_color_table', 'gca_color_table'), - ), - empty=dict(argstr='--empty', - ), - environ=dict(nohash=True, - usedefault=True, - ), - etiv=dict(argstr='--etiv', - ), - etiv_only=dict(), - euler=dict(argstr='--euler', - ), - exclude_ctx_gm_wm=dict(argstr='--excl-ctxgmwm', - ), - exclude_id=dict(argstr='--excludeid %d', - ), - frame=dict(argstr='--frame %d', - ), - gca_color_table=dict(argstr='--ctab-gca %s', - xor=('color_table_file', 'default_color_table', 'gca_color_table'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--i %s', - ), - in_intensity=dict(argstr='--in %s --in-intensity-name %s', - ), - intensity_units=dict(argstr='--in-intensity-units %s', - requires=['in_intensity'], - ), - mask_erode=dict(argstr='--maskerode %d', - ), - mask_file=dict(argstr='--mask %s', - ), - mask_frame=dict(requires=['mask_file'], - ), - mask_invert=dict(argstr='--maskinvert', - ), - mask_sign=dict(), - mask_thresh=dict(argstr='--maskthresh %f', - ), - multiply=dict(argstr='--mul %f', - ), - non_empty_only=dict(argstr='--nonempty', - ), - partial_volume_file=dict(argstr='--pv %s', - ), - segment_id=dict(argstr='--id %s...', - ), - segmentation_file=dict(argstr='--seg %s', - mandatory=True, - xor=('segmentation_file', 'annot', 'surf_label'), - ), - sf_avg_file=dict(argstr='--sfavg %s', - ), - subcort_gm=dict(argstr='--subcortgray', - ), - subjects_dir=dict(), - summary_file=dict(argstr='--sum %s', - genfile=True, - position=-1, - ), - supratent=dict(argstr='--supratent', - ), - surf_label=dict(argstr='--slabel %s %s %s', - mandatory=True, - xor=('segmentation_file', 'annot', 'surf_label'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - total_gray=dict(argstr='--totalgray', - ), - vox=dict(argstr='--vox %s', - ), - wm_vol_from_surf=dict(argstr='--surf-wm-vol', - ), + input_map = dict( + annot=dict( + argstr='--annot %s %s %s', + mandatory=True, + xor=('segmentation_file', 'annot', 'surf_label'), + ), + args=dict(argstr='%s', ), + avgwf_file=dict(argstr='--avgwfvol %s', ), + avgwf_txt_file=dict(argstr='--avgwf %s', ), + brain_vol=dict(argstr='--%s', ), + brainmask_file=dict(argstr='--brainmask %s', ), + calc_power=dict(argstr='--%s', ), + calc_snr=dict(argstr='--snr', ), + color_table_file=dict( + argstr='--ctab %s', + xor=('color_table_file', 'default_color_table', 'gca_color_table'), + ), + cortex_vol_from_surf=dict(argstr='--surf-ctx-vol', ), + default_color_table=dict( + argstr='--ctab-default', + xor=('color_table_file', 'default_color_table', 'gca_color_table'), + ), + empty=dict(argstr='--empty', ), + environ=dict( + nohash=True, + usedefault=True, + ), + etiv=dict(argstr='--etiv', ), + etiv_only=dict(), + euler=dict(argstr='--euler', ), + exclude_ctx_gm_wm=dict(argstr='--excl-ctxgmwm', ), + exclude_id=dict(argstr='--excludeid %d', ), + frame=dict(argstr='--frame %d', ), + gca_color_table=dict( + argstr='--ctab-gca %s', + xor=('color_table_file', 'default_color_table', 'gca_color_table'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(argstr='--i %s', ), + in_intensity=dict(argstr='--in %s --in-intensity-name %s', ), + intensity_units=dict( + argstr='--in-intensity-units %s', + requires=['in_intensity'], + ), + mask_erode=dict(argstr='--maskerode %d', ), + mask_file=dict(argstr='--mask %s', ), + mask_frame=dict(requires=['mask_file'], ), + mask_invert=dict(argstr='--maskinvert', ), + mask_sign=dict(), + mask_thresh=dict(argstr='--maskthresh %f', ), + multiply=dict(argstr='--mul %f', ), + non_empty_only=dict(argstr='--nonempty', ), + partial_volume_file=dict(argstr='--pv %s', ), + segment_id=dict(argstr='--id %s...', ), + segmentation_file=dict( + argstr='--seg %s', + mandatory=True, + xor=('segmentation_file', 'annot', 'surf_label'), + ), + sf_avg_file=dict(argstr='--sfavg %s', ), + subcort_gm=dict(argstr='--subcortgray', ), + subjects_dir=dict(), + summary_file=dict( + argstr='--sum %s', + genfile=True, + position=-1, + ), + supratent=dict(argstr='--supratent', ), + surf_label=dict( + argstr='--slabel %s %s %s', + mandatory=True, + xor=('segmentation_file', 'annot', 'surf_label'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + total_gray=dict(argstr='--totalgray', ), + vox=dict(argstr='--vox %s', ), + wm_vol_from_surf=dict(argstr='--surf-wm-vol', ), ) inputs = SegStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SegStats_outputs(): - output_map = dict(avgwf_file=dict(), - avgwf_txt_file=dict(), - sf_avg_file=dict(), - summary_file=dict(), + output_map = dict( + avgwf_file=dict(), + avgwf_txt_file=dict(), + sf_avg_file=dict(), + summary_file=dict(), ) outputs = SegStats.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py b/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py index 45f79b2259..f528748743 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py @@ -4,145 +4,118 @@ def test_SegStatsReconAll_inputs(): - input_map = dict(annot=dict(argstr='--annot %s %s %s', - mandatory=True, - xor=('segmentation_file', 'annot', 'surf_label'), - ), - args=dict(argstr='%s', - ), - aseg=dict(), - avgwf_file=dict(argstr='--avgwfvol %s', - ), - avgwf_txt_file=dict(argstr='--avgwf %s', - ), - brain_vol=dict(argstr='--%s', - ), - brainmask_file=dict(argstr='--brainmask %s', - ), - calc_power=dict(argstr='--%s', - ), - calc_snr=dict(argstr='--snr', - ), - color_table_file=dict(argstr='--ctab %s', - xor=('color_table_file', 'default_color_table', 'gca_color_table'), - ), - copy_inputs=dict(), - cortex_vol_from_surf=dict(argstr='--surf-ctx-vol', - ), - default_color_table=dict(argstr='--ctab-default', - xor=('color_table_file', 'default_color_table', 'gca_color_table'), - ), - empty=dict(argstr='--empty', - ), - environ=dict(nohash=True, - usedefault=True, - ), - etiv=dict(argstr='--etiv', - ), - etiv_only=dict(), - euler=dict(argstr='--euler', - ), - exclude_ctx_gm_wm=dict(argstr='--excl-ctxgmwm', - ), - exclude_id=dict(argstr='--excludeid %d', - ), - frame=dict(argstr='--frame %d', - ), - gca_color_table=dict(argstr='--ctab-gca %s', - xor=('color_table_file', 'default_color_table', 'gca_color_table'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--i %s', - ), - in_intensity=dict(argstr='--in %s --in-intensity-name %s', - ), - intensity_units=dict(argstr='--in-intensity-units %s', - requires=['in_intensity'], - ), - lh_orig_nofix=dict(mandatory=True, - ), - lh_pial=dict(mandatory=True, - ), - lh_white=dict(mandatory=True, - ), - mask_erode=dict(argstr='--maskerode %d', - ), - mask_file=dict(argstr='--mask %s', - ), - mask_frame=dict(requires=['mask_file'], - ), - mask_invert=dict(argstr='--maskinvert', - ), - mask_sign=dict(), - mask_thresh=dict(argstr='--maskthresh %f', - ), - multiply=dict(argstr='--mul %f', - ), - non_empty_only=dict(argstr='--nonempty', - ), - partial_volume_file=dict(argstr='--pv %s', - ), - presurf_seg=dict(), - rh_orig_nofix=dict(mandatory=True, - ), - rh_pial=dict(mandatory=True, - ), - rh_white=dict(mandatory=True, - ), - ribbon=dict(mandatory=True, - ), - segment_id=dict(argstr='--id %s...', - ), - segmentation_file=dict(argstr='--seg %s', - mandatory=True, - xor=('segmentation_file', 'annot', 'surf_label'), - ), - sf_avg_file=dict(argstr='--sfavg %s', - ), - subcort_gm=dict(argstr='--subcortgray', - ), - subject_id=dict(argstr='--subject %s', - mandatory=True, - usedefault=True, - ), - subjects_dir=dict(), - summary_file=dict(argstr='--sum %s', - genfile=True, - position=-1, - ), - supratent=dict(argstr='--supratent', - ), - surf_label=dict(argstr='--slabel %s %s %s', - mandatory=True, - xor=('segmentation_file', 'annot', 'surf_label'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - total_gray=dict(argstr='--totalgray', - ), - transform=dict(mandatory=True, - ), - vox=dict(argstr='--vox %s', - ), - wm_vol_from_surf=dict(argstr='--surf-wm-vol', - ), + input_map = dict( + annot=dict( + argstr='--annot %s %s %s', + mandatory=True, + xor=('segmentation_file', 'annot', 'surf_label'), + ), + args=dict(argstr='%s', ), + aseg=dict(), + avgwf_file=dict(argstr='--avgwfvol %s', ), + avgwf_txt_file=dict(argstr='--avgwf %s', ), + brain_vol=dict(argstr='--%s', ), + brainmask_file=dict(argstr='--brainmask %s', ), + calc_power=dict(argstr='--%s', ), + calc_snr=dict(argstr='--snr', ), + color_table_file=dict( + argstr='--ctab %s', + xor=('color_table_file', 'default_color_table', 'gca_color_table'), + ), + copy_inputs=dict(), + cortex_vol_from_surf=dict(argstr='--surf-ctx-vol', ), + default_color_table=dict( + argstr='--ctab-default', + xor=('color_table_file', 'default_color_table', 'gca_color_table'), + ), + empty=dict(argstr='--empty', ), + environ=dict( + nohash=True, + usedefault=True, + ), + etiv=dict(argstr='--etiv', ), + etiv_only=dict(), + euler=dict(argstr='--euler', ), + exclude_ctx_gm_wm=dict(argstr='--excl-ctxgmwm', ), + exclude_id=dict(argstr='--excludeid %d', ), + frame=dict(argstr='--frame %d', ), + gca_color_table=dict( + argstr='--ctab-gca %s', + xor=('color_table_file', 'default_color_table', 'gca_color_table'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(argstr='--i %s', ), + in_intensity=dict(argstr='--in %s --in-intensity-name %s', ), + intensity_units=dict( + argstr='--in-intensity-units %s', + requires=['in_intensity'], + ), + lh_orig_nofix=dict(mandatory=True, ), + lh_pial=dict(mandatory=True, ), + lh_white=dict(mandatory=True, ), + mask_erode=dict(argstr='--maskerode %d', ), + mask_file=dict(argstr='--mask %s', ), + mask_frame=dict(requires=['mask_file'], ), + mask_invert=dict(argstr='--maskinvert', ), + mask_sign=dict(), + mask_thresh=dict(argstr='--maskthresh %f', ), + multiply=dict(argstr='--mul %f', ), + non_empty_only=dict(argstr='--nonempty', ), + partial_volume_file=dict(argstr='--pv %s', ), + presurf_seg=dict(), + rh_orig_nofix=dict(mandatory=True, ), + rh_pial=dict(mandatory=True, ), + rh_white=dict(mandatory=True, ), + ribbon=dict(mandatory=True, ), + segment_id=dict(argstr='--id %s...', ), + segmentation_file=dict( + argstr='--seg %s', + mandatory=True, + xor=('segmentation_file', 'annot', 'surf_label'), + ), + sf_avg_file=dict(argstr='--sfavg %s', ), + subcort_gm=dict(argstr='--subcortgray', ), + subject_id=dict( + argstr='--subject %s', + mandatory=True, + usedefault=True, + ), + subjects_dir=dict(), + summary_file=dict( + argstr='--sum %s', + genfile=True, + position=-1, + ), + supratent=dict(argstr='--supratent', ), + surf_label=dict( + argstr='--slabel %s %s %s', + mandatory=True, + xor=('segmentation_file', 'annot', 'surf_label'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + total_gray=dict(argstr='--totalgray', ), + transform=dict(mandatory=True, ), + vox=dict(argstr='--vox %s', ), + wm_vol_from_surf=dict(argstr='--surf-wm-vol', ), ) inputs = SegStatsReconAll.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SegStatsReconAll_outputs(): - output_map = dict(avgwf_file=dict(), - avgwf_txt_file=dict(), - sf_avg_file=dict(), - summary_file=dict(), + output_map = dict( + avgwf_file=dict(), + avgwf_txt_file=dict(), + sf_avg_file=dict(), + summary_file=dict(), ) outputs = SegStatsReconAll.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py b/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py index b6ad0b3891..5ec97d6a8a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py @@ -4,50 +4,55 @@ def test_SegmentCC_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - copy_inputs=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-aseg %s', - mandatory=True, - ), - in_norm=dict(mandatory=True, - ), - out_file=dict(argstr='-o %s', - hash_files=False, - keep_extension=False, - name_source=['in_file'], - name_template='%s.auto.mgz', - ), - out_rotation=dict(argstr='-lta %s', - mandatory=True, - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + copy_inputs=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-aseg %s', + mandatory=True, + ), + in_norm=dict(mandatory=True, ), + out_file=dict( + argstr='-o %s', + hash_files=False, + keep_extension=False, + name_source=['in_file'], + name_template='%s.auto.mgz', + ), + out_rotation=dict( + argstr='-lta %s', + mandatory=True, + ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SegmentCC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SegmentCC_outputs(): - output_map = dict(out_file=dict(), - out_rotation=dict(), + output_map = dict( + out_file=dict(), + out_rotation=dict(), ) outputs = SegmentCC.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py b/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py index 5109680305..fe7196ff5e 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py @@ -4,38 +4,40 @@ def test_SegmentWM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SegmentWM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SegmentWM_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SegmentWM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py b/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py index 06035d71d0..9f3a2dcc29 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py @@ -4,56 +4,62 @@ def test_Smooth_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--i %s', - mandatory=True, - ), - num_iters=dict(argstr='--niters %d', - mandatory=True, - xor=['surface_fwhm'], - ), - proj_frac=dict(argstr='--projfrac %s', - xor=['proj_frac_avg'], - ), - proj_frac_avg=dict(argstr='--projfrac-avg %.2f %.2f %.2f', - xor=['proj_frac'], - ), - reg_file=dict(argstr='--reg %s', - mandatory=True, - ), - smoothed_file=dict(argstr='--o %s', - genfile=True, - ), - subjects_dir=dict(), - surface_fwhm=dict(argstr='--fwhm %f', - mandatory=True, - requires=['reg_file'], - xor=['num_iters'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vol_fwhm=dict(argstr='--vol-fwhm %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--i %s', + mandatory=True, + ), + num_iters=dict( + argstr='--niters %d', + mandatory=True, + xor=['surface_fwhm'], + ), + proj_frac=dict( + argstr='--projfrac %s', + xor=['proj_frac_avg'], + ), + proj_frac_avg=dict( + argstr='--projfrac-avg %.2f %.2f %.2f', + xor=['proj_frac'], + ), + reg_file=dict( + argstr='--reg %s', + mandatory=True, + ), + smoothed_file=dict( + argstr='--o %s', + genfile=True, + ), + subjects_dir=dict(), + surface_fwhm=dict( + argstr='--fwhm %f', + mandatory=True, + requires=['reg_file'], + xor=['num_iters'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vol_fwhm=dict(argstr='--vol-fwhm %f', ), ) inputs = Smooth.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Smooth_outputs(): - output_map = dict(smoothed_file=dict(), - ) + output_map = dict(smoothed_file=dict(), ) outputs = Smooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py b/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py index eb2d70bec1..3c2ad64b53 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py @@ -4,63 +4,53 @@ def test_SmoothTessellation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - curvature_averaging_iterations=dict(argstr='-a %d', - ), - disable_estimates=dict(argstr='-nw', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gaussian_curvature_norm_steps=dict(argstr='%d ', - ), - gaussian_curvature_smoothing_steps=dict(argstr='%d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-2, - ), - normalize_area=dict(argstr='-area', - ), - out_area_file=dict(argstr='-b %s', - ), - out_curvature_file=dict(argstr='-c %s', - ), - out_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - seed=dict(argstr='-seed %d', - ), - smoothing_iterations=dict(argstr='-n %d', - ), - snapshot_writing_iterations=dict(argstr='-w %d', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_gaussian_curvature_smoothing=dict(argstr='-g', - ), - use_momentum=dict(argstr='-m', - ), + input_map = dict( + args=dict(argstr='%s', ), + curvature_averaging_iterations=dict(argstr='-a %d', ), + disable_estimates=dict(argstr='-nw', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gaussian_curvature_norm_steps=dict(argstr='%d ', ), + gaussian_curvature_smoothing_steps=dict(argstr='%d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-2, + ), + normalize_area=dict(argstr='-area', ), + out_area_file=dict(argstr='-b %s', ), + out_curvature_file=dict(argstr='-c %s', ), + out_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + seed=dict(argstr='-seed %d', ), + smoothing_iterations=dict(argstr='-n %d', ), + snapshot_writing_iterations=dict(argstr='-w %d', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_gaussian_curvature_smoothing=dict(argstr='-g', ), + use_momentum=dict(argstr='-m', ), ) inputs = SmoothTessellation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SmoothTessellation_outputs(): - output_map = dict(surface=dict(), - ) + output_map = dict(surface=dict(), ) outputs = SmoothTessellation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py b/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py index ca5dd22c17..1ed350ee6d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py @@ -4,48 +4,47 @@ def test_Sphere_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - position=-2, - ), - in_smoothwm=dict(copyfile=True, - ), - magic=dict(argstr='-q', - ), - num_threads=dict(), - out_file=dict(argstr='%s', - hash_files=False, - name_source=['in_file'], - name_template='%s.sphere', - position=-1, - ), - seed=dict(argstr='-seed %d', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + position=-2, + ), + in_smoothwm=dict(copyfile=True, ), + magic=dict(argstr='-q', ), + num_threads=dict(), + out_file=dict( + argstr='%s', + hash_files=False, + name_source=['in_file'], + name_template='%s.sphere', + position=-1, + ), + seed=dict(argstr='-seed %d', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Sphere.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Sphere_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Sphere.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py b/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py index 54b5aab351..7942f5250a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py @@ -4,63 +4,67 @@ def test_SphericalAverage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - erode=dict(argstr='-erode %d', - ), - fname=dict(argstr='%s', - mandatory=True, - position=-5, - ), - hemisphere=dict(argstr='%s', - mandatory=True, - position=-4, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_average=dict(argstr='%s', - genfile=True, - position=-2, - ), - in_orig=dict(argstr='-orig %s', - ), - in_surf=dict(argstr='%s', - mandatory=True, - position=-3, - ), - out_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - subject_id=dict(argstr='-o %s', - mandatory=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='-t %.1f', - ), - which=dict(argstr='%s', - mandatory=True, - position=-6, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + erode=dict(argstr='-erode %d', ), + fname=dict( + argstr='%s', + mandatory=True, + position=-5, + ), + hemisphere=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_average=dict( + argstr='%s', + genfile=True, + position=-2, + ), + in_orig=dict(argstr='-orig %s', ), + in_surf=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + out_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + subject_id=dict( + argstr='-o %s', + mandatory=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='-t %.1f', ), + which=dict( + argstr='%s', + mandatory=True, + position=-6, + ), ) inputs = SphericalAverage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SphericalAverage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SphericalAverage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py b/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py index d97095b429..da83b0b9ef 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py @@ -4,65 +4,70 @@ def test_Surface2VolTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hemi=dict(argstr='--hemi %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mkmask=dict(argstr='--mkmask', - xor=['source_file'], - ), - projfrac=dict(argstr='--projfrac %s', - ), - reg_file=dict(argstr='--volreg %s', - mandatory=True, - xor=['subject_id'], - ), - source_file=dict(argstr='--surfval %s', - copyfile=False, - mandatory=True, - xor=['mkmask'], - ), - subject_id=dict(argstr='--identity %s', - xor=['reg_file'], - ), - subjects_dir=dict(argstr='--sd %s', - ), - surf_name=dict(argstr='--surf %s', - ), - template_file=dict(argstr='--template %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformed_file=dict(argstr='--outvol %s', - hash_files=False, - name_source=['source_file'], - name_template='%s_asVol.nii', - ), - vertexvol_file=dict(argstr='--vtxvol %s', - hash_files=False, - name_source=['source_file'], - name_template='%s_asVol_vertex.nii', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemi=dict( + argstr='--hemi %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mkmask=dict( + argstr='--mkmask', + xor=['source_file'], + ), + projfrac=dict(argstr='--projfrac %s', ), + reg_file=dict( + argstr='--volreg %s', + mandatory=True, + xor=['subject_id'], + ), + source_file=dict( + argstr='--surfval %s', + copyfile=False, + mandatory=True, + xor=['mkmask'], + ), + subject_id=dict( + argstr='--identity %s', + xor=['reg_file'], + ), + subjects_dir=dict(argstr='--sd %s', ), + surf_name=dict(argstr='--surf %s', ), + template_file=dict(argstr='--template %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformed_file=dict( + argstr='--outvol %s', + hash_files=False, + name_source=['source_file'], + name_template='%s_asVol.nii', + ), + vertexvol_file=dict( + argstr='--vtxvol %s', + hash_files=False, + name_source=['source_file'], + name_template='%s_asVol_vertex.nii', + ), ) inputs = Surface2VolTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Surface2VolTransform_outputs(): - output_map = dict(transformed_file=dict(), - vertexvol_file=dict(), + output_map = dict( + transformed_file=dict(), + vertexvol_file=dict(), ) outputs = Surface2VolTransform.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py index a0a18ba287..e4dd282f9a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py @@ -4,53 +4,59 @@ def test_SurfaceSmooth_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cortex=dict(argstr='--cortex', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm=dict(argstr='--fwhm %.4f', - xor=['smooth_iters'], - ), - hemi=dict(argstr='--hemi %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--sval %s', - mandatory=True, - ), - out_file=dict(argstr='--tval %s', - genfile=True, - ), - reshape=dict(argstr='--reshape', - ), - smooth_iters=dict(argstr='--smooth %d', - xor=['fwhm'], - ), - subject_id=dict(argstr='--s %s', - mandatory=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + cortex=dict( + argstr='--cortex', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr='--fwhm %.4f', + xor=['smooth_iters'], + ), + hemi=dict( + argstr='--hemi %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--sval %s', + mandatory=True, + ), + out_file=dict( + argstr='--tval %s', + genfile=True, + ), + reshape=dict(argstr='--reshape', ), + smooth_iters=dict( + argstr='--smooth %d', + xor=['fwhm'], + ), + subject_id=dict( + argstr='--s %s', + mandatory=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SurfaceSmooth.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SurfaceSmooth_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SurfaceSmooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py index b0c4a7c482..7f146550b6 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py @@ -4,107 +4,106 @@ def test_SurfaceSnapshots_inputs(): - input_map = dict(annot_file=dict(argstr='-annotation %s', - xor=['annot_name'], - ), - annot_name=dict(argstr='-annotation %s', - xor=['annot_file'], - ), - args=dict(argstr='%s', - ), - colortable=dict(argstr='-colortable %s', - ), - demean_overlay=dict(argstr='-zm', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hemi=dict(argstr='%s', - mandatory=True, - position=2, - ), - identity_reg=dict(argstr='-overlay-reg-identity', - xor=['overlay_reg', 'identity_reg', 'mni152_reg'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - invert_overlay=dict(argstr='-invphaseflag 1', - ), - label_file=dict(argstr='-label %s', - xor=['label_name'], - ), - label_name=dict(argstr='-label %s', - xor=['label_file'], - ), - label_outline=dict(argstr='-label-outline', - ), - label_under=dict(argstr='-labels-under', - ), - mni152_reg=dict(argstr='-mni152reg', - xor=['overlay_reg', 'identity_reg', 'mni152_reg'], - ), - orig_suffix=dict(argstr='-orig %s', - ), - overlay=dict(argstr='-overlay %s', - requires=['overlay_range'], - ), - overlay_range=dict(argstr='%s', - ), - overlay_range_offset=dict(argstr='-foffset %.3f', - ), - overlay_reg=dict(argstr='-overlay-reg %s', - xor=['overlay_reg', 'identity_reg', 'mni152_reg'], - ), - patch_file=dict(argstr='-patch %s', - ), - reverse_overlay=dict(argstr='-revphaseflag 1', - ), - screenshot_stem=dict(), - show_color_scale=dict(argstr='-colscalebarflag 1', - ), - show_color_text=dict(argstr='-colscaletext 1', - ), - show_curv=dict(argstr='-curv', - xor=['show_gray_curv'], - ), - show_gray_curv=dict(argstr='-gray', - xor=['show_curv'], - ), - six_images=dict(), - sphere_suffix=dict(argstr='-sphere %s', - ), - stem_template_args=dict(requires=['screenshot_stem'], - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=1, - ), - subjects_dir=dict(), - surface=dict(argstr='%s', - mandatory=True, - position=3, - ), - tcl_script=dict(argstr='%s', - genfile=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - truncate_overlay=dict(argstr='-truncphaseflag 1', - ), + input_map = dict( + annot_file=dict( + argstr='-annotation %s', + xor=['annot_name'], + ), + annot_name=dict( + argstr='-annotation %s', + xor=['annot_file'], + ), + args=dict(argstr='%s', ), + colortable=dict(argstr='-colortable %s', ), + demean_overlay=dict(argstr='-zm', ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemi=dict( + argstr='%s', + mandatory=True, + position=2, + ), + identity_reg=dict( + argstr='-overlay-reg-identity', + xor=['overlay_reg', 'identity_reg', 'mni152_reg'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + invert_overlay=dict(argstr='-invphaseflag 1', ), + label_file=dict( + argstr='-label %s', + xor=['label_name'], + ), + label_name=dict( + argstr='-label %s', + xor=['label_file'], + ), + label_outline=dict(argstr='-label-outline', ), + label_under=dict(argstr='-labels-under', ), + mni152_reg=dict( + argstr='-mni152reg', + xor=['overlay_reg', 'identity_reg', 'mni152_reg'], + ), + orig_suffix=dict(argstr='-orig %s', ), + overlay=dict( + argstr='-overlay %s', + requires=['overlay_range'], + ), + overlay_range=dict(argstr='%s', ), + overlay_range_offset=dict(argstr='-foffset %.3f', ), + overlay_reg=dict( + argstr='-overlay-reg %s', + xor=['overlay_reg', 'identity_reg', 'mni152_reg'], + ), + patch_file=dict(argstr='-patch %s', ), + reverse_overlay=dict(argstr='-revphaseflag 1', ), + screenshot_stem=dict(), + show_color_scale=dict(argstr='-colscalebarflag 1', ), + show_color_text=dict(argstr='-colscaletext 1', ), + show_curv=dict( + argstr='-curv', + xor=['show_gray_curv'], + ), + show_gray_curv=dict( + argstr='-gray', + xor=['show_curv'], + ), + six_images=dict(), + sphere_suffix=dict(argstr='-sphere %s', ), + stem_template_args=dict(requires=['screenshot_stem'], ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=1, + ), + subjects_dir=dict(), + surface=dict( + argstr='%s', + mandatory=True, + position=3, + ), + tcl_script=dict( + argstr='%s', + genfile=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + truncate_overlay=dict(argstr='-truncphaseflag 1', ), ) inputs = SurfaceSnapshots.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SurfaceSnapshots_outputs(): - output_map = dict(snapshots=dict(), - ) + output_map = dict(snapshots=dict(), ) outputs = SurfaceSnapshots.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py index fd3cb37931..714208568d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py @@ -4,61 +4,64 @@ def test_SurfaceTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hemi=dict(argstr='--hemi %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_file=dict(argstr='--tval %s', - genfile=True, - ), - reshape=dict(argstr='--reshape', - ), - reshape_factor=dict(argstr='--reshape-factor', - ), - source_annot_file=dict(argstr='--sval-annot %s', - mandatory=True, - xor=['source_file'], - ), - source_file=dict(argstr='--sval %s', - mandatory=True, - xor=['source_annot_file'], - ), - source_subject=dict(argstr='--srcsubject %s', - mandatory=True, - ), - source_type=dict(argstr='--sfmt %s', - requires=['source_file'], - ), - subjects_dir=dict(), - target_ico_order=dict(argstr='--trgicoorder %d', - ), - target_subject=dict(argstr='--trgsubject %s', - mandatory=True, - ), - target_type=dict(argstr='--tfmt %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemi=dict( + argstr='--hemi %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='--tval %s', + genfile=True, + ), + reshape=dict(argstr='--reshape', ), + reshape_factor=dict(argstr='--reshape-factor', ), + source_annot_file=dict( + argstr='--sval-annot %s', + mandatory=True, + xor=['source_file'], + ), + source_file=dict( + argstr='--sval %s', + mandatory=True, + xor=['source_annot_file'], + ), + source_subject=dict( + argstr='--srcsubject %s', + mandatory=True, + ), + source_type=dict( + argstr='--sfmt %s', + requires=['source_file'], + ), + subjects_dir=dict(), + target_ico_order=dict(argstr='--trgicoorder %d', ), + target_subject=dict( + argstr='--trgsubject %s', + mandatory=True, + ), + target_type=dict(argstr='--tfmt %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SurfaceTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SurfaceTransform_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SurfaceTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py b/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py index 6c96565317..73c00988b1 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py @@ -4,56 +4,63 @@ def test_SynthesizeFLASH_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixed_weighting=dict(argstr='-w', - position=1, - ), - flip_angle=dict(argstr='%.2f', - mandatory=True, - position=3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_file=dict(argstr='%s', - genfile=True, - ), - pd_image=dict(argstr='%s', - mandatory=True, - position=6, - ), - subjects_dir=dict(), - t1_image=dict(argstr='%s', - mandatory=True, - position=5, - ), - te=dict(argstr='%.3f', - mandatory=True, - position=4, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tr=dict(argstr='%.2f', - mandatory=True, - position=2, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_weighting=dict( + argstr='-w', + position=1, + ), + flip_angle=dict( + argstr='%.2f', + mandatory=True, + position=3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='%s', + genfile=True, + ), + pd_image=dict( + argstr='%s', + mandatory=True, + position=6, + ), + subjects_dir=dict(), + t1_image=dict( + argstr='%s', + mandatory=True, + position=5, + ), + te=dict( + argstr='%.3f', + mandatory=True, + position=4, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tr=dict( + argstr='%.2f', + mandatory=True, + position=2, + ), ) inputs = SynthesizeFLASH.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SynthesizeFLASH_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SynthesizeFLASH.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py b/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py index f7f3136f77..70b6c3f181 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py @@ -4,39 +4,42 @@ def test_TalairachAVI_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - atlas=dict(argstr='--atlas %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--i %s', - mandatory=True, - ), - out_file=dict(argstr='--xfm %s', - mandatory=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + atlas=dict(argstr='--atlas %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--i %s', + mandatory=True, + ), + out_file=dict( + argstr='--xfm %s', + mandatory=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TalairachAVI.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TalairachAVI_outputs(): - output_map = dict(out_file=dict(), - out_log=dict(), - out_txt=dict(), + output_map = dict( + out_file=dict(), + out_log=dict(), + out_txt=dict(), ) outputs = TalairachAVI.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py b/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py index 63ff45a3fe..dda9216579 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py @@ -4,35 +4,35 @@ def test_TalairachQC_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - log_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + log_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TalairachQC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TalairachQC_outputs(): - output_map = dict(log_file=dict(usedefault=True, - ), - ) + output_map = dict(log_file=dict(usedefault=True, ), ) outputs = TalairachQC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py b/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py index a4f018bd7e..fa61b93251 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py @@ -4,71 +4,71 @@ def test_Tkregister2_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fsl_in_matrix=dict(argstr='--fsl %s', - ), - fsl_out=dict(argstr='--fslregout %s', - ), - fstal=dict(argstr='--fstal', - xor=['target_image', 'moving_image', 'reg_file'], - ), - fstarg=dict(argstr='--fstarg', - xor=['target_image'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - invert_lta_in=dict(requires=['lta_in'], - ), - invert_lta_out=dict(argstr='--ltaout-inv', - requires=['lta_in'], - ), - lta_in=dict(argstr='--lta %s', - ), - lta_out=dict(argstr='--ltaout %s', - ), - moving_image=dict(argstr='--mov %s', - mandatory=True, - ), - movscale=dict(argstr='--movscale %f', - ), - noedit=dict(argstr='--noedit', - usedefault=True, - ), - reg_file=dict(argstr='--reg %s', - mandatory=True, - usedefault=True, - ), - reg_header=dict(argstr='--regheader', - ), - subject_id=dict(argstr='--s %s', - ), - subjects_dir=dict(), - target_image=dict(argstr='--targ %s', - xor=['fstarg'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xfm=dict(argstr='--xfm %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fsl_in_matrix=dict(argstr='--fsl %s', ), + fsl_out=dict(argstr='--fslregout %s', ), + fstal=dict( + argstr='--fstal', + xor=['target_image', 'moving_image', 'reg_file'], + ), + fstarg=dict( + argstr='--fstarg', + xor=['target_image'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + invert_lta_in=dict(requires=['lta_in'], ), + invert_lta_out=dict( + argstr='--ltaout-inv', + requires=['lta_in'], + ), + lta_in=dict(argstr='--lta %s', ), + lta_out=dict(argstr='--ltaout %s', ), + moving_image=dict( + argstr='--mov %s', + mandatory=True, + ), + movscale=dict(argstr='--movscale %f', ), + noedit=dict( + argstr='--noedit', + usedefault=True, + ), + reg_file=dict( + argstr='--reg %s', + mandatory=True, + usedefault=True, + ), + reg_header=dict(argstr='--regheader', ), + subject_id=dict(argstr='--s %s', ), + subjects_dir=dict(), + target_image=dict( + argstr='--targ %s', + xor=['fstarg'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xfm=dict(argstr='--xfm %s', ), ) inputs = Tkregister2.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Tkregister2_outputs(): - output_map = dict(fsl_file=dict(), - lta_file=dict(), - reg_file=dict(), + output_map = dict( + fsl_file=dict(), + lta_file=dict(), + reg_file=dict(), ) outputs = Tkregister2.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py b/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py index 991a0e895f..29b2065276 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py @@ -4,52 +4,51 @@ def test_UnpackSDICOMDir_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - config=dict(argstr='-cfg %s', - mandatory=True, - xor=('run_info', 'config', 'seq_config'), - ), - dir_structure=dict(argstr='-%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - log_file=dict(argstr='-log %s', - ), - no_info_dump=dict(argstr='-noinfodump', - ), - no_unpack_err=dict(argstr='-no-unpackerr', - ), - output_dir=dict(argstr='-targ %s', - ), - run_info=dict(argstr='-run %d %s %s %s', - mandatory=True, - xor=('run_info', 'config', 'seq_config'), - ), - scan_only=dict(argstr='-scanonly %s', - ), - seq_config=dict(argstr='-seqcfg %s', - mandatory=True, - xor=('run_info', 'config', 'seq_config'), - ), - source_dir=dict(argstr='-src %s', - mandatory=True, - ), - spm_zeropad=dict(argstr='-nspmzeropad %d', - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + config=dict( + argstr='-cfg %s', + mandatory=True, + xor=('run_info', 'config', 'seq_config'), + ), + dir_structure=dict(argstr='-%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + log_file=dict(argstr='-log %s', ), + no_info_dump=dict(argstr='-noinfodump', ), + no_unpack_err=dict(argstr='-no-unpackerr', ), + output_dir=dict(argstr='-targ %s', ), + run_info=dict( + argstr='-run %d %s %s %s', + mandatory=True, + xor=('run_info', 'config', 'seq_config'), + ), + scan_only=dict(argstr='-scanonly %s', ), + seq_config=dict( + argstr='-seqcfg %s', + mandatory=True, + xor=('run_info', 'config', 'seq_config'), + ), + source_dir=dict( + argstr='-src %s', + mandatory=True, + ), + spm_zeropad=dict(argstr='-nspmzeropad %d', ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = UnpackSDICOMDir.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py b/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py index 1eaed2521b..89f6299d0d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py @@ -4,64 +4,66 @@ def test_VolumeMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - aseg=dict(xor=['in_aseg'], - ), - copy_inputs=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_aseg=dict(argstr='--aseg_name %s', - xor=['aseg'], - ), - left_ribbonlabel=dict(argstr='--label_left_ribbon %d', - mandatory=True, - ), - left_whitelabel=dict(argstr='--label_left_white %d', - mandatory=True, - ), - lh_pial=dict(mandatory=True, - ), - lh_white=dict(mandatory=True, - ), - rh_pial=dict(mandatory=True, - ), - rh_white=dict(mandatory=True, - ), - right_ribbonlabel=dict(argstr='--label_right_ribbon %d', - mandatory=True, - ), - right_whitelabel=dict(argstr='--label_right_white %d', - mandatory=True, - ), - save_ribbon=dict(argstr='--save_ribbon', - ), - subject_id=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - subjects_dir=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + aseg=dict(xor=['in_aseg'], ), + copy_inputs=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_aseg=dict( + argstr='--aseg_name %s', + xor=['aseg'], + ), + left_ribbonlabel=dict( + argstr='--label_left_ribbon %d', + mandatory=True, + ), + left_whitelabel=dict( + argstr='--label_left_white %d', + mandatory=True, + ), + lh_pial=dict(mandatory=True, ), + lh_white=dict(mandatory=True, ), + rh_pial=dict(mandatory=True, ), + rh_white=dict(mandatory=True, ), + right_ribbonlabel=dict( + argstr='--label_right_ribbon %d', + mandatory=True, + ), + right_whitelabel=dict( + argstr='--label_right_white %d', + mandatory=True, + ), + save_ribbon=dict(argstr='--save_ribbon', ), + subject_id=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + subjects_dir=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = VolumeMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VolumeMask_outputs(): - output_map = dict(lh_ribbon=dict(), - out_ribbon=dict(), - rh_ribbon=dict(), + output_map = dict( + lh_ribbon=dict(), + out_ribbon=dict(), + rh_ribbon=dict(), ) outputs = VolumeMask.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py b/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py index f1f7469161..af9dceda12 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py @@ -4,47 +4,50 @@ def test_WatershedSkullStrip_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - brain_atlas=dict(argstr='-brain_atlas %s', - position=-4, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - subjects_dir=dict(), - t1=dict(argstr='-T1', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='%s', - position=-3, - ), + input_map = dict( + args=dict(argstr='%s', ), + brain_atlas=dict( + argstr='-brain_atlas %s', + position=-4, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + subjects_dir=dict(), + t1=dict(argstr='-T1', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict( + argstr='%s', + position=-3, + ), ) inputs = WatershedSkullStrip.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WatershedSkullStrip_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = WatershedSkullStrip.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_model.py b/nipype/interfaces/freesurfer/tests/test_model.py index a30a29b0ac..cd8d129690 100644 --- a/nipype/interfaces/freesurfer/tests/test_model.py +++ b/nipype/interfaces/freesurfer/tests/test_model.py @@ -31,7 +31,8 @@ def test_concatenate(tmpdir): # Test default behavior res = model.Concatenate(in_files=[in1, in2]).run() - assert res.outputs.concatenated_file == tmpdir.join('concat_output.nii.gz').strpath + assert res.outputs.concatenated_file == tmpdir.join( + 'concat_output.nii.gz').strpath assert np.allclose(nb.load('concat_output.nii.gz').get_data(), out_data) # Test specified concatenated_file @@ -41,17 +42,16 @@ def test_concatenate(tmpdir): # Test in workflow wf = pe.Workflow('test_concatenate', base_dir=tmpdir.strpath) - concat = pe.Node(model.Concatenate(in_files=[in1, in2], - concatenated_file=out), - name='concat') + concat = pe.Node( + model.Concatenate(in_files=[in1, in2], concatenated_file=out), + name='concat') wf.add_nodes([concat]) wf.run() - assert np.allclose(nb.load(tmpdir.join( - 'test_concatenate', - 'concat', out).strpath).get_data(), - out_data) + assert np.allclose( + nb.load(tmpdir.join('test_concatenate', 'concat', + out).strpath).get_data(), out_data) # Test a simple statistic - res = model.Concatenate(in_files=[in1, in2], concatenated_file=out, - stats='mean').run() + res = model.Concatenate( + in_files=[in1, in2], concatenated_file=out, stats='mean').run() assert np.allclose(nb.load(out, mmap=NUMPY_MMAP).get_data(), mean_data) diff --git a/nipype/interfaces/freesurfer/tests/test_preprocess.py b/nipype/interfaces/freesurfer/tests/test_preprocess.py index 4965329fae..a0d06884ca 100644 --- a/nipype/interfaces/freesurfer/tests/test_preprocess.py +++ b/nipype/interfaces/freesurfer/tests/test_preprocess.py @@ -12,7 +12,8 @@ from nipype import LooseVersion -@pytest.mark.skipif(freesurfer.no_freesurfer(), reason="freesurfer is not installed") +@pytest.mark.skipif( + freesurfer.no_freesurfer(), reason="freesurfer is not installed") def test_robustregister(create_files_in_directory): filelist, outdir = create_files_in_directory @@ -23,7 +24,8 @@ def test_robustregister(create_files_in_directory): assert reg.cmd == 'mri_robust_register' # test raising error with mandatory args absent - with pytest.raises(ValueError): reg.run() + with pytest.raises(ValueError): + reg.run() # .inputs based parameters setting reg.inputs.source_file = filelist[0] @@ -34,14 +36,20 @@ def test_robustregister(create_files_in_directory): (cwd, filelist[0][:-4], filelist[0], filelist[1])) # constructor based parameter setting - reg2 = freesurfer.RobustRegister(source_file=filelist[0], target_file=filelist[1], outlier_sens=3.0, - out_reg_file='foo.lta', half_targ=True) - assert reg2.cmdline == ('mri_robust_register --halfdst %s_halfway.nii --lta foo.lta ' - '--sat 3.0000 --mov %s --dst %s' - % (os.path.join(outdir, filelist[1][:-4]), filelist[0], filelist[1])) - - -@pytest.mark.skipif(freesurfer.no_freesurfer(), reason="freesurfer is not installed") + reg2 = freesurfer.RobustRegister( + source_file=filelist[0], + target_file=filelist[1], + outlier_sens=3.0, + out_reg_file='foo.lta', + half_targ=True) + assert reg2.cmdline == ( + 'mri_robust_register --halfdst %s_halfway.nii --lta foo.lta ' + '--sat 3.0000 --mov %s --dst %s' % + (os.path.join(outdir, filelist[1][:-4]), filelist[0], filelist[1])) + + +@pytest.mark.skipif( + freesurfer.no_freesurfer(), reason="freesurfer is not installed") def test_fitmsparams(create_files_in_directory): filelist, outdir = create_files_in_directory @@ -51,20 +59,28 @@ def test_fitmsparams(create_files_in_directory): assert fit.cmd == 'mri_ms_fitparms' # test raising error with mandatory args absent - with pytest.raises(ValueError): fit.run() + with pytest.raises(ValueError): + fit.run() # .inputs based parameters setting fit.inputs.in_files = filelist fit.inputs.out_dir = outdir - assert fit.cmdline == 'mri_ms_fitparms %s %s %s' % (filelist[0], filelist[1], outdir) + assert fit.cmdline == 'mri_ms_fitparms %s %s %s' % (filelist[0], + filelist[1], outdir) # constructor based parameter setting - fit2 = freesurfer.FitMSParams(in_files=filelist, te_list=[1.5, 3.5], flip_list=[20, 30], out_dir=outdir) - assert fit2.cmdline == ('mri_ms_fitparms -te %.3f -fa %.1f %s -te %.3f -fa %.1f %s %s' - % (1.500, 20.0, filelist[0], 3.500, 30.0, filelist[1], outdir)) - - -@pytest.mark.skipif(freesurfer.no_freesurfer(), reason="freesurfer is not installed") + fit2 = freesurfer.FitMSParams( + in_files=filelist, + te_list=[1.5, 3.5], + flip_list=[20, 30], + out_dir=outdir) + assert fit2.cmdline == ( + 'mri_ms_fitparms -te %.3f -fa %.1f %s -te %.3f -fa %.1f %s %s' % + (1.500, 20.0, filelist[0], 3.500, 30.0, filelist[1], outdir)) + + +@pytest.mark.skipif( + freesurfer.no_freesurfer(), reason="freesurfer is not installed") def test_synthesizeflash(create_files_in_directory): filelist, outdir = create_files_in_directory @@ -74,7 +90,8 @@ def test_synthesizeflash(create_files_in_directory): assert syn.cmd == 'mri_synthesize' # test raising error with mandatory args absent - with pytest.raises(ValueError): syn.run() + with pytest.raises(ValueError): + syn.run() # .inputs based parameters setting syn.inputs.t1_image = filelist[0] @@ -83,15 +100,20 @@ def test_synthesizeflash(create_files_in_directory): syn.inputs.te = 4.5 syn.inputs.tr = 20 - assert syn.cmdline == ('mri_synthesize 20.00 30.00 4.500 %s %s %s' - % (filelist[0], filelist[1], os.path.join(outdir, 'synth-flash_30.mgz'))) + assert syn.cmdline == ('mri_synthesize 20.00 30.00 4.500 %s %s %s' % + (filelist[0], filelist[1], + os.path.join(outdir, 'synth-flash_30.mgz'))) # constructor based parameters setting - syn2 = freesurfer.SynthesizeFLASH(t1_image=filelist[0], pd_image=filelist[1], flip_angle=20, te=5, tr=25) - assert syn2.cmdline == ('mri_synthesize 25.00 20.00 5.000 %s %s %s' - % (filelist[0], filelist[1], os.path.join(outdir, 'synth-flash_20.mgz'))) + syn2 = freesurfer.SynthesizeFLASH( + t1_image=filelist[0], pd_image=filelist[1], flip_angle=20, te=5, tr=25) + assert syn2.cmdline == ('mri_synthesize 25.00 20.00 5.000 %s %s %s' % + (filelist[0], filelist[1], + os.path.join(outdir, 'synth-flash_20.mgz'))) -@pytest.mark.skipif(freesurfer.no_freesurfer(), reason="freesurfer is not installed") + +@pytest.mark.skipif( + freesurfer.no_freesurfer(), reason="freesurfer is not installed") def test_mandatory_outvol(create_files_in_directory): filelist, outdir = create_files_in_directory mni = freesurfer.MNIBiasCorrection() @@ -100,7 +122,8 @@ def test_mandatory_outvol(create_files_in_directory): assert mni.cmd == "mri_nu_correct.mni" # test raising error with mandatory args absent - with pytest.raises(ValueError): mni.cmdline + with pytest.raises(ValueError): + mni.cmdline # test with minimal args mni.inputs.in_file = filelist[0] @@ -109,22 +132,24 @@ def test_mandatory_outvol(create_files_in_directory): base, ext2 = os.path.splitext(base) ext = ext2 + ext - assert mni.cmdline == ( - 'mri_nu_correct.mni --i %s --o %s_output%s' % (filelist[0], base, ext)) + assert mni.cmdline == ('mri_nu_correct.mni --i %s --o %s_output%s' % + (filelist[0], base, ext)) # test with custom outfile mni.inputs.out_file = 'new_corrected_file.mgz' - assert mni.cmdline == ('mri_nu_correct.mni --i %s --o new_corrected_file.mgz' - % (filelist[0])) + assert mni.cmdline == ( + 'mri_nu_correct.mni --i %s --o new_corrected_file.mgz' % (filelist[0])) # constructor based tests - mni2 = freesurfer.MNIBiasCorrection(in_file=filelist[0], - out_file='bias_corrected_output', - iterations=4) - assert mni2.cmdline == ('mri_nu_correct.mni --i %s --n 4 --o bias_corrected_output' - % filelist[0]) + mni2 = freesurfer.MNIBiasCorrection( + in_file=filelist[0], out_file='bias_corrected_output', iterations=4) + assert mni2.cmdline == ( + 'mri_nu_correct.mni --i %s --n 4 --o bias_corrected_output' % + filelist[0]) + -@pytest.mark.skipif(freesurfer.no_freesurfer(), reason="freesurfer is not installed") +@pytest.mark.skipif( + freesurfer.no_freesurfer(), reason="freesurfer is not installed") def test_bbregister(create_files_in_directory): filelist, outdir = create_files_in_directory bbr = freesurfer.BBRegister() @@ -156,7 +181,8 @@ def test_bbregister(create_files_in_directory): assert bbr.cmdline == ('bbregister --t2 --init-fsl ' '--reg {base}_bbreg_fsaverage.dat ' '--mov {full} --s fsaverage'.format( - full=filelist[0], base=base)) + full=filelist[0], base=base)) + def test_FSVersion(): """Check that FSVersion is a string that can be compared with LooseVersion diff --git a/nipype/interfaces/freesurfer/tests/test_utils.py b/nipype/interfaces/freesurfer/tests/test_utils.py index c033a1e346..f3ff8fd5ee 100644 --- a/nipype/interfaces/freesurfer/tests/test_utils.py +++ b/nipype/interfaces/freesurfer/tests/test_utils.py @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open -import os, os.path as op +import os +import os.path as op import pytest from nipype.testing.fixtures import (create_files_in_directory_plus_dummy_file, create_surf_file_in_directory) @@ -22,7 +24,8 @@ def test_sample2surf(create_files_in_directory_plus_dummy_file): assert s2s.cmd == 'mri_vol2surf' # Test mandatory args exception - with pytest.raises(ValueError): s2s.run() + with pytest.raises(ValueError): + s2s.run() # Create testing files files, cwd = create_files_in_directory_plus_dummy_file @@ -37,22 +40,27 @@ def test_sample2surf(create_files_in_directory_plus_dummy_file): s2s.inputs.sampling_method = "point" # Test a basic command line - assert s2s.cmdline == ("mri_vol2surf " - "--hemi lh --o %s --ref %s --reg reg.dat --projfrac 0.500 --mov %s" - % (os.path.join(cwd, "lh.a.mgz"), files[1], files[0])) + assert s2s.cmdline == ( + "mri_vol2surf " + "--hemi lh --o %s --ref %s --reg reg.dat --projfrac 0.500 --mov %s" % + (os.path.join(cwd, "lh.a.mgz"), files[1], files[0])) # Test identity - s2sish = fs.SampleToSurface(source_file=files[1], reference_file=files[0], hemi="rh") + s2sish = fs.SampleToSurface( + source_file=files[1], reference_file=files[0], hemi="rh") assert s2s != s2sish # Test hits file name creation s2s.inputs.hits_file = True - assert s2s._get_outfilename("hits_file") == os.path.join(cwd, "lh.a_hits.mgz") + assert s2s._get_outfilename("hits_file") == os.path.join( + cwd, "lh.a_hits.mgz") # Test that a 2-tuple range raises an error def set_illegal_range(): s2s.inputs.sampling_range = (.2, .5) - with pytest.raises(TraitError): set_illegal_range() + + with pytest.raises(TraitError): + set_illegal_range() @pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") @@ -64,7 +72,8 @@ def test_surfsmooth(create_surf_file_in_directory): assert smooth.cmd == "mri_surf2surf" # Test mandatory args exception - with pytest.raises(ValueError): smooth.run() + with pytest.raises(ValueError): + smooth.run() # Create testing files surf, cwd = create_surf_file_in_directory @@ -83,7 +92,11 @@ def test_surfsmooth(create_surf_file_in_directory): # Test identity shmooth = fs.SurfaceSmooth( - subject_id="fsaverage", fwhm=6, in_file=surf, hemi="lh", out_file="lh.a_smooth.nii") + subject_id="fsaverage", + fwhm=6, + in_file=surf, + hemi="lh", + out_file="lh.a_smooth.nii") assert smooth != shmooth @@ -96,7 +109,8 @@ def test_surfxfm(create_surf_file_in_directory): assert xfm.cmd == "mri_surf2surf" # Test mandatory args exception - with pytest.raises(ValueError): xfm.run() + with pytest.raises(ValueError): + xfm.run() # Create testing files surf, cwd = create_surf_file_in_directory @@ -114,7 +128,10 @@ def test_surfxfm(create_surf_file_in_directory): # Test identity xfmish = fs.SurfaceTransform( - source_subject="fsaverage", target_subject="my_subject", source_file=surf, hemi="lh") + source_subject="fsaverage", + target_subject="my_subject", + source_file=surf, + hemi="lh") assert xfm != xfmish @@ -127,7 +144,8 @@ def test_surfshots(create_files_in_directory_plus_dummy_file): assert fotos.cmd == "tksurfer" # Test mandatory args exception - with pytest.raises(ValueError): fotos.run() + with pytest.raises(ValueError): + fotos.run() # Create testing files files, cwd = create_files_in_directory_plus_dummy_file @@ -141,7 +159,8 @@ def test_surfshots(create_files_in_directory_plus_dummy_file): assert fotos.cmdline == "tksurfer fsaverage lh pial -tcl snapshots.tcl" # Test identity - schmotos = fs.SurfaceSnapshots(subject_id="mysubject", hemi="rh", surface="white") + schmotos = fs.SurfaceSnapshots( + subject_id="mysubject", hemi="rh", surface="white") assert fotos != schmotos # Test that the tcl script gets written @@ -157,7 +176,8 @@ def test_surfshots(create_files_in_directory_plus_dummy_file): try: hold_display = os.environ["DISPLAY"] del os.environ["DISPLAY"] - with pytest.raises(RuntimeError): fotos.run() + with pytest.raises(RuntimeError): + fotos.run() os.environ["DISPLAY"] = hold_display except KeyError: pass @@ -165,26 +185,26 @@ def test_surfshots(create_files_in_directory_plus_dummy_file): @pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") def test_mrisexpand(tmpdir): - fssrc = FreeSurferSource(subjects_dir=fs.Info.subjectsdir(), - subject_id='fsaverage', hemi='lh') + fssrc = FreeSurferSource( + subjects_dir=fs.Info.subjectsdir(), subject_id='fsaverage', hemi='lh') fsavginfo = fssrc.run().outputs.get() # dt=60 to ensure very short runtime - expand_if = fs.MRIsExpand(in_file=fsavginfo['smoothwm'], - out_name='expandtmp', - distance=1, - dt=60) + expand_if = fs.MRIsExpand( + in_file=fsavginfo['smoothwm'], out_name='expandtmp', distance=1, dt=60) expand_nd = pe.Node( - fs.MRIsExpand(in_file=fsavginfo['smoothwm'], - out_name='expandtmp', - distance=1, - dt=60), + fs.MRIsExpand( + in_file=fsavginfo['smoothwm'], + out_name='expandtmp', + distance=1, + dt=60), name='expand_node') # Interfaces should have same command line at instantiation - orig_cmdline = 'mris_expand -T 60 {} 1 expandtmp'.format(fsavginfo['smoothwm']) + orig_cmdline = 'mris_expand -T 60 {} 1 expandtmp'.format( + fsavginfo['smoothwm']) assert expand_if.cmdline == orig_cmdline assert expand_nd.interface.cmdline == orig_cmdline diff --git a/nipype/interfaces/freesurfer/utils.py b/nipype/interfaces/freesurfer/utils.py index 97ae831b26..0fdfd8bfdb 100644 --- a/nipype/interfaces/freesurfer/utils.py +++ b/nipype/interfaces/freesurfer/utils.py @@ -10,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, open import os @@ -21,25 +22,37 @@ from ...utils.filemanip import fname_presuffix, split_filename from ..base import (TraitedSpec, File, traits, OutputMultiPath, isdefined, CommandLine, CommandLineInputSpec) -from .base import (FSCommand, FSTraitedSpec, FSSurfaceCommand, - FSScriptCommand, FSScriptOutputSpec, - FSTraitedSpecOpenMP, FSCommandOpenMP) +from .base import (FSCommand, FSTraitedSpec, FSSurfaceCommand, FSScriptCommand, + FSScriptOutputSpec, FSTraitedSpecOpenMP, FSCommandOpenMP) __docformat__ = 'restructuredtext' -filemap = dict(cor='cor', mgh='mgh', mgz='mgz', minc='mnc', - afni='brik', brik='brik', bshort='bshort', - spm='img', analyze='img', analyze4d='img', - bfloat='bfloat', nifti1='img', nii='nii', - niigz='nii.gz', gii='gii') - -filetypes = ['cor', 'mgh', 'mgz', 'minc', 'analyze', - 'analyze4d', 'spm', 'afni', 'brik', 'bshort', - 'bfloat', 'sdt', 'outline', 'otl', 'gdf', - 'nifti1', 'nii', 'niigz'] +filemap = dict( + cor='cor', + mgh='mgh', + mgz='mgz', + minc='mnc', + afni='brik', + brik='brik', + bshort='bshort', + spm='img', + analyze='img', + analyze4d='img', + bfloat='bfloat', + nifti1='img', + nii='nii', + niigz='nii.gz', + gii='gii') + +filetypes = [ + 'cor', 'mgh', 'mgz', 'minc', 'analyze', 'analyze4d', 'spm', 'afni', 'brik', + 'bshort', 'bfloat', 'sdt', 'outline', 'otl', 'gdf', 'nifti1', 'nii', + 'niigz' +] implicit_filetypes = ['gii'] logger = logging.getLogger('interface') + def copy2subjdir(cls, in_file, folder=None, basename=None, subject_id=None): """Method to copy an input to the subjects directory""" # check that the input is defined @@ -49,18 +62,18 @@ def copy2subjdir(cls, in_file, folder=None, basename=None, subject_id=None): if isdefined(cls.inputs.subjects_dir): subjects_dir = cls.inputs.subjects_dir else: - subjects_dir = os.getcwd() #if not use cwd + subjects_dir = os.getcwd() # if not use cwd # check for subject_id if not subject_id: if isdefined(cls.inputs.subject_id): subject_id = cls.inputs.subject_id else: - subject_id = 'subject_id' #default + subject_id = 'subject_id' # default # check for basename - if basename == None: + if basename is None: basename = os.path.basename(in_file) # check which folder to put the file in - if folder != None: + if folder is not None: out_dir = os.path.join(subjects_dir, subject_id, folder) else: out_dir = os.path.join(subjects_dir, subject_id) @@ -72,6 +85,7 @@ def copy2subjdir(cls, in_file, folder=None, basename=None, subject_id=None): shutil.copy(in_file, out_file) return out_file + def createoutputdirs(outputs): """create all output directories. If not created, some freesurfer interfaces fail""" for output in list(outputs.values()): @@ -82,94 +96,169 @@ def createoutputdirs(outputs): class SampleToSurfaceInputSpec(FSTraitedSpec): - source_file = File(exists=True, mandatory=True, argstr="--mov %s", - desc="volume to sample values from") - reference_file = File(exists=True, argstr="--ref %s", - desc="reference volume (default is orig.mgz)") - - hemi = traits.Enum("lh", "rh", mandatory=True, argstr="--hemi %s", - desc="target hemisphere") - surface = traits.String(argstr="--surf %s", desc="target surface (default is white)") + source_file = File( + exists=True, + mandatory=True, + argstr="--mov %s", + desc="volume to sample values from") + reference_file = File( + exists=True, + argstr="--ref %s", + desc="reference volume (default is orig.mgz)") + + hemi = traits.Enum( + "lh", + "rh", + mandatory=True, + argstr="--hemi %s", + desc="target hemisphere") + surface = traits.String( + argstr="--surf %s", desc="target surface (default is white)") reg_xors = ["reg_file", "reg_header", "mni152reg"] - reg_file = File(exists=True, argstr="--reg %s", mandatory=True, xor=reg_xors, - desc="source-to-reference registration file") - reg_header = traits.Bool(argstr="--regheader %s", requires=["subject_id"], - mandatory=True, xor=reg_xors, - desc="register based on header geometry") - mni152reg = traits.Bool(argstr="--mni152reg", - mandatory=True, xor=reg_xors, - desc="source volume is in MNI152 space") - - apply_rot = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr="--rot %.3f %.3f %.3f", - desc="rotation angles (in degrees) to apply to reg matrix") - apply_trans = traits.Tuple(traits.Float, traits.Float, traits.Float, - argstr="--trans %.3f %.3f %.3f", - desc="translation (in mm) to apply to reg matrix") - override_reg_subj = traits.Bool(argstr="--srcsubject %s", requires=["subject_id"], - desc="override the subject in the reg file header") - - sampling_method = traits.Enum("point", "max", "average", - mandatory=True, argstr="%s", xor=["projection_stem"], - requires=["sampling_range", "sampling_units"], - desc="how to sample -- at a point or at the max or average over a range") - sampling_range = traits.Either(traits.Float, - traits.Tuple(traits.Float, traits.Float, traits.Float), - desc="sampling range - a point or a tuple of (min, max, step)") - sampling_units = traits.Enum("mm", "frac", desc="sampling range type -- either 'mm' or 'frac'") - projection_stem = traits.String(mandatory=True, xor=["sampling_method"], - desc="stem for precomputed linear estimates and volume fractions") - - smooth_vol = traits.Float(argstr="--fwhm %.3f", desc="smooth input volume (mm fwhm)") - smooth_surf = traits.Float(argstr="--surf-fwhm %.3f", desc="smooth output surface (mm fwhm)") - - interp_method = traits.Enum("nearest", "trilinear", argstr="--interp %s", - desc="interpolation method") - - cortex_mask = traits.Bool(argstr="--cortex", xor=["mask_label"], - desc="mask the target surface with hemi.cortex.label") - mask_label = File(exists=True, argstr="--mask %s", xor=["cortex_mask"], - desc="label file to mask output with") - - float2int_method = traits.Enum("round", "tkregister", argstr="--float2int %s", - desc="method to convert reg matrix values (default is round)") - fix_tk_reg = traits.Bool(argstr="--fixtkreg", desc="make reg matrix round-compatible") + reg_file = File( + exists=True, + argstr="--reg %s", + mandatory=True, + xor=reg_xors, + desc="source-to-reference registration file") + reg_header = traits.Bool( + argstr="--regheader %s", + requires=["subject_id"], + mandatory=True, + xor=reg_xors, + desc="register based on header geometry") + mni152reg = traits.Bool( + argstr="--mni152reg", + mandatory=True, + xor=reg_xors, + desc="source volume is in MNI152 space") + + apply_rot = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr="--rot %.3f %.3f %.3f", + desc="rotation angles (in degrees) to apply to reg matrix") + apply_trans = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr="--trans %.3f %.3f %.3f", + desc="translation (in mm) to apply to reg matrix") + override_reg_subj = traits.Bool( + argstr="--srcsubject %s", + requires=["subject_id"], + desc="override the subject in the reg file header") + + sampling_method = traits.Enum( + "point", + "max", + "average", + mandatory=True, + argstr="%s", + xor=["projection_stem"], + requires=["sampling_range", "sampling_units"], + desc="how to sample -- at a point or at the max or average over a range" + ) + sampling_range = traits.Either( + traits.Float, + traits.Tuple(traits.Float, traits.Float, traits.Float), + desc="sampling range - a point or a tuple of (min, max, step)") + sampling_units = traits.Enum( + "mm", "frac", desc="sampling range type -- either 'mm' or 'frac'") + projection_stem = traits.String( + mandatory=True, + xor=["sampling_method"], + desc="stem for precomputed linear estimates and volume fractions") + + smooth_vol = traits.Float( + argstr="--fwhm %.3f", desc="smooth input volume (mm fwhm)") + smooth_surf = traits.Float( + argstr="--surf-fwhm %.3f", desc="smooth output surface (mm fwhm)") + + interp_method = traits.Enum( + "nearest", + "trilinear", + argstr="--interp %s", + desc="interpolation method") + + cortex_mask = traits.Bool( + argstr="--cortex", + xor=["mask_label"], + desc="mask the target surface with hemi.cortex.label") + mask_label = File( + exists=True, + argstr="--mask %s", + xor=["cortex_mask"], + desc="label file to mask output with") + + float2int_method = traits.Enum( + "round", + "tkregister", + argstr="--float2int %s", + desc="method to convert reg matrix values (default is round)") + fix_tk_reg = traits.Bool( + argstr="--fixtkreg", desc="make reg matrix round-compatible") subject_id = traits.String(desc="subject id") - target_subject = traits.String(argstr="--trgsubject %s", - desc="sample to surface of different subject than source") - surf_reg = traits.Either(traits.Bool, traits.Str(), - argstr="--surfreg %s", requires=["target_subject"], - desc="use surface registration to target subject") - ico_order = traits.Int(argstr="--icoorder %d", requires=["target_subject"], - desc="icosahedron order when target_subject is 'ico'") - - reshape = traits.Bool(argstr="--reshape", xor=["no_reshape"], - desc="reshape surface vector to fit in non-mgh format") - no_reshape = traits.Bool(argstr="--noreshape", xor=["reshape"], - desc="do not reshape surface vector (default)") - reshape_slices = traits.Int(argstr="--rf %d", desc="number of 'slices' for reshaping") - scale_input = traits.Float(argstr="--scale %.3f", - desc="multiple all intensities by scale factor") - frame = traits.Int(argstr="--frame %d", desc="save only one frame (0-based)") - - out_file = File(argstr="--o %s", genfile=True, desc="surface file to write") - out_type = traits.Enum(filetypes + implicit_filetypes, - argstr="--out_type %s", desc="output file type") - hits_file = traits.Either(traits.Bool, File(exists=True), argstr="--srchit %s", - desc="save image with number of hits at each voxel") - hits_type = traits.Enum(filetypes, argstr="--srchit_type", desc="hits file type") - vox_file = traits.Either(traits.Bool, File, argstr="--nvox %s", - desc="text file with the number of voxels intersecting the surface") + target_subject = traits.String( + argstr="--trgsubject %s", + desc="sample to surface of different subject than source") + surf_reg = traits.Either( + traits.Bool, + traits.Str(), + argstr="--surfreg %s", + requires=["target_subject"], + desc="use surface registration to target subject") + ico_order = traits.Int( + argstr="--icoorder %d", + requires=["target_subject"], + desc="icosahedron order when target_subject is 'ico'") + + reshape = traits.Bool( + argstr="--reshape", + xor=["no_reshape"], + desc="reshape surface vector to fit in non-mgh format") + no_reshape = traits.Bool( + argstr="--noreshape", + xor=["reshape"], + desc="do not reshape surface vector (default)") + reshape_slices = traits.Int( + argstr="--rf %d", desc="number of 'slices' for reshaping") + scale_input = traits.Float( + argstr="--scale %.3f", desc="multiple all intensities by scale factor") + frame = traits.Int( + argstr="--frame %d", desc="save only one frame (0-based)") + + out_file = File( + argstr="--o %s", genfile=True, desc="surface file to write") + out_type = traits.Enum( + filetypes + implicit_filetypes, + argstr="--out_type %s", + desc="output file type") + hits_file = traits.Either( + traits.Bool, + File(exists=True), + argstr="--srchit %s", + desc="save image with number of hits at each voxel") + hits_type = traits.Enum( + filetypes, argstr="--srchit_type", desc="hits file type") + vox_file = traits.Either( + traits.Bool, + File, + argstr="--nvox %s", + desc="text file with the number of voxels intersecting the surface") class SampleToSurfaceOutputSpec(TraitedSpec): out_file = File(exists=True, desc="surface file") - hits_file = File(exists=True, desc="image with number of hits at each voxel") - vox_file = File(exists=True, - desc="text file with the number of voxels intersecting the surface") + hits_file = File( + exists=True, desc="image with number of hits at each voxel") + vox_file = File( + exists=True, + desc="text file with the number of voxels intersecting the surface") class SampleToSurface(FSCommand): @@ -257,11 +346,12 @@ def _get_outfilename(self, opt="out_file"): suffix = "_hits.mgz" else: suffix = '.mgz' - outfile = fname_presuffix(self.inputs.source_file, - newpath=os.getcwd(), - prefix=self.inputs.hemi + ".", - suffix=suffix, - use_ext=False) + outfile = fname_presuffix( + self.inputs.source_file, + newpath=os.getcwd(), + prefix=self.inputs.hemi + ".", + suffix=suffix, + use_ext=False) return outfile def _list_outputs(self): @@ -275,11 +365,12 @@ def _list_outputs(self): voxfile = self.inputs.vox_file if isdefined(voxfile): if isinstance(voxfile, bool): - voxfile = fname_presuffix(self.inputs.source_file, - newpath=os.getcwd(), - prefix=self.inputs.hemi + ".", - suffix="_vox.txt", - use_ext=False) + voxfile = fname_presuffix( + self.inputs.source_file, + newpath=os.getcwd(), + prefix=self.inputs.hemi + ".", + suffix="_vox.txt", + use_ext=False) outputs["vox_file"] = voxfile return outputs @@ -291,17 +382,34 @@ def _gen_filename(self, name): class SurfaceSmoothInputSpec(FSTraitedSpec): - in_file = File(mandatory=True, argstr="--sval %s", desc="source surface file") - subject_id = traits.String(mandatory=True, argstr="--s %s", desc="subject id of surface file") - hemi = traits.Enum("lh", "rh", argstr="--hemi %s", mandatory=True, desc="hemisphere to operate on") - fwhm = traits.Float(argstr="--fwhm %.4f", xor=["smooth_iters"], - desc="effective FWHM of the smoothing process") - smooth_iters = traits.Int(argstr="--smooth %d", xor=["fwhm"], - desc="iterations of the smoothing process") - cortex = traits.Bool(True, argstr="--cortex", usedefault=True, desc="only smooth within $hemi.cortex.label") - reshape = traits.Bool(argstr="--reshape", - desc="reshape surface vector to fit in non-mgh format") - out_file = File(argstr="--tval %s", genfile=True, desc="surface file to write") + in_file = File( + mandatory=True, argstr="--sval %s", desc="source surface file") + subject_id = traits.String( + mandatory=True, argstr="--s %s", desc="subject id of surface file") + hemi = traits.Enum( + "lh", + "rh", + argstr="--hemi %s", + mandatory=True, + desc="hemisphere to operate on") + fwhm = traits.Float( + argstr="--fwhm %.4f", + xor=["smooth_iters"], + desc="effective FWHM of the smoothing process") + smooth_iters = traits.Int( + argstr="--smooth %d", + xor=["fwhm"], + desc="iterations of the smoothing process") + cortex = traits.Bool( + True, + argstr="--cortex", + usedefault=True, + desc="only smooth within $hemi.cortex.label") + reshape = traits.Bool( + argstr="--reshape", + desc="reshape surface vector to fit in non-mgh format") + out_file = File( + argstr="--tval %s", genfile=True, desc="surface file to write") class SurfaceSmoothOutputSpec(TraitedSpec): @@ -350,9 +458,8 @@ def _list_outputs(self): kernel = self.inputs.fwhm else: kernel = self.inputs.smooth_iters - outputs["out_file"] = fname_presuffix(in_file, - suffix="_smooth%d" % kernel, - newpath=os.getcwd()) + outputs["out_file"] = fname_presuffix( + in_file, suffix="_smooth%d" % kernel, newpath=os.getcwd()) return outputs def _gen_filename(self, name): @@ -362,34 +469,59 @@ def _gen_filename(self, name): class SurfaceTransformInputSpec(FSTraitedSpec): - source_file = File(exists=True, mandatory=True, argstr="--sval %s", - xor=['source_annot_file'], - desc="surface file with source values") - source_annot_file = File(exists=True, mandatory=True, - argstr="--sval-annot %s", - xor=['source_file'], - desc="surface annotation file") - source_subject = traits.String(mandatory=True, argstr="--srcsubject %s", - desc="subject id for source surface") - hemi = traits.Enum("lh", "rh", argstr="--hemi %s", mandatory=True, - desc="hemisphere to transform") - target_subject = traits.String(mandatory=True, argstr="--trgsubject %s", - desc="subject id of target surface") - target_ico_order = traits.Enum(1, 2, 3, 4, 5, 6, 7, - argstr="--trgicoorder %d", - desc=("order of the icosahedron if " - "target_subject is 'ico'")) - source_type = traits.Enum(filetypes, argstr='--sfmt %s', - requires=['source_file'], - desc="source file format") - target_type = traits.Enum(filetypes + implicit_filetypes, argstr='--tfmt %s', - desc="output format") - reshape = traits.Bool(argstr="--reshape", - desc="reshape output surface to conform with Nifti") - reshape_factor = traits.Int(argstr="--reshape-factor", - desc="number of slices in reshaped image") - out_file = File(argstr="--tval %s", genfile=True, - desc="surface file to write") + source_file = File( + exists=True, + mandatory=True, + argstr="--sval %s", + xor=['source_annot_file'], + desc="surface file with source values") + source_annot_file = File( + exists=True, + mandatory=True, + argstr="--sval-annot %s", + xor=['source_file'], + desc="surface annotation file") + source_subject = traits.String( + mandatory=True, + argstr="--srcsubject %s", + desc="subject id for source surface") + hemi = traits.Enum( + "lh", + "rh", + argstr="--hemi %s", + mandatory=True, + desc="hemisphere to transform") + target_subject = traits.String( + mandatory=True, + argstr="--trgsubject %s", + desc="subject id of target surface") + target_ico_order = traits.Enum( + 1, + 2, + 3, + 4, + 5, + 6, + 7, + argstr="--trgicoorder %d", + desc=("order of the icosahedron if " + "target_subject is 'ico'")) + source_type = traits.Enum( + filetypes, + argstr='--sfmt %s', + requires=['source_file'], + desc="source file format") + target_type = traits.Enum( + filetypes + implicit_filetypes, + argstr='--tfmt %s', + desc="output format") + reshape = traits.Bool( + argstr="--reshape", + desc="reshape output surface to conform with Nifti") + reshape_factor = traits.Int( + argstr="--reshape-factor", desc="number of slices in reshaped image") + out_file = File( + argstr="--tval %s", genfile=True, desc="surface file to write") class SurfaceTransformOutputSpec(TraitedSpec): @@ -446,9 +578,13 @@ def _list_outputs(self): # Some recon-all files don't have a proper extension (e.g. "lh.thickness") # so we have to account for that here - bad_extensions = [".%s" % e for e in ["area", "mid", "pial", "avg_curv", "curv", "inflated", - "jacobian_white", "orig", "nofix", "smoothwm", "crv", - "sphere", "sulc", "thickness", "volume", "white"]] + bad_extensions = [ + ".%s" % e for e in [ + "area", "mid", "pial", "avg_curv", "curv", "inflated", + "jacobian_white", "orig", "nofix", "smoothwm", "crv", + "sphere", "sulc", "thickness", "volume", "white" + ] + ] use_ext = True if split_filename(source)[2] in bad_extensions: source = source + ".stripme" @@ -457,10 +593,11 @@ def _list_outputs(self): if isdefined(self.inputs.target_type): ext = "." + filemap[self.inputs.target_type] use_ext = False - outputs["out_file"] = fname_presuffix(source, - suffix=".%s%s" % (self.inputs.target_subject, ext), - newpath=os.getcwd(), - use_ext=use_ext) + outputs["out_file"] = fname_presuffix( + source, + suffix=".%s%s" % (self.inputs.target_subject, ext), + newpath=os.getcwd(), + use_ext=use_ext) else: outputs["out_file"] = os.path.abspath(self.inputs.out_file) return outputs @@ -472,42 +609,56 @@ def _gen_filename(self, name): class Surface2VolTransformInputSpec(FSTraitedSpec): - source_file = File(exists=True, argstr='--surfval %s', - copyfile=False, mandatory=True, xor=['mkmask'], - desc='This is the source of the surface values') - hemi = traits.Str(argstr='--hemi %s', mandatory=True, - desc='hemisphere of data') - transformed_file = File(name_template="%s_asVol.nii", desc='Output volume', - argstr='--outvol %s', - name_source=['source_file'], hash_files=False) - reg_file = File(exists=True, argstr='--volreg %s', - mandatory=True, - desc='tkRAS-to-tkRAS matrix (tkregister2 format)', - xor=['subject_id']) - template_file = File(exists=True, argstr='--template %s', - desc='Output template volume') - mkmask = traits.Bool(desc='make a mask instead of loading surface values', - argstr='--mkmask', xor=['source_file']) - vertexvol_file = File(name_template="%s_asVol_vertex.nii", - desc=('Path name of the vertex output volume, which ' - 'is the same as output volume except that the ' - 'value of each voxel is the vertex-id that is ' - 'mapped to that voxel.'), - argstr='--vtxvol %s', name_source=['source_file'], - hash_files=False) - surf_name = traits.Str(argstr='--surf %s', - desc='surfname (default is white)') + source_file = File( + exists=True, + argstr='--surfval %s', + copyfile=False, + mandatory=True, + xor=['mkmask'], + desc='This is the source of the surface values') + hemi = traits.Str( + argstr='--hemi %s', mandatory=True, desc='hemisphere of data') + transformed_file = File( + name_template="%s_asVol.nii", + desc='Output volume', + argstr='--outvol %s', + name_source=['source_file'], + hash_files=False) + reg_file = File( + exists=True, + argstr='--volreg %s', + mandatory=True, + desc='tkRAS-to-tkRAS matrix (tkregister2 format)', + xor=['subject_id']) + template_file = File( + exists=True, argstr='--template %s', desc='Output template volume') + mkmask = traits.Bool( + desc='make a mask instead of loading surface values', + argstr='--mkmask', + xor=['source_file']) + vertexvol_file = File( + name_template="%s_asVol_vertex.nii", + desc=('Path name of the vertex output volume, which ' + 'is the same as output volume except that the ' + 'value of each voxel is the vertex-id that is ' + 'mapped to that voxel.'), + argstr='--vtxvol %s', + name_source=['source_file'], + hash_files=False) + surf_name = traits.Str( + argstr='--surf %s', desc='surfname (default is white)') projfrac = traits.Float(argstr='--projfrac %s', desc='thickness fraction') - subjects_dir = traits.Str(argstr='--sd %s', - desc=('freesurfer subjects directory defaults to ' - '$SUBJECTS_DIR')) - subject_id = traits.Str(argstr='--identity %s', desc='subject id', - xor=['reg_file']) + subjects_dir = traits.Str( + argstr='--sd %s', + desc=('freesurfer subjects directory defaults to ' + '$SUBJECTS_DIR')) + subject_id = traits.Str( + argstr='--identity %s', desc='subject id', xor=['reg_file']) class Surface2VolTransformOutputSpec(TraitedSpec): - transformed_file = File(exists=True, - desc='Path to output file if used normally') + transformed_file = File( + exists=True, desc='Path to output file if used normally') vertexvol_file = File(desc='vertex map volume path id. Optional') @@ -537,26 +688,49 @@ class Surface2VolTransform(FSCommand): class ApplyMaskInputSpec(FSTraitedSpec): - in_file = File(exists=True, mandatory=True, position=-3, argstr="%s", - desc="input image (will be masked)") - mask_file = File(exists=True, mandatory=True, position=-2, argstr="%s", - desc="image defining mask space") - out_file = File(name_source=['in_file'], name_template='%s_masked', - hash_files=True, keep_extension=True, - position=-1, argstr="%s", - desc="final image to write") - xfm_file = File(exists=True, argstr="-xform %s", - desc="LTA-format transformation matrix to align mask with input") + in_file = File( + exists=True, + mandatory=True, + position=-3, + argstr="%s", + desc="input image (will be masked)") + mask_file = File( + exists=True, + mandatory=True, + position=-2, + argstr="%s", + desc="image defining mask space") + out_file = File( + name_source=['in_file'], + name_template='%s_masked', + hash_files=True, + keep_extension=True, + position=-1, + argstr="%s", + desc="final image to write") + xfm_file = File( + exists=True, + argstr="-xform %s", + desc="LTA-format transformation matrix to align mask with input") invert_xfm = traits.Bool(argstr="-invert", desc="invert transformation") - xfm_source = File(exists=True, argstr="-lta_src %s", desc="image defining transform source space") - xfm_target = File(exists=True, argstr="-lta_dst %s", desc="image defining transform target space") - use_abs = traits.Bool(argstr="-abs", desc="take absolute value of mask before applying") - mask_thresh = traits.Float(argstr="-T %.4f", desc="threshold mask before applying") + xfm_source = File( + exists=True, + argstr="-lta_src %s", + desc="image defining transform source space") + xfm_target = File( + exists=True, + argstr="-lta_dst %s", + desc="image defining transform target space") + use_abs = traits.Bool( + argstr="-abs", desc="take absolute value of mask before applying") + mask_thresh = traits.Float( + argstr="-T %.4f", desc="threshold mask before applying") keep_mask_deletion_edits = traits.Bool( argstr="-keep_mask_deletion_edits", desc="transfer voxel-deletion edits (voxels=1) from mask to out vol") - transfer = traits.Int(argstr="-transfer %d", - desc="transfer only voxel value # from mask to out") + transfer = traits.Int( + argstr="-transfer %d", + desc="transfer only voxel value # from mask to out") class ApplyMaskOutputSpec(TraitedSpec): @@ -579,78 +753,121 @@ class ApplyMask(FSCommand): class SurfaceSnapshotsInputSpec(FSTraitedSpec): - subject_id = traits.String(position=1, argstr="%s", mandatory=True, - desc="subject to visualize") - hemi = traits.Enum("lh", "rh", position=2, argstr="%s", mandatory=True, - desc="hemisphere to visualize") - surface = traits.String(position=3, argstr="%s", mandatory=True, - desc="surface to visualize") - - show_curv = traits.Bool(argstr="-curv", desc="show curvature", xor=["show_gray_curv"]) - show_gray_curv = traits.Bool(argstr="-gray", desc="show curvature in gray", xor=["show_curv"]) - - overlay = File(exists=True, argstr="-overlay %s", desc="load an overlay volume/surface", - requires=["overlay_range"]) + subject_id = traits.String( + position=1, argstr="%s", mandatory=True, desc="subject to visualize") + hemi = traits.Enum( + "lh", + "rh", + position=2, + argstr="%s", + mandatory=True, + desc="hemisphere to visualize") + surface = traits.String( + position=3, argstr="%s", mandatory=True, desc="surface to visualize") + + show_curv = traits.Bool( + argstr="-curv", desc="show curvature", xor=["show_gray_curv"]) + show_gray_curv = traits.Bool( + argstr="-gray", desc="show curvature in gray", xor=["show_curv"]) + + overlay = File( + exists=True, + argstr="-overlay %s", + desc="load an overlay volume/surface", + requires=["overlay_range"]) reg_xors = ["overlay_reg", "identity_reg", "mni152_reg"] - overlay_reg = traits.File(exists=True, argstr="-overlay-reg %s", xor=reg_xors, - desc="registration matrix file to register overlay to surface") - identity_reg = traits.Bool(argstr="-overlay-reg-identity", xor=reg_xors, - desc="use the identity matrix to register the overlay to the surface") - mni152_reg = traits.Bool(argstr="-mni152reg", xor=reg_xors, - desc="use to display a volume in MNI152 space on the average subject") - - overlay_range = traits.Either(traits.Float, - traits.Tuple(traits.Float, traits.Float), - traits.Tuple(traits.Float, traits.Float, traits.Float), - desc="overlay range--either min, (min, max) or (min, mid, max)", - argstr="%s") - overlay_range_offset = traits.Float(argstr="-foffset %.3f", - desc="overlay range will be symettric around offset value") - - truncate_overlay = traits.Bool(argstr="-truncphaseflag 1", - desc="truncate the overlay display") - reverse_overlay = traits.Bool(argstr="-revphaseflag 1", - desc="reverse the overlay display") - invert_overlay = traits.Bool(argstr="-invphaseflag 1", - desc="invert the overlay display") + overlay_reg = traits.File( + exists=True, + argstr="-overlay-reg %s", + xor=reg_xors, + desc="registration matrix file to register overlay to surface") + identity_reg = traits.Bool( + argstr="-overlay-reg-identity", + xor=reg_xors, + desc="use the identity matrix to register the overlay to the surface") + mni152_reg = traits.Bool( + argstr="-mni152reg", + xor=reg_xors, + desc="use to display a volume in MNI152 space on the average subject") + + overlay_range = traits.Either( + traits.Float, + traits.Tuple(traits.Float, traits.Float), + traits.Tuple(traits.Float, traits.Float, traits.Float), + desc="overlay range--either min, (min, max) or (min, mid, max)", + argstr="%s") + overlay_range_offset = traits.Float( + argstr="-foffset %.3f", + desc="overlay range will be symettric around offset value") + + truncate_overlay = traits.Bool( + argstr="-truncphaseflag 1", desc="truncate the overlay display") + reverse_overlay = traits.Bool( + argstr="-revphaseflag 1", desc="reverse the overlay display") + invert_overlay = traits.Bool( + argstr="-invphaseflag 1", desc="invert the overlay display") demean_overlay = traits.Bool(argstr="-zm", desc="remove mean from overlay") - annot_file = File(exists=True, argstr="-annotation %s", xor=["annot_name"], - desc="path to annotation file to display") - annot_name = traits.String(argstr="-annotation %s", xor=["annot_file"], - desc="name of annotation to display (must be in $subject/label directory") - - label_file = File(exists=True, argstr="-label %s", xor=["label_name"], - desc="path to label file to display") - label_name = traits.String(argstr="-label %s", xor=["label_file"], - desc="name of label to display (must be in $subject/label directory") - - colortable = File(exists=True, argstr="-colortable %s", desc="load colortable file") - label_under = traits.Bool(argstr="-labels-under", desc="draw label/annotation under overlay") - label_outline = traits.Bool(argstr="-label-outline", desc="draw label/annotation as outline") + annot_file = File( + exists=True, + argstr="-annotation %s", + xor=["annot_name"], + desc="path to annotation file to display") + annot_name = traits.String( + argstr="-annotation %s", + xor=["annot_file"], + desc= + "name of annotation to display (must be in $subject/label directory") + + label_file = File( + exists=True, + argstr="-label %s", + xor=["label_name"], + desc="path to label file to display") + label_name = traits.String( + argstr="-label %s", + xor=["label_file"], + desc="name of label to display (must be in $subject/label directory") + + colortable = File( + exists=True, argstr="-colortable %s", desc="load colortable file") + label_under = traits.Bool( + argstr="-labels-under", desc="draw label/annotation under overlay") + label_outline = traits.Bool( + argstr="-label-outline", desc="draw label/annotation as outline") patch_file = File(exists=True, argstr="-patch %s", desc="load a patch") - orig_suffix = traits.String(argstr="-orig %s", desc="set the orig surface suffix string") - sphere_suffix = traits.String(argstr="-sphere %s", desc="set the sphere.reg suffix string") + orig_suffix = traits.String( + argstr="-orig %s", desc="set the orig surface suffix string") + sphere_suffix = traits.String( + argstr="-sphere %s", desc="set the sphere.reg suffix string") - show_color_scale = traits.Bool(argstr="-colscalebarflag 1", - desc="display the color scale bar") - show_color_text = traits.Bool(argstr="-colscaletext 1", - desc="display text in the color scale bar") + show_color_scale = traits.Bool( + argstr="-colscalebarflag 1", desc="display the color scale bar") + show_color_text = traits.Bool( + argstr="-colscaletext 1", desc="display text in the color scale bar") six_images = traits.Bool(desc="also take anterior and posterior snapshots") - screenshot_stem = traits.String(desc="stem to use for screenshot file names") - stem_template_args = traits.List(traits.String, requires=["screenshot_stem"], - desc="input names to use as arguments for a string-formated stem template") - tcl_script = File(exists=True, argstr="%s", genfile=True, - desc="override default screenshot script") + screenshot_stem = traits.String( + desc="stem to use for screenshot file names") + stem_template_args = traits.List( + traits.String, + requires=["screenshot_stem"], + desc= + "input names to use as arguments for a string-formated stem template") + tcl_script = File( + exists=True, + argstr="%s", + genfile=True, + desc="override default screenshot script") class SurfaceSnapshotsOutputSpec(TraitedSpec): - snapshots = OutputMultiPath(File(exists=True), - desc="tiff images of the surface from different perspectives") + snapshots = OutputMultiPath( + File(exists=True), + desc="tiff images of the surface from different perspectives") class SurfaceSnapshots(FSCommand): @@ -696,7 +913,9 @@ def _format_arg(self, name, spec, value): if len(value) == 2: return "-fminmax %.3f %.3f" % value else: - return "-fminmax %.3f %.3f -fmid %.3f" % (value[0], value[2], value[1]) + return "-fminmax %.3f %.3f -fmid %.3f" % (value[0], + value[2], + value[1]) elif name == "annot_name" and isdefined(value): # Matching annot by name needs to strip the leading hemi and trailing # extension strings @@ -709,8 +928,8 @@ def _format_arg(self, name, spec, value): def _run_interface(self, runtime): if not isdefined(self.inputs.screenshot_stem): - stem = "%s_%s_%s" % ( - self.inputs.subject_id, self.inputs.hemi, self.inputs.surface) + stem = "%s_%s_%s" % (self.inputs.subject_id, self.inputs.hemi, + self.inputs.surface) else: stem = self.inputs.screenshot_stem stem_args = self.inputs.stem_template_args @@ -719,15 +938,18 @@ def _run_interface(self, runtime): stem = stem % args # Check if the DISPLAY variable is set -- should avoid crashes (might not?) if "DISPLAY" not in os.environ: - raise RuntimeError("Graphics are not enabled -- cannot run tksurfer") + raise RuntimeError( + "Graphics are not enabled -- cannot run tksurfer") runtime.environ["_SNAPSHOT_STEM"] = stem self._write_tcl_script() runtime = super(SurfaceSnapshots, self)._run_interface(runtime) # If a display window can't be opened, this will crash on # aggregate_outputs. Let's try to parse stderr and raise a # better exception here if that happened. - errors = ["surfer: failed, no suitable display found", - "Fatal Error in tksurfer.bin: could not open display"] + errors = [ + "surfer: failed, no suitable display found", + "Fatal Error in tksurfer.bin: could not open display" + ] for err in errors: if err in runtime.stderr: self.raise_exception(runtime) @@ -738,28 +960,22 @@ def _run_interface(self, runtime): def _write_tcl_script(self): fid = open("snapshots.tcl", "w") - script = ["save_tiff $env(_SNAPSHOT_STEM)-lat.tif", - "make_lateral_view", - "rotate_brain_y 180", - "redraw", - "save_tiff $env(_SNAPSHOT_STEM)-med.tif", - "make_lateral_view", - "rotate_brain_x 90", - "redraw", - "save_tiff $env(_SNAPSHOT_STEM)-ven.tif", - "make_lateral_view", - "rotate_brain_x -90", - "redraw", - "save_tiff $env(_SNAPSHOT_STEM)-dor.tif"] + script = [ + "save_tiff $env(_SNAPSHOT_STEM)-lat.tif", "make_lateral_view", + "rotate_brain_y 180", "redraw", + "save_tiff $env(_SNAPSHOT_STEM)-med.tif", "make_lateral_view", + "rotate_brain_x 90", "redraw", + "save_tiff $env(_SNAPSHOT_STEM)-ven.tif", "make_lateral_view", + "rotate_brain_x -90", "redraw", + "save_tiff $env(_SNAPSHOT_STEM)-dor.tif" + ] if isdefined(self.inputs.six_images) and self.inputs.six_images: - script.extend(["make_lateral_view", - "rotate_brain_y 90", - "redraw", - "save_tiff $env(_SNAPSHOT_STEM)-pos.tif", - "make_lateral_view", - "rotate_brain_y -90", - "redraw", - "save_tiff $env(_SNAPSHOT_STEM)-ant.tif"]) + script.extend([ + "make_lateral_view", "rotate_brain_y 90", "redraw", + "save_tiff $env(_SNAPSHOT_STEM)-pos.tif", "make_lateral_view", + "rotate_brain_y -90", "redraw", + "save_tiff $env(_SNAPSHOT_STEM)-ant.tif" + ]) script.append("exit") fid.write("\n".join(script)) @@ -768,7 +984,8 @@ def _write_tcl_script(self): def _list_outputs(self): outputs = self._outputs().get() if not isdefined(self.inputs.screenshot_stem): - stem = "%s_%s_%s" % (self.inputs.subject_id, self.inputs.hemi, self.inputs.surface) + stem = "%s_%s_%s" % (self.inputs.subject_id, self.inputs.hemi, + self.inputs.surface) else: stem = self.inputs.screenshot_stem stem_args = self.inputs.stem_template_args @@ -856,49 +1073,96 @@ class MRIsConvertInputSpec(FSTraitedSpec): """ Uses Freesurfer's mris_convert to convert surface files to various formats """ - annot_file = File(exists=True, argstr="--annot %s", - desc="input is annotation or gifti label data") - - parcstats_file = File(exists=True, argstr="--parcstats %s", - desc="infile is name of text file containing label/val pairs") - - label_file = File(exists=True, argstr="--label %s", - desc="infile is .label file, label is name of this label") - - scalarcurv_file = File(exists=True, argstr="-c %s", - desc="input is scalar curv overlay file (must still specify surface)") - - functional_file = File(exists=True, argstr="-f %s", - desc="input is functional time-series or other multi-frame data (must specify surface)") - - labelstats_outfile = File(exists=False, argstr="--labelstats %s", - desc="outfile is name of gifti file to which label stats will be written") - - patch = traits.Bool(argstr="-p", desc="input is a patch, not a full surface") - rescale = traits.Bool(argstr="-r", desc="rescale vertex xyz so total area is same as group average") - normal = traits.Bool(argstr="-n", desc="output is an ascii file where vertex data") - xyz_ascii = traits.Bool(argstr="-a", desc="Print only surface xyz to ascii file") - vertex = traits.Bool(argstr="-v", desc="Writes out neighbors of a vertex in each row") + annot_file = File( + exists=True, + argstr="--annot %s", + desc="input is annotation or gifti label data") + + parcstats_file = File( + exists=True, + argstr="--parcstats %s", + desc="infile is name of text file containing label/val pairs") + + label_file = File( + exists=True, + argstr="--label %s", + desc="infile is .label file, label is name of this label") + + scalarcurv_file = File( + exists=True, + argstr="-c %s", + desc="input is scalar curv overlay file (must still specify surface)") + + functional_file = File( + exists=True, + argstr="-f %s", + desc= + "input is functional time-series or other multi-frame data (must specify surface)" + ) + + labelstats_outfile = File( + exists=False, + argstr="--labelstats %s", + desc= + "outfile is name of gifti file to which label stats will be written") + + patch = traits.Bool( + argstr="-p", desc="input is a patch, not a full surface") + rescale = traits.Bool( + argstr="-r", + desc="rescale vertex xyz so total area is same as group average") + normal = traits.Bool( + argstr="-n", desc="output is an ascii file where vertex data") + xyz_ascii = traits.Bool( + argstr="-a", desc="Print only surface xyz to ascii file") + vertex = traits.Bool( + argstr="-v", desc="Writes out neighbors of a vertex in each row") scale = traits.Float(argstr="-s %.3f", desc="scale vertex xyz by scale") - dataarray_num = traits.Int(argstr="--da_num %d", desc="if input is gifti, 'num' specifies which data array to use") + dataarray_num = traits.Int( + argstr="--da_num %d", + desc="if input is gifti, 'num' specifies which data array to use") - talairachxfm_subjid = traits.String(argstr="-t %s", desc="apply talairach xfm of subject to vertex xyz") + talairachxfm_subjid = traits.String( + argstr="-t %s", desc="apply talairach xfm of subject to vertex xyz") origname = traits.String(argstr="-o %s", desc="read orig positions") - in_file = File(exists=True, mandatory=True, position=-2, argstr='%s', desc='File to read/convert') - out_file = File(argstr='%s', position=-1, genfile=True, - xor=['out_datatype'], mandatory=True, - desc='output filename or True to generate one') - - out_datatype = traits.Enum("asc", "ico", "tri", "stl", "vtk", "gii", "mgh", "mgz", - xor=['out_file'], mandatory=True, - desc="These file formats are supported: ASCII: .asc" - "ICO: .ico, .tri GEO: .geo STL: .stl VTK: .vtk GIFTI: .gii MGH surface-encoded 'volume': .mgh, .mgz") - to_scanner = traits.Bool(argstr="--to-scanner", - desc="convert coordinates from native FS (tkr) coords to scanner coords") - to_tkr = traits.Bool(argstr="--to-tkr", - desc="convert coordinates from scanner coords to native FS (tkr) coords") + in_file = File( + exists=True, + mandatory=True, + position=-2, + argstr='%s', + desc='File to read/convert') + out_file = File( + argstr='%s', + position=-1, + genfile=True, + xor=['out_datatype'], + mandatory=True, + desc='output filename or True to generate one') + + out_datatype = traits.Enum( + "asc", + "ico", + "tri", + "stl", + "vtk", + "gii", + "mgh", + "mgz", + xor=['out_file'], + mandatory=True, + desc="These file formats are supported: ASCII: .asc" + "ICO: .ico, .tri GEO: .geo STL: .stl VTK: .vtk GIFTI: .gii MGH surface-encoded 'volume': .mgh, .mgz" + ) + to_scanner = traits.Bool( + argstr="--to-scanner", + desc="convert coordinates from native FS (tkr) coords to scanner coords" + ) + to_tkr = traits.Bool( + argstr="--to-tkr", + desc="convert coordinates from scanner coords to native FS (tkr) coords" + ) class MRIsConvertOutputSpec(TraitedSpec): @@ -964,20 +1228,30 @@ class MRIsCombineInputSpec(FSTraitedSpec): """ Uses Freesurfer's mris_convert to combine two surface files into one. """ - in_files = traits.List(File(Exists=True), maxlen=2, minlen=2, - mandatory=True, position=1, argstr='--combinesurfs %s', - desc='Two surfaces to be combined.') - out_file = File(argstr='%s', position=-1, genfile=True, - mandatory=True, - desc='Output filename. Combined surfaces from in_files.') + in_files = traits.List( + File(Exists=True), + maxlen=2, + minlen=2, + mandatory=True, + position=1, + argstr='--combinesurfs %s', + desc='Two surfaces to be combined.') + out_file = File( + argstr='%s', + position=-1, + genfile=True, + mandatory=True, + desc='Output filename. Combined surfaces from in_files.') class MRIsCombineOutputSpec(TraitedSpec): """ Uses Freesurfer's mris_convert to combine two surface files into one. """ - out_file = File(exists=True, desc='Output filename. Combined surfaces from ' - 'in_files.') + out_file = File( + exists=True, + desc='Output filename. Combined surfaces from ' + 'in_files.') class MRIsCombine(FSSurfaceCommand): @@ -1035,12 +1309,30 @@ class MRITessellateInputSpec(FSTraitedSpec): Uses Freesurfer's mri_tessellate to create surfaces by tessellating a given input volume """ - in_file = File(exists=True, mandatory=True, position=-3, argstr='%s', desc='Input volume to tesselate voxels from.') - label_value = traits.Int(position=-2, argstr='%d', mandatory=True, - desc='Label value which to tesselate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)') - out_file = File(argstr='%s', position=-1, genfile=True, desc='output filename or True to generate one') - tesselate_all_voxels = traits.Bool(argstr='-a', desc='Tessellate the surface of all voxels with different labels') - use_real_RAS_coordinates = traits.Bool(argstr='-n', desc='Saves surface with real RAS coordinates where c_(r,a,s) != 0') + in_file = File( + exists=True, + mandatory=True, + position=-3, + argstr='%s', + desc='Input volume to tesselate voxels from.') + label_value = traits.Int( + position=-2, + argstr='%d', + mandatory=True, + desc= + 'Label value which to tesselate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)' + ) + out_file = File( + argstr='%s', + position=-1, + genfile=True, + desc='output filename or True to generate one') + tesselate_all_voxels = traits.Bool( + argstr='-a', + desc='Tessellate the surface of all voxels with different labels') + use_real_RAS_coordinates = traits.Bool( + argstr='-n', + desc='Saves surface with real RAS coordinates where c_(r,a,s) != 0') class MRITessellateOutputSpec(TraitedSpec): @@ -1088,23 +1380,49 @@ def _gen_outfilename(self): class MRIPretessInputSpec(FSTraitedSpec): - in_filled = File(exists=True, mandatory=True, position=-4, argstr='%s', - desc=('filled volume, usually wm.mgz')) - label = traits.Either(traits.Str('wm'), traits.Int(1), argstr='%s', default='wm', - mandatory=True, usedefault=True, position=-3, - desc=('label to be picked up, can be a Freesurfer\'s string like ' - '\'wm\' or a label value (e.g. 127 for rh or 255 for lh)')) - in_norm = File(exists=True, mandatory=True, position=-2, argstr='%s', - desc=('the normalized, brain-extracted T1w image. Usually norm.mgz')) - out_file = File(position=-1, argstr='%s', name_source=['in_filled'], name_template='%s_pretesswm', - keep_extension=True, desc='the output file after mri_pretess.') - - nocorners = traits.Bool(False, argstr='-nocorners', desc=('do not remove corner configurations' - ' in addition to edge ones.')) + in_filled = File( + exists=True, + mandatory=True, + position=-4, + argstr='%s', + desc=('filled volume, usually wm.mgz')) + label = traits.Either( + traits.Str('wm'), + traits.Int(1), + argstr='%s', + default='wm', + mandatory=True, + usedefault=True, + position=-3, + desc=('label to be picked up, can be a Freesurfer\'s string like ' + '\'wm\' or a label value (e.g. 127 for rh or 255 for lh)')) + in_norm = File( + exists=True, + mandatory=True, + position=-2, + argstr='%s', + desc=('the normalized, brain-extracted T1w image. Usually norm.mgz')) + out_file = File( + position=-1, + argstr='%s', + name_source=['in_filled'], + name_template='%s_pretesswm', + keep_extension=True, + desc='the output file after mri_pretess.') + + nocorners = traits.Bool( + False, + argstr='-nocorners', + desc=('do not remove corner configurations' + ' in addition to edge ones.')) keep = traits.Bool(False, argstr='-keep', desc=('keep WM edits')) - test = traits.Bool(False, argstr='-test', desc=('adds a voxel that should be removed by ' - 'mri_pretess. The value of the voxel is set to that of an ON-edited WM, ' - 'so it should be kept with -keep. The output will NOT be saved.')) + test = traits.Bool( + False, + argstr='-test', + desc= + ('adds a voxel that should be removed by ' + 'mri_pretess. The value of the voxel is set to that of an ON-edited WM, ' + 'so it should be kept with -keep. The output will NOT be saved.')) class MRIPretessOutputSpec(TraitedSpec): @@ -1145,12 +1463,32 @@ class MRIMarchingCubesInputSpec(FSTraitedSpec): Uses Freesurfer's mri_mc to create surfaces by tessellating a given input volume """ - in_file = File(exists=True, mandatory=True, position=1, argstr='%s', desc='Input volume to tesselate voxels from.') - label_value = traits.Int(position=2, argstr='%d', mandatory=True, - desc='Label value which to tesselate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)') - connectivity_value = traits.Int(1, position=-1, argstr='%d', usedefault=True, - desc='Alter the marching cubes connectivity: 1=6+,2=18,3=6,4=26 (default=1)') - out_file = File(argstr='./%s', position=-2, genfile=True, desc='output filename or True to generate one') + in_file = File( + exists=True, + mandatory=True, + position=1, + argstr='%s', + desc='Input volume to tesselate voxels from.') + label_value = traits.Int( + position=2, + argstr='%d', + mandatory=True, + desc= + 'Label value which to tesselate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)' + ) + connectivity_value = traits.Int( + 1, + position=-1, + argstr='%d', + usedefault=True, + desc= + 'Alter the marching cubes connectivity: 1=6+,2=18,3=6,4=26 (default=1)' + ) + out_file = File( + argstr='./%s', + position=-2, + genfile=True, + desc='output filename or True to generate one') class MRIMarchingCubesOutputSpec(TraitedSpec): @@ -1194,7 +1532,8 @@ def _gen_outfilename(self): return os.path.abspath(self.inputs.out_file) else: _, name, ext = split_filename(self.inputs.in_file) - return os.path.abspath(name + ext + '_' + str(self.inputs.label_value)) + return os.path.abspath( + name + ext + '_' + str(self.inputs.label_value)) class SmoothTessellationInputSpec(FSTraitedSpec): @@ -1202,26 +1541,46 @@ class SmoothTessellationInputSpec(FSTraitedSpec): This program smooths the tessellation of a surface using 'mris_smooth' """ - in_file = File(exists=True, mandatory=True, argstr='%s', - position=-2, copyfile=True, - desc='Input volume to tesselate voxels from.') - curvature_averaging_iterations = traits.Int(argstr='-a %d', desc='Number of curvature averaging iterations (default=10)') - smoothing_iterations = traits.Int(argstr='-n %d', desc='Number of smoothing iterations (default=10)') - snapshot_writing_iterations = traits.Int(argstr='-w %d', desc='Write snapshot every "n" iterations') - - use_gaussian_curvature_smoothing = traits.Bool(argstr='-g', desc='Use Gaussian curvature smoothing') - gaussian_curvature_norm_steps = traits.Int(argstr='%d ', desc='Use Gaussian curvature smoothing') - gaussian_curvature_smoothing_steps = traits.Int(argstr='%d', desc='Use Gaussian curvature smoothing') - - disable_estimates = traits.Bool(argstr='-nw', desc='Disables the writing of curvature and area estimates') - normalize_area = traits.Bool(argstr='-area', desc='Normalizes the area after smoothing') + in_file = File( + exists=True, + mandatory=True, + argstr='%s', + position=-2, + copyfile=True, + desc='Input volume to tesselate voxels from.') + curvature_averaging_iterations = traits.Int( + argstr='-a %d', + desc='Number of curvature averaging iterations (default=10)') + smoothing_iterations = traits.Int( + argstr='-n %d', desc='Number of smoothing iterations (default=10)') + snapshot_writing_iterations = traits.Int( + argstr='-w %d', desc='Write snapshot every "n" iterations') + + use_gaussian_curvature_smoothing = traits.Bool( + argstr='-g', desc='Use Gaussian curvature smoothing') + gaussian_curvature_norm_steps = traits.Int( + argstr='%d ', desc='Use Gaussian curvature smoothing') + gaussian_curvature_smoothing_steps = traits.Int( + argstr='%d', desc='Use Gaussian curvature smoothing') + + disable_estimates = traits.Bool( + argstr='-nw', + desc='Disables the writing of curvature and area estimates') + normalize_area = traits.Bool( + argstr='-area', desc='Normalizes the area after smoothing') use_momentum = traits.Bool(argstr='-m', desc='Uses momentum') - out_file = File(argstr='%s', position=-1, genfile=True, desc='output filename or True to generate one') - out_curvature_file = File(argstr='-c %s', desc='Write curvature to ?h.curvname (default "curv")') - out_area_file = File(argstr='-b %s', desc='Write area to ?h.areaname (default "area")') - seed = traits.Int(argstr="-seed %d", - desc="Seed for setting random number generator") + out_file = File( + argstr='%s', + position=-1, + genfile=True, + desc='output filename or True to generate one') + out_curvature_file = File( + argstr='-c %s', desc='Write curvature to ?h.curvname (default "curv")') + out_area_file = File( + argstr='-b %s', desc='Write area to ?h.areaname (default "area")') + seed = traits.Int( + argstr="-seed %d", desc="Seed for setting random number generator") class SmoothTessellationOutputSpec(TraitedSpec): @@ -1281,11 +1640,17 @@ def _run_interface(self, runtime): class MakeAverageSubjectInputSpec(FSTraitedSpec): - subjects_ids = traits.List(traits.Str(), argstr='--subjects %s', - desc='freesurfer subjects ids to average', - mandatory=True, sep=' ') - out_name = File('average', argstr='--out %s', - desc='name for the average subject', usedefault=True) + subjects_ids = traits.List( + traits.Str(), + argstr='--subjects %s', + desc='freesurfer subjects ids to average', + mandatory=True, + sep=' ') + out_name = File( + 'average', + argstr='--out %s', + desc='name for the average subject', + usedefault=True) class MakeAverageSubjectOutputSpec(TraitedSpec): @@ -1316,11 +1681,18 @@ def _list_outputs(self): class ExtractMainComponentInputSpec(CommandLineInputSpec): - in_file = File(exists=True, mandatory=True, argstr='%s', position=1, - desc='input surface file') - out_file = File(name_template='%s.maincmp', name_source='in_file', - argstr='%s', position=2, - desc='surface containing main component') + in_file = File( + exists=True, + mandatory=True, + argstr='%s', + position=1, + desc='input surface file') + out_file = File( + name_template='%s.maincmp', + name_source='in_file', + argstr='%s', + position=2, + desc='surface containing main component') class ExtractMainComponentOutputSpec(TraitedSpec): @@ -1346,46 +1718,68 @@ class ExtractMainComponent(CommandLine): class Tkregister2InputSpec(FSTraitedSpec): - target_image = File(exists=True, argstr="--targ %s", - xor=['fstarg'], - desc='target volume') - fstarg = traits.Bool(False, argstr='--fstarg', - xor=['target_image'], - desc='use subject\'s T1 as reference') - - moving_image = File(exists=True, mandatory=True, argstr="--mov %s", - desc='moving volume') + target_image = File( + exists=True, argstr="--targ %s", xor=['fstarg'], desc='target volume') + fstarg = traits.Bool( + False, + argstr='--fstarg', + xor=['target_image'], + desc='use subject\'s T1 as reference') + + moving_image = File( + exists=True, mandatory=True, argstr="--mov %s", desc='moving volume') # Input registration file options - fsl_in_matrix = File(exists=True, argstr="--fsl %s", - desc='fsl-style registration input matrix') - xfm = File(exists=True, argstr='--xfm %s', - desc='use a matrix in MNI coordinates as initial registration') - lta_in = File(exists=True, argstr='--lta %s', - desc='use a matrix in MNI coordinates as initial registration') - invert_lta_in = traits.Bool(requires=['lta_in'], - desc='Invert input LTA before applying') + fsl_in_matrix = File( + exists=True, + argstr="--fsl %s", + desc='fsl-style registration input matrix') + xfm = File( + exists=True, + argstr='--xfm %s', + desc='use a matrix in MNI coordinates as initial registration') + lta_in = File( + exists=True, + argstr='--lta %s', + desc='use a matrix in MNI coordinates as initial registration') + invert_lta_in = traits.Bool( + requires=['lta_in'], desc='Invert input LTA before applying') # Output registration file options - fsl_out = traits.Either(True, File, argstr='--fslregout %s', - desc='compute an FSL-compatible resgitration matrix') - lta_out = traits.Either(True, File, argstr='--ltaout %s', - desc='output registration file (LTA format)') - invert_lta_out = traits.Bool(argstr='--ltaout-inv', requires=['lta_in'], - desc='Invert input LTA before applying') - - subject_id = traits.String(argstr="--s %s", - desc='freesurfer subject ID') - noedit = traits.Bool(True, argstr="--noedit", usedefault=True, - desc='do not open edit window (exit)') - reg_file = File('register.dat', usedefault=True, - mandatory=True, argstr='--reg %s', - desc='freesurfer-style registration file') - reg_header = traits.Bool(False, argstr='--regheader', - desc='compute regstration from headers') - fstal = traits.Bool(False, argstr='--fstal', - xor=['target_image', 'moving_image', 'reg_file'], - desc='set mov to be tal and reg to be tal xfm') - movscale = traits.Float(argstr='--movscale %f', - desc='adjust registration matrix to scale mov') + fsl_out = traits.Either( + True, + File, + argstr='--fslregout %s', + desc='compute an FSL-compatible resgitration matrix') + lta_out = traits.Either( + True, + File, + argstr='--ltaout %s', + desc='output registration file (LTA format)') + invert_lta_out = traits.Bool( + argstr='--ltaout-inv', + requires=['lta_in'], + desc='Invert input LTA before applying') + + subject_id = traits.String(argstr="--s %s", desc='freesurfer subject ID') + noedit = traits.Bool( + True, + argstr="--noedit", + usedefault=True, + desc='do not open edit window (exit)') + reg_file = File( + 'register.dat', + usedefault=True, + mandatory=True, + argstr='--reg %s', + desc='freesurfer-style registration file') + reg_header = traits.Bool( + False, argstr='--regheader', desc='compute regstration from headers') + fstal = traits.Bool( + False, + argstr='--fstal', + xor=['target_image', 'moving_image', 'reg_file'], + desc='set mov to be tal and reg to be tal xfm') + movscale = traits.Float( + argstr='--movscale %f', desc='adjust registration matrix to scale mov') class Tkregister2OutputSpec(TraitedSpec): @@ -1472,13 +1866,25 @@ def _gen_outfilename(self): class AddXFormToHeaderInputSpec(FSTraitedSpec): # required - in_file = File(exists=True, mandatory=True, position=- - 2, argstr="%s", desc="input volume") + in_file = File( + exists=True, + mandatory=True, + position=-2, + argstr="%s", + desc="input volume") # transform file does NOT need to exist at the time if using copy_name - transform = File(exists=False, mandatory=True, - position=-3, argstr="%s", desc="xfm file") - out_file = File('output.mgz', position=-1, argstr="%s", - usedefault=True, desc="output volume") + transform = File( + exists=False, + mandatory=True, + position=-3, + argstr="%s", + desc="xfm file") + out_file = File( + 'output.mgz', + position=-1, + argstr="%s", + usedefault=True, + desc="output volume") # optional copy_name = traits.Bool( argstr="-c", desc="do not try to load the xfmfile, just copy name") @@ -1532,13 +1938,25 @@ def _list_outputs(self): class CheckTalairachAlignmentInputSpec(FSTraitedSpec): - in_file = File(argstr='-xfm %s', xor=['subject'], exists=True, mandatory=True, position=-1, - desc="specify the talairach.xfm file to check") - subject = traits.String(argstr='-subj %s', xor=['in_file'], mandatory=True, position=-1, - desc="specify subject's name") + in_file = File( + argstr='-xfm %s', + xor=['subject'], + exists=True, + mandatory=True, + position=-1, + desc="specify the talairach.xfm file to check") + subject = traits.String( + argstr='-subj %s', + xor=['in_file'], + mandatory=True, + position=-1, + desc="specify subject's name") # optional - threshold = traits.Float(default=0.010, argstr='-T %.3f', desc="Talairach transforms for subjects with p-values <= T " + - "are considered as very unlikely default=0.010") + threshold = traits.Float( + default=0.010, + argstr='-T %.3f', + desc="Talairach transforms for subjects with p-values <= T " + + "are considered as very unlikely default=0.010") class CheckTalairachAlignmentOutputSpec(TraitedSpec): @@ -1574,13 +1992,17 @@ def _list_outputs(self): class TalairachAVIInputSpec(FSTraitedSpec): - in_file = File(argstr='--i %s', exists=True, mandatory=True, - desc="input volume") - out_file = File(argstr='--xfm %s', mandatory=True, exists=False, - desc="output xfm file") + in_file = File( + argstr='--i %s', exists=True, mandatory=True, desc="input volume") + out_file = File( + argstr='--xfm %s', + mandatory=True, + exists=False, + desc="output xfm file") # optional atlas = traits.String( - argstr='--atlas %s', desc="alternate target atlas (in freesurfer/average dir)") + argstr='--atlas %s', + desc="alternate target atlas (in freesurfer/average dir)") class TalairachAVIOutputSpec(TraitedSpec): @@ -1620,14 +2042,19 @@ def _list_outputs(self): outputs = self._outputs().get() outputs['out_file'] = os.path.abspath(self.inputs.out_file) outputs['out_log'] = os.path.abspath('talairach_avi.log') - outputs['out_txt'] = os.path.join(os.path.dirname( - self.inputs.out_file), 'talsrcimg_to_' + str(self.inputs.atlas) + 't4_vox2vox.txt') + outputs['out_txt'] = os.path.join( + os.path.dirname(self.inputs.out_file), + 'talsrcimg_to_' + str(self.inputs.atlas) + 't4_vox2vox.txt') return outputs class TalairachQCInputSpec(FSTraitedSpec): - log_file = File(argstr='%s', mandatory=True, exists=True, - position=0, desc="The log file for TalairachQC") + log_file = File( + argstr='%s', + mandatory=True, + exists=True, + position=0, + desc="The log file for TalairachQC") class TalairachQC(FSScriptCommand): @@ -1647,18 +2074,35 @@ class TalairachQC(FSScriptCommand): class RemoveNeckInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", exists=True, mandatory=True, - position=-4, desc="Input file for RemoveNeck") - out_file = File(argstr="%s", exists=False, - name_source=['in_file'], name_template="%s_noneck", - hash_files=False, keep_extension=True, - position=-1, desc="Output file for RemoveNeck") - transform = File(argstr="%s", exists=True, mandatory=True, - position=-3, desc="Input transform file for RemoveNeck") - template = File(argstr="%s", exists=True, mandatory=True, - position=-2, desc="Input template file for RemoveNeck") + in_file = File( + argstr="%s", + exists=True, + mandatory=True, + position=-4, + desc="Input file for RemoveNeck") + out_file = File( + argstr="%s", + exists=False, + name_source=['in_file'], + name_template="%s_noneck", + hash_files=False, + keep_extension=True, + position=-1, + desc="Output file for RemoveNeck") + transform = File( + argstr="%s", + exists=True, + mandatory=True, + position=-3, + desc="Input transform file for RemoveNeck") + template = File( + argstr="%s", + exists=True, + mandatory=True, + position=-2, + desc="Input template file for RemoveNeck") # optional - radius = traits.Int(argstr="-radius %d", desc="Radius") + radius = traits.Int(argstr="-radius %d", desc="Radius") class RemoveNeckOutputSpec(TraitedSpec): @@ -1696,15 +2140,27 @@ def _list_outputs(self): class MRIFillInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", mandatory=True, exists=True, position=-2, - desc="Input white matter file") - out_file = File(argstr="%s", mandatory=True, exists=False, position=-1, - desc="Output filled volume file name for MRIFill") + in_file = File( + argstr="%s", + mandatory=True, + exists=True, + position=-2, + desc="Input white matter file") + out_file = File( + argstr="%s", + mandatory=True, + exists=False, + position=-1, + desc="Output filled volume file name for MRIFill") # optional - segmentation = File(argstr="-segmentation %s", exists=True, - desc="Input segmentation file for MRIFill") - transform = File(argstr="-xform %s", exists=True, - desc="Input transform file for MRIFill") + segmentation = File( + argstr="-segmentation %s", + exists=True, + desc="Input segmentation file for MRIFill") + transform = File( + argstr="-xform %s", + exists=True, + desc="Input transform file for MRIFill") log_file = File(argstr="-a %s", desc="Output log file for MRIFill") @@ -1712,6 +2168,7 @@ class MRIFillOutputSpec(TraitedSpec): out_file = File(exists=False, desc="Output file from MRIFill") log_file = File(desc="Output log file from MRIFill") + class MRIFill(FSCommand): """ This program creates hemispheric cutting planes and fills white matter @@ -1740,20 +2197,29 @@ def _list_outputs(self): class MRIsInflateInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", position=-2, mandatory=True, - exists=True, copyfile=True, - desc="Input file for MRIsInflate") - out_file = File(argstr="%s", position=-1, exists=False, - name_source=['in_file'], name_template="%s.inflated", - hash_files=False, keep_extension=True, - desc="Output file for MRIsInflate") + in_file = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + copyfile=True, + desc="Input file for MRIsInflate") + out_file = File( + argstr="%s", + position=-1, + exists=False, + name_source=['in_file'], + name_template="%s.inflated", + hash_files=False, + keep_extension=True, + desc="Output file for MRIsInflate") # optional - out_sulc = File( exists=False, - xor=['no_save_sulc'], - desc="Output sulc file") - no_save_sulc = traits.Bool(argstr='-no-save-sulc', - xor=['out_sulc'], - desc="Do not save sulc file as output") + out_sulc = File( + exists=False, xor=['no_save_sulc'], desc="Output sulc file") + no_save_sulc = traits.Bool( + argstr='-no-save-sulc', + xor=['out_sulc'], + desc="Do not save sulc file as output") class MRIsInflateOutputSpec(TraitedSpec): @@ -1789,25 +2255,39 @@ def _list_outputs(self): class SphereInputSpec(FSTraitedSpecOpenMP): - in_file = File(argstr="%s", position=-2, copyfile=True, - mandatory=True, exists=True, - desc="Input file for Sphere") - out_file = File(argstr="%s", position=-1, exists=False, - name_source=['in_file'], hash_files=False, - name_template='%s.sphere', - desc="Output file for Sphere") + in_file = File( + argstr="%s", + position=-2, + copyfile=True, + mandatory=True, + exists=True, + desc="Input file for Sphere") + out_file = File( + argstr="%s", + position=-1, + exists=False, + name_source=['in_file'], + hash_files=False, + name_template='%s.sphere', + desc="Output file for Sphere") # optional - seed = traits.Int(argstr="-seed %d", - desc="Seed for setting random number generator") - magic = traits.Bool(argstr="-q", - desc="No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu") - in_smoothwm = File( exists=True, copyfile=True, - desc="Input surface required when -q flag is not selected") + seed = traits.Int( + argstr="-seed %d", desc="Seed for setting random number generator") + magic = traits.Bool( + argstr="-q", + desc= + "No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu" + ) + in_smoothwm = File( + exists=True, + copyfile=True, + desc="Input surface required when -q flag is not selected") class SphereOutputSpec(TraitedSpec): out_file = File(exists=False, desc="Output file for Sphere") + class Sphere(FSCommandOpenMP): """ This program will add a template into an average surface @@ -1831,33 +2311,48 @@ def _list_outputs(self): class FixTopologyInputSpec(FSTraitedSpec): - in_orig = File(exists=True, mandatory=True, - desc="Undocumented input file .orig") - in_inflated = File(exists=True, mandatory=True, - desc="Undocumented input file .inflated") - in_brain = File(exists=True, mandatory=True, - desc="Implicit input brain.mgz") - in_wm = File(exists=True, mandatory=True, - desc="Implicit input wm.mgz") - hemisphere = traits.String(position=-1, argstr="%s", mandatory=True, - desc="Hemisphere being processed") - subject_id = traits.String('subject_id', position=-2, argstr="%s", - mandatory=True, usedefault=True, - desc="Subject being processed") - copy_inputs = traits.Bool(mandatory=True, - desc="If running as a node, set this to True " + - "otherwise, the topology fixing will be done " + - "in place.") + in_orig = File( + exists=True, + mandatory=True, + desc="Undocumented input file .orig") + in_inflated = File( + exists=True, + mandatory=True, + desc="Undocumented input file .inflated") + in_brain = File( + exists=True, mandatory=True, desc="Implicit input brain.mgz") + in_wm = File(exists=True, mandatory=True, desc="Implicit input wm.mgz") + hemisphere = traits.String( + position=-1, + argstr="%s", + mandatory=True, + desc="Hemisphere being processed") + subject_id = traits.String( + 'subject_id', + position=-2, + argstr="%s", + mandatory=True, + usedefault=True, + desc="Subject being processed") + copy_inputs = traits.Bool( + mandatory=True, + desc="If running as a node, set this to True " + + "otherwise, the topology fixing will be done " + "in place.") # optional - seed = traits.Int(argstr="-seed %d", - desc="Seed for setting random number generator") - ga = traits.Bool(argstr="-ga", - desc="No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu") - mgz = traits.Bool(argstr="-mgz", - desc="No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu") - sphere = traits.File(argstr="-sphere %s", - desc="Sphere input file") + seed = traits.Int( + argstr="-seed %d", desc="Seed for setting random number generator") + ga = traits.Bool( + argstr="-ga", + desc= + "No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu" + ) + mgz = traits.Bool( + argstr="-mgz", + desc= + "No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu" + ) + sphere = traits.File(argstr="-sphere %s", desc="Sphere input file") class FixTopologyOutputSpec(TraitedSpec): @@ -1897,17 +2392,20 @@ def run(self, **inputs): hemi = self.inputs.hemisphere copy2subjdir(self, self.inputs.sphere, folder='surf') # the orig file is edited in place - self.inputs.in_orig = copy2subjdir(self, - self.inputs.in_orig, - folder='surf', - basename='{0}.orig'.format(hemi)) - copy2subjdir(self, self.inputs.in_inflated, - folder='surf', - basename='{0}.inflated'.format(hemi)) - copy2subjdir(self, self.inputs.in_brain, - folder='mri', basename='brain.mgz') - copy2subjdir(self, self.inputs.in_wm, - folder='mri', basename='wm.mgz') + self.inputs.in_orig = copy2subjdir( + self, + self.inputs.in_orig, + folder='surf', + basename='{0}.orig'.format(hemi)) + copy2subjdir( + self, + self.inputs.in_inflated, + folder='surf', + basename='{0}.inflated'.format(hemi)) + copy2subjdir( + self, self.inputs.in_brain, folder='mri', basename='brain.mgz') + copy2subjdir( + self, self.inputs.in_wm, folder='mri', basename='wm.mgz') return super(FixTopology, self).run(**inputs) def _format_arg(self, name, spec, value): @@ -1924,8 +2422,12 @@ def _list_outputs(self): class EulerNumberInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", position=-1, mandatory=True, exists=True, - desc="Input file for EulerNumber") + in_file = File( + argstr="%s", + position=-1, + mandatory=True, + exists=True, + desc="Input file for EulerNumber") class EulerNumberOutputSpec(TraitedSpec): @@ -1955,13 +2457,22 @@ def _list_outputs(self): class RemoveIntersectionInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", position=-2, mandatory=True, - exists=True, copyfile=True, - desc="Input file for RemoveIntersection") - out_file = File(argstr="%s", position=-1, exists=False, - name_source=['in_file'], name_template='%s', - hash_files=False, keep_extension=True, - desc="Output file for RemoveIntersection") + in_file = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + copyfile=True, + desc="Input file for RemoveIntersection") + out_file = File( + argstr="%s", + position=-1, + exists=False, + name_source=['in_file'], + name_template='%s', + hash_files=False, + keep_extension=True, + desc="Output file for RemoveIntersection") class RemoveIntersectionOutputSpec(TraitedSpec): @@ -1993,53 +2504,72 @@ def _list_outputs(self): class MakeSurfacesInputSpec(FSTraitedSpec): # required - hemisphere = traits.Enum('lh', 'rh', - position=-1, argstr="%s", mandatory=True, - desc="Hemisphere being processed") - subject_id = traits.String('subject_id', usedefault=True, - position=-2, argstr="%s", mandatory=True, - desc="Subject being processed") + hemisphere = traits.Enum( + 'lh', + 'rh', + position=-1, + argstr="%s", + mandatory=True, + desc="Hemisphere being processed") + subject_id = traits.String( + 'subject_id', + usedefault=True, + position=-2, + argstr="%s", + mandatory=True, + desc="Subject being processed") # implicit - in_orig = File(exists=True, mandatory=True, argstr='-orig %s', - desc="Implicit input file .orig") - in_wm = File(exists=True, mandatory=True, - desc="Implicit input file wm.mgz") - in_filled = File(exists=True, mandatory=True, - desc="Implicit input file filled.mgz") + in_orig = File( + exists=True, + mandatory=True, + argstr='-orig %s', + desc="Implicit input file .orig") + in_wm = File( + exists=True, mandatory=True, desc="Implicit input file wm.mgz") + in_filled = File( + exists=True, mandatory=True, desc="Implicit input file filled.mgz") # optional in_white = File(exists=True, desc="Implicit input that is sometimes used") - in_label = File(exists=True, xor=['noaparc'], - desc="Implicit input label/.aparc.annot") - orig_white = File(argstr="-orig_white %s", exists=True, - desc="Specify a white surface to start with") - orig_pial = File(argstr="-orig_pial %s", exists=True, requires=['in_label'], - desc="Specify a pial surface to start with") - fix_mtl = traits.Bool(argstr="-fix_mtl", - desc="Undocumented flag") - no_white = traits.Bool(argstr="-nowhite", - desc="Undocumented flag") - white_only = traits.Bool(argstr="-whiteonly", - desc="Undocumented flage") - in_aseg = File(argstr="-aseg %s", exists=True, - desc="Input segmentation file") - in_T1 = File(argstr="-T1 %s", exists=True, - desc="Input brain or T1 file") + in_label = File( + exists=True, + xor=['noaparc'], + desc="Implicit input label/.aparc.annot") + orig_white = File( + argstr="-orig_white %s", + exists=True, + desc="Specify a white surface to start with") + orig_pial = File( + argstr="-orig_pial %s", + exists=True, + requires=['in_label'], + desc="Specify a pial surface to start with") + fix_mtl = traits.Bool(argstr="-fix_mtl", desc="Undocumented flag") + no_white = traits.Bool(argstr="-nowhite", desc="Undocumented flag") + white_only = traits.Bool(argstr="-whiteonly", desc="Undocumented flage") + in_aseg = File( + argstr="-aseg %s", exists=True, desc="Input segmentation file") + in_T1 = File(argstr="-T1 %s", exists=True, desc="Input brain or T1 file") mgz = traits.Bool( argstr="-mgz", - desc="No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu") + desc= + "No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu" + ) noaparc = traits.Bool( - argstr="-noaparc", xor=['in_label'], - desc="No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu") + argstr="-noaparc", + xor=['in_label'], + desc= + "No documentation. Direct questions to analysis-bugs@nmr.mgh.harvard.edu" + ) maximum = traits.Float( - argstr="-max %.1f", desc="No documentation (used for longitudinal processing)") + argstr="-max %.1f", + desc="No documentation (used for longitudinal processing)") longitudinal = traits.Bool( - argstr="-long", desc="No documentation (used for longitudinal processing)") - white = traits.String(argstr="-white %s", - desc="White surface name") + argstr="-long", + desc="No documentation (used for longitudinal processing)") + white = traits.String(argstr="-white %s", desc="White surface name") copy_inputs = traits.Bool( - desc="If running as a node, set this to True." + - "This will copy the input files to the node " + - "directory.") + desc="If running as a node, set this to True." + + "This will copy the input files to the node " + "directory.") class MakeSurfacesOutputSpec(TraitedSpec): @@ -2086,29 +2616,31 @@ def run(self, **inputs): self.inputs.subjects_dir = os.getcwd() if 'subjects_dir' in inputs: inputs['subjects_dir'] = self.inputs.subjects_dir - copy2subjdir(self, self.inputs.in_wm, - folder='mri', basename='wm.mgz') - copy2subjdir(self, self.inputs.in_filled, - folder='mri', basename='filled.mgz') - copy2subjdir(self, self.inputs.in_white, - 'surf', '{0}.white'.format(self.inputs.hemisphere)) - for originalfile in [self.inputs.in_aseg, - self.inputs.in_T1]: + copy2subjdir( + self, self.inputs.in_wm, folder='mri', basename='wm.mgz') + copy2subjdir( + self, + self.inputs.in_filled, + folder='mri', + basename='filled.mgz') + copy2subjdir(self, self.inputs.in_white, 'surf', + '{0}.white'.format(self.inputs.hemisphere)) + for originalfile in [self.inputs.in_aseg, self.inputs.in_T1]: copy2subjdir(self, originalfile, folder='mri') - for originalfile in [self.inputs.orig_white, - self.inputs.orig_pial, - self.inputs.in_orig]: + for originalfile in [ + self.inputs.orig_white, self.inputs.orig_pial, + self.inputs.in_orig + ]: copy2subjdir(self, originalfile, folder='surf') if isdefined(self.inputs.in_label): copy2subjdir(self, self.inputs.in_label, 'label', '{0}.aparc.annot'.format(self.inputs.hemisphere)) else: - os.makedirs(os.path.join(self.inputs.subjects_dir, - self.inputs.subject_id, - 'label')) + os.makedirs( + os.path.join(self.inputs.subjects_dir, + self.inputs.subject_id, 'label')) return super(MakeSurfaces, self).run(**inputs) - def _format_arg(self, name, spec, value): if name in ['in_T1', 'in_aseg']: # These inputs do not take full paths as inputs or even basenames @@ -2119,7 +2651,7 @@ def _format_arg(self, name, spec, value): else: prefix = basename if prefix == 'aseg': - return # aseg is already the default + return # aseg is already the default return spec.argstr % prefix elif name in ['orig_white', 'orig_pial']: # these inputs do take full file paths or even basenames @@ -2144,16 +2676,19 @@ def _list_outputs(self): dest_dir = os.path.join(self.inputs.subjects_dir, self.inputs.subject_id, 'surf') # labels are saved in the label directory - label_dir = os.path.join( - self.inputs.subjects_dir, self.inputs.subject_id, 'label') + label_dir = os.path.join(self.inputs.subjects_dir, + self.inputs.subject_id, 'label') if not self.inputs.no_white: outputs["out_white"] = os.path.join( - dest_dir, str(self.inputs.hemisphere) + '.white') + dest_dir, + str(self.inputs.hemisphere) + '.white') # The curv and area files must have the hemisphere names as a prefix outputs["out_curv"] = os.path.join( - dest_dir, str(self.inputs.hemisphere) + '.curv') + dest_dir, + str(self.inputs.hemisphere) + '.curv') outputs["out_area"] = os.path.join( - dest_dir, str(self.inputs.hemisphere) + '.area') + dest_dir, + str(self.inputs.hemisphere) + '.area') # Something determines when a pial surface and thickness file is generated # but documentation doesn't say what. # The orig_pial input is just a guess @@ -2161,31 +2696,47 @@ def _list_outputs(self): outputs["out_curv"] = outputs["out_curv"] + ".pial" outputs["out_area"] = outputs["out_area"] + ".pial" outputs["out_pial"] = os.path.join( - dest_dir, str(self.inputs.hemisphere) + '.pial') + dest_dir, + str(self.inputs.hemisphere) + '.pial') outputs["out_thickness"] = os.path.join( - dest_dir, str(self.inputs.hemisphere) + '.thickness') + dest_dir, + str(self.inputs.hemisphere) + '.thickness') else: # when a pial surface is generated, the cortex label file is not # generated outputs["out_cortex"] = os.path.join( - label_dir, str(self.inputs.hemisphere) + '.cortex.label') + label_dir, + str(self.inputs.hemisphere) + '.cortex.label') return outputs class CurvatureInputSpec(FSTraitedSpec): - in_file = File(argstr="%s", position=-2, mandatory=True, exists=True, - copyfile=True, desc="Input file for Curvature") + in_file = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + copyfile=True, + desc="Input file for Curvature") # optional threshold = traits.Float( - argstr="-thresh %.3f", desc="Undocumented input threshold") - n = traits.Bool(argstr="-n", - desc="Undocumented boolean flag") - averages = traits.Int(argstr="-a %d", - desc="Perform this number iterative averages of curvature measure before saving") - save = traits.Bool(argstr="-w", - desc="Save curvature files (will only generate screen output without this option)") - distances = traits.Tuple(traits.Int, traits.Int, argstr="-distances %d %d", - desc="Undocumented input integer distances") + argstr="-thresh %.3f", desc="Undocumented input threshold") + n = traits.Bool(argstr="-n", desc="Undocumented boolean flag") + averages = traits.Int( + argstr="-a %d", + desc= + "Perform this number iterative averages of curvature measure before saving" + ) + save = traits.Bool( + argstr="-w", + desc= + "Save curvature files (will only generate screen output without this option)" + ) + distances = traits.Tuple( + traits.Int, + traits.Int, + argstr="-distances %d %d", + desc="Undocumented input integer distances") copy_input = traits.Bool(desc="Copy input file to current directory") @@ -2233,32 +2784,54 @@ def _list_outputs(self): class CurvatureStatsInputSpec(FSTraitedSpec): - surface = File(argstr="-F %s", exists=True, - desc="Specify surface file for CurvatureStats") - curvfile1 = File(argstr="%s", position=-2, mandatory=True, exists=True, - desc="Input file for CurvatureStats") - curvfile2 = File(argstr="%s", position=-1, mandatory=True, exists=True, - desc="Input file for CurvatureStats") - hemisphere = traits.Enum('lh', 'rh', - position=-3, argstr="%s", mandatory=True, - desc="Hemisphere being processed") - subject_id = traits.String('subject_id', usedefault=True, - position=-4, argstr="%s", mandatory=True, - desc="Subject being processed") - out_file = File(argstr="-o %s", exists=False, - name_source=['hemisphere'], name_template='%s.curv.stats', - hash_files=False, desc="Output curvature stats file") + surface = File( + argstr="-F %s", + exists=True, + desc="Specify surface file for CurvatureStats") + curvfile1 = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + desc="Input file for CurvatureStats") + curvfile2 = File( + argstr="%s", + position=-1, + mandatory=True, + exists=True, + desc="Input file for CurvatureStats") + hemisphere = traits.Enum( + 'lh', + 'rh', + position=-3, + argstr="%s", + mandatory=True, + desc="Hemisphere being processed") + subject_id = traits.String( + 'subject_id', + usedefault=True, + position=-4, + argstr="%s", + mandatory=True, + desc="Subject being processed") + out_file = File( + argstr="-o %s", + exists=False, + name_source=['hemisphere'], + name_template='%s.curv.stats', + hash_files=False, + desc="Output curvature stats file") # optional - min_max = traits.Bool(argstr="-m", - desc="Output min / max information for the processed curvature.") - values = traits.Bool(argstr="-G", - desc="Triggers a series of derived curvature values") - write = traits.Bool(argstr="--writeCurvatureFiles", - desc="Write curvature files") + min_max = traits.Bool( + argstr="-m", + desc="Output min / max information for the processed curvature.") + values = traits.Bool( + argstr="-G", desc="Triggers a series of derived curvature values") + write = traits.Bool( + argstr="--writeCurvatureFiles", desc="Write curvature files") copy_inputs = traits.Bool( - desc="If running as a node, set this to True." + - "This will copy the input files to the node " + - "directory.") + desc="If running as a node, set this to True." + + "This will copy the input files to the node " + "directory.") class CurvatureStatsOutputSpec(TraitedSpec): @@ -2329,17 +2902,31 @@ def run(self, **inputs): copy2subjdir(self, self.inputs.curvfile2, 'surf') return super(CurvatureStats, self).run(**inputs) + class JacobianInputSpec(FSTraitedSpec): # required - in_origsurf = File(argstr="%s", position=-3, mandatory=True, exists=True, - desc="Original surface") - in_mappedsurf = File(argstr="%s", position=-2, mandatory=True, exists=True, - desc="Mapped surface") + in_origsurf = File( + argstr="%s", + position=-3, + mandatory=True, + exists=True, + desc="Original surface") + in_mappedsurf = File( + argstr="%s", + position=-2, + mandatory=True, + exists=True, + desc="Mapped surface") # optional - out_file = File(argstr="%s", exists=False, position=-1, - name_source=['in_origsurf'], hash_files=False, - name_template='%s.jacobian', keep_extension=False, - desc="Output Jacobian of the surface mapping") + out_file = File( + argstr="%s", + exists=False, + position=-1, + name_source=['in_origsurf'], + hash_files=False, + name_template='%s.jacobian', + keep_extension=False, + desc="Output Jacobian of the surface mapping") class JacobianOutputSpec(TraitedSpec): @@ -2373,20 +2960,37 @@ def _list_outputs(self): class MRIsCalcInputSpec(FSTraitedSpec): # required - in_file1 = File(argstr="%s", position=-3, mandatory=True, exists=True, - desc="Input file 1") - action = traits.String(argstr="%s", position=-2, mandatory=True, - desc="Action to perform on input file(s)") - out_file = File(argstr="-o %s", mandatory=True, - desc="Output file after calculation") + in_file1 = File( + argstr="%s", + position=-3, + mandatory=True, + exists=True, + desc="Input file 1") + action = traits.String( + argstr="%s", + position=-2, + mandatory=True, + desc="Action to perform on input file(s)") + out_file = File( + argstr="-o %s", mandatory=True, desc="Output file after calculation") # optional - in_file2 = File(argstr="%s", exists=True, position=-1, - xor=['in_float', 'in_int'], desc="Input file 2") - in_float = traits.Float(argstr="%f", position=-1, - xor=['in_file2', 'in_int'], desc="Input float") - in_int = traits.Int(argstr="%d", position=-1, - xor=['in_file2', 'in_float'], desc="Input integer") + in_file2 = File( + argstr="%s", + exists=True, + position=-1, + xor=['in_float', 'in_int'], + desc="Input file 2") + in_float = traits.Float( + argstr="%f", + position=-1, + xor=['in_file2', 'in_int'], + desc="Input float") + in_int = traits.Int( + argstr="%d", + position=-1, + xor=['in_file2', 'in_float'], + desc="Input integer") class MRIsCalcOutputSpec(TraitedSpec): @@ -2429,39 +3033,59 @@ def _list_outputs(self): class VolumeMaskInputSpec(FSTraitedSpec): - left_whitelabel = traits.Int(argstr="--label_left_white %d", mandatory=True, - desc="Left white matter label") - left_ribbonlabel = traits.Int(argstr="--label_left_ribbon %d", mandatory=True, - desc="Left cortical ribbon label") - right_whitelabel = traits.Int(argstr="--label_right_white %d", mandatory=True, - desc="Right white matter label") - right_ribbonlabel = traits.Int(argstr="--label_right_ribbon %d", mandatory=True, - desc="Right cortical ribbon label") - lh_pial = File(mandatory=True, exists=True, - desc="Implicit input left pial surface") - rh_pial = File(mandatory=True, exists=True, - desc="Implicit input right pial surface") - lh_white = File(mandatory=True, exists=True, - desc="Implicit input left white matter surface") - rh_white = File(mandatory=True, exists=True, - desc="Implicit input right white matter surface") - aseg = File(exists=True, - xor=['in_aseg'], - desc="Implicit aseg.mgz segmentation. " + - "Specify a different aseg by using the 'in_aseg' input.") - subject_id = traits.String('subject_id', usedefault=True, - position=-1, argstr="%s", mandatory=True, - desc="Subject being processed") + left_whitelabel = traits.Int( + argstr="--label_left_white %d", + mandatory=True, + desc="Left white matter label") + left_ribbonlabel = traits.Int( + argstr="--label_left_ribbon %d", + mandatory=True, + desc="Left cortical ribbon label") + right_whitelabel = traits.Int( + argstr="--label_right_white %d", + mandatory=True, + desc="Right white matter label") + right_ribbonlabel = traits.Int( + argstr="--label_right_ribbon %d", + mandatory=True, + desc="Right cortical ribbon label") + lh_pial = File( + mandatory=True, exists=True, desc="Implicit input left pial surface") + rh_pial = File( + mandatory=True, exists=True, desc="Implicit input right pial surface") + lh_white = File( + mandatory=True, + exists=True, + desc="Implicit input left white matter surface") + rh_white = File( + mandatory=True, + exists=True, + desc="Implicit input right white matter surface") + aseg = File( + exists=True, + xor=['in_aseg'], + desc="Implicit aseg.mgz segmentation. " + + "Specify a different aseg by using the 'in_aseg' input.") + subject_id = traits.String( + 'subject_id', + usedefault=True, + position=-1, + argstr="%s", + mandatory=True, + desc="Subject being processed") # optional - in_aseg = File(argstr="--aseg_name %s", - exists=True, xor=['aseg'], - desc="Input aseg file for VolumeMask") - save_ribbon = traits.Bool(argstr="--save_ribbon", - desc="option to save just the ribbon for the " + - "hemispheres in the format ?h.ribbon.mgz") - copy_inputs = traits.Bool(desc="If running as a node, set this to True." + - "This will copy the implicit input files to the " + - "node directory.") + in_aseg = File( + argstr="--aseg_name %s", + exists=True, + xor=['aseg'], + desc="Input aseg file for VolumeMask") + save_ribbon = traits.Bool( + argstr="--save_ribbon", + desc="option to save just the ribbon for the " + + "hemispheres in the format ?h.ribbon.mgz") + copy_inputs = traits.Bool( + desc="If running as a node, set this to True." + + "This will copy the implicit input files to the " + "node directory.") class VolumeMaskOutputSpec(TraitedSpec): @@ -2534,63 +3158,106 @@ def _list_outputs(self): class ParcellationStatsInputSpec(FSTraitedSpec): # required - subject_id = traits.String('subject_id', usedefault=True, - position=-3, argstr="%s", mandatory=True, - desc="Subject being processed") - hemisphere = traits.Enum('lh', 'rh', - position=-2, argstr="%s", mandatory=True, - desc="Hemisphere being processed") + subject_id = traits.String( + 'subject_id', + usedefault=True, + position=-3, + argstr="%s", + mandatory=True, + desc="Subject being processed") + hemisphere = traits.Enum( + 'lh', + 'rh', + position=-2, + argstr="%s", + mandatory=True, + desc="Hemisphere being processed") # implicit - wm = File(mandatory=True, exists=True, - desc="Input file must be /mri/wm.mgz") - lh_white = File(mandatory=True, exists=True, - desc="Input file must be /surf/lh.white") - rh_white = File(mandatory=True, exists=True, - desc="Input file must be /surf/rh.white") - lh_pial = File(mandatory=True, exists=True, - desc="Input file must be /surf/lh.pial") - rh_pial = File(mandatory=True, exists=True, - desc="Input file must be /surf/rh.pial") - transform = File(mandatory=True, exists=True, - desc="Input file must be /mri/transforms/talairach.xfm") - thickness = File(mandatory=True, exists=True, - desc="Input file must be /surf/?h.thickness") - brainmask = File(mandatory=True, exists=True, - desc="Input file must be /mri/brainmask.mgz") - aseg = File(mandatory=True, exists=True, - desc="Input file must be /mri/aseg.presurf.mgz") - ribbon = File(mandatory=True, exists=True, - desc="Input file must be /mri/ribbon.mgz") - cortex_label = File(exists=True, - desc="implicit input file {hemi}.cortex.label") + wm = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/wm.mgz") + lh_white = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/lh.white") + rh_white = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/rh.white") + lh_pial = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/lh.pial") + rh_pial = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/rh.pial") + transform = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/transforms/talairach.xfm") + thickness = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/?h.thickness") + brainmask = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/brainmask.mgz") + aseg = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/aseg.presurf.mgz") + ribbon = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/ribbon.mgz") + cortex_label = File( + exists=True, desc="implicit input file {hemi}.cortex.label") # optional - surface = traits.String(position=-1, argstr="%s", - desc="Input surface (e.g. 'white')") - mgz = traits.Bool(argstr="-mgz", - desc="Look for mgz files") - in_cortex = traits.File(argstr="-cortex %s", exists=True, - desc="Input cortex label") - in_annotation = traits.File(argstr="-a %s", exists=True, xor=['in_label'], - desc="compute properties for each label in the annotation file separately") - in_label = traits.File(argstr="-l %s", exists=True, xor=['in_annotatoin', 'out_color'], - desc="limit calculations to specified label") - tabular_output = traits.Bool(argstr="-b", - desc="Tabular output") - out_table = traits.File(argstr="-f %s", exists=False, genfile=True, - requires=['tabular_output'], desc="Table output to tablefile") - out_color = traits.File(argstr="-c %s", exists=False, genfile=True, xor=['in_label'], - desc="Output annotation files's colortable to text file") - copy_inputs = traits.Bool(desc="If running as a node, set this to True." + - "This will copy the input files to the node " + - "directory.") - th3 = traits.Bool(argstr="-th3", requires=["cortex_label"], - desc="turns on new vertex-wise volume calc for mris_anat_stats") + surface = traits.String( + position=-1, argstr="%s", desc="Input surface (e.g. 'white')") + mgz = traits.Bool(argstr="-mgz", desc="Look for mgz files") + in_cortex = traits.File( + argstr="-cortex %s", exists=True, desc="Input cortex label") + in_annotation = traits.File( + argstr="-a %s", + exists=True, + xor=['in_label'], + desc= + "compute properties for each label in the annotation file separately") + in_label = traits.File( + argstr="-l %s", + exists=True, + xor=['in_annotatoin', 'out_color'], + desc="limit calculations to specified label") + tabular_output = traits.Bool(argstr="-b", desc="Tabular output") + out_table = traits.File( + argstr="-f %s", + exists=False, + genfile=True, + requires=['tabular_output'], + desc="Table output to tablefile") + out_color = traits.File( + argstr="-c %s", + exists=False, + genfile=True, + xor=['in_label'], + desc="Output annotation files's colortable to text file") + copy_inputs = traits.Bool( + desc="If running as a node, set this to True." + + "This will copy the input files to the node " + "directory.") + th3 = traits.Bool( + argstr="-th3", + requires=["cortex_label"], + desc="turns on new vertex-wise volume calc for mris_anat_stats") class ParcellationStatsOutputSpec(TraitedSpec): out_table = File(exists=False, desc="Table output to tablefile") - out_color = File(exists=False, - desc="Output annotation files's colortable to text file") + out_color = File( + exists=False, desc="Output annotation files's colortable to text file") class ParcellationStats(FSCommand): @@ -2636,17 +3303,15 @@ def run(self, **inputs): copy2subjdir(self, self.inputs.rh_pial, 'surf', 'rh.pial') copy2subjdir(self, self.inputs.wm, 'mri', 'wm.mgz') copy2subjdir(self, self.inputs.transform, - os.path.join('mri', 'transforms'), - 'talairach.xfm') + os.path.join('mri', 'transforms'), 'talairach.xfm') copy2subjdir(self, self.inputs.brainmask, 'mri', 'brainmask.mgz') copy2subjdir(self, self.inputs.aseg, 'mri', 'aseg.presurf.mgz') copy2subjdir(self, self.inputs.ribbon, 'mri', 'ribbon.mgz') copy2subjdir(self, self.inputs.thickness, 'surf', '{0}.thickness'.format(self.inputs.hemisphere)) if isdefined(self.inputs.cortex_label): - copy2subjdir( - self, self.inputs.cortex_label, 'label', - '{0}.cortex.label'.format(self.inputs.hemisphere)) + copy2subjdir(self, self.inputs.cortex_label, 'label', + '{0}.cortex.label'.format(self.inputs.hemisphere)) createoutputdirs(self._list_outputs()) return super(ParcellationStats, self).run(**inputs) @@ -2661,14 +3326,15 @@ def _list_outputs(self): outputs["out_table"] = os.path.abspath(self.inputs.out_table) else: # subject stats directory - stats_dir = os.path.join( - self.inputs.subjects_dir, self.inputs.subject_id, 'stats') + stats_dir = os.path.join(self.inputs.subjects_dir, + self.inputs.subject_id, 'stats') if isdefined(self.inputs.in_annotation): # if out_table is not defined just tag .stats on the end # instead of .annot if self.inputs.surface == 'pial': basename = os.path.basename( - self.inputs.in_annotation).replace('.annot', '.pial.stats') + self.inputs.in_annotation).replace( + '.annot', '.pial.stats') else: basename = os.path.basename( self.inputs.in_annotation).replace('.annot', '.stats') @@ -2676,11 +3342,11 @@ def _list_outputs(self): # if out_table is not defined just tag .stats on the end # instead of .label if self.inputs.surface == 'pial': - basename = os.path.basename( - self.inputs.in_label).replace('.label', '.pial.stats') + basename = os.path.basename(self.inputs.in_label).replace( + '.label', '.pial.stats') else: - basename = os.path.basename( - self.inputs.in_label).replace('.label', '.stats') + basename = os.path.basename(self.inputs.in_label).replace( + '.label', '.stats') else: basename = str(self.inputs.hemisphere) + '.aparc.annot.stats' outputs["out_table"] = os.path.join(stats_dir, basename) @@ -2699,48 +3365,66 @@ def _list_outputs(self): # if the out_color table is not defined, one with the annotation # name will be created if 'BA' in annot: - outputs["out_color"] = os.path.join(out_dir, annot + 'ctab') + outputs["out_color"] = os.path.join( + out_dir, annot + 'ctab') else: outputs["out_color"] = os.path.join( out_dir, 'aparc.annot.' + annot + 'ctab') else: - outputs["out_color"] = os.path.join( - out_dir, 'aparc.annot.ctab') + outputs["out_color"] = os.path.join(out_dir, + 'aparc.annot.ctab') return outputs class ContrastInputSpec(FSTraitedSpec): # required - subject_id = traits.String('subject_id', argstr="--s %s", usedefault=True, - mandatory=True, desc="Subject being processed") - hemisphere = traits.Enum('lh', 'rh', - argstr="--%s-only", mandatory=True, - desc="Hemisphere being processed") + subject_id = traits.String( + 'subject_id', + argstr="--s %s", + usedefault=True, + mandatory=True, + desc="Subject being processed") + hemisphere = traits.Enum( + 'lh', + 'rh', + argstr="--%s-only", + mandatory=True, + desc="Hemisphere being processed") # implicit - thickness = File(mandatory=True, exists=True, - desc="Input file must be /surf/?h.thickness") - white = File(mandatory=True, exists=True, - desc="Input file must be /surf/.white") - annotation = traits.File(mandatory=True, exists=True, - desc="Input annotation file must be /label/.aparc.annot") - cortex = traits.File(mandatory=True, exists=True, - desc="Input cortex label must be /label/.cortex.label") - orig = File(exists=True, mandatory=True, - desc="Implicit input file mri/orig.mgz") - rawavg = File(exists=True, mandatory=True, - desc="Implicit input file mri/rawavg.mgz") - copy_inputs = traits.Bool(desc="If running as a node, set this to True." + - "This will copy the input files to the node " + - "directory.") + thickness = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/?h.thickness") + white = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/.white") + annotation = traits.File( + mandatory=True, + exists=True, + desc= + "Input annotation file must be /label/.aparc.annot" + ) + cortex = traits.File( + mandatory=True, + exists=True, + desc= + "Input cortex label must be /label/.cortex.label" + ) + orig = File( + exists=True, mandatory=True, desc="Implicit input file mri/orig.mgz") + rawavg = File( + exists=True, mandatory=True, desc="Implicit input file mri/rawavg.mgz") + copy_inputs = traits.Bool( + desc="If running as a node, set this to True." + + "This will copy the input files to the node " + "directory.") class ContrastOutputSpec(TraitedSpec): - out_contrast = File(exists=False, - desc="Output contrast file from Contrast") - out_stats = File(exists=False, - desc="Output stats file from Contrast") - out_log = File(exists=True, - desc="Output log from Contrast") + out_contrast = File( + exists=False, desc="Output contrast file from Contrast") + out_stats = File(exists=False, desc="Output stats file from Contrast") + out_log = File(exists=True, desc="Output log from Contrast") class Contrast(FSCommand): @@ -2789,37 +3473,57 @@ def run(self, **inputs): def _list_outputs(self): outputs = self._outputs().get() - subject_dir = os.path.join( - self.inputs.subjects_dir, self.inputs.subject_id) + subject_dir = os.path.join(self.inputs.subjects_dir, + self.inputs.subject_id) outputs["out_contrast"] = os.path.join( - subject_dir, 'surf', str(self.inputs.hemisphere) + '.w-g.pct.mgh') + subject_dir, 'surf', + str(self.inputs.hemisphere) + '.w-g.pct.mgh') outputs["out_stats"] = os.path.join( - subject_dir, 'stats', str(self.inputs.hemisphere) + '.w-g.pct.stats') - outputs["out_log"] = os.path.join( - subject_dir, 'scripts', 'pctsurfcon.log') + subject_dir, 'stats', + str(self.inputs.hemisphere) + '.w-g.pct.stats') + outputs["out_log"] = os.path.join(subject_dir, 'scripts', + 'pctsurfcon.log') return outputs class RelabelHypointensitiesInputSpec(FSTraitedSpec): # required - lh_white = File(mandatory=True, exists=True, copyfile=True, - desc="Implicit input file must be lh.white") - rh_white = File(mandatory=True, exists=True, copyfile=True, - desc="Implicit input file must be rh.white") - aseg = File(argstr="%s", position=-3, mandatory=True, exists=True, - desc="Input aseg file") - surf_directory = traits.Directory('.', argstr="%s", position=-2, exists=True, - usedefault=True, - desc="Directory containing lh.white and rh.white") - out_file = File(argstr="%s", position=-1, exists=False, - name_source=['aseg'], name_template='%s.hypos.mgz', - hash_files=False, keep_extension=False, - desc="Output aseg file") + lh_white = File( + mandatory=True, + exists=True, + copyfile=True, + desc="Implicit input file must be lh.white") + rh_white = File( + mandatory=True, + exists=True, + copyfile=True, + desc="Implicit input file must be rh.white") + aseg = File( + argstr="%s", + position=-3, + mandatory=True, + exists=True, + desc="Input aseg file") + surf_directory = traits.Directory( + '.', + argstr="%s", + position=-2, + exists=True, + usedefault=True, + desc="Directory containing lh.white and rh.white") + out_file = File( + argstr="%s", + position=-1, + exists=False, + name_source=['aseg'], + name_template='%s.hypos.mgz', + hash_files=False, + keep_extension=False, + desc="Output aseg file") class RelabelHypointensitiesOutputSpec(TraitedSpec): - out_file = File(argstr="%s", exists=False, - desc="Output aseg file") + out_file = File(argstr="%s", exists=False, desc="Output aseg file") class RelabelHypointensities(FSCommand): @@ -2850,53 +3554,77 @@ def _list_outputs(self): class Aparc2AsegInputSpec(FSTraitedSpec): # required - subject_id = traits.String('subject_id', argstr="--s %s", usedefault=True, - mandatory=True, desc="Subject being processed") - out_file = File(argstr="--o %s", exists=False, mandatory=True, - desc="Full path of file to save the output segmentation in") + subject_id = traits.String( + 'subject_id', + argstr="--s %s", + usedefault=True, + mandatory=True, + desc="Subject being processed") + out_file = File( + argstr="--o %s", + exists=False, + mandatory=True, + desc="Full path of file to save the output segmentation in") # implicit - lh_white = File(mandatory=True, exists=True, - desc="Input file must be /surf/lh.white") - rh_white = File(mandatory=True, exists=True, - desc="Input file must be /surf/rh.white") - lh_pial = File(mandatory=True, exists=True, - desc="Input file must be /surf/lh.pial") - rh_pial = File(mandatory=True, exists=True, - desc="Input file must be /surf/rh.pial") - lh_ribbon = File(mandatory=True, exists=True, - desc="Input file must be /mri/lh.ribbon.mgz") - rh_ribbon = File(mandatory=True, exists=True, - desc="Input file must be /mri/rh.ribbon.mgz") - ribbon = File(mandatory=True, exists=True, - desc="Input file must be /mri/ribbon.mgz") - lh_annotation = File(mandatory=True, exists=True, - desc="Input file must be /label/lh.aparc.annot") - rh_annotation = File(mandatory=True, exists=True, - desc="Input file must be /label/rh.aparc.annot") + lh_white = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/lh.white") + rh_white = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/rh.white") + lh_pial = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/lh.pial") + rh_pial = File( + mandatory=True, + exists=True, + desc="Input file must be /surf/rh.pial") + lh_ribbon = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/lh.ribbon.mgz") + rh_ribbon = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/rh.ribbon.mgz") + ribbon = File( + mandatory=True, + exists=True, + desc="Input file must be /mri/ribbon.mgz") + lh_annotation = File( + mandatory=True, + exists=True, + desc="Input file must be /label/lh.aparc.annot") + rh_annotation = File( + mandatory=True, + exists=True, + desc="Input file must be /label/rh.aparc.annot") # optional - filled = File(exists=True, - desc="Implicit input filled file. Only required with FS v5.3.") - aseg = File(argstr="--aseg %s", exists=True, - desc="Input aseg file") - volmask = traits.Bool(argstr="--volmask", - desc="Volume mask flag") - ctxseg = File(argstr="--ctxseg %s", exists=True, - desc="") - label_wm = traits.Bool(argstr="--labelwm", - desc=""" + filled = File( + exists=True, + desc="Implicit input filled file. Only required with FS v5.3.") + aseg = File(argstr="--aseg %s", exists=True, desc="Input aseg file") + volmask = traits.Bool(argstr="--volmask", desc="Volume mask flag") + ctxseg = File(argstr="--ctxseg %s", exists=True, desc="") + label_wm = traits.Bool( + argstr="--labelwm", + desc=""" For each voxel labeled as white matter in the aseg, re-assign its label to be that of the closest cortical point if its distance is less than dmaxctx """) - hypo_wm = traits.Bool(argstr="--hypo-as-wm", - desc="Label hypointensities as WM") - rip_unknown = traits.Bool(argstr="--rip-unknown", - desc="Do not label WM based on 'unknown' corical label") - a2009s = traits.Bool(argstr="--a2009s", - desc="Using the a2009s atlas") - copy_inputs = traits.Bool(desc="If running as a node, set this to True." + - "This will copy the input files to the node " + - "directory.") + hypo_wm = traits.Bool( + argstr="--hypo-as-wm", desc="Label hypointensities as WM") + rip_unknown = traits.Bool( + argstr="--rip-unknown", + desc="Do not label WM based on 'unknown' corical label") + a2009s = traits.Bool(argstr="--a2009s", desc="Using the a2009s atlas") + copy_inputs = traits.Bool( + desc="If running as a node, set this to True." + + "This will copy the input files to the node " + "directory.") class Aparc2AsegOutputSpec(TraitedSpec): @@ -2981,15 +3709,16 @@ def _list_outputs(self): class Apas2AsegInputSpec(FSTraitedSpec): # required - in_file = File(argstr="--i %s", mandatory=True, exists=True, - desc="Input aparc+aseg.mgz") - out_file = File(argstr="--o %s", mandatory=True, - desc="Output aseg file") + in_file = File( + argstr="--i %s", + mandatory=True, + exists=True, + desc="Input aparc+aseg.mgz") + out_file = File(argstr="--o %s", mandatory=True, desc="Output aseg file") class Apas2AsegOutputSpec(TraitedSpec): - out_file = File(argstr="%s", exists=False, - desc="Output aseg file") + out_file = File(argstr="%s", exists=False, desc="Output aseg file") class Apas2Aseg(FSCommand): @@ -3023,13 +3752,22 @@ class MRIsExpandInputSpec(FSTraitedSpec): # Input spec derived from # https://github.com/freesurfer/freesurfer/blob/102e053/mris_expand/mris_expand.c in_file = File( - exists=True, mandatory=True, argstr='%s', position=-3, copyfile=False, + exists=True, + mandatory=True, + argstr='%s', + position=-3, + copyfile=False, desc='Surface to expand') distance = traits.Float( - mandatory=True, argstr='%g', position=-2, + mandatory=True, + argstr='%g', + position=-2, desc='Distance in mm or fraction of cortical thickness') out_name = traits.Str( - 'expanded', argstr='%s', position=-1, usedefault=True, + 'expanded', + argstr='%s', + position=-1, + usedefault=True, desc=('Output surface file\n' 'If no path, uses directory of `in_file`\n' 'If no path AND missing "lh." or "rh.", derive from `in_file`')) @@ -3037,29 +3775,31 @@ class MRIsExpandInputSpec(FSTraitedSpec): argstr='-thickness', desc='Expand by fraction of cortical thickness, not mm') thickness_name = traits.Str( - argstr="-thickness_name %s", copyfile=False, + argstr="-thickness_name %s", + copyfile=False, desc=('Name of thickness file (implicit: "thickness")\n' 'If no path, uses directory of `in_file`\n' 'If no path AND missing "lh." or "rh.", derive from `in_file`')) pial = traits.Str( - argstr='-pial %s', copyfile=False, + argstr='-pial %s', + copyfile=False, desc=('Name of pial file (implicit: "pial")\n' 'If no path, uses directory of `in_file`\n' 'If no path AND missing "lh." or "rh.", derive from `in_file`')) sphere = traits.Str( - 'sphere', copyfile=False, usedefault=True, + 'sphere', + copyfile=False, + usedefault=True, desc='WARNING: Do not change this trait') spring = traits.Float(argstr='-S %g', desc="Spring term (implicit: 0.05)") dt = traits.Float(argstr='-T %g', desc='dt (implicit: 0.25)') write_iterations = traits.Int( - argstr='-W %d', - desc='Write snapshots of expansion every N iterations') + argstr='-W %d', desc='Write snapshots of expansion every N iterations') smooth_averages = traits.Int( argstr='-A %d', desc='Smooth surface with N iterations after expansion') nsurfaces = traits.Int( - argstr='-N %d', - desc='Number of surfacces to write during expansion') + argstr='-N %d', desc='Number of surfacces to write during expansion') # # Requires dev version - Re-add when min_ver/max_ver support this # # https://github.com/freesurfer/freesurfer/blob/9730cb9/mris_expand/mris_expand.c # navgs = traits.Tuple( @@ -3117,8 +3857,8 @@ def _normalize_filenames(self): thickness_name = self.inputs.thickness_name if not isdefined(thickness_name): thickness_name = 'thickness' - self.inputs.thickness_name = self._associated_file(in_file, - thickness_name) + self.inputs.thickness_name = self._associated_file( + in_file, thickness_name) self.inputs.sphere = self._associated_file(in_file, self.inputs.sphere) @@ -3127,35 +3867,68 @@ class LTAConvertInputSpec(CommandLineInputSpec): # Inputs _in_xor = ('in_lta', 'in_fsl', 'in_mni', 'in_reg', 'in_niftyreg', 'in_itk') in_lta = traits.Either( - File(exists=True), 'identity.nofile', argstr='--inlta %s', - mandatory=True, xor=_in_xor, desc='input transform of LTA type') + File(exists=True), + 'identity.nofile', + argstr='--inlta %s', + mandatory=True, + xor=_in_xor, + desc='input transform of LTA type') in_fsl = File( - exists=True, argstr='--infsl %s', mandatory=True, xor=_in_xor, + exists=True, + argstr='--infsl %s', + mandatory=True, + xor=_in_xor, desc='input transform of FSL type') in_mni = File( - exists=True, argstr='--inmni %s', mandatory=True, xor=_in_xor, + exists=True, + argstr='--inmni %s', + mandatory=True, + xor=_in_xor, desc='input transform of MNI/XFM type') in_reg = File( - exists=True, argstr='--inreg %s', mandatory=True, xor=_in_xor, + exists=True, + argstr='--inreg %s', + mandatory=True, + xor=_in_xor, desc='input transform of TK REG type (deprecated format)') in_niftyreg = File( - exists=True, argstr='--inniftyreg %s', mandatory=True, xor=_in_xor, + exists=True, + argstr='--inniftyreg %s', + mandatory=True, + xor=_in_xor, desc='input transform of Nifty Reg type (inverse RAS2RAS)') in_itk = File( - exists=True, argstr='--initk %s', mandatory=True, xor=_in_xor, + exists=True, + argstr='--initk %s', + mandatory=True, + xor=_in_xor, desc='input transform of ITK type') # Outputs out_lta = traits.Either( - traits.Bool, File, argstr='--outlta %s', + traits.Bool, + File, + argstr='--outlta %s', desc='output linear transform (LTA Freesurfer format)') - out_fsl = traits.Either(traits.Bool, File, argstr='--outfsl %s', - desc='output transform in FSL format') - out_mni = traits.Either(traits.Bool, File, argstr='--outmni %s', - desc='output transform in MNI/XFM format') - out_reg = traits.Either(traits.Bool, File, argstr='--outreg %s', - desc='output transform in reg dat format') - out_itk = traits.Either(traits.Bool, File, argstr='--outitk %s', - desc='output transform in ITK format') + out_fsl = traits.Either( + traits.Bool, + File, + argstr='--outfsl %s', + desc='output transform in FSL format') + out_mni = traits.Either( + traits.Bool, + File, + argstr='--outmni %s', + desc='output transform in MNI/XFM format') + out_reg = traits.Either( + traits.Bool, + File, + argstr='--outreg %s', + desc='output transform in reg dat format') + out_itk = traits.Either( + traits.Bool, + File, + argstr='--outitk %s', + desc='output transform in ITK format') # Optional flags invert = traits.Bool(argstr='--invert') ltavox2vox = traits.Bool(argstr='--ltavox2vox', requires=['out_lta']) @@ -3165,8 +3938,8 @@ class LTAConvertInputSpec(CommandLineInputSpec): class LTAConvertOutputSpec(TraitedSpec): - out_lta = File(exists=True, - desc='output linear transform (LTA Freesurfer format)') + out_lta = File( + exists=True, desc='output linear transform (LTA Freesurfer format)') out_fsl = File(exists=True, desc='output transform in FSL format') out_mni = File(exists=True, desc='output transform in MNI/XFM format') out_reg = File(exists=True, desc='output transform in reg dat format') diff --git a/nipype/interfaces/fsl/__init__.py b/nipype/interfaces/fsl/__init__.py index 9524a731d6..b3302d65b3 100644 --- a/nipype/interfaces/fsl/__init__.py +++ b/nipype/interfaces/fsl/__init__.py @@ -8,25 +8,23 @@ """ from .base import (FSLCommand, Info, check_fsl, no_fsl, no_fsl_course_data) -from .preprocess import (FAST, FLIRT, ApplyXFM, BET, MCFLIRT, FNIRT, - ApplyWarp, SliceTimer, SUSAN, PRELUDE, FUGUE, FIRST) +from .preprocess import (FAST, FLIRT, ApplyXFM, BET, MCFLIRT, FNIRT, ApplyWarp, + SliceTimer, SUSAN, PRELUDE, FUGUE, FIRST) from .model import (Level1Design, FEAT, FEATModel, FILMGLS, FEATRegister, FLAMEO, ContrastMgr, MultipleRegressDesign, L2Model, SMM, MELODIC, SmoothEstimate, Cluster, Randomise, GLM) -from .utils import (AvScale, Smooth, Merge, ExtractROI, Split, ImageMaths, ImageMeants, - ImageStats, FilterRegressor, Overlay, Slicer, - PlotTimeSeries, PlotMotionParams, ConvertXFM, - SwapDimensions, PowerSpectrum, Reorient2Std, - Complex, InvWarp, WarpUtils, ConvertWarp, WarpPoints, - WarpPointsToStd, WarpPointsFromStd, RobustFOV, - CopyGeom, MotionOutliers) +from .utils import ( + AvScale, Smooth, Merge, ExtractROI, Split, ImageMaths, ImageMeants, + ImageStats, FilterRegressor, Overlay, Slicer, PlotTimeSeries, + PlotMotionParams, ConvertXFM, SwapDimensions, PowerSpectrum, Reorient2Std, + Complex, InvWarp, WarpUtils, ConvertWarp, WarpPoints, WarpPointsToStd, + WarpPointsFromStd, RobustFOV, CopyGeom, MotionOutliers) -from .epi import (PrepareFieldmap, TOPUP, ApplyTOPUP, Eddy, EPIDeWarp, - SigLoss, EddyCorrect, EpiReg) -from .dti import (BEDPOSTX, XFibres, DTIFit, - ProbTrackX, ProbTrackX2, - VecReg, ProjThresh, FindTheBiggest, DistanceMap, - TractSkeleton, MakeDyadicVectors, BEDPOSTX5, XFibres5) +from .epi import (PrepareFieldmap, TOPUP, ApplyTOPUP, Eddy, EPIDeWarp, SigLoss, + EddyCorrect, EpiReg) +from .dti import (BEDPOSTX, XFibres, DTIFit, ProbTrackX, ProbTrackX2, VecReg, + ProjThresh, FindTheBiggest, DistanceMap, TractSkeleton, + MakeDyadicVectors, BEDPOSTX5, XFibres5) from .maths import (ChangeDataType, Threshold, MeanImage, ApplyMask, IsotropicSmooth, TemporalFilter, DilateImage, ErodeImage, SpatialFilter, UnaryMaths, BinaryMaths, MultiImageMaths, diff --git a/nipype/interfaces/fsl/aroma.py b/nipype/interfaces/fsl/aroma.py index fb8dc82bd8..97b3b17046 100644 --- a/nipype/interfaces/fsl/aroma.py +++ b/nipype/interfaces/fsl/aroma.py @@ -11,64 +11,94 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import -from ..base import (TraitedSpec, CommandLineInputSpec, CommandLine, - File, Directory, traits, isdefined) +from __future__ import (print_function, division, unicode_literals, + absolute_import) +from ..base import (TraitedSpec, CommandLineInputSpec, CommandLine, File, + Directory, traits, isdefined) import os class ICA_AROMAInputSpec(CommandLineInputSpec): - feat_dir = Directory(exists=True, mandatory=True, - argstr='-feat %s', - xor=['in_file', 'mat_file', 'fnirt_warp_file', 'motion_parameters'], - desc='If a feat directory exists and temporal filtering ' - 'has not been run yet, ICA_AROMA can use the files in ' - 'this directory.') - in_file = File(exists=True, mandatory=True, - argstr='-i %s', xor=['feat_dir'], - desc='volume to be denoised') - out_dir = Directory('out', genfile=True, - argstr='-o %s', - desc='output directory') - mask = File(exists=True, argstr='-m %s', xor=['feat_dir'], - desc='path/name volume mask') - dim = traits.Int(argstr='-dim %d', - desc='Dimensionality reduction when running ' - 'MELODIC (defualt is automatic estimation)') - TR = traits.Float(argstr='-tr %.3f', - desc='TR in seconds. If this is not specified ' - 'the TR will be extracted from the ' - 'header of the fMRI nifti file.') - melodic_dir = Directory(exists=True, argstr='-meldir %s', - desc='path to MELODIC directory if MELODIC has already been run') - mat_file = File(exists=True, argstr='-affmat %s', xor=['feat_dir'], - desc='path/name of the mat-file describing the ' - 'affine registration (e.g. FSL FLIRT) of the ' - 'functional data to structural space (.mat file)') - fnirt_warp_file = File(exists=True, argstr='-warp %s', xor=['feat_dir'], - desc='File name of the warp-file describing ' - 'the non-linear registration (e.g. FSL FNIRT) ' - 'of the structural data to MNI152 space (.nii.gz)') - motion_parameters = File(exists=True, mandatory=True, - argstr='-mc %s', xor=['feat_dir'], - desc='motion parameters file') - denoise_type = traits.Enum('nonaggr', 'aggr', 'both', 'no', usedefault=True, - mandatory=True, argstr='-den %s', - desc='Type of denoising strategy:\n' - '-no: only classification, no denoising\n' - '-nonaggr (default): non-aggresssive denoising, i.e. partial component regression\n' - '-aggr: aggressive denoising, i.e. full component regression\n' - '-both: both aggressive and non-aggressive denoising (two outputs)') + feat_dir = Directory( + exists=True, + mandatory=True, + argstr='-feat %s', + xor=['in_file', 'mat_file', 'fnirt_warp_file', 'motion_parameters'], + desc='If a feat directory exists and temporal filtering ' + 'has not been run yet, ICA_AROMA can use the files in ' + 'this directory.') + in_file = File( + exists=True, + mandatory=True, + argstr='-i %s', + xor=['feat_dir'], + desc='volume to be denoised') + out_dir = Directory( + 'out', genfile=True, argstr='-o %s', desc='output directory') + mask = File( + exists=True, + argstr='-m %s', + xor=['feat_dir'], + desc='path/name volume mask') + dim = traits.Int( + argstr='-dim %d', + desc='Dimensionality reduction when running ' + 'MELODIC (defualt is automatic estimation)') + TR = traits.Float( + argstr='-tr %.3f', + desc='TR in seconds. If this is not specified ' + 'the TR will be extracted from the ' + 'header of the fMRI nifti file.') + melodic_dir = Directory( + exists=True, + argstr='-meldir %s', + desc='path to MELODIC directory if MELODIC has already been run') + mat_file = File( + exists=True, + argstr='-affmat %s', + xor=['feat_dir'], + desc='path/name of the mat-file describing the ' + 'affine registration (e.g. FSL FLIRT) of the ' + 'functional data to structural space (.mat file)') + fnirt_warp_file = File( + exists=True, + argstr='-warp %s', + xor=['feat_dir'], + desc='File name of the warp-file describing ' + 'the non-linear registration (e.g. FSL FNIRT) ' + 'of the structural data to MNI152 space (.nii.gz)') + motion_parameters = File( + exists=True, + mandatory=True, + argstr='-mc %s', + xor=['feat_dir'], + desc='motion parameters file') + denoise_type = traits.Enum( + 'nonaggr', + 'aggr', + 'both', + 'no', + usedefault=True, + mandatory=True, + argstr='-den %s', + desc='Type of denoising strategy:\n' + '-no: only classification, no denoising\n' + '-nonaggr (default): non-aggresssive denoising, i.e. partial component regression\n' + '-aggr: aggressive denoising, i.e. full component regression\n' + '-both: both aggressive and non-aggressive denoising (two outputs)') + class ICA_AROMAOutputSpec(TraitedSpec): - aggr_denoised_file = File(exists=True, - desc='if generated: aggressively denoised volume') - nonaggr_denoised_file = File(exists=True, - desc='if generated: non aggressively denoised volume' ) - out_dir = Directory(exists=True, - desc='directory contains (in addition to the denoised files): ' - 'melodic.ica + classified_motion_components + ' - 'classification_overview + feature_scores + melodic_ic_mni)') + aggr_denoised_file = File( + exists=True, desc='if generated: aggressively denoised volume') + nonaggr_denoised_file = File( + exists=True, desc='if generated: non aggressively denoised volume') + out_dir = Directory( + exists=True, + desc='directory contains (in addition to the denoised files): ' + 'melodic.ica + classified_motion_components + ' + 'classification_overview + feature_scores + melodic_ic_mni)') + class ICA_AROMA(CommandLine): """ @@ -111,9 +141,11 @@ def _list_outputs(self): out_dir = outputs['out_dir'] if self.inputs.denoise_type in ('aggr', 'both'): - outputs['aggr_denoised_file'] = os.path.join(out_dir, 'denoised_func_data_aggr.nii.gz') + outputs['aggr_denoised_file'] = os.path.join( + out_dir, 'denoised_func_data_aggr.nii.gz') if self.inputs.denoise_type in ('nonaggr', 'both'): - outputs['nonaggr_denoised_file'] = os.path.join(out_dir, 'denoised_func_data_nonaggr.nii.gz') + outputs['nonaggr_denoised_file'] = os.path.join( + out_dir, 'denoised_func_data_nonaggr.nii.gz') return outputs def _gen_filename(self, name): diff --git a/nipype/interfaces/fsl/base.py b/nipype/interfaces/fsl/base.py index 2bb120e097..59dc759d2e 100644 --- a/nipype/interfaces/fsl/base.py +++ b/nipype/interfaces/fsl/base.py @@ -25,14 +25,16 @@ See the docstrings of the individual classes for examples. """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from glob import glob import os from ... import logging from ...utils.filemanip import fname_presuffix -from ..base import traits, isdefined, CommandLine, CommandLineInputSpec, PackageInfo +from ..base import (traits, isdefined, CommandLine, CommandLineInputSpec, + PackageInfo) from ...external.due import BibTeX IFLOGGER = logging.getLogger('interface') @@ -55,14 +57,15 @@ class Info(PackageInfo): """ - ftypes = {'NIFTI': '.nii', - 'NIFTI_PAIR': '.img', - 'NIFTI_GZ': '.nii.gz', - 'NIFTI_PAIR_GZ': '.img.gz'} + ftypes = { + 'NIFTI': '.nii', + 'NIFTI_PAIR': '.img', + 'NIFTI_GZ': '.nii.gz', + 'NIFTI_PAIR_GZ': '.img.gz' + } if os.getenv('FSLDIR'): - version_file = os.path.join( - os.getenv('FSLDIR'), 'etc', 'fslversion') + version_file = os.path.join(os.getenv('FSLDIR'), 'etc', 'fslversion') @staticmethod def parse_version(raw_info): @@ -121,8 +124,10 @@ def standard_image(img_name=None): raise Exception('FSL environment variables not set') stdpath = os.path.join(fsldir, 'data', 'standard') if img_name is None: - return [filename.replace(stdpath + '/', '') - for filename in glob(os.path.join(stdpath, '*nii*'))] + return [ + filename.replace(stdpath + '/', '') + for filename in glob(os.path.join(stdpath, '*nii*')) + ] return os.path.join(stdpath, img_name) @@ -137,8 +142,8 @@ class FSLCommandInputSpec(CommandLineInputSpec): ------- fsl.ExtractRoi(tmin=42, tsize=1, output_type='NIFTI') """ - output_type = traits.Enum('NIFTI', list(Info.ftypes.keys()), - desc='FSL output type') + output_type = traits.Enum( + 'NIFTI', list(Info.ftypes.keys()), desc='FSL output type') class FSLCommand(CommandLine): @@ -149,17 +154,19 @@ class FSLCommand(CommandLine): input_spec = FSLCommandInputSpec _output_type = None - references_ = [{'entry': BibTeX('@article{JenkinsonBeckmannBehrensWoolrichSmith2012,' - 'author={M. Jenkinson, C.F. Beckmann, T.E. Behrens, ' - 'M.W. Woolrich, and S.M. Smith},' - 'title={FSL},' - 'journal={NeuroImage},' - 'volume={62},' - 'pages={782-790},' - 'year={2012},' - '}'), - 'tags': ['implementation'], - }] + references_ = [{ + 'entry': + BibTeX('@article{JenkinsonBeckmannBehrensWoolrichSmith2012,' + 'author={M. Jenkinson, C.F. Beckmann, T.E. Behrens, ' + 'M.W. Woolrich, and S.M. Smith},' + 'title={FSL},' + 'journal={NeuroImage},' + 'volume={62},' + 'pages={782-790},' + 'year={2012},' + '}'), + 'tags': ['implementation'], + }] def __init__(self, **inputs): super(FSLCommand, self).__init__(**inputs) @@ -196,7 +203,11 @@ def set_default_output_type(cls, output_type): def version(self): return Info.version() - def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, + def _gen_fname(self, + basename, + cwd=None, + suffix=None, + change_ext=True, ext=None): """Generate a filename based on the given parameters. @@ -238,8 +249,8 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, suffix = ext if suffix is None: suffix = '' - fname = fname_presuffix(basename, suffix=suffix, - use_ext=False, newpath=cwd) + fname = fname_presuffix( + basename, suffix=suffix, use_ext=False, newpath=cwd) return fname def _overload_extension(self, value, name=None): @@ -267,5 +278,5 @@ def no_fsl(): def no_fsl_course_data(): """check if fsl_course data is present""" - return not ('FSL_COURSE_DATA' in os.environ and - os.path.isdir(os.path.abspath(os.environ['FSL_COURSE_DATA']))) + return not ('FSL_COURSE_DATA' in os.environ and os.path.isdir( + os.path.abspath(os.environ['FSL_COURSE_DATA']))) diff --git a/nipype/interfaces/fsl/dti.py b/nipype/interfaces/fsl/dti.py index 812515fcda..cf14d1072f 100644 --- a/nipype/interfaces/fsl/dti.py +++ b/nipype/interfaces/fsl/dti.py @@ -12,44 +12,66 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, open import os import warnings from ...utils.filemanip import fname_presuffix, split_filename, copyfile -from ..base import (TraitedSpec, isdefined, File, Directory, - InputMultiPath, OutputMultiPath, traits) +from ..base import (TraitedSpec, isdefined, File, Directory, InputMultiPath, + OutputMultiPath, traits) from .base import (FSLCommand, FSLCommandInputSpec, Info) + class DTIFitInputSpec(FSLCommandInputSpec): - dwi = File(exists=True, desc='diffusion weighted image data file', - argstr='-k %s', position=0, mandatory=True) - base_name = traits.Str("dtifit_", desc=('base_name that all output files ' - 'will start with'), - argstr='-o %s', position=1, usedefault=True) - mask = File(exists=True, desc='bet binary mask file', - argstr='-m %s', position=2, mandatory=True) - bvecs = File(exists=True, desc='b vectors file', - argstr='-r %s', position=3, mandatory=True) - bvals = File(exists=True, desc='b values file', - argstr='-b %s', position=4, mandatory=True) + dwi = File( + exists=True, + desc='diffusion weighted image data file', + argstr='-k %s', + position=0, + mandatory=True) + base_name = traits.Str( + "dtifit_", + desc=('base_name that all output files ' + 'will start with'), + argstr='-o %s', + position=1, + usedefault=True) + mask = File( + exists=True, + desc='bet binary mask file', + argstr='-m %s', + position=2, + mandatory=True) + bvecs = File( + exists=True, + desc='b vectors file', + argstr='-r %s', + position=3, + mandatory=True) + bvals = File( + exists=True, + desc='b values file', + argstr='-b %s', + position=4, + mandatory=True) min_z = traits.Int(argstr='-z %d', desc='min z') max_z = traits.Int(argstr='-Z %d', desc='max z') min_y = traits.Int(argstr='-y %d', desc='min y') max_y = traits.Int(argstr='-Y %d', desc='max y') min_x = traits.Int(argstr='-x %d', desc='min x') max_x = traits.Int(argstr='-X %d', desc='max x') - save_tensor = traits.Bool(desc='save the elements of the tensor', - argstr='--save_tensor') + save_tensor = traits.Bool( + desc='save the elements of the tensor', argstr='--save_tensor') sse = traits.Bool(desc='output sum of squared errors', argstr='--sse') - cni = File(exists=True, desc='input counfound regressors', - argstr='--cni=%s') - little_bit = traits.Bool(desc='only process small area of brain', - argstr='--littlebit') - gradnonlin = File(exists=True, argstr='--gradnonlin=%s', - desc='gradient non linearities') + cni = File( + exists=True, desc='input counfound regressors', argstr='--cni=%s') + little_bit = traits.Bool( + desc='only process small area of brain', argstr='--littlebit') + gradnonlin = File( + exists=True, argstr='--gradnonlin=%s', desc='gradient non linearities') class DTIFitOutputSpec(TraitedSpec): @@ -60,15 +82,16 @@ class DTIFitOutputSpec(TraitedSpec): L2 = File(exists=True, desc='path/name of file with the 2nd eigenvalue') L3 = File(exists=True, desc='path/name of file with the 3rd eigenvalue') MD = File(exists=True, desc='path/name of file with the mean diffusivity') - FA = File(exists=True, - desc='path/name of file with the fractional anisotropy') - MO = File(exists=True, - desc='path/name of file with the mode of anisotropy') - S0 = File(exists=True, - desc=('path/name of file with the raw T2 signal with no ' - 'diffusion weighting')) - tensor = File(exists=True, - desc='path/name of file with the 4D tensor volume') + FA = File( + exists=True, desc='path/name of file with the fractional anisotropy') + MO = File( + exists=True, desc='path/name of file with the mode of anisotropy') + S0 = File( + exists=True, + desc=('path/name of file with the raw T2 signal with no ' + 'diffusion weighting')) + tensor = File( + exists=True, desc='path/name of file with the 4D tensor volume') class DTIFit(FSLCommand): @@ -98,99 +121,147 @@ def _list_outputs(self): outputs = self.output_spec().get() for k in list(outputs.keys()): if k not in ('outputtype', 'environ', 'args'): - if k != 'tensor' or (isdefined(self.inputs.save_tensor) and - self.inputs.save_tensor): + if k != 'tensor' or (isdefined(self.inputs.save_tensor) + and self.inputs.save_tensor): outputs[k] = self._gen_fname( self.inputs.base_name, suffix='_' + k) return outputs class FSLXCommandInputSpec(FSLCommandInputSpec): - dwi = File(exists=True, argstr='--data=%s', mandatory=True, - desc='diffusion weighted image data file') - mask = File(exists=True, argstr='--mask=%s', mandatory=True, - desc='brain binary mask file (i.e. from BET)') - bvecs = File(exists=True, argstr='--bvecs=%s', mandatory=True, - desc='b vectors file') - bvals = File(exists=True, argstr='--bvals=%s', mandatory=True, - desc='b values file') + dwi = File( + exists=True, + argstr='--data=%s', + mandatory=True, + desc='diffusion weighted image data file') + mask = File( + exists=True, + argstr='--mask=%s', + mandatory=True, + desc='brain binary mask file (i.e. from BET)') + bvecs = File( + exists=True, + argstr='--bvecs=%s', + mandatory=True, + desc='b vectors file') + bvals = File( + exists=True, argstr='--bvals=%s', mandatory=True, desc='b values file') logdir = Directory('.', argstr='--logdir=%s', usedefault=True) n_fibres = traits.Range( - usedefault=True, low=1, default=2, argstr='--nfibres=%d', - desc=('Maximum number of fibres to fit in each voxel'), mandatory=True) - model = traits.Enum(1, 2, 3, argstr='--model=%d', - desc=('use monoexponential (1, default, required for ' - 'single-shell) or multiexponential (2, multi-' - 'shell) model')) - fudge = traits.Int(argstr='--fudge=%d', - desc='ARD fudge factor') - n_jumps = traits.Int(5000, argstr='--njumps=%d', - desc='Num of jumps to be made by MCMC') - burn_in = traits.Range(low=0, default=0, argstr='--burnin=%d', - desc=('Total num of jumps at start of MCMC to be ' - 'discarded')) - burn_in_no_ard = traits.Range(low=0, default=0, argstr='--burninnoard=%d', - desc=('num of burnin jumps before the ard is' - ' imposed')) - sample_every = traits.Range(low=0, default=1, argstr='--sampleevery=%d', - desc='Num of jumps for each sample (MCMC)') - update_proposal_every = traits.Range(low=1, default=40, - argstr='--updateproposalevery=%d', - desc=('Num of jumps for each update ' - 'to the proposal density std ' - '(MCMC)')) - seed = traits.Int(argstr='--seed=%d', - desc='seed for pseudo random number generator') + usedefault=True, + low=1, + default=2, + argstr='--nfibres=%d', + desc=('Maximum number of fibres to fit in each voxel'), + mandatory=True) + model = traits.Enum( + 1, + 2, + 3, + argstr='--model=%d', + desc=('use monoexponential (1, default, required for ' + 'single-shell) or multiexponential (2, multi-' + 'shell) model')) + fudge = traits.Int(argstr='--fudge=%d', desc='ARD fudge factor') + n_jumps = traits.Int( + 5000, argstr='--njumps=%d', desc='Num of jumps to be made by MCMC') + burn_in = traits.Range( + low=0, + default=0, + argstr='--burnin=%d', + desc=('Total num of jumps at start of MCMC to be ' + 'discarded')) + burn_in_no_ard = traits.Range( + low=0, + default=0, + argstr='--burninnoard=%d', + desc=('num of burnin jumps before the ard is' + ' imposed')) + sample_every = traits.Range( + low=0, + default=1, + argstr='--sampleevery=%d', + desc='Num of jumps for each sample (MCMC)') + update_proposal_every = traits.Range( + low=1, + default=40, + argstr='--updateproposalevery=%d', + desc=('Num of jumps for each update ' + 'to the proposal density std ' + '(MCMC)')) + seed = traits.Int( + argstr='--seed=%d', desc='seed for pseudo random number generator') _xor_inputs1 = ('no_ard', 'all_ard') - no_ard = traits.Bool(argstr='--noard', xor=_xor_inputs1, - desc='Turn ARD off on all fibres') - all_ard = traits.Bool(argstr='--allard', xor=_xor_inputs1, - desc='Turn ARD on on all fibres') + no_ard = traits.Bool( + argstr='--noard', xor=_xor_inputs1, desc='Turn ARD off on all fibres') + all_ard = traits.Bool( + argstr='--allard', xor=_xor_inputs1, desc='Turn ARD on on all fibres') _xor_inputs2 = ('no_spat', 'non_linear', 'cnlinear') - no_spat = traits.Bool(argstr='--nospat', xor=_xor_inputs2, - desc='Initialise with tensor, not spatially') - non_linear = traits.Bool(argstr='--nonlinear', xor=_xor_inputs2, - desc='Initialise with nonlinear fitting') - cnlinear = traits.Bool(argstr='--cnonlinear', xor=_xor_inputs2, - desc=('Initialise with constrained nonlinear ' - 'fitting')) + no_spat = traits.Bool( + argstr='--nospat', + xor=_xor_inputs2, + desc='Initialise with tensor, not spatially') + non_linear = traits.Bool( + argstr='--nonlinear', + xor=_xor_inputs2, + desc='Initialise with nonlinear fitting') + cnlinear = traits.Bool( + argstr='--cnonlinear', + xor=_xor_inputs2, + desc=('Initialise with constrained nonlinear ' + 'fitting')) rician = traits.Bool(argstr='--rician', desc=('use Rician noise modeling')) _xor_inputs3 = ['f0_noard', 'f0_ard'] - f0_noard = traits.Bool(argstr='--f0', xor=_xor_inputs3, - desc=('Noise floor model: add to the model an ' - 'unattenuated signal compartment f0')) - f0_ard = traits.Bool(argstr='--f0 --ardf0', xor=_xor_inputs3 + ['all_ard'], - desc=('Noise floor model: add to the model an ' - 'unattenuated signal compartment f0')) - force_dir = traits.Bool(True, argstr='--forcedir', usedefault=True, - desc=('use the actual directory name given ' - '(do not add + to make a new directory)')) + f0_noard = traits.Bool( + argstr='--f0', + xor=_xor_inputs3, + desc=('Noise floor model: add to the model an ' + 'unattenuated signal compartment f0')) + f0_ard = traits.Bool( + argstr='--f0 --ardf0', + xor=_xor_inputs3 + ['all_ard'], + desc=('Noise floor model: add to the model an ' + 'unattenuated signal compartment f0')) + force_dir = traits.Bool( + True, + argstr='--forcedir', + usedefault=True, + desc=('use the actual directory name given ' + '(do not add + to make a new directory)')) class FSLXCommandOutputSpec(TraitedSpec): - dyads = OutputMultiPath(File(exists=True), desc=('Mean of PDD distribution' - ' in vector form.')) - fsamples = OutputMultiPath(File(exists=True), desc=('Samples from the ' - 'distribution on f ' - 'anisotropy')) - mean_dsamples = File(exists=True, - desc='Mean of distribution on diffusivity d') - mean_fsamples = OutputMultiPath(File(exists=True), - desc=('Mean of distribution on f ' - 'anisotropy')) - mean_S0samples = File(exists=True, desc=('Mean of distribution on T2w' - 'baseline signal intensity S0')) - mean_tausamples = File(exists=True, desc=('Mean of distribution on ' - 'tau samples (only with rician ' - 'noise)')) - phsamples = OutputMultiPath(File(exists=True), - desc=('phi samples, per fiber')) - thsamples = OutputMultiPath(File(exists=True), - desc=('theta samples, per fiber')) + dyads = OutputMultiPath( + File(exists=True), + desc=('Mean of PDD distribution' + ' in vector form.')) + fsamples = OutputMultiPath( + File(exists=True), + desc=('Samples from the ' + 'distribution on f ' + 'anisotropy')) + mean_dsamples = File( + exists=True, desc='Mean of distribution on diffusivity d') + mean_fsamples = OutputMultiPath( + File(exists=True), desc=('Mean of distribution on f ' + 'anisotropy')) + mean_S0samples = File( + exists=True, + desc=('Mean of distribution on T2w' + 'baseline signal intensity S0')) + mean_tausamples = File( + exists=True, + desc=('Mean of distribution on ' + 'tau samples (only with rician ' + 'noise)')) + phsamples = OutputMultiPath( + File(exists=True), desc=('phi samples, per fiber')) + thsamples = OutputMultiPath( + File(exists=True), desc=('theta samples, per fiber')) class FSLXCommand(FSLCommand): @@ -216,93 +287,117 @@ def _list_outputs(self, out_dir=None): else: out_dir = os.path.abspath('logdir') - multi_out = ['dyads', 'fsamples', 'mean_fsamples', - 'phsamples', 'thsamples'] + multi_out = [ + 'dyads', 'fsamples', 'mean_fsamples', 'phsamples', 'thsamples' + ] single_out = ['mean_dsamples', 'mean_S0samples'] for k in single_out: outputs[k] = self._gen_fname(k, cwd=out_dir) if isdefined(self.inputs.rician) and self.inputs.rician: - outputs['mean_tausamples'] = self._gen_fname('mean_tausamples', - cwd=out_dir) + outputs['mean_tausamples'] = self._gen_fname( + 'mean_tausamples', cwd=out_dir) for k in multi_out: outputs[k] = [] for i in range(1, n_fibres + 1): - outputs['fsamples'].append(self._gen_fname('f%dsamples' % i, - cwd=out_dir)) + outputs['fsamples'].append( + self._gen_fname('f%dsamples' % i, cwd=out_dir)) outputs['mean_fsamples'].append( self._gen_fname('mean_f%dsamples' % i, cwd=out_dir)) for i in range(1, n_fibres + 1): - outputs['dyads'].append(self._gen_fname('dyads%d' % i, - cwd=out_dir)) - outputs['phsamples'].append(self._gen_fname('ph%dsamples' % i, - cwd=out_dir)) - outputs['thsamples'].append(self._gen_fname('th%dsamples' % i, - cwd=out_dir)) + outputs['dyads'].append( + self._gen_fname('dyads%d' % i, cwd=out_dir)) + outputs['phsamples'].append( + self._gen_fname('ph%dsamples' % i, cwd=out_dir)) + outputs['thsamples'].append( + self._gen_fname('th%dsamples' % i, cwd=out_dir)) return outputs class BEDPOSTX5InputSpec(FSLXCommandInputSpec): - dwi = File(exists=True, desc='diffusion weighted image data file', - mandatory=True) + dwi = File( + exists=True, desc='diffusion weighted image data file', mandatory=True) mask = File(exists=True, desc='bet binary mask file', mandatory=True) bvecs = File(exists=True, desc='b vectors file', mandatory=True) bvals = File(exists=True, desc='b values file', mandatory=True) logdir = Directory(argstr='--logdir=%s') n_fibres = traits.Range( - usedefault=True, low=1, default=2, argstr='-n %d', - desc=('Maximum number of fibres to fit in each voxel'), mandatory=True) - model = traits.Enum(1, 2, 3, argstr='-model %d', - desc=('use monoexponential (1, default, required for ' - 'single-shell) or multiexponential (2, multi-' - 'shell) model')) - fudge = traits.Int(argstr='-w %d', - desc='ARD fudge factor') - n_jumps = traits.Int(5000, argstr='-j %d', - desc='Num of jumps to be made by MCMC') - burn_in = traits.Range(low=0, default=0, argstr='-b %d', - desc=('Total num of jumps at start of MCMC to be ' - 'discarded')) - sample_every = traits.Range(low=0, default=1, argstr='-s %d', - desc='Num of jumps for each sample (MCMC)') - out_dir = Directory('bedpostx', mandatory=True, desc='output directory', - usedefault=True, position=1, argstr='%s') - gradnonlin = traits.Bool(False, argstr='-g', - desc=('consider gradient nonlinearities, ' - 'default off')) - grad_dev = File(exists=True, - desc='grad_dev file, if gradnonlin, -g is True') + usedefault=True, + low=1, + default=2, + argstr='-n %d', + desc=('Maximum number of fibres to fit in each voxel'), + mandatory=True) + model = traits.Enum( + 1, + 2, + 3, + argstr='-model %d', + desc=('use monoexponential (1, default, required for ' + 'single-shell) or multiexponential (2, multi-' + 'shell) model')) + fudge = traits.Int(argstr='-w %d', desc='ARD fudge factor') + n_jumps = traits.Int( + 5000, argstr='-j %d', desc='Num of jumps to be made by MCMC') + burn_in = traits.Range( + low=0, + default=0, + argstr='-b %d', + desc=('Total num of jumps at start of MCMC to be ' + 'discarded')) + sample_every = traits.Range( + low=0, + default=1, + argstr='-s %d', + desc='Num of jumps for each sample (MCMC)') + out_dir = Directory( + 'bedpostx', + mandatory=True, + desc='output directory', + usedefault=True, + position=1, + argstr='%s') + gradnonlin = traits.Bool( + False, + argstr='-g', + desc=('consider gradient nonlinearities, ' + 'default off')) + grad_dev = File( + exists=True, desc='grad_dev file, if gradnonlin, -g is True') use_gpu = traits.Bool(False, desc='Use the GPU version of bedpostx') class BEDPOSTX5OutputSpec(TraitedSpec): - mean_dsamples = File(exists=True, - desc='Mean of distribution on diffusivity d') - mean_fsamples = OutputMultiPath(File(exists=True), - desc=('Mean of distribution on f ' - 'anisotropy')) - mean_S0samples = File(exists=True, desc=('Mean of distribution on T2w' - 'baseline signal intensity S0')) - mean_phsamples = OutputMultiPath(File(exists=True), - desc='Mean of distribution on phi') - mean_thsamples = OutputMultiPath(File(exists=True), - desc='Mean of distribution on theta') - merged_thsamples = OutputMultiPath(File(exists=True), - desc=('Samples from the distribution ' - 'on theta')) - merged_phsamples = OutputMultiPath(File(exists=True), - desc=('Samples from the distribution ' - 'on phi')) - merged_fsamples = OutputMultiPath(File(exists=True), - desc=('Samples from the distribution on ' - 'anisotropic volume fraction')) - dyads = OutputMultiPath(File(exists=True), - desc='Mean of PDD distribution in vector form.') + mean_dsamples = File( + exists=True, desc='Mean of distribution on diffusivity d') + mean_fsamples = OutputMultiPath( + File(exists=True), desc=('Mean of distribution on f ' + 'anisotropy')) + mean_S0samples = File( + exists=True, + desc=('Mean of distribution on T2w' + 'baseline signal intensity S0')) + mean_phsamples = OutputMultiPath( + File(exists=True), desc='Mean of distribution on phi') + mean_thsamples = OutputMultiPath( + File(exists=True), desc='Mean of distribution on theta') + merged_thsamples = OutputMultiPath( + File(exists=True), desc=('Samples from the distribution ' + 'on theta')) + merged_phsamples = OutputMultiPath( + File(exists=True), desc=('Samples from the distribution ' + 'on phi')) + merged_fsamples = OutputMultiPath( + File(exists=True), + desc=('Samples from the distribution on ' + 'anisotropic volume fraction')) + dyads = OutputMultiPath( + File(exists=True), desc='Mean of PDD distribution in vector form.') dyads_dispersion = OutputMultiPath(File(exists=True), desc=('Dispersion')) @@ -355,15 +450,11 @@ def _run_interface(self, runtime): os.makedirs(subjectdir) _, _, ext = split_filename(self.inputs.mask) copyfile(self.inputs.mask, - os.path.join(subjectdir, - 'nodif_brain_mask' + ext)) + os.path.join(subjectdir, 'nodif_brain_mask' + ext)) _, _, ext = split_filename(self.inputs.dwi) - copyfile(self.inputs.dwi, - os.path.join(subjectdir, 'data' + ext)) - copyfile(self.inputs.bvals, - os.path.join(subjectdir, 'bvals')) - copyfile(self.inputs.bvecs, - os.path.join(subjectdir, 'bvecs')) + copyfile(self.inputs.dwi, os.path.join(subjectdir, 'data' + ext)) + copyfile(self.inputs.bvals, os.path.join(subjectdir, 'bvals')) + copyfile(self.inputs.bvecs, os.path.join(subjectdir, 'bvecs')) if isdefined(self.inputs.grad_dev): _, _, ext = split_filename(self.inputs.grad_dev) copyfile(self.inputs.grad_dev, @@ -378,10 +469,11 @@ def _list_outputs(self): outputs = self.output_spec().get() n_fibres = self.inputs.n_fibres - multi_out = ['merged_thsamples', 'merged_fsamples', - 'merged_phsamples', 'mean_phsamples', - 'mean_thsamples', 'mean_fsamples', - 'dyads_dispersion', 'dyads'] + multi_out = [ + 'merged_thsamples', 'merged_fsamples', 'merged_phsamples', + 'mean_phsamples', 'mean_thsamples', 'mean_fsamples', + 'dyads_dispersion', 'dyads' + ] single_out = ['mean_dsamples', 'mean_S0samples'] @@ -412,8 +504,10 @@ def _list_outputs(self): class XFibres5InputSpec(FSLXCommandInputSpec): - gradnonlin = File(exists=True, argstr='--gradnonlin=%s', - desc='gradient file corresponding to slice') + gradnonlin = File( + exists=True, + argstr='--gradnonlin=%s', + desc='gradient file corresponding to slice') class XFibres5(FSLXCommand): @@ -425,6 +519,7 @@ class XFibres5(FSLXCommand): input_spec = XFibres5InputSpec output_spec = FSLXCommandOutputSpec + XFibres = XFibres5 BEDPOSTX = BEDPOSTX5 @@ -433,141 +528,192 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): thsamples = InputMultiPath(File(exists=True), mandatory=True) phsamples = InputMultiPath(File(exists=True), mandatory=True) fsamples = InputMultiPath(File(exists=True), mandatory=True) - samples_base_name = traits.Str("merged", - desc=('the rootname/base_name for samples ' - 'files'), - argstr='--samples=%s', usedefault=True) - mask = File(exists=True, desc='bet binary mask file in diffusion space', - argstr='-m %s', mandatory=True) - seed = traits.Either(File(exists=True), traits.List(File(exists=True)), - traits.List(traits.List(traits.Int(), - minlen=3, maxlen=3)), - desc=('seed volume(s), or voxel(s) or freesurfer ' - 'label file'), - argstr='--seed=%s', mandatory=True) - target_masks = InputMultiPath(File(exits=True), - desc=('list of target masks - required for ' - 'seeds_to_targets classification'), - argstr='--targetmasks=%s') - waypoints = File(exists=True, - desc=('waypoint mask or ascii list of waypoint masks - ' - 'only keep paths going through ALL the masks'), - argstr='--waypoints=%s') - network = traits.Bool(desc=('activate network mode - only keep paths ' - 'going through at least one seed mask ' - '(required if multiple seed masks)'), - argstr='--network') - seed_ref = File(exists=True, - desc=('reference vol to define seed space in simple mode ' - '- diffusion space assumed if absent'), - argstr='--seedref=%s') - out_dir = Directory(exists=True, argstr='--dir=%s', - desc='directory to put the final volumes in', - genfile=True) - force_dir = traits.Bool(True, - desc=('use the actual directory name given - i.e. ' - 'do not add + to make a new directory'), - argstr='--forcedir', usedefault=True) - opd = traits.Bool(True, desc='outputs path distributions', - argstr='--opd', usedefault=True) - correct_path_distribution = traits.Bool(desc=('correct path distribution ' - 'for the length of the ' - 'pathways'), - argstr='--pd') + samples_base_name = traits.Str( + "merged", + desc=('the rootname/base_name for samples ' + 'files'), + argstr='--samples=%s', + usedefault=True) + mask = File( + exists=True, + desc='bet binary mask file in diffusion space', + argstr='-m %s', + mandatory=True) + seed = traits.Either( + File(exists=True), + traits.List(File(exists=True)), + traits.List(traits.List(traits.Int(), minlen=3, maxlen=3)), + desc=('seed volume(s), or voxel(s) or freesurfer ' + 'label file'), + argstr='--seed=%s', + mandatory=True) + target_masks = InputMultiPath( + File(exits=True), + desc=('list of target masks - required for ' + 'seeds_to_targets classification'), + argstr='--targetmasks=%s') + waypoints = File( + exists=True, + desc=('waypoint mask or ascii list of waypoint masks - ' + 'only keep paths going through ALL the masks'), + argstr='--waypoints=%s') + network = traits.Bool( + desc=('activate network mode - only keep paths ' + 'going through at least one seed mask ' + '(required if multiple seed masks)'), + argstr='--network') + seed_ref = File( + exists=True, + desc=('reference vol to define seed space in simple mode ' + '- diffusion space assumed if absent'), + argstr='--seedref=%s') + out_dir = Directory( + exists=True, + argstr='--dir=%s', + desc='directory to put the final volumes in', + genfile=True) + force_dir = traits.Bool( + True, + desc=('use the actual directory name given - i.e. ' + 'do not add + to make a new directory'), + argstr='--forcedir', + usedefault=True) + opd = traits.Bool( + True, + desc='outputs path distributions', + argstr='--opd', + usedefault=True) + correct_path_distribution = traits.Bool( + desc=('correct path distribution ' + 'for the length of the ' + 'pathways'), + argstr='--pd') os2t = traits.Bool(desc='Outputs seeds to targets', argstr='--os2t') # paths_file = File('nipype_fdtpaths', usedefault=True, argstr='--out=%s', # desc='produces an output file (default is fdt_paths)') - avoid_mp = File(exists=True, - desc=('reject pathways passing through locations given by ' - 'this mask'), - argstr='--avoid=%s') - stop_mask = File(exists=True, argstr='--stop=%s', - desc='stop tracking at locations given by this mask file') - xfm = File(exists=True, argstr='--xfm=%s', - desc=('transformation matrix taking seed space to DTI space ' - '(either FLIRT matrix or FNIRT warp_field) - default is ' - 'identity')) - inv_xfm = File(argstr='--invxfm=%s', - desc=('transformation matrix taking DTI space to seed ' - 'space (compulsory when using a warp_field for ' - 'seeds_to_dti)')) - n_samples = traits.Int(5000, argstr='--nsamples=%d', - desc='number of samples - default=5000', - usedefault=True) - n_steps = traits.Int(argstr='--nsteps=%d', - desc='number of steps per sample - default=2000') - dist_thresh = traits.Float(argstr='--distthresh=%.3f', - desc=('discards samples shorter than this ' - 'threshold (in mm - default=0)')) - c_thresh = traits.Float(argstr='--cthr=%.3f', - desc='curvature threshold - default=0.2') - sample_random_points = traits.Bool(argstr='--sampvox', - desc=('sample random points within ' - 'seed voxels')) - step_length = traits.Float(argstr='--steplength=%.3f', - desc='step_length in mm - default=0.5') - loop_check = traits.Bool(argstr='--loopcheck', - desc=('perform loop_checks on paths - slower, ' - 'but allows lower curvature threshold')) - use_anisotropy = traits.Bool(argstr='--usef', - desc='use anisotropy to constrain tracking') - rand_fib = traits.Enum(0, 1, 2, 3, argstr='--randfib=%d', - desc=('options: 0 - default, 1 - to randomly ' - 'sample initial fibres (with f > fibthresh), ' - '2 - to sample in proportion fibres (with ' - 'f>fibthresh) to f, 3 - to sample ALL ' - 'populations at random (even if ' - 'f fibthresh), ' + '2 - to sample in proportion fibres (with ' + 'f>fibthresh) to f, 3 - to sample ALL ' + 'populations at random (even if ' + 'f>> from nipype.interfaces import fsl >>> pbx = fsl.ProbTrackX(samples_base_name='merged', mask='mask.nii', \ seed='MASK_average_thal_right.nii', mode='seedmask', \ - xfm='trans.mat', n_samples=3, n_steps=10, force_dir=True, opd=True, os2t=True, \ - target_masks = ['targets_MASK1.nii', 'targets_MASK2.nii'], \ - thsamples='merged_thsamples.nii', fsamples='merged_fsamples.nii', phsamples='merged_phsamples.nii', \ - out_dir='.') + xfm='trans.mat', n_samples=3, n_steps=10, force_dir=True, opd=True, \ + os2t=True, target_masks = ['targets_MASK1.nii', 'targets_MASK2.nii'], \ + thsamples='merged_thsamples.nii', fsamples='merged_fsamples.nii', \ + phsamples='merged_phsamples.nii', out_dir='.') >>> pbx.cmdline 'probtrackx --forcedir -m mask.nii --mode=seedmask --nsamples=3 --nsteps=10 --opd --os2t --dir=. --samples=merged --seed=MASK_average_thal_right.nii --targetmasks=targets.txt --xfm=trans.mat' @@ -600,17 +746,20 @@ def __init__(self, **inputs): def _run_interface(self, runtime): for i in range(1, len(self.inputs.thsamples) + 1): _, _, ext = split_filename(self.inputs.thsamples[i - 1]) - copyfile(self.inputs.thsamples[i - 1], - self.inputs.samples_base_name + "_th%dsamples" % i + ext, - copy=False) + copyfile( + self.inputs.thsamples[i - 1], + self.inputs.samples_base_name + "_th%dsamples" % i + ext, + copy=False) _, _, ext = split_filename(self.inputs.thsamples[i - 1]) - copyfile(self.inputs.phsamples[i - 1], - self.inputs.samples_base_name + "_ph%dsamples" % i + ext, - copy=False) + copyfile( + self.inputs.phsamples[i - 1], + self.inputs.samples_base_name + "_ph%dsamples" % i + ext, + copy=False) _, _, ext = split_filename(self.inputs.thsamples[i - 1]) - copyfile(self.inputs.fsamples[i - 1], - self.inputs.samples_base_name + "_f%dsamples" % i + ext, - copy=False) + copyfile( + self.inputs.fsamples[i - 1], + self.inputs.samples_base_name + "_f%dsamples" % i + ext, + copy=False) if isdefined(self.inputs.target_masks): f = open("targets.txt", "w") @@ -650,10 +799,11 @@ def _list_outputs(self): outputs['log'] = os.path.abspath( os.path.join(out_dir, 'probtrackx.log')) - # utputs['way_total'] = os.path.abspath(os.path.join(out_dir, 'waytotal')) + # utputs['way_total'] = os.path.abspath(os.path.join(out_dir, + # 'waytotal')) if isdefined(self.inputs.opd is True): - if (isinstance(self.inputs.seed, list) and - isinstance(self.inputs.seed[0], list)): + if (isinstance(self.inputs.seed, list) + and isinstance(self.inputs.seed[0], list)): outputs['fdt_paths'] = [] for seed in self.inputs.seed: outputs['fdt_paths'].append( @@ -661,7 +811,8 @@ def _list_outputs(self): self._gen_fname( ("fdt_paths_%s" % ("_".join([str(s) for s in seed]))), - cwd=out_dir, suffix=''))) + cwd=out_dir, + suffix=''))) else: outputs['fdt_paths'] = os.path.abspath( self._gen_fname("fdt_paths", cwd=out_dir, suffix='')) @@ -670,98 +821,125 @@ def _list_outputs(self): if isdefined(self.inputs.target_masks): outputs['targets'] = [] for target in self.inputs.target_masks: - outputs['targets'].append(os.path.abspath( - self._gen_fname('seeds_to_' + os.path.split(target)[1], - cwd=out_dir, - suffix=''))) + outputs['targets'].append( + os.path.abspath( + self._gen_fname( + 'seeds_to_' + os.path.split(target)[1], + cwd=out_dir, + suffix=''))) if isdefined(self.inputs.verbose) and self.inputs.verbose == 2: - outputs['particle_files'] = [os.path.abspath( - os.path.join(out_dir, 'particle%d' % i)) - for i in range(self.inputs.n_samples)] + outputs['particle_files'] = [ + os.path.abspath(os.path.join(out_dir, 'particle%d' % i)) + for i in range(self.inputs.n_samples) + ] return outputs def _gen_filename(self, name): if name == "out_dir": return os.getcwd() elif name == "mode": - if (isinstance(self.inputs.seed, list) and - isinstance(self.inputs.seed[0], list)): + if (isinstance(self.inputs.seed, list) + and isinstance(self.inputs.seed[0], list)): return "simple" else: return "seedmask" class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec): - simple = traits.Bool(desc=('rack from a list of voxels (seed must be a ' - 'ASCII list of coordinates)'), - usedefault=False, argstr='--simple') - fopd = File(exists=True, - desc='Other mask for binning tract distribution', - argstr='--fopd=%s') - waycond = traits.Enum("OR", "AND", argstr='--waycond=%s', - desc=('Waypoint condition. Either "AND" (default) ' - 'or "OR"')) - wayorder = traits.Bool(desc=('Reject streamlines that do not hit ' - 'waypoints in given order. Only valid if ' - 'waycond=AND'), - argstr='--wayorder') - onewaycondition = traits.Bool(desc=('Apply waypoint conditions to each ' - 'half tract separately'), - argstr='--onewaycondition') - omatrix1 = traits.Bool(desc='Output matrix1 - SeedToSeed Connectivity', - argstr='--omatrix1') - distthresh1 = traits.Float(argstr='--distthresh1=%.3f', - desc=('Discards samples (in matrix1) shorter ' - 'than this threshold (in mm - ' - 'default=0)')) - omatrix2 = traits.Bool(desc='Output matrix2 - SeedToLowResMask', - argstr='--omatrix2', requires=['target2']) - target2 = File(exists=True, - desc=('Low resolution binary brain mask for storing ' - 'connectivity distribution in matrix2 mode'), - argstr='--target2=%s') - omatrix3 = traits.Bool(desc='Output matrix3 (NxN connectivity matrix)', - argstr='--omatrix3', - requires=['target3', 'lrtarget3']) - target3 = File(exists=True, - desc=('Mask used for NxN connectivity matrix (or Nxn if ' - 'lrtarget3 is set)'), - argstr='--target3=%s') - lrtarget3 = File(exists=True, - desc='Column-space mask used for Nxn connectivity matrix', - argstr='--lrtarget3=%s') - distthresh3 = traits.Float(argstr='--distthresh3=%.3f', - desc=('Discards samples (in matrix3) shorter ' - 'than this threshold (in mm - ' - 'default=0)')) - omatrix4 = traits.Bool(desc=('Output matrix4 - DtiMaskToSeed (special ' - 'Oxford Sparse Format)'), - argstr='--omatrix4') - colmask4 = File(exists=True, - desc='Mask for columns of matrix4 (default=seed mask)', - argstr='--colmask4=%s') - target4 = File(exists=True, desc='Brain mask in DTI space', - argstr='--target4=%s') - meshspace = traits.Enum("caret", "freesurfer", "first", "vox", - argstr='--meshspace=%s', - desc=('Mesh reference space - either "caret" ' - '(default) or "freesurfer" or "first" or ' - '"vox"')) + simple = traits.Bool( + desc=('rack from a list of voxels (seed must be a ' + 'ASCII list of coordinates)'), + usedefault=False, + argstr='--simple') + fopd = File( + exists=True, + desc='Other mask for binning tract distribution', + argstr='--fopd=%s') + waycond = traits.Enum( + "OR", + "AND", + argstr='--waycond=%s', + desc=('Waypoint condition. Either "AND" (default) ' + 'or "OR"')) + wayorder = traits.Bool( + desc=('Reject streamlines that do not hit ' + 'waypoints in given order. Only valid if ' + 'waycond=AND'), + argstr='--wayorder') + onewaycondition = traits.Bool( + desc=('Apply waypoint conditions to each ' + 'half tract separately'), + argstr='--onewaycondition') + omatrix1 = traits.Bool( + desc='Output matrix1 - SeedToSeed Connectivity', argstr='--omatrix1') + distthresh1 = traits.Float( + argstr='--distthresh1=%.3f', + desc=('Discards samples (in matrix1) shorter ' + 'than this threshold (in mm - ' + 'default=0)')) + omatrix2 = traits.Bool( + desc='Output matrix2 - SeedToLowResMask', + argstr='--omatrix2', + requires=['target2']) + target2 = File( + exists=True, + desc=('Low resolution binary brain mask for storing ' + 'connectivity distribution in matrix2 mode'), + argstr='--target2=%s') + omatrix3 = traits.Bool( + desc='Output matrix3 (NxN connectivity matrix)', + argstr='--omatrix3', + requires=['target3', 'lrtarget3']) + target3 = File( + exists=True, + desc=('Mask used for NxN connectivity matrix (or Nxn if ' + 'lrtarget3 is set)'), + argstr='--target3=%s') + lrtarget3 = File( + exists=True, + desc='Column-space mask used for Nxn connectivity matrix', + argstr='--lrtarget3=%s') + distthresh3 = traits.Float( + argstr='--distthresh3=%.3f', + desc=('Discards samples (in matrix3) shorter ' + 'than this threshold (in mm - ' + 'default=0)')) + omatrix4 = traits.Bool( + desc=('Output matrix4 - DtiMaskToSeed (special ' + 'Oxford Sparse Format)'), + argstr='--omatrix4') + colmask4 = File( + exists=True, + desc='Mask for columns of matrix4 (default=seed mask)', + argstr='--colmask4=%s') + target4 = File( + exists=True, desc='Brain mask in DTI space', argstr='--target4=%s') + meshspace = traits.Enum( + "caret", + "freesurfer", + "first", + "vox", + argstr='--meshspace=%s', + desc=('Mesh reference space - either "caret" ' + '(default) or "freesurfer" or "first" or ' + '"vox"')) class ProbTrackX2OutputSpec(ProbTrackXOutputSpec): - network_matrix = File(exists=True, - desc=('the network matrix generated by --omatrix1 ' - 'option')) - matrix1_dot = File(exists=True, - desc='Output matrix1.dot - SeedToSeed Connectivity') - lookup_tractspace = File(exists=True, - desc=('lookup_tractspace generated by ' - '--omatrix2 option')) - matrix2_dot = File(exists=True, - desc='Output matrix2.dot - SeedToLowResMask') - matrix3_dot = File(exists=True, - desc='Output matrix3 - NxN connectivity matrix') + network_matrix = File( + exists=True, + desc=('the network matrix generated by --omatrix1 ' + 'option')) + matrix1_dot = File( + exists=True, desc='Output matrix1.dot - SeedToSeed Connectivity') + lookup_tractspace = File( + exists=True, + desc=('lookup_tractspace generated by ' + '--omatrix2 option')) + matrix2_dot = File( + exists=True, desc='Output matrix2.dot - SeedToLowResMask') + matrix3_dot = File( + exists=True, desc='Output matrix3 - NxN connectivity matrix') class ProbTrackX2(ProbTrackX): @@ -795,7 +973,8 @@ def _list_outputs(self): else: out_dir = self.inputs.out_dir - outputs['way_total'] = os.path.abspath(os.path.join(out_dir, 'waytotal')) + outputs['way_total'] = os.path.abspath( + os.path.join(out_dir, 'waytotal')) if isdefined(self.inputs.omatrix1): outputs['network_matrix'] = os.path.abspath( @@ -816,46 +995,65 @@ def _list_outputs(self): class VecRegInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr='-i %s', - desc='filename for input vector or tensor field', - mandatory=True) - out_file = File(argstr='-o %s', - desc=('filename for output registered vector or tensor ' - 'field'), - genfile=True, hash_files=False) - ref_vol = File(exists=True, argstr='-r %s', - desc='filename for reference (target) volume', - mandatory=True) - affine_mat = File(exists=True, argstr='-t %s', - desc='filename for affine transformation matrix') - warp_field = File(exists=True, argstr='-w %s', - desc=('filename for 4D warp field for nonlinear ' - 'registration')) - rotation_mat = File(exists=True, argstr='--rotmat=%s', - desc=('filename for secondary affine matrix if set, ' - 'this will be used for the rotation of the ' - 'vector/tensor field')) - rotation_warp = File(exists=True, argstr='--rotwarp=%s', - desc=('filename for secondary warp field if set, ' - 'this will be used for the rotation of the ' - 'vector/tensor field')) - interpolation = traits.Enum("nearestneighbour", "trilinear", - "sinc", "spline", - argstr='--interp=%s', - desc=('interpolation method : ' - 'nearestneighbour, trilinear (default), ' - 'sinc or spline')) - mask = File(exists=True, argstr='-m %s', - desc='brain mask in input space') - ref_mask = File(exists=True, argstr='--refmask=%s', - desc=('brain mask in output space (useful for speed up of ' - 'nonlinear reg)')) + in_file = File( + exists=True, + argstr='-i %s', + desc='filename for input vector or tensor field', + mandatory=True) + out_file = File( + argstr='-o %s', + desc=('filename for output registered vector or tensor ' + 'field'), + genfile=True, + hash_files=False) + ref_vol = File( + exists=True, + argstr='-r %s', + desc='filename for reference (target) volume', + mandatory=True) + affine_mat = File( + exists=True, + argstr='-t %s', + desc='filename for affine transformation matrix') + warp_field = File( + exists=True, + argstr='-w %s', + desc=('filename for 4D warp field for nonlinear ' + 'registration')) + rotation_mat = File( + exists=True, + argstr='--rotmat=%s', + desc=('filename for secondary affine matrix if set, ' + 'this will be used for the rotation of the ' + 'vector/tensor field')) + rotation_warp = File( + exists=True, + argstr='--rotwarp=%s', + desc=('filename for secondary warp field if set, ' + 'this will be used for the rotation of the ' + 'vector/tensor field')) + interpolation = traits.Enum( + "nearestneighbour", + "trilinear", + "sinc", + "spline", + argstr='--interp=%s', + desc=('interpolation method : ' + 'nearestneighbour, trilinear (default), ' + 'sinc or spline')) + mask = File(exists=True, argstr='-m %s', desc='brain mask in input space') + ref_mask = File( + exists=True, + argstr='--refmask=%s', + desc=('brain mask in output space (useful for speed up of ' + 'nonlinear reg)')) class VecRegOutputSpec(TraitedSpec): - out_file = File(exists=True, - desc=('path/name of filename for the registered vector or ' - 'tensor field')) + out_file = File( + exists=True, + desc=('path/name of filename for the registered vector or ' + 'tensor field')) class VecReg(FSLCommand): @@ -890,8 +1088,8 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = self.inputs.out_file - if (not isdefined(outputs['out_file']) and - isdefined(self.inputs.in_file)): + if (not isdefined(outputs['out_file']) + and isdefined(self.inputs.in_file)): pth, base_name = os.path.split(self.inputs.in_file) outputs['out_file'] = self._gen_fname( base_name, cwd=os.path.abspath(pth), suffix='_vreg') @@ -906,19 +1104,25 @@ def _gen_filename(self, name): class ProjThreshInputSpec(FSLCommandInputSpec): - in_files = traits.List(File(exists=True), argstr='%s', - desc='a list of input volumes', - mandatory=True, position=0) - threshold = traits.Int(argstr='%d', - desc=('threshold indicating minimum number of seed ' - 'voxels entering this mask region'), - mandatory=True, position=1) + in_files = traits.List( + File(exists=True), + argstr='%s', + desc='a list of input volumes', + mandatory=True, + position=0) + threshold = traits.Int( + argstr='%d', + desc=('threshold indicating minimum number of seed ' + 'voxels entering this mask region'), + mandatory=True, + position=1) class ProjThreshOuputSpec(TraitedSpec): - out_files = traits.List(File(exists=True), - desc=('path/name of output volume after ' - 'thresholding')) + out_files = traits.List( + File(exists=True), + desc=('path/name of output volume after ' + 'thresholding')) class ProjThresh(FSLCommand): @@ -946,25 +1150,35 @@ def _list_outputs(self): outputs['out_files'] = [] for name in self.inputs.in_files: cwd, base_name = os.path.split(name) - outputs['out_files'].append(self._gen_fname( - base_name, cwd=cwd, - suffix='_proj_seg_thr_{}'.format(self.inputs.threshold))) + outputs['out_files'].append( + self._gen_fname( + base_name, + cwd=cwd, + suffix='_proj_seg_thr_{}'.format(self.inputs.threshold))) return outputs class FindTheBiggestInputSpec(FSLCommandInputSpec): - in_files = traits.List(File(exists=True), argstr='%s', - desc=('a list of input volumes or a ' - 'singleMatrixFile'), - position=0, mandatory=True) - out_file = File(argstr='%s', - desc='file with the resulting segmentation', - position=2, genfile=True, hash_files=False) + in_files = traits.List( + File(exists=True), + argstr='%s', + desc=('a list of input volumes or a ' + 'singleMatrixFile'), + position=0, + mandatory=True) + out_file = File( + argstr='%s', + desc='file with the resulting segmentation', + position=2, + genfile=True, + hash_files=False) class FindTheBiggestOutputSpec(TraitedSpec): - out_file = File(exists=True, argstr='%s', - desc='output file indexed in order of input files') + out_file = File( + exists=True, + argstr='%s', + desc='output file indexed in order of input files') class FindTheBiggest(FSLCommand): @@ -990,16 +1204,16 @@ class FindTheBiggest(FSLCommand): def _run_interface(self, runtime): if not isdefined(self.inputs.out_file): - self.inputs.out_file = self._gen_fname('biggestSegmentation', - suffix='') + self.inputs.out_file = self._gen_fname( + 'biggestSegmentation', suffix='') return super(FindTheBiggest, self)._run_interface(runtime) def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = self.inputs.out_file if not isdefined(outputs['out_file']): - outputs['out_file'] = self._gen_fname('biggestSegmentation', - suffix='') + outputs['out_file'] = self._gen_fname( + 'biggestSegmentation', suffix='') outputs['out_file'] = os.path.abspath(outputs['out_file']) return outputs @@ -1012,29 +1226,39 @@ def _gen_filename(self, name): class TractSkeletonInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, argstr="-i %s", - desc="input image (typcially mean FA volume)") + in_file = File( + exists=True, + mandatory=True, + argstr="-i %s", + desc="input image (typcially mean FA volume)") _proj_inputs = ["threshold", "distance_map", "data_file"] - project_data = traits.Bool(argstr="-p %.3f %s %s %s %s", - requires=_proj_inputs, - desc="project data onto skeleton") + project_data = traits.Bool( + argstr="-p %.3f %s %s %s %s", + requires=_proj_inputs, + desc="project data onto skeleton") threshold = traits.Float(desc="skeleton threshold value") distance_map = File(exists=True, desc="distance map image") - search_mask_file = File(exists=True, xor=["use_cingulum_mask"], - desc="mask in which to use alternate search rule") - use_cingulum_mask = traits.Bool(True, usedefault=True, - xor=["search_mask_file"], - desc=("perform alternate search using " - "built-in cingulum mask")) - data_file = File(exists=True, - desc="4D data to project onto skeleton (usually FA)") - alt_data_file = File(exists=True, argstr="-a %s", - desc="4D non-FA data to project onto skeleton") - alt_skeleton = File(exists=True, argstr="-s %s", - desc="alternate skeleton to use") + search_mask_file = File( + exists=True, + xor=["use_cingulum_mask"], + desc="mask in which to use alternate search rule") + use_cingulum_mask = traits.Bool( + True, + usedefault=True, + xor=["search_mask_file"], + desc=("perform alternate search using " + "built-in cingulum mask")) + data_file = File( + exists=True, desc="4D data to project onto skeleton (usually FA)") + alt_data_file = File( + exists=True, + argstr="-a %s", + desc="4D non-FA data to project onto skeleton") + alt_skeleton = File( + exists=True, argstr="-s %s", desc="alternate skeleton to use") projected_data = File(desc="input data projected onto skeleton") - skeleton_file = traits.Either(traits.Bool, File, argstr="-o %s", - desc="write out skeleton image") + skeleton_file = traits.Either( + traits.Bool, File, argstr="-o %s", desc="write out skeleton image") class TractSkeletonOutputSpec(TraitedSpec): @@ -1104,35 +1328,50 @@ def _list_outputs(self): if isdefined(_si.alt_data_file): stem = _si.alt_data_file outputs["projected_data"] = fname_presuffix( - stem, suffix="_skeletonised", newpath=os.getcwd(), + stem, + suffix="_skeletonised", + newpath=os.getcwd(), use_ext=True) if isdefined(_si.skeleton_file) and _si.skeleton_file: outputs["skeleton_file"] = _si.skeleton_file if isinstance(_si.skeleton_file, bool): outputs["skeleton_file"] = fname_presuffix( - _si.in_file, suffix="_skeleton", newpath=os.getcwd(), + _si.in_file, + suffix="_skeleton", + newpath=os.getcwd(), use_ext=True) return outputs class DistanceMapInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, argstr="--in=%s", - desc="image to calculate distance values for") - mask_file = File(exists=True, argstr="--mask=%s", - desc="binary mask to contrain calculations") + in_file = File( + exists=True, + mandatory=True, + argstr="--in=%s", + desc="image to calculate distance values for") + mask_file = File( + exists=True, + argstr="--mask=%s", + desc="binary mask to contrain calculations") invert_input = traits.Bool(argstr="--invert", desc="invert input image") - local_max_file = traits.Either(traits.Bool, File, argstr="--localmax=%s", - desc="write an image of the local maxima", - hash_files=False) - distance_map = File(genfile=True, argstr="--out=%s", - desc="distance map to write", hash_files=False) + local_max_file = traits.Either( + traits.Bool, + File, + argstr="--localmax=%s", + desc="write an image of the local maxima", + hash_files=False) + distance_map = File( + genfile=True, + argstr="--out=%s", + desc="distance map to write", + hash_files=False) class DistanceMapOutputSpec(TraitedSpec): - distance_map = File(exists=True, - desc="value is distance to nearest nonzero voxels") + distance_map = File( + exists=True, desc="value is distance to nearest nonzero voxels") local_max_file = File(desc="image of local maxima") @@ -1165,16 +1404,19 @@ def _list_outputs(self): _si = self.inputs outputs["distance_map"] = _si.distance_map if not isdefined(_si.distance_map): - outputs["distance_map"] = fname_presuffix(_si.in_file, - suffix="_dstmap", - use_ext=True, - newpath=os.getcwd()) + outputs["distance_map"] = fname_presuffix( + _si.in_file, + suffix="_dstmap", + use_ext=True, + newpath=os.getcwd()) outputs["distance_map"] = os.path.abspath(outputs["distance_map"]) if isdefined(_si.local_max_file): outputs["local_max_file"] = _si.local_max_file if isinstance(_si.local_max_file, bool): outputs["local_max_file"] = fname_presuffix( - _si.in_file, suffix="_lclmax", use_ext=True, + _si.in_file, + suffix="_lclmax", + use_ext=True, newpath=os.getcwd()) outputs["local_max_file"] = os.path.abspath( outputs["local_max_file"]) @@ -1190,12 +1432,13 @@ class MakeDyadicVectorsInputSpec(FSLCommandInputSpec): theta_vol = File(exists=True, mandatory=True, position=0, argstr="%s") phi_vol = File(exists=True, mandatory=True, position=1, argstr="%s") mask = File(exists=True, position=2, argstr="%s") - output = File("dyads", position=3, usedefault=True, argstr="%s", - hash_files=False) - perc = traits.Float(desc=("the {perc}% angle of the output cone of " - "uncertainty (output will be in degrees)"), - position=4, - argstr="%f") + output = File( + "dyads", position=3, usedefault=True, argstr="%s", hash_files=False) + perc = traits.Float( + desc=("the {perc}% angle of the output cone of " + "uncertainty (output will be in degrees)"), + position=4, + argstr="%f") class MakeDyadicVectorsOutputSpec(TraitedSpec): @@ -1214,7 +1457,7 @@ class MakeDyadicVectors(FSLCommand): def _list_outputs(self): outputs = self.output_spec().get() outputs["dyads"] = self._gen_fname(self.inputs.output) - outputs["dispersion"] = self._gen_fname(self.inputs.output, - suffix="_dispersion") + outputs["dispersion"] = self._gen_fname( + self.inputs.output, suffix="_dispersion") return outputs diff --git a/nipype/interfaces/fsl/epi.py b/nipype/interfaces/fsl/epi.py index 0beb60b3c0..7cfbbac79a 100644 --- a/nipype/interfaces/fsl/epi.py +++ b/nipype/interfaces/fsl/epi.py @@ -24,30 +24,48 @@ from ...utils.filemanip import split_filename from ...utils import NUMPY_MMAP -from ..base import (traits, TraitedSpec, InputMultiPath, File, - isdefined) +from ..base import (traits, TraitedSpec, InputMultiPath, File, isdefined) from .base import FSLCommand, FSLCommandInputSpec, Info class PrepareFieldmapInputSpec(FSLCommandInputSpec): - scanner = traits.String('SIEMENS', argstr='%s', position=1, - desc='must be SIEMENS', usedefault=True) - in_phase = File(exists=True, argstr='%s', position=2, mandatory=True, - desc=('Phase difference map, in SIEMENS format range from ' - '0-4096 or 0-8192)')) - in_magnitude = File(exists=True, argstr='%s', position=3, mandatory=True, - desc='Magnitude difference map, brain extracted') - delta_TE = traits.Float(2.46, usedefault=True, mandatory=True, argstr='%f', - position=-2, - desc=('echo time difference of the ' - 'fieldmap sequence in ms. (usually 2.46ms in' - ' Siemens)')) - nocheck = traits.Bool(False, position=-1, argstr='--nocheck', - usedefault=True, - desc=('do not perform sanity checks for image ' - 'size/range/dimensions')) - out_fieldmap = File(argstr='%s', position=4, - desc='output name for prepared fieldmap') + scanner = traits.String( + 'SIEMENS', + argstr='%s', + position=1, + desc='must be SIEMENS', + usedefault=True) + in_phase = File( + exists=True, + argstr='%s', + position=2, + mandatory=True, + desc=('Phase difference map, in SIEMENS format range from ' + '0-4096 or 0-8192)')) + in_magnitude = File( + exists=True, + argstr='%s', + position=3, + mandatory=True, + desc='Magnitude difference map, brain extracted') + delta_TE = traits.Float( + 2.46, + usedefault=True, + mandatory=True, + argstr='%f', + position=-2, + desc=('echo time difference of the ' + 'fieldmap sequence in ms. (usually 2.46ms in' + ' Siemens)')) + nocheck = traits.Bool( + False, + position=-1, + argstr='--nocheck', + usedefault=True, + desc=('do not perform sanity checks for image ' + 'size/range/dimensions')) + out_fieldmap = File( + argstr='%s', position=4, desc='output name for prepared fieldmap') class PrepareFieldmapOutputSpec(TraitedSpec): @@ -106,8 +124,7 @@ def _run_interface(self, runtime): if runtime.returncode == 0: out_file = self.inputs.out_fieldmap im = nb.load(out_file, mmap=NUMPY_MMAP) - dumb_img = nb.Nifti1Image(np.zeros(im.shape), im.affine, - im.header) + dumb_img = nb.Nifti1Image(np.zeros(im.shape), im.affine, im.header) out_nii = nb.funcs.concat_images((im, dumb_img)) nb.save(out_nii, out_file) @@ -115,110 +132,169 @@ def _run_interface(self, runtime): class TOPUPInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, - desc='name of 4D file with images', argstr='--imain=%s') - encoding_file = File(exists=True, mandatory=True, - xor=['encoding_direction'], - desc='name of text file with PE directions/times', - argstr='--datain=%s') - encoding_direction = traits.List(traits.Enum('y', 'x', 'z', 'x-', 'y-', - 'z-'), mandatory=True, - xor=['encoding_file'], - requires=['readout_times'], - argstr='--datain=%s', - desc=('encoding direction for automatic ' - 'generation of encoding_file')) - readout_times = InputMultiPath(traits.Float, - requires=['encoding_direction'], - xor=['encoding_file'], mandatory=True, - desc=('readout times (dwell times by # ' - 'phase-encode steps minus 1)')) - out_base = File(desc=('base-name of output files (spline ' - 'coefficients (Hz) and movement parameters)'), - name_source=['in_file'], name_template='%s_base', - argstr='--out=%s', hash_files=False) - out_field = File(argstr='--fout=%s', hash_files=False, - name_source=['in_file'], name_template='%s_field', - desc='name of image file with field (Hz)') - out_warp_prefix = traits.Str("warpfield", argstr='--dfout=%s', hash_files=False, - desc='prefix for the warpfield images (in mm)', - usedefault=True) - out_mat_prefix = traits.Str("xfm", argstr='--rbmout=%s', hash_files=False, - desc='prefix for the realignment matrices', - usedefault=True) - out_jac_prefix = traits.Str("jac", argstr='--jacout=%s', - hash_files=False, - desc='prefix for the warpfield images', - usedefault=True) - out_corrected = File(argstr='--iout=%s', hash_files=False, - name_source=['in_file'], name_template='%s_corrected', - desc='name of 4D image file with unwarped images') - out_logfile = File(argstr='--logout=%s', desc='name of log-file', - name_source=['in_file'], name_template='%s_topup.log', - keep_extension=True, hash_files=False) + in_file = File( + exists=True, + mandatory=True, + desc='name of 4D file with images', + argstr='--imain=%s') + encoding_file = File( + exists=True, + mandatory=True, + xor=['encoding_direction'], + desc='name of text file with PE directions/times', + argstr='--datain=%s') + encoding_direction = traits.List( + traits.Enum('y', 'x', 'z', 'x-', 'y-', 'z-'), + mandatory=True, + xor=['encoding_file'], + requires=['readout_times'], + argstr='--datain=%s', + desc=('encoding direction for automatic ' + 'generation of encoding_file')) + readout_times = InputMultiPath( + traits.Float, + requires=['encoding_direction'], + xor=['encoding_file'], + mandatory=True, + desc=('readout times (dwell times by # ' + 'phase-encode steps minus 1)')) + out_base = File( + desc=('base-name of output files (spline ' + 'coefficients (Hz) and movement parameters)'), + name_source=['in_file'], + name_template='%s_base', + argstr='--out=%s', + hash_files=False) + out_field = File( + argstr='--fout=%s', + hash_files=False, + name_source=['in_file'], + name_template='%s_field', + desc='name of image file with field (Hz)') + out_warp_prefix = traits.Str( + "warpfield", + argstr='--dfout=%s', + hash_files=False, + desc='prefix for the warpfield images (in mm)', + usedefault=True) + out_mat_prefix = traits.Str( + "xfm", + argstr='--rbmout=%s', + hash_files=False, + desc='prefix for the realignment matrices', + usedefault=True) + out_jac_prefix = traits.Str( + "jac", + argstr='--jacout=%s', + hash_files=False, + desc='prefix for the warpfield images', + usedefault=True) + out_corrected = File( + argstr='--iout=%s', + hash_files=False, + name_source=['in_file'], + name_template='%s_corrected', + desc='name of 4D image file with unwarped images') + out_logfile = File( + argstr='--logout=%s', + desc='name of log-file', + name_source=['in_file'], + name_template='%s_topup.log', + keep_extension=True, + hash_files=False) # TODO: the following traits admit values separated by commas, one value # per registration level inside topup. - warp_res = traits.Float(10.0, argstr='--warpres=%f', - desc=('(approximate) resolution (in mm) of warp ' - 'basis for the different sub-sampling levels' - '.')) - subsamp = traits.Int(1, argstr='--subsamp=%d', - desc='sub-sampling scheme') - fwhm = traits.Float(8.0, argstr='--fwhm=%f', - desc='FWHM (in mm) of gaussian smoothing kernel') - config = traits.String('b02b0.cnf', argstr='--config=%s', usedefault=True, - desc=('Name of config file specifying command line ' - 'arguments')) - max_iter = traits.Int(5, argstr='--miter=%d', - desc='max # of non-linear iterations') - reg_lambda = traits.Float(1.0, argstr='--miter=%0.f', - desc=('lambda weighting value of the ' - 'regularisation term')) - ssqlambda = traits.Enum(1, 0, argstr='--ssqlambda=%d', - desc=('Weight lambda by the current value of the ' - 'ssd. If used (=1), the effective weight of ' - 'regularisation term becomes higher for the ' - 'initial iterations, therefore initial steps' - ' are a little smoother than they would ' - 'without weighting. This reduces the ' - 'risk of finding a local minimum.')) - regmod = traits.Enum('bending_energy', 'membrane_energy', - argstr='--regmod=%s', - desc=('Regularisation term implementation. Defaults ' - 'to bending_energy. Note that the two functions' - ' have vastly different scales. The membrane ' - 'energy is based on the first derivatives and ' - 'the bending energy on the second derivatives. ' - 'The second derivatives will typically be much ' - 'smaller than the first derivatives, so input ' - 'lambda will have to be larger for ' - 'bending_energy to yield approximately the same' - ' level of regularisation.')) - estmov = traits.Enum(1, 0, argstr='--estmov=%d', - desc='estimate movements if set') - minmet = traits.Enum(0, 1, argstr='--minmet=%d', - desc=('Minimisation method 0=Levenberg-Marquardt, ' - '1=Scaled Conjugate Gradient')) - splineorder = traits.Int(3, argstr='--splineorder=%d', - desc=('order of spline, 2->Qadratic spline, ' - '3->Cubic spline')) - numprec = traits.Enum('double', 'float', argstr='--numprec=%s', - desc=('Precision for representing Hessian, double ' - 'or float.')) - interp = traits.Enum('spline', 'linear', argstr='--interp=%s', - desc='Image interpolation model, linear or spline.') - scale = traits.Enum(0, 1, argstr='--scale=%d', - desc=('If set (=1), the images are individually scaled' - ' to a common mean')) - regrid = traits.Enum(1, 0, argstr='--regrid=%d', - desc=('If set (=1), the calculations are done in a ' - 'different grid')) + warp_res = traits.Float( + 10.0, + argstr='--warpres=%f', + desc=('(approximate) resolution (in mm) of warp ' + 'basis for the different sub-sampling levels' + '.')) + subsamp = traits.Int(1, argstr='--subsamp=%d', desc='sub-sampling scheme') + fwhm = traits.Float( + 8.0, + argstr='--fwhm=%f', + desc='FWHM (in mm) of gaussian smoothing kernel') + config = traits.String( + 'b02b0.cnf', + argstr='--config=%s', + usedefault=True, + desc=('Name of config file specifying command line ' + 'arguments')) + max_iter = traits.Int( + 5, argstr='--miter=%d', desc='max # of non-linear iterations') + reg_lambda = traits.Float( + 1.0, + argstr='--miter=%0.f', + desc=('lambda weighting value of the ' + 'regularisation term')) + ssqlambda = traits.Enum( + 1, + 0, + argstr='--ssqlambda=%d', + desc=('Weight lambda by the current value of the ' + 'ssd. If used (=1), the effective weight of ' + 'regularisation term becomes higher for the ' + 'initial iterations, therefore initial steps' + ' are a little smoother than they would ' + 'without weighting. This reduces the ' + 'risk of finding a local minimum.')) + regmod = traits.Enum( + 'bending_energy', + 'membrane_energy', + argstr='--regmod=%s', + desc=('Regularisation term implementation. Defaults ' + 'to bending_energy. Note that the two functions' + ' have vastly different scales. The membrane ' + 'energy is based on the first derivatives and ' + 'the bending energy on the second derivatives. ' + 'The second derivatives will typically be much ' + 'smaller than the first derivatives, so input ' + 'lambda will have to be larger for ' + 'bending_energy to yield approximately the same' + ' level of regularisation.')) + estmov = traits.Enum( + 1, 0, argstr='--estmov=%d', desc='estimate movements if set') + minmet = traits.Enum( + 0, + 1, + argstr='--minmet=%d', + desc=('Minimisation method 0=Levenberg-Marquardt, ' + '1=Scaled Conjugate Gradient')) + splineorder = traits.Int( + 3, + argstr='--splineorder=%d', + desc=('order of spline, 2->Qadratic spline, ' + '3->Cubic spline')) + numprec = traits.Enum( + 'double', + 'float', + argstr='--numprec=%s', + desc=('Precision for representing Hessian, double ' + 'or float.')) + interp = traits.Enum( + 'spline', + 'linear', + argstr='--interp=%s', + desc='Image interpolation model, linear or spline.') + scale = traits.Enum( + 0, + 1, + argstr='--scale=%d', + desc=('If set (=1), the images are individually scaled' + ' to a common mean')) + regrid = traits.Enum( + 1, + 0, + argstr='--regrid=%d', + desc=('If set (=1), the calculations are done in a ' + 'different grid')) class TOPUPOutputSpec(TraitedSpec): - out_fieldcoef = File(exists=True, - desc='file containing the field coefficients') + out_fieldcoef = File( + exists=True, desc='file containing the field coefficients') out_movpar = File(exists=True, desc='movpar.txt output file') out_enc_file = File(desc='encoding directions file output for applytopup') out_field = File(desc='name of image file with field (Hz)') @@ -279,32 +355,35 @@ def _list_outputs(self): base_path = None else: base = split_filename(self.inputs.in_file)[1] + '_base' - outputs['out_fieldcoef'] = self._gen_fname(base, suffix='_fieldcoef', - cwd=base_path) - outputs['out_movpar'] = self._gen_fname(base, suffix='_movpar', - ext='.txt', cwd=base_path) + outputs['out_fieldcoef'] = self._gen_fname( + base, suffix='_fieldcoef', cwd=base_path) + outputs['out_movpar'] = self._gen_fname( + base, suffix='_movpar', ext='.txt', cwd=base_path) n_vols = nb.load(self.inputs.in_file).shape[-1] ext = Info.output_type_to_ext(self.inputs.output_type) fmt = os.path.abspath('{prefix}_{i:02d}{ext}').format outputs['out_warps'] = [ fmt(prefix=self.inputs.out_warp_prefix, i=i, ext=ext) - for i in range(1, n_vols + 1)] + for i in range(1, n_vols + 1) + ] outputs['out_jacs'] = [ fmt(prefix=self.inputs.out_jac_prefix, i=i, ext=ext) - for i in range(1, n_vols + 1)] + for i in range(1, n_vols + 1) + ] outputs['out_mats'] = [ fmt(prefix=self.inputs.out_mat_prefix, i=i, ext=".mat") - for i in range(1, n_vols + 1)] + for i in range(1, n_vols + 1) + ] if isdefined(self.inputs.encoding_direction): outputs['out_enc_file'] = self._get_encfilename() return outputs def _get_encfilename(self): - out_file = os.path.join(os.getcwd(), - ('%s_encfile.txt' % - split_filename(self.inputs.in_file)[1])) + out_file = os.path.join( + os.getcwd(), + ('%s_encfile.txt' % split_filename(self.inputs.in_file)[1])) return out_file def _generate_encfile(self): @@ -323,8 +402,10 @@ def _generate_encfile(self): direction = 1.0 if encdir.endswith('-'): direction = -1.0 - line = [float(val[0] == encdir[0]) * direction - for val in ['x', 'y', 'z']] + [durations[idx]] + line = [ + float(val[0] == encdir[0]) * direction + for val in ['x', 'y', 'z'] + ] + [durations[idx]] lines.append(line) np.savetxt(out_file, np.array(lines), fmt=b'%d %d %d %.8f') return out_file @@ -336,37 +417,64 @@ def _overload_extension(self, value, name=None): class ApplyTOPUPInputSpec(FSLCommandInputSpec): - in_files = InputMultiPath(File(exists=True), mandatory=True, - desc='name of file with images', - argstr='--imain=%s', sep=',') - encoding_file = File(exists=True, mandatory=True, - desc='name of text file with PE directions/times', - argstr='--datain=%s') + in_files = InputMultiPath( + File(exists=True), + mandatory=True, + desc='name of file with images', + argstr='--imain=%s', + sep=',') + encoding_file = File( + exists=True, + mandatory=True, + desc='name of text file with PE directions/times', + argstr='--datain=%s') in_index = traits.List( - traits.Int, argstr='--inindex=%s', sep=',', + traits.Int, + argstr='--inindex=%s', + sep=',', desc='comma separated list of indices corresponding to --datain') - in_topup_fieldcoef = File(exists=True, argstr="--topup=%s", copyfile=False, - requires=['in_topup_movpar'], - desc=('topup file containing the field ' - 'coefficients')) - in_topup_movpar = File(exists=True, requires=['in_topup_fieldcoef'], - copyfile=False, desc='topup movpar.txt file') - out_corrected = File(desc='output (warped) image', - name_source=['in_files'], - name_template='%s_corrected', - argstr='--out=%s') - method = traits.Enum('jac', 'lsr', argstr='--method=%s', - desc=('use jacobian modulation (jac) or least-squares' - ' resampling (lsr)')) - interp = traits.Enum('trilinear', 'spline', argstr='--interp=%s', - desc='interpolation method') - datatype = traits.Enum('char', 'short', 'int', 'float', 'double', - argstr='-d=%s', desc='force output data type') + in_topup_fieldcoef = File( + exists=True, + argstr="--topup=%s", + copyfile=False, + requires=['in_topup_movpar'], + desc=('topup file containing the field ' + 'coefficients')) + in_topup_movpar = File( + exists=True, + requires=['in_topup_fieldcoef'], + copyfile=False, + desc='topup movpar.txt file') + out_corrected = File( + desc='output (warped) image', + name_source=['in_files'], + name_template='%s_corrected', + argstr='--out=%s') + method = traits.Enum( + 'jac', + 'lsr', + argstr='--method=%s', + desc=('use jacobian modulation (jac) or least-squares' + ' resampling (lsr)')) + interp = traits.Enum( + 'trilinear', + 'spline', + argstr='--interp=%s', + desc='interpolation method') + datatype = traits.Enum( + 'char', + 'short', + 'int', + 'float', + 'double', + argstr='-d=%s', + desc='force output data type') class ApplyTOPUPOutputSpec(TraitedSpec): - out_corrected = File(exists=True, desc=('name of 4D image file with ' - 'unwarped images')) + out_corrected = File( + exists=True, desc=('name of 4D image file with ' + 'unwarped images')) class ApplyTOPUP(FSLCommand): @@ -407,7 +515,8 @@ def _parse_inputs(self, skip=None): # parameters file, for N input images. if not isdefined(self.inputs.in_index): self.inputs.in_index = list( - range(1, len(self.inputs.in_files) + 1)) + range(1, + len(self.inputs.in_files) + 1)) return super(ApplyTOPUP, self)._parse_inputs(skip=skip) @@ -418,88 +527,146 @@ def _format_arg(self, name, spec, value): class EddyInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, argstr='--imain=%s', - desc=('File containing all the images to estimate ' - 'distortions for')) - in_mask = File(exists=True, mandatory=True, argstr='--mask=%s', - desc='Mask to indicate brain') - in_index = File(exists=True, mandatory=True, argstr='--index=%s', - desc=('File containing indices for all volumes in --imain ' - 'into --acqp and --topup')) - in_acqp = File(exists=True, mandatory=True, argstr='--acqp=%s', - desc='File containing acquisition parameters') - in_bvec = File(exists=True, mandatory=True, argstr='--bvecs=%s', - desc=('File containing the b-vectors for all volumes in ' - '--imain')) - in_bval = File(exists=True, mandatory=True, argstr='--bvals=%s', - desc=('File containing the b-values for all volumes in ' - '--imain')) - out_base = traits.Str('eddy_corrected', argstr='--out=%s', - usedefault=True, - desc=('basename for output (warped) image')) - session = File(exists=True, argstr='--session=%s', - desc=('File containing session indices for all volumes in ' - '--imain')) - in_topup_fieldcoef = File(exists=True, argstr="--topup=%s", - requires=['in_topup_movpar'], - desc=('topup file containing the field ' - 'coefficients')) - in_topup_movpar = File(exists=True, requires=['in_topup_fieldcoef'], - desc='topup movpar.txt file') - - flm = traits.Enum('linear', 'quadratic', 'cubic', argstr='--flm=%s', - desc='First level EC model') - - slm = traits.Enum('none', 'linear', 'quadratic', argstr='--slm=%s', - desc='Second level EC model') - - fep = traits.Bool(False, argstr='--fep', - desc='Fill empty planes in x- or y-directions') - - interp = traits.Enum('spline', 'trilinear', argstr='--interp=%s', - desc='Interpolation model for estimation step') - - nvoxhp = traits.Int(1000, argstr='--nvoxhp=%s', - desc=('# of voxels used to estimate the ' - 'hyperparameters')) - - fudge_factor = traits.Float(10.0, argstr='--ff=%s', - desc=('Fudge factor for hyperparameter ' - 'error variance')) - - dont_sep_offs_move = traits.Bool(False, argstr='--dont_sep_offs_move', - desc=('Do NOT attempt to separate ' - 'field offset from subject ' - 'movement')) - - dont_peas = traits.Bool(False, argstr='--dont_peas', - desc="Do NOT perform a post-eddy alignment of " - "shells") - - fwhm = traits.Float(desc=('FWHM for conditioning filter when estimating ' - 'the parameters'), argstr='--fwhm=%s') + in_file = File( + exists=True, + mandatory=True, + argstr='--imain=%s', + desc=('File containing all the images to estimate ' + 'distortions for')) + in_mask = File( + exists=True, + mandatory=True, + argstr='--mask=%s', + desc='Mask to indicate brain') + in_index = File( + exists=True, + mandatory=True, + argstr='--index=%s', + desc=('File containing indices for all volumes in --imain ' + 'into --acqp and --topup')) + in_acqp = File( + exists=True, + mandatory=True, + argstr='--acqp=%s', + desc='File containing acquisition parameters') + in_bvec = File( + exists=True, + mandatory=True, + argstr='--bvecs=%s', + desc=('File containing the b-vectors for all volumes in ' + '--imain')) + in_bval = File( + exists=True, + mandatory=True, + argstr='--bvals=%s', + desc=('File containing the b-values for all volumes in ' + '--imain')) + out_base = traits.Str( + 'eddy_corrected', + argstr='--out=%s', + usedefault=True, + desc=('basename for output (warped) image')) + session = File( + exists=True, + argstr='--session=%s', + desc=('File containing session indices for all volumes in ' + '--imain')) + in_topup_fieldcoef = File( + exists=True, + argstr="--topup=%s", + requires=['in_topup_movpar'], + desc=('topup file containing the field ' + 'coefficients')) + in_topup_movpar = File( + exists=True, + requires=['in_topup_fieldcoef'], + desc='topup movpar.txt file') + + flm = traits.Enum( + 'linear', + 'quadratic', + 'cubic', + argstr='--flm=%s', + desc='First level EC model') + + slm = traits.Enum( + 'none', + 'linear', + 'quadratic', + argstr='--slm=%s', + desc='Second level EC model') + + fep = traits.Bool( + False, argstr='--fep', desc='Fill empty planes in x- or y-directions') + + interp = traits.Enum( + 'spline', + 'trilinear', + argstr='--interp=%s', + desc='Interpolation model for estimation step') + + nvoxhp = traits.Int( + 1000, + argstr='--nvoxhp=%s', + desc=('# of voxels used to estimate the ' + 'hyperparameters')) + + fudge_factor = traits.Float( + 10.0, + argstr='--ff=%s', + desc=('Fudge factor for hyperparameter ' + 'error variance')) + + dont_sep_offs_move = traits.Bool( + False, + argstr='--dont_sep_offs_move', + desc=('Do NOT attempt to separate ' + 'field offset from subject ' + 'movement')) + + dont_peas = traits.Bool( + False, + argstr='--dont_peas', + desc="Do NOT perform a post-eddy alignment of " + "shells") + + fwhm = traits.Float( + desc=('FWHM for conditioning filter when estimating ' + 'the parameters'), + argstr='--fwhm=%s') niter = traits.Int(5, argstr='--niter=%s', desc='Number of iterations') - method = traits.Enum('jac', 'lsr', argstr='--resamp=%s', - desc=('Final resampling method (jacobian/least ' - 'squares)')) - repol = traits.Bool(False, argstr='--repol', - desc='Detect and replace outlier slices') - num_threads = traits.Int(1, usedefault=True, nohash=True, - desc="Number of openmp threads to use") - is_shelled = traits.Bool(False, argstr='--data_is_shelled', - desc="Override internal check to ensure that " - "date are acquired on a set of b-value " - "shells") - field = traits.Str(argstr='--field=%s', - desc="NonTOPUP fieldmap scaled in Hz - filename has " - "to be provided without an extension. TOPUP is " - "strongly recommended") - field_mat = File(exists=True, argstr='--field_mat=%s', - desc="Matrix that specifies the relative locations of " - "the field specified by --field and first volume " - "in file --imain") + method = traits.Enum( + 'jac', + 'lsr', + argstr='--resamp=%s', + desc=('Final resampling method (jacobian/least ' + 'squares)')) + repol = traits.Bool( + False, argstr='--repol', desc='Detect and replace outlier slices') + num_threads = traits.Int( + 1, + usedefault=True, + nohash=True, + desc="Number of openmp threads to use") + is_shelled = traits.Bool( + False, + argstr='--data_is_shelled', + desc="Override internal check to ensure that " + "date are acquired on a set of b-value " + "shells") + field = traits.Str( + argstr='--field=%s', + desc="NonTOPUP fieldmap scaled in Hz - filename has " + "to be provided without an extension. TOPUP is " + "strongly recommended") + field_mat = File( + exists=True, + argstr='--field_mat=%s', + desc="Matrix that specifies the relative locations of " + "the field specified by --field and first volume " + "in file --imain") use_cuda = traits.Bool(False, desc="Run eddy using cuda gpu") @@ -507,22 +674,26 @@ class EddyOutputSpec(TraitedSpec): out_corrected = File( exists=True, desc='4D image file containing all the corrected volumes') out_parameter = File( - exists=True, desc=('text file with parameters definining the field and' - 'movement for each scan')) + exists=True, + desc=('text file with parameters definining the field and' + 'movement for each scan')) out_rotated_bvecs = File( exists=True, desc='File containing rotated b-values for all volumes') out_movement_rms = File( exists=True, desc='Summary of the "total movement" in each volume') out_restricted_movement_rms = File( - exists=True, desc=('Summary of the "total movement" in each volume ' - 'disregarding translation in the PE direction')) + exists=True, + desc=('Summary of the "total movement" in each volume ' + 'disregarding translation in the PE direction')) out_shell_alignment_parameters = File( - exists=True, desc=('File containing rigid body movement parameters ' - 'between the different shells as estimated by a ' - 'post-hoc mutual information based registration')) + exists=True, + desc=('File containing rigid body movement parameters ' + 'between the different shells as estimated by a ' + 'post-hoc mutual information based registration')) out_outlier_report = File( - exists=True, desc=('Text-file with a plain language report on what ' - 'outlier slices eddy has found')) + exists=True, + desc=('Text-file with a plain language report on what ' + 'outlier slices eddy has found')) class Eddy(FSLCommand): @@ -590,8 +761,7 @@ def _run_interface(self, runtime): # If 'eddy_openmp' is missing, use 'eddy' FSLDIR = os.getenv('FSLDIR', '') cmd = self._cmd - if all((FSLDIR != '', - cmd == 'eddy_openmp', + if all((FSLDIR != '', cmd == 'eddy_openmp', not os.path.exists(os.path.join(FSLDIR, 'bin', cmd)))): self._cmd = 'eddy' runtime = super(Eddy, self)._run_interface(runtime) @@ -622,8 +792,8 @@ def _list_outputs(self): out_restricted_movement_rms = os.path.abspath( '%s.eddy_restricted_movement_rms' % self.inputs.out_base) out_shell_alignment_parameters = os.path.abspath( - '%s.eddy_post_eddy_shell_alignment_parameters' - % self.inputs.out_base) + '%s.eddy_post_eddy_shell_alignment_parameters' % + self.inputs.out_base) out_outlier_report = os.path.abspath( '%s.eddy_outlier_report' % self.inputs.out_base) @@ -644,27 +814,19 @@ def _list_outputs(self): class SigLossInputSpec(FSLCommandInputSpec): - in_file = File(mandatory=True, - exists=True, - argstr='-i %s', - desc='b0 fieldmap file') - out_file = File(argstr='-s %s', - desc='output signal loss estimate file', - genfile=True) - - mask_file = File(exists=True, - argstr='-m %s', - desc='brain mask file') - echo_time = traits.Float(argstr='--te=%f', - desc='echo time in seconds') - slice_direction = traits.Enum('x', 'y', 'z', - argstr='-d %s', - desc='slicing direction') + in_file = File( + mandatory=True, exists=True, argstr='-i %s', desc='b0 fieldmap file') + out_file = File( + argstr='-s %s', desc='output signal loss estimate file', genfile=True) + + mask_file = File(exists=True, argstr='-m %s', desc='brain mask file') + echo_time = traits.Float(argstr='--te=%f', desc='echo time in seconds') + slice_direction = traits.Enum( + 'x', 'y', 'z', argstr='-d %s', desc='slicing direction') class SigLossOuputSpec(TraitedSpec): - out_file = File(exists=True, - desc='signal loss estimate file') + out_file = File(exists=True, desc='signal loss estimate file') class SigLoss(FSLCommand): @@ -692,10 +854,10 @@ class SigLoss(FSLCommand): def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = self.inputs.out_file - if ((not isdefined(outputs['out_file'])) and - (isdefined(self.inputs.in_file))): - outputs['out_file'] = self._gen_fname(self.inputs.in_file, - suffix='_sigloss') + if ((not isdefined(outputs['out_file'])) + and (isdefined(self.inputs.in_file))): + outputs['out_file'] = self._gen_fname( + self.inputs.in_file, suffix='_sigloss') return outputs def _gen_filename(self, name): @@ -705,62 +867,95 @@ def _gen_filename(self, name): class EpiRegInputSpec(FSLCommandInputSpec): - epi = File(exists=True, argstr='--epi=%s', mandatory=True, - position=-4, desc='EPI image') - t1_head = File(exists=True, argstr='--t1=%s', mandatory=True, - position=-3, desc='wholehead T1 image') - t1_brain = File(exists=True, argstr='--t1brain=%s', mandatory=True, - position=-2, desc='brain extracted T1 image') - out_base = traits.String("epi2struct", desc='output base name', - argstr='--out=%s', - position=-1, usedefault=True) - fmap = File(exists=True, argstr='--fmap=%s', - desc='fieldmap image (in rad/s)') - fmapmag = File(exists=True, argstr='--fmapmag=%s', - desc='fieldmap magnitude image - wholehead') - fmapmagbrain = File(exists=True, argstr='--fmapmagbrain=%s', - desc='fieldmap magnitude image - brain extracted') - wmseg = File(exists=True, argstr='--wmseg=%s', - desc='white matter segmentation of T1 image, has to be named \ + epi = File( + exists=True, + argstr='--epi=%s', + mandatory=True, + position=-4, + desc='EPI image') + t1_head = File( + exists=True, + argstr='--t1=%s', + mandatory=True, + position=-3, + desc='wholehead T1 image') + t1_brain = File( + exists=True, + argstr='--t1brain=%s', + mandatory=True, + position=-2, + desc='brain extracted T1 image') + out_base = traits.String( + "epi2struct", + desc='output base name', + argstr='--out=%s', + position=-1, + usedefault=True) + fmap = File( + exists=True, argstr='--fmap=%s', desc='fieldmap image (in rad/s)') + fmapmag = File( + exists=True, + argstr='--fmapmag=%s', + desc='fieldmap magnitude image - wholehead') + fmapmagbrain = File( + exists=True, + argstr='--fmapmagbrain=%s', + desc='fieldmap magnitude image - brain extracted') + wmseg = File( + exists=True, + argstr='--wmseg=%s', + desc='white matter segmentation of T1 image, has to be named \ like the t1brain and end on _wmseg') - echospacing = traits.Float(argstr='--echospacing=%f', - desc='Effective EPI echo spacing \ + echospacing = traits.Float( + argstr='--echospacing=%f', + desc='Effective EPI echo spacing \ (sometimes called dwell time) - in seconds') - pedir = traits.Enum('x', 'y', 'z', '-x', '-y', '-z', argstr='--pedir=%s', - desc='phase encoding direction, dir = x/y/z/-x/-y/-z') - - weight_image = File(exists=True, argstr='--weight=%s', - desc='weighting image (in T1 space)') - no_fmapreg = traits.Bool(False, argstr='--nofmapreg', - desc='do not perform registration of fmap to T1 \ + pedir = traits.Enum( + 'x', + 'y', + 'z', + '-x', + '-y', + '-z', + argstr='--pedir=%s', + desc='phase encoding direction, dir = x/y/z/-x/-y/-z') + + weight_image = File( + exists=True, + argstr='--weight=%s', + desc='weighting image (in T1 space)') + no_fmapreg = traits.Bool( + False, + argstr='--nofmapreg', + desc='do not perform registration of fmap to T1 \ (use if fmap already registered)') - no_clean = traits.Bool(True, argstr='--noclean', usedefault=True, - desc='do not clean up intermediate files') + no_clean = traits.Bool( + True, + argstr='--noclean', + usedefault=True, + desc='do not clean up intermediate files') class EpiRegOutputSpec(TraitedSpec): - out_file = File(exists=True, - desc='unwarped and coregistered epi input') - out_1vol = File(exists=True, - desc='unwarped and coregistered single volume') - fmap2str_mat = File(exists=True, - desc='rigid fieldmap-to-structural transform') - fmap2epi_mat = File(exists=True, - desc='rigid fieldmap-to-epi transform') + out_file = File(exists=True, desc='unwarped and coregistered epi input') + out_1vol = File( + exists=True, desc='unwarped and coregistered single volume') + fmap2str_mat = File( + exists=True, desc='rigid fieldmap-to-structural transform') + fmap2epi_mat = File(exists=True, desc='rigid fieldmap-to-epi transform') fmap_epi = File(exists=True, desc='fieldmap in epi space') fmap_str = File(exists=True, desc='fieldmap in structural space') - fmapmag_str = File(exists=True, - desc='fieldmap magnitude image in structural space') - epi2str_inv = File(exists=True, - desc='rigid structural-to-epi transform') - epi2str_mat = File(exists=True, - desc='rigid epi-to-structural transform') + fmapmag_str = File( + exists=True, desc='fieldmap magnitude image in structural space') + epi2str_inv = File(exists=True, desc='rigid structural-to-epi transform') + epi2str_mat = File(exists=True, desc='rigid epi-to-structural transform') shiftmap = File(exists=True, desc='shiftmap in epi space') - fullwarp = File(exists=True, - desc='warpfield to unwarp epi and transform into \ + fullwarp = File( + exists=True, + desc='warpfield to unwarp epi and transform into \ structural space') - wmseg = File(exists=True, - desc='white matter segmentation used in flirt bbr') + wmseg = File( + exists=True, desc='white matter segmentation used in flirt bbr') wmedge = File(exists=True, desc='white matter edges for visualization') @@ -799,8 +994,8 @@ def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = os.path.join(os.getcwd(), self.inputs.out_base + '.nii.gz') - if (not (isdefined(self.inputs.no_fmapreg) and - self.inputs.no_fmapreg) and isdefined(self.inputs.fmap)): + if (not (isdefined(self.inputs.no_fmapreg) and self.inputs.no_fmapreg) + and isdefined(self.inputs.fmap)): outputs['out_1vol'] = os.path.join( os.getcwd(), self.inputs.out_base + '_1vol.nii.gz') outputs['fmap2str_mat'] = os.path.join( @@ -821,8 +1016,8 @@ def _list_outputs(self): outputs['epi2str_inv'] = os.path.join( os.getcwd(), self.inputs.out_base + '_inv.mat') - outputs['epi2str_mat'] = os.path.join( - os.getcwd(), self.inputs.out_base + '.mat') + outputs['epi2str_mat'] = os.path.join(os.getcwd(), + self.inputs.out_base + '.mat') outputs['wmedge'] = os.path.join( os.getcwd(), self.inputs.out_base + '_fast_wmedge.nii.gz') outputs['wmseg'] = os.path.join( @@ -837,38 +1032,46 @@ def _list_outputs(self): class EPIDeWarpInputSpec(FSLCommandInputSpec): - mag_file = File(exists=True, - desc='Magnitude file', - argstr='--mag %s', position=0, mandatory=True) - dph_file = File(exists=True, - desc='Phase file assumed to be scaled from 0 to 4095', - argstr='--dph %s', mandatory=True) - exf_file = File(exists=True, - desc='example func volume (or use epi)', - argstr='--exf %s') - epi_file = File(exists=True, - desc='EPI volume to unwarp', - argstr='--epi %s') - tediff = traits.Float(2.46, usedefault=True, - desc='difference in B0 field map TEs', - argstr='--tediff %s') - esp = traits.Float(0.58, desc='EPI echo spacing', - argstr='--esp %s', usedefault=True) - sigma = traits.Int(2, usedefault=True, argstr='--sigma %s', - desc="2D spatial gaussing smoothing \ + mag_file = File( + exists=True, + desc='Magnitude file', + argstr='--mag %s', + position=0, + mandatory=True) + dph_file = File( + exists=True, + desc='Phase file assumed to be scaled from 0 to 4095', + argstr='--dph %s', + mandatory=True) + exf_file = File( + exists=True, + desc='example func volume (or use epi)', + argstr='--exf %s') + epi_file = File( + exists=True, desc='EPI volume to unwarp', argstr='--epi %s') + tediff = traits.Float( + 2.46, + usedefault=True, + desc='difference in B0 field map TEs', + argstr='--tediff %s') + esp = traits.Float( + 0.58, desc='EPI echo spacing', argstr='--esp %s', usedefault=True) + sigma = traits.Int( + 2, + usedefault=True, + argstr='--sigma %s', + desc="2D spatial gaussing smoothing \ stdev (default = 2mm)") - vsm = traits.String(genfile=True, desc='voxel shift map', - argstr='--vsm %s') - exfdw = traits.String(desc='dewarped example func volume', genfile=True, - argstr='--exfdw %s') - epidw = traits.String(desc='dewarped epi volume', genfile=False, - argstr='--epidw %s') - tmpdir = traits.String(genfile=True, desc='tmpdir', - argstr='--tmpdir %s') - nocleanup = traits.Bool(True, usedefault=True, desc='no cleanup', - argstr='--nocleanup') - cleanup = traits.Bool(desc='cleanup', - argstr='--cleanup') + vsm = traits.String( + genfile=True, desc='voxel shift map', argstr='--vsm %s') + exfdw = traits.String( + desc='dewarped example func volume', genfile=True, argstr='--exfdw %s') + epidw = traits.String( + desc='dewarped epi volume', genfile=False, argstr='--epidw %s') + tmpdir = traits.String(genfile=True, desc='tmpdir', argstr='--tmpdir %s') + nocleanup = traits.Bool( + True, usedefault=True, desc='no cleanup', argstr='--nocleanup') + cleanup = traits.Bool(desc='cleanup', argstr='--cleanup') class EPIDeWarpOutputSpec(TraitedSpec): @@ -922,14 +1125,12 @@ def _run_interface(self, runtime): def _gen_filename(self, name): if name == 'exfdw': if isdefined(self.inputs.exf_file): - return self._gen_fname(self.inputs.exf_file, - suffix="_exfdw") + return self._gen_fname(self.inputs.exf_file, suffix="_exfdw") else: return self._gen_fname("exfdw") if name == 'epidw': if isdefined(self.inputs.epi_file): - return self._gen_fname(self.inputs.epi_file, - suffix="_epidw") + return self._gen_fname(self.inputs.epi_file, suffix="_epidw") if name == 'vsm': return self._gen_fname('vsm') if name == 'tmpdir': @@ -952,28 +1153,40 @@ def _list_outputs(self): else: outputs['vsm_file'] = self._gen_fname(self.inputs.vsm) if not isdefined(self.inputs.tmpdir): - outputs[ - 'exf_mask'] = self._gen_fname(cwd=self._gen_filename('tmpdir'), - basename='maskexf') + outputs['exf_mask'] = self._gen_fname( + cwd=self._gen_filename('tmpdir'), basename='maskexf') else: - outputs['exf_mask'] = self._gen_fname(cwd=self.inputs.tmpdir, - basename='maskexf') + outputs['exf_mask'] = self._gen_fname( + cwd=self.inputs.tmpdir, basename='maskexf') return outputs class EddyCorrectInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, desc='4D input file', argstr='%s', position=0, - mandatory=True) - out_file = File(desc='4D output file', argstr='%s', position=1, - name_source=['in_file'], name_template='%s_edc', - output_name='eddy_corrected') - ref_num = traits.Int(0, argstr='%d', position=2, desc='reference number', - mandatory=True, usedefault=True) + in_file = File( + exists=True, + desc='4D input file', + argstr='%s', + position=0, + mandatory=True) + out_file = File( + desc='4D output file', + argstr='%s', + position=1, + name_source=['in_file'], + name_template='%s_edc', + output_name='eddy_corrected') + ref_num = traits.Int( + 0, + argstr='%d', + position=2, + desc='reference number', + mandatory=True, + usedefault=True) class EddyCorrectOutputSpec(TraitedSpec): - eddy_corrected = File(exists=True, - desc='path/name of 4D eddy corrected output file') + eddy_corrected = File( + exists=True, desc='path/name of 4D eddy corrected output file') class EddyCorrect(FSLCommand): diff --git a/nipype/interfaces/fsl/fix.py b/nipype/interfaces/fsl/fix.py index cd4aacfedb..ebe986eb79 100644 --- a/nipype/interfaces/fsl/fix.py +++ b/nipype/interfaces/fsl/fix.py @@ -12,7 +12,7 @@ will fail and comment on that. EXAMPLE: -subject_list = ['1','2','3'] +subject_list = ['1', '2', '3'] fix_pipeline = pe.Workflow(name='fix_pipeline') fix_pipeline.base_dir = os.path.abspath('./') @@ -54,34 +54,31 @@ outgraph = fix_pipeline.run() """ -from __future__ import print_function, division, unicode_literals, absolute_import - -from ..base import ( - TraitedSpec, - CommandLineInputSpec, - CommandLine, - InputMultiPath, - OutputMultiPath, - BaseInterface, - BaseInterfaceInputSpec, - traits, - Directory, - File, - isdefined -) +from __future__ import (print_function, division, unicode_literals, + absolute_import) + +from ..base import (TraitedSpec, CommandLineInputSpec, CommandLine, + InputMultiPath, OutputMultiPath, BaseInterface, + BaseInterfaceInputSpec, traits, Directory, File, isdefined) import os class TrainingSetCreatorInputSpec(BaseInterfaceInputSpec): - mel_icas_in = InputMultiPath(Directory(exists=True), copyfile=False, - desc='Melodic output directories', - argstr='%s', position=-1) + mel_icas_in = InputMultiPath( + Directory(exists=True), + copyfile=False, + desc='Melodic output directories', + argstr='%s', + position=-1) class TrainingSetCreatorOutputSpec(TraitedSpec): - mel_icas_out = OutputMultiPath(Directory(exists=True), copyfile=False, - desc='Hand labels for noise vs signal', - argstr='%s', position=-1) + mel_icas_out = OutputMultiPath( + Directory(exists=True), + copyfile=False, + desc='Hand labels for noise vs signal', + argstr='%s', + position=-1) class TrainingSetCreator(BaseInterface): @@ -100,34 +97,42 @@ class TrainingSetCreator(BaseInterface): def _run_interface(self, runtime): mel_icas = [] for item in self.inputs.mel_icas_in: - if os.path.exists(os.path.join(item,'hand_labels_noise.txt')): + if os.path.exists(os.path.join(item, 'hand_labels_noise.txt')): mel_icas.append(item) if len(mel_icas) == 0: - raise Exception('%s did not find any hand_labels_noise.txt files in the following directories: %s' % (self.__class__.__name__, mel_icas)) + raise Exception( + '%s did not find any hand_labels_noise.txt files in the following directories: %s' + % (self.__class__.__name__, mel_icas)) return runtime def _list_outputs(self): mel_icas = [] for item in self.inputs.mel_icas_in: - if os.path.exists(os.path.join(item,'hand_labels_noise.txt')): + if os.path.exists(os.path.join(item, 'hand_labels_noise.txt')): mel_icas.append(item) outputs = self._outputs().get() outputs['mel_icas_out'] = mel_icas return outputs - - class FeatureExtractorInputSpec(CommandLineInputSpec): - mel_ica = Directory(exists=True, copyfile=False, desc='Melodic output directory or directories', - argstr='%s', position=-1) + mel_ica = Directory( + exists=True, + copyfile=False, + desc='Melodic output directory or directories', + argstr='%s', + position=-1) class FeatureExtractorOutputSpec(TraitedSpec): - mel_ica = Directory(exists=True, copyfile=False, desc='Melodic output directory or directories', - argstr='%s', position=-1) + mel_ica = Directory( + exists=True, + copyfile=False, + desc='Melodic output directory or directories', + argstr='%s', + position=-1) class FeatureExtractor(CommandLine): @@ -145,13 +150,23 @@ def _list_outputs(self): class TrainingInputSpec(CommandLineInputSpec): - mel_icas = InputMultiPath(Directory(exists=True), copyfile=False, - desc='Melodic output directories', - argstr='%s', position=-1) + mel_icas = InputMultiPath( + Directory(exists=True), + copyfile=False, + desc='Melodic output directories', + argstr='%s', + position=-1) - trained_wts_filestem = traits.Str(desc='trained-weights filestem, used for trained_wts_file and output directories', argstr='%s', position=1) + trained_wts_filestem = traits.Str( + desc= + 'trained-weights filestem, used for trained_wts_file and output directories', + argstr='%s', + position=1) - loo = traits.Bool(argstr='-l', desc='full leave-one-out test with classifier training', position=2) + loo = traits.Bool( + argstr='-l', + desc='full leave-one-out test with classifier training', + position=2) class TrainingOutputSpec(TraitedSpec): @@ -169,26 +184,40 @@ class Training(CommandLine): def _list_outputs(self): outputs = self.output_spec().get() if isdefined(self.inputs.trained_wts_filestem): - outputs['trained_wts_file'] = os.path.abspath(self.inputs.trained_wts_filestem + '.RData') + outputs['trained_wts_file'] = os.path.abspath( + self.inputs.trained_wts_filestem + '.RData') else: - outputs['trained_wts_file'] = os.path.abspath('trained_wts_file.RData') + outputs['trained_wts_file'] = os.path.abspath( + 'trained_wts_file.RData') return outputs - - class AccuracyTesterInputSpec(CommandLineInputSpec): - mel_icas = InputMultiPath(Directory(exists=True), copyfile=False, - desc='Melodic output directories', - argstr='%s', position=3, mandatory=True) + mel_icas = InputMultiPath( + Directory(exists=True), + copyfile=False, + desc='Melodic output directories', + argstr='%s', + position=3, + mandatory=True) - trained_wts_file = File(desc='trained-weights file', argstr='%s', position=1, mandatory=True) + trained_wts_file = File( + desc='trained-weights file', argstr='%s', position=1, mandatory=True) - output_directory = Directory(desc='Path to folder in which to store the results of the accuracy test.', argstr='%s', position=2, mandatory=True) + output_directory = Directory( + desc= + 'Path to folder in which to store the results of the accuracy test.', + argstr='%s', + position=2, + mandatory=True) class AccuracyTesterOutputSpec(TraitedSpec): - output_directory = Directory(desc='Path to folder in which to store the results of the accuracy test.', argstr='%s', position=1) + output_directory = Directory( + desc= + 'Path to folder in which to store the results of the accuracy test.', + argstr='%s', + position=1) class AccuracyTester(CommandLine): @@ -203,25 +232,47 @@ class AccuracyTester(CommandLine): def _list_outputs(self): outputs = self.output_spec().get() if isdefined(self.inputs.output_directory): - outputs['output_directory'] = Directory(exists=False, value=self.inputs.output_directory) + outputs['output_directory'] = Directory( + exists=False, value=self.inputs.output_directory) else: - outputs['output_directory'] = Directory(exists=False, value='accuracy_test') + outputs['output_directory'] = Directory( + exists=False, value='accuracy_test') return outputs - class ClassifierInputSpec(CommandLineInputSpec): - mel_ica = Directory(exists=True, copyfile=False, desc='Melodic output directory or directories', - argstr='%s', position=1) - - trained_wts_file = File(exists=True, desc='trained-weights file', argstr='%s', position=2, mandatory=True, copyfile=False) + mel_ica = Directory( + exists=True, + copyfile=False, + desc='Melodic output directory or directories', + argstr='%s', + position=1) + + trained_wts_file = File( + exists=True, + desc='trained-weights file', + argstr='%s', + position=2, + mandatory=True, + copyfile=False) + + thresh = traits.Int( + argstr='%d', + desc='Threshold for cleanup.', + position=-1, + mandatory=True) + + artifacts_list_file = File( + desc= + 'Text file listing which ICs are artifacts; can be the output from classification or can be created manually' + ) - thresh = traits.Int(argstr='%d', desc='Threshold for cleanup.', position=-1, mandatory=True) - - artifacts_list_file = File(desc='Text file listing which ICs are artifacts; can be the output from classification or can be created manually') class ClassifierOutputSpec(TraitedSpec): - artifacts_list_file = File(desc='Text file listing which ICs are artifacts; can be the output from classification or can be created manually') + artifacts_list_file = File( + desc= + 'Text file listing which ICs are artifacts; can be the output from classification or can be created manually' + ) class Classifier(CommandLine): @@ -243,34 +294,49 @@ def _gen_artifacts_list_file(self, mel_ica, thresh): def _list_outputs(self): outputs = self.output_spec().get() - outputs['artifacts_list_file'] = self._gen_artifacts_list_file(self.inputs.mel_ica, self.inputs.thresh) + outputs['artifacts_list_file'] = self._gen_artifacts_list_file( + self.inputs.mel_ica, self.inputs.thresh) return outputs - - class CleanerInputSpec(CommandLineInputSpec): - artifacts_list_file = File(exists=True, argstr='%s', position=1, mandatory=True, desc='Text file listing which ICs are artifacts; can be the output from classification or can be created manually') - - cleanup_motion = traits.Bool(argstr='-m', - desc='cleanup motion confounds, looks for design.fsf for highpass filter cut-off', - position=2) - - highpass = traits.Float(100, argstr='-m -h %f', usedefault=True, - desc='cleanup motion confounds', position=2) - - aggressive = traits.Bool(argstr='-A', - desc='Apply aggressive (full variance) cleanup, instead of the default less-aggressive (unique variance) cleanup.', position=3) - - confound_file = traits.File(argstr='-x %s', - desc='Include additional confound file.', position=4) - - confound_file_1 = traits.File(argstr='-x %s', - desc='Include additional confound file.', position=5) - - confound_file_2 = traits.File(argstr='-x %s', - desc='Include additional confound file.', position=6) + artifacts_list_file = File( + exists=True, + argstr='%s', + position=1, + mandatory=True, + desc= + 'Text file listing which ICs are artifacts; can be the output from classification or can be created manually' + ) + + cleanup_motion = traits.Bool( + argstr='-m', + desc= + 'cleanup motion confounds, looks for design.fsf for highpass filter cut-off', + position=2) + + highpass = traits.Float( + 100, + argstr='-m -h %f', + usedefault=True, + desc='cleanup motion confounds', + position=2) + + aggressive = traits.Bool( + argstr='-A', + desc= + 'Apply aggressive (full variance) cleanup, instead of the default less-aggressive (unique variance) cleanup.', + position=3) + + confound_file = traits.File( + argstr='-x %s', desc='Include additional confound file.', position=4) + + confound_file_1 = traits.File( + argstr='-x %s', desc='Include additional confound file.', position=5) + + confound_file_2 = traits.File( + argstr='-x %s', desc='Include additional confound file.', position=6) class CleanerOutputSpec(TraitedSpec): @@ -288,13 +354,17 @@ class Cleaner(CommandLine): def _get_cleaned_functional_filename(self, artifacts_list_filename): ''' extract the proper filename from the first line of the artifacts file ''' artifacts_list_file = open(artifacts_list_filename, 'r') - functional_filename, extension = artifacts_list_file.readline().split('.') - artifacts_list_file_path, artifacts_list_filename = os.path.split(artifacts_list_filename) + functional_filename, extension = artifacts_list_file.readline().split( + '.') + artifacts_list_file_path, artifacts_list_filename = os.path.split( + artifacts_list_filename) - return(os.path.join(artifacts_list_file_path, functional_filename + '_clean.nii.gz')) + return (os.path.join(artifacts_list_file_path, + functional_filename + '_clean.nii.gz')) def _list_outputs(self): outputs = self.output_spec().get() - outputs['cleaned_functional_file'] = self._get_cleaned_functional_filename(self.inputs.artifacts_list_file) + outputs[ + 'cleaned_functional_file'] = self._get_cleaned_functional_filename( + self.inputs.artifacts_list_file) return outputs - diff --git a/nipype/interfaces/fsl/maths.py b/nipype/interfaces/fsl/maths.py index f403c5c402..ef54b81965 100644 --- a/nipype/interfaces/fsl/maths.py +++ b/nipype/interfaces/fsl/maths.py @@ -11,7 +11,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import numpy as np @@ -21,21 +22,36 @@ class MathsInput(FSLCommandInputSpec): - in_file = File(position=2, argstr="%s", exists=True, mandatory=True, - desc="image to operate on") - out_file = File(genfile=True, position=-2, argstr="%s", - desc="image to write", hash_files=False) + in_file = File( + position=2, + argstr="%s", + exists=True, + mandatory=True, + desc="image to operate on") + out_file = File( + genfile=True, + position=-2, + argstr="%s", + desc="image to write", + hash_files=False) _dtypes = ["float", "char", "int", "short", "double", "input"] - internal_datatype = traits.Enum(*_dtypes, position=1, argstr="-dt %s", - desc=("datatype to use for calculations " - "(default is float)")) - output_datatype = traits.Enum(*_dtypes, - position=-1, argstr="-odt %s", - desc=("datatype to use for output (default " - "uses input type)")) - - nan2zeros = traits.Bool(position=3, argstr='-nan', - desc='change NaNs to zeros before doing anything') + internal_datatype = traits.Enum( + *_dtypes, + position=1, + argstr="-dt %s", + desc=("datatype to use for calculations " + "(default is float)")) + output_datatype = traits.Enum( + *_dtypes, + position=-1, + argstr="-odt %s", + desc=("datatype to use for output (default " + "uses input type)")) + + nan2zeros = traits.Bool( + position=3, + argstr='-nan', + desc='change NaNs to zeros before doing anything') class MathsOutput(TraitedSpec): @@ -54,8 +70,8 @@ def _list_outputs(self): outputs = self.output_spec().get() outputs["out_file"] = self.inputs.out_file if not isdefined(self.inputs.out_file): - outputs["out_file"] = self._gen_fname(self.inputs.in_file, - suffix=self._suffix) + outputs["out_file"] = self._gen_fname( + self.inputs.in_file, suffix=self._suffix) outputs["out_file"] = os.path.abspath(outputs["out_file"]) return outputs @@ -68,10 +84,12 @@ def _gen_filename(self, name): class ChangeDataTypeInput(MathsInput): _dtypes = ["float", "char", "int", "short", "double", "input"] - output_datatype = traits.Enum(*_dtypes, - position=-1, argstr="-odt %s", - mandatory=True, - desc="output data type") + output_datatype = traits.Enum( + *_dtypes, + position=-1, + argstr="-odt %s", + mandatory=True, + desc="output data type") class ChangeDataType(MathsCommand): @@ -84,10 +102,13 @@ class ChangeDataType(MathsCommand): class ThresholdInputSpec(MathsInput): - thresh = traits.Float(mandatory=True, position=4, argstr="%s", - desc="threshold value") - direction = traits.Enum("below", "above", usedefault=True, - desc="zero-out either below or above thresh value") + thresh = traits.Float( + mandatory=True, position=4, argstr="%s", desc="threshold value") + direction = traits.Enum( + "below", + "above", + usedefault=True, + desc="zero-out either below or above thresh value") use_robust_range = traits.Bool( desc="interpret thresh as percentage (0-100) of robust range") use_nonzero_voxels = traits.Bool( @@ -110,8 +131,8 @@ def _format_arg(self, name, spec, value): arg += "u" arg += "thr" if isdefined(_si.use_robust_range) and _si.use_robust_range: - if (isdefined(_si.use_nonzero_voxels) and - _si.use_nonzero_voxels): + if (isdefined(_si.use_nonzero_voxels) + and _si.use_nonzero_voxels): arg += "P" else: arg += "p" @@ -122,9 +143,15 @@ def _format_arg(self, name, spec, value): class StdImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%sstd", position=4, - desc="dimension to standard deviate across") + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%sstd", + position=4, + desc="dimension to standard deviate across") class StdImage(MathsCommand): @@ -137,9 +164,15 @@ class StdImage(MathsCommand): class MeanImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%smean", position=4, - desc="dimension to mean across") + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%smean", + position=4, + desc="dimension to mean across") class MeanImage(MathsCommand): @@ -152,9 +185,15 @@ class MeanImage(MathsCommand): class MaxImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%smax", position=4, - desc="dimension to max across") + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%smax", + position=4, + desc="dimension to max across") class MaxImage(MathsCommand): @@ -176,13 +215,23 @@ class MaxImage(MathsCommand): class PercentileImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%sperc", position=4, - desc="dimension to percentile across") - perc = traits.Range(low=0, high=100, usedefault=False, - argstr="%f", position=5, - desc=("nth percentile (0-100) of FULL RANGE " - "across dimension")) + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%sperc", + position=4, + desc="dimension to percentile across") + perc = traits.Range( + low=0, + high=100, + usedefault=False, + argstr="%f", + position=5, + desc=("nth percentile (0-100) of FULL RANGE " + "across dimension")) class PercentileImage(MathsCommand): @@ -205,9 +254,15 @@ class PercentileImage(MathsCommand): class MaxnImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%smaxn", position=4, - desc="dimension to index max across") + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%smaxn", + position=4, + desc="dimension to index max across") class MaxnImage(MathsCommand): @@ -221,9 +276,15 @@ class MaxnImage(MathsCommand): class MinImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%smin", position=4, - desc="dimension to min across") + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%smin", + position=4, + desc="dimension to min across") class MinImage(MathsCommand): @@ -236,9 +297,15 @@ class MinImage(MathsCommand): class MedianImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%smedian", position=4, - desc="dimension to median across") + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%smedian", + position=4, + desc="dimension to median across") class MedianImage(MathsCommand): @@ -251,10 +318,16 @@ class MedianImage(MathsCommand): class AR1ImageInput(MathsInput): - dimension = traits.Enum("T", "X", "Y", "Z", usedefault=True, - argstr="-%sar1", position=4, - desc=("dimension to find AR(1) coefficient" - "across")) + dimension = traits.Enum( + "T", + "X", + "Y", + "Z", + usedefault=True, + argstr="-%sar1", + position=4, + desc=("dimension to find AR(1) coefficient" + "across")) class AR1Image(MathsCommand): @@ -268,12 +341,18 @@ class AR1Image(MathsCommand): class IsotropicSmoothInput(MathsInput): - fwhm = traits.Float(mandatory=True, xor=["sigma"], - position=4, argstr="-s %.5f", - desc="fwhm of smoothing kernel [mm]") - sigma = traits.Float(mandatory=True, xor=["fwhm"], - position=4, argstr="-s %.5f", - desc="sigma of smoothing kernel [mm]") + fwhm = traits.Float( + mandatory=True, + xor=["sigma"], + position=4, + argstr="-s %.5f", + desc="fwhm of smoothing kernel [mm]") + sigma = traits.Float( + mandatory=True, + xor=["fwhm"], + position=4, + argstr="-s %.5f", + desc="sigma of smoothing kernel [mm]") class IsotropicSmooth(MathsCommand): @@ -292,8 +371,12 @@ def _format_arg(self, name, spec, value): class ApplyMaskInput(MathsInput): - mask_file = File(exists=True, mandatory=True, argstr="-mas %s", position=4, - desc="binary image defining mask space") + mask_file = File( + exists=True, + mandatory=True, + argstr="-mas %s", + position=4, + desc="binary image defining mask space") class ApplyMask(MathsCommand): @@ -306,23 +389,41 @@ class ApplyMask(MathsCommand): class KernelInput(MathsInput): - kernel_shape = traits.Enum("3D", "2D", "box", "boxv", "gauss", "sphere", - "file", - argstr="-kernel %s", position=4, - desc="kernel shape to use") - kernel_size = traits.Float(argstr="%.4f", position=5, xor=["kernel_file"], - desc=("kernel size - voxels for box/boxv, mm " - "for sphere, mm sigma for gauss")) - kernel_file = File(exists=True, argstr="%s", position=5, - xor=["kernel_size"], - desc="use external file for kernel") + kernel_shape = traits.Enum( + "3D", + "2D", + "box", + "boxv", + "gauss", + "sphere", + "file", + argstr="-kernel %s", + position=4, + desc="kernel shape to use") + kernel_size = traits.Float( + argstr="%.4f", + position=5, + xor=["kernel_file"], + desc=("kernel size - voxels for box/boxv, mm " + "for sphere, mm sigma for gauss")) + kernel_file = File( + exists=True, + argstr="%s", + position=5, + xor=["kernel_size"], + desc="use external file for kernel") class DilateInput(KernelInput): - operation = traits.Enum("mean", "modal", "max", argstr="-dil%s", - position=6, mandatory=True, - desc="filtering operation to perfoem in dilation") + operation = traits.Enum( + "mean", + "modal", + "max", + argstr="-dil%s", + position=6, + mandatory=True, + desc="filtering operation to perfoem in dilation") class DilateImage(MathsCommand): @@ -340,10 +441,13 @@ def _format_arg(self, name, spec, value): class ErodeInput(KernelInput): - minimum_filter = traits.Bool(argstr="%s", position=6, usedefault=True, - default_value=False, - desc=("if true, minimum filter rather than " - "erosion by zeroing-out")) + minimum_filter = traits.Bool( + argstr="%s", + position=6, + usedefault=True, + default_value=False, + desc=("if true, minimum filter rather than " + "erosion by zeroing-out")) class ErodeImage(MathsCommand): @@ -363,9 +467,14 @@ def _format_arg(self, name, spec, value): class SpatialFilterInput(KernelInput): - operation = traits.Enum("mean", "median", "meanu", argstr="-f%s", - position=6, mandatory=True, - desc="operation to filter with") + operation = traits.Enum( + "mean", + "median", + "meanu", + argstr="-f%s", + position=6, + mandatory=True, + desc="operation to filter with") class SpatialFilter(MathsCommand): @@ -378,12 +487,34 @@ class SpatialFilter(MathsCommand): class UnaryMathsInput(MathsInput): - operation = traits.Enum("exp", "log", "sin", "cos", "tan", "asin", "acos", - "atan", "sqr", "sqrt", "recip", "abs", "bin", - "binv", "fillh", "fillh26", "index", "edge", "nan", - "nanm", "rand", "randn", "range", - argstr="-%s", position=4, mandatory=True, - desc="operation to perform") + operation = traits.Enum( + "exp", + "log", + "sin", + "cos", + "tan", + "asin", + "acos", + "atan", + "sqr", + "sqrt", + "recip", + "abs", + "bin", + "binv", + "fillh", + "fillh26", + "index", + "edge", + "nan", + "nanm", + "rand", + "randn", + "range", + argstr="-%s", + position=4, + mandatory=True, + desc="operation to perform") class UnaryMaths(MathsCommand): @@ -399,15 +530,31 @@ def _list_outputs(self): class BinaryMathsInput(MathsInput): - operation = traits.Enum("add", "sub", "mul", "div", "rem", "max", "min", - mandatory=True, argstr="-%s", position=4, - desc="operation to perform") - operand_file = File(exists=True, argstr="%s", mandatory=True, - position=5, xor=["operand_value"], - desc="second image to perform operation with") - operand_value = traits.Float(argstr="%.8f", mandatory=True, - position=5, xor=["operand_file"], - desc="value to perform operation with") + operation = traits.Enum( + "add", + "sub", + "mul", + "div", + "rem", + "max", + "min", + mandatory=True, + argstr="-%s", + position=4, + desc="operation to perform") + operand_file = File( + exists=True, + argstr="%s", + mandatory=True, + position=5, + xor=["operand_value"], + desc="second image to perform operation with") + operand_value = traits.Float( + argstr="%.8f", + mandatory=True, + position=5, + xor=["operand_file"], + desc="value to perform operation with") class BinaryMaths(MathsCommand): @@ -420,12 +567,17 @@ class BinaryMaths(MathsCommand): class MultiImageMathsInput(MathsInput): - op_string = traits.String(position=4, argstr="%s", mandatory=True, - desc=("python formatted string of operations " - "to perform")) - operand_files = InputMultiPath(File(exists=True), mandatory=True, - desc=("list of file names to plug into op " - "string")) + op_string = traits.String( + position=4, + argstr="%s", + mandatory=True, + desc=("python formatted string of operations " + "to perform")) + operand_files = InputMultiPath( + File(exists=True), + mandatory=True, + desc=("list of file names to plug into op " + "string")) class MultiImageMaths(MathsCommand): @@ -453,12 +605,18 @@ def _format_arg(self, name, spec, value): class TemporalFilterInput(MathsInput): - lowpass_sigma = traits.Float(-1, argstr="%.6f", position=5, - usedefault=True, - desc="lowpass filter sigma (in volumes)") - highpass_sigma = traits.Float(-1, argstr="-bptf %.6f", position=4, - usedefault=True, - desc="highpass filter sigma (in volumes)") + lowpass_sigma = traits.Float( + -1, + argstr="%.6f", + position=5, + usedefault=True, + desc="lowpass filter sigma (in volumes)") + highpass_sigma = traits.Float( + -1, + argstr="-bptf %.6f", + position=4, + usedefault=True, + desc="highpass filter sigma (in volumes)") class TemporalFilter(MathsCommand): diff --git a/nipype/interfaces/fsl/model.py b/nipype/interfaces/fsl/model.py index 0dbf7c6bd1..6b2224adb4 100644 --- a/nipype/interfaces/fsl/model.py +++ b/nipype/interfaces/fsl/model.py @@ -11,7 +11,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, open import os @@ -26,33 +27,38 @@ from ...utils.filemanip import list_to_filename, filename_to_list from ...utils.misc import human_order_sorted from ...external.due import BibTeX -from ..base import (File, traits, isdefined, - TraitedSpec, BaseInterface, Directory, - InputMultiPath, OutputMultiPath, +from ..base import (File, traits, isdefined, TraitedSpec, BaseInterface, + Directory, InputMultiPath, OutputMultiPath, BaseInterfaceInputSpec) from .base import FSLCommand, FSLCommandInputSpec, Info class Level1DesignInputSpec(BaseInterfaceInputSpec): - interscan_interval = traits.Float(mandatory=True, - desc='Interscan interval (in secs)') - session_info = traits.Any(mandatory=True, - desc=('Session specific information generated ' - 'by ``modelgen.SpecifyModel``')) + interscan_interval = traits.Float( + mandatory=True, desc='Interscan interval (in secs)') + session_info = traits.Any( + mandatory=True, + desc=('Session specific information generated ' + 'by ``modelgen.SpecifyModel``')) bases = traits.Either( - traits.Dict(traits.Enum('dgamma'), traits.Dict( - traits.Enum('derivs'), traits.Bool)), - traits.Dict(traits.Enum('gamma'), traits.Dict( - traits.Enum('derivs', 'gammasigma', 'gammadelay'))), - traits.Dict(traits.Enum('custom'), traits.Dict( - traits.Enum('bfcustompath'), traits.Str)), + traits.Dict( + traits.Enum('dgamma'), + traits.Dict(traits.Enum('derivs'), traits.Bool)), + traits.Dict( + traits.Enum('gamma'), + traits.Dict(traits.Enum('derivs', 'gammasigma', 'gammadelay'))), + traits.Dict( + traits.Enum('custom'), + traits.Dict(traits.Enum('bfcustompath'), traits.Str)), traits.Dict(traits.Enum('none'), traits.Dict()), traits.Dict(traits.Enum('none'), traits.Enum(None)), mandatory=True, desc=("name of basis function and options e.g., " - "{'dgamma': {'derivs': True}}"),) - orthogonalization = traits.Dict(traits.Int, traits.Dict(traits.Int, - traits.Either(traits.Bool,traits.Int)), + "{'dgamma': {'derivs': True}}"), + ) + orthogonalization = traits.Dict( + traits.Int, + traits.Dict(traits.Int, traits.Either(traits.Bool, traits.Int)), desc=("which regressors to make orthogonal e.g., " "{1: {0:0,1:0,2:0}, 2: {0:1,1:1,2:0}} to make the second " "regressor in a 2-regressor model orthogonal to the first."), @@ -64,34 +70,21 @@ class Level1DesignInputSpec(BaseInterfaceInputSpec): repeat this option for FILMGLS by setting autocorr_noestimate to True", mandatory=True) contrasts = traits.List( - traits.Either(traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('F'), - traits.List( - traits.Either( - traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List( - traits.Str), - traits.List( - traits.Float)), - traits.Tuple( - traits.Str, - traits.Enum('T'), - traits.List( - traits.Str), - traits.List( - traits.Float), - traits.List( - traits.Float)))))), + traits.Either( + traits.Tuple(traits.Str, traits.Enum('T'), traits.List(traits.Str), + traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('T'), traits.List(traits.Str), + traits.List(traits.Float), traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('F'), + traits.List( + traits.Either( + traits.Tuple(traits.Str, traits.Enum('T'), + traits.List(traits.Str), + traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('T'), + traits.List(traits.Str), + traits.List(traits.Float), + traits.List(traits.Float)))))), desc="List of contrasts with each contrast being a list of the form - \ [('name', 'stat', [condition list], [weight list], [session list])]. if \ session list is None or not provided, all sessions are used. For F \ @@ -100,10 +93,10 @@ class Level1DesignInputSpec(BaseInterfaceInputSpec): class Level1DesignOutputSpec(TraitedSpec): - fsf_files = OutputMultiPath(File(exists=True), - desc='FSL feat specification files') - ev_files = OutputMultiPath(traits.List(File(exists=True)), - desc='condition information files') + fsf_files = OutputMultiPath( + File(exists=True), desc='FSL feat specification files') + ev_files = OutputMultiPath( + traits.List(File(exists=True)), desc='condition information files') class Level1Design(BaseInterface): @@ -132,9 +125,9 @@ def _create_ev_file(self, evfname, evinfo): f.write('%f\n' % i[0]) f.close() - def _create_ev_files( - self, cwd, runinfo, runidx, ev_parameters, orthogonalization, - contrasts, do_tempfilter, basis_key): + def _create_ev_files(self, cwd, runinfo, runidx, ev_parameters, + orthogonalization, contrasts, do_tempfilter, + basis_key): """Creates EV files from condition and regressor information. Parameters: @@ -159,14 +152,14 @@ def _create_ev_files( basis_key = "hrf" elif basis_key == "gamma": try: - _ = ev_parameters['gammasigma'] + _ = ev_parameters['gammasigma'] except KeyError: - ev_parameters['gammasigma'] = 3 + ev_parameters['gammasigma'] = 3 try: - _ = ev_parameters['gammadelay'] + _ = ev_parameters['gammadelay'] except KeyError: - ev_parameters['gammadelay'] = 6 - ev_template = load_template('feat_ev_'+basis_key+'.tcl') + ev_parameters['gammadelay'] = 6 + ev_template = load_template('feat_ev_' + basis_key + '.tcl') ev_none = load_template('feat_ev_none.tcl') ev_ortho = load_template('feat_ev_ortho.tcl') ev_txt = '' @@ -200,28 +193,31 @@ def _create_ev_files( ev_parameters['ev_num'] = num_evs[0] ev_parameters['ev_name'] = name ev_parameters['tempfilt_yn'] = do_tempfilter - if not 'basisorth' in ev_parameters: + if 'basisorth' not in ev_parameters: ev_parameters['basisorth'] = 1 - if not 'basisfnum' in ev_parameters: + if 'basisfnum' not in ev_parameters: ev_parameters['basisfnum'] = 1 try: ev_parameters['fsldir'] = os.environ['FSLDIR'] except KeyError: if basis_key == 'flobs': - raise Exception('FSL environment variables not set') + raise Exception( + 'FSL environment variables not set') else: ev_parameters['fsldir'] = '/usr/share/fsl' - ev_parameters['temporalderiv'] = int(bool(ev_parameters.get('derivs', False))) + ev_parameters['temporalderiv'] = int( + bool(ev_parameters.get('derivs', False))) if ev_parameters['temporalderiv']: evname.append(name + 'TD') num_evs[1] += 1 ev_txt += ev_template.substitute(ev_parameters) elif field == 'regress': evinfo = [[j] for j in cond['val']] - ev_txt += ev_none.substitute(ev_num=num_evs[0], - ev_name=name, - tempfilt_yn=do_tempfilter, - cond_file=evfname) + ev_txt += ev_none.substitute( + ev_num=num_evs[0], + ev_name=name, + tempfilt_yn=do_tempfilter, + cond_file=evfname) ev_txt += "\n" conds[name] = evfname self._create_ev_file(evfname, evinfo) @@ -232,7 +228,8 @@ def _create_ev_files( orthogonal = int(orthogonalization[i][j]) except (KeyError, TypeError, ValueError, IndexError): orthogonal = 0 - ev_txt += ev_ortho.substitute(c0=i, c1=j, orthogonal=orthogonal) + ev_txt += ev_ortho.substitute( + c0=i, c1=j, orthogonal=orthogonal) ev_txt += "\n" # add contrast info to fsf file if isdefined(contrasts): @@ -268,9 +265,8 @@ def _create_ev_files( if con[1] == 'F': continue tidx = ttest_idx.index(j) + 1 - ev_txt += contrast_prolog.substitute(cnum=tidx, - ctype=ctype, - cname=con[0]) + ev_txt += contrast_prolog.substitute( + cnum=tidx, ctype=ctype, cname=con[0]) count = 0 for c in range(1, len(evname) + 1): if evname[c - 1].endswith('TD') and ctype == 'orig': @@ -286,8 +282,8 @@ def _create_ev_files( for fconidx in ftest_idx: fval = 0 - if (con[0] in con_map.keys() and - fconidx in con_map[con[0]]): + if (con[0] in con_map.keys() + and fconidx in con_map[con[0]]): fval = 1 ev_txt += contrast_ftest_element.substitute( cnum=ftest_idx.index(fconidx) + 1, @@ -301,8 +297,8 @@ def _create_ev_files( for j, _ in enumerate(contrasts): for k, _ in enumerate(contrasts): if j != k: - ev_txt += contrastmask_element.substitute(c1=j + 1, - c2=k + 1) + ev_txt += contrastmask_element.substitute( + c1=j + 1, c2=k + 1) ev_txt += contrastmask_footer.substitute() return num_evs, ev_txt @@ -344,10 +340,9 @@ def _run_interface(self, runtime): do_tempfilter = 1 if info['hpf'] == np.inf: do_tempfilter = 0 - num_evs, cond_txt = self._create_ev_files(cwd, info, i, ev_parameters, - self.inputs.orthogonalization, - self.inputs.contrasts, - do_tempfilter, basis_key) + num_evs, cond_txt = self._create_ev_files( + cwd, info, i, ev_parameters, self.inputs.orthogonalization, + self.inputs.contrasts, do_tempfilter, basis_key) nim = load(func_files[i]) (_, _, _, timepoints) = nim.shape fsf_txt = fsf_header.substitute( @@ -359,8 +354,7 @@ def _run_interface(self, runtime): num_evs_real=num_evs[1], num_tcon=n_tcon, num_fcon=n_fcon, - high_pass_filter_cutoff=info[ - 'hpf'], + high_pass_filter_cutoff=info['hpf'], temphp_yn=do_tempfilter, func_file=func_files[i]) fsf_txt += cond_txt @@ -388,11 +382,12 @@ def _list_outputs(self): for i, cond in enumerate(runinfo[field]): name = cond['name'] evname.append(name) - evfname = os.path.join( - cwd, 'ev_%s_%d_%d.txt' % (name, runno, - len(evname))) + evfname = os.path.join(cwd, + 'ev_%s_%d_%d.txt' % (name, runno, + len(evname))) if field == 'cond': - ev_parameters['temporalderiv'] = int(bool(ev_parameters.get('derivs', False))) + ev_parameters['temporalderiv'] = int( + bool(ev_parameters.get('derivs', False))) if ev_parameters['temporalderiv']: evname.append(name + 'TD') outputs['ev_files'][runno].append( @@ -401,8 +396,12 @@ def _list_outputs(self): class FEATInputSpec(FSLCommandInputSpec): - fsf_file = File(exists=True, mandatory=True, argstr="%s", position=0, - desc="File specifying the feat design spec file") + fsf_file = File( + exists=True, + mandatory=True, + argstr="%s", + position=0, + desc="File specifying the feat design spec file") class FEATOutputSpec(TraitedSpec): @@ -436,22 +435,29 @@ def _list_outputs(self): if not outputs['feat_dir']: if is_ica: outputs['feat_dir'] = glob(os.path.join(os.getcwd(), - '*ica'))[0] + '*ica'))[0] else: outputs['feat_dir'] = glob(os.path.join(os.getcwd(), - '*feat'))[0] + '*feat'))[0] print('Outputs from FEATmodel:', outputs) return outputs class FEATModelInputSpec(FSLCommandInputSpec): - fsf_file = File(exists=True, mandatory=True, argstr="%s", position=0, - desc="File specifying the feat design spec file", - copyfile=False) - ev_files = traits.List(File(exists=True), - mandatory=True, argstr="%s", - desc="Event spec files generated by level1design", - position=1, copyfile=False) + fsf_file = File( + exists=True, + mandatory=True, + argstr="%s", + position=0, + desc="File specifying the feat design spec file", + copyfile=False) + ev_files = traits.List( + File(exists=True), + mandatory=True, + argstr="%s", + desc="Event spec files generated by level1design", + position=1, + copyfile=False) class FEATModelOutpuSpec(TraitedSpec): @@ -475,8 +481,9 @@ class FEATModel(FSLCommand): def _format_arg(self, name, trait_spec, value): if name == 'fsf_file': - return super(FEATModel, self)._format_arg( - name, trait_spec, self._get_design_root(value)) + return super(FEATModel, + self)._format_arg(name, trait_spec, + self._get_design_root(value)) elif name == 'ev_files': return '' else: @@ -512,152 +519,210 @@ def _list_outputs(self): class FILMGLSInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, position=-3, - argstr='%s', - desc='input data file') - design_file = File(exists=True, position=-2, - argstr='%s', - desc='design matrix file') - threshold = traits.Range(default=1000., low=0.0, argstr='%f', - position=-1, usedefault=True, - desc='threshold') - smooth_autocorr = traits.Bool(argstr='-sa', - desc='Smooth auto corr estimates') - mask_size = traits.Int(argstr='-ms %d', - desc="susan mask size") - brightness_threshold = traits.Range(low=0, argstr='-epith %d', - desc=('susan brightness threshold, ' - 'otherwise it is estimated')) + in_file = File( + exists=True, + mandatory=True, + position=-3, + argstr='%s', + desc='input data file') + design_file = File( + exists=True, position=-2, argstr='%s', desc='design matrix file') + threshold = traits.Range( + default=1000., + low=0.0, + argstr='%f', + position=-1, + usedefault=True, + desc='threshold') + smooth_autocorr = traits.Bool( + argstr='-sa', desc='Smooth auto corr estimates') + mask_size = traits.Int(argstr='-ms %d', desc="susan mask size") + brightness_threshold = traits.Range( + low=0, + argstr='-epith %d', + desc=('susan brightness threshold, ' + 'otherwise it is estimated')) full_data = traits.Bool(argstr='-v', desc='output full data') - _estimate_xor = ['autocorr_estimate_only', 'fit_armodel', 'tukey_window', - 'multitaper_product', 'use_pava', 'autocorr_noestimate'] - autocorr_estimate_only = traits.Bool(argstr='-ac', - xor=_estimate_xor, - desc=('perform autocorrelation ' - 'estimatation only')) - fit_armodel = traits.Bool(argstr='-ar', xor=_estimate_xor, - desc=('fits autoregressive model - default is ' - 'to use tukey with M=sqrt(numvols)')) - tukey_window = traits.Int(argstr='-tukey %d', xor=_estimate_xor, - desc='tukey window size to estimate autocorr') - multitaper_product = traits.Int(argstr='-mt %d', xor=_estimate_xor, - desc=('multitapering with slepian tapers ' - 'and num is the time-bandwidth ' - 'product')) + _estimate_xor = [ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ] + autocorr_estimate_only = traits.Bool( + argstr='-ac', + xor=_estimate_xor, + desc=('perform autocorrelation ' + 'estimatation only')) + fit_armodel = traits.Bool( + argstr='-ar', + xor=_estimate_xor, + desc=('fits autoregressive model - default is ' + 'to use tukey with M=sqrt(numvols)')) + tukey_window = traits.Int( + argstr='-tukey %d', + xor=_estimate_xor, + desc='tukey window size to estimate autocorr') + multitaper_product = traits.Int( + argstr='-mt %d', + xor=_estimate_xor, + desc=('multitapering with slepian tapers ' + 'and num is the time-bandwidth ' + 'product')) use_pava = traits.Bool( argstr='-pava', desc='estimates autocorr using PAVA') - autocorr_noestimate = traits.Bool(argstr='-noest', xor=_estimate_xor, - desc='do not estimate autocorrs') - output_pwdata = traits.Bool(argstr='-output_pwdata', - desc=('output prewhitened data and average ' - 'design matrix')) - results_dir = Directory('results', argstr='-rn %s', usedefault=True, - desc='directory to store results in') + autocorr_noestimate = traits.Bool( + argstr='-noest', xor=_estimate_xor, desc='do not estimate autocorrs') + output_pwdata = traits.Bool( + argstr='-output_pwdata', + desc=('output prewhitened data and average ' + 'design matrix')) + results_dir = Directory( + 'results', + argstr='-rn %s', + usedefault=True, + desc='directory to store results in') class FILMGLSInputSpec505(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, position=-3, - argstr='--in=%s', desc='input data file') - design_file = File(exists=True, position=-2, - argstr='--pd=%s', desc='design matrix file') - threshold = traits.Range(default=1000., low=0.0, argstr='--thr=%f', - position=-1, usedefault=True, desc='threshold') - smooth_autocorr = traits.Bool(argstr='--sa', - desc='Smooth auto corr estimates') + in_file = File( + exists=True, + mandatory=True, + position=-3, + argstr='--in=%s', + desc='input data file') + design_file = File( + exists=True, position=-2, argstr='--pd=%s', desc='design matrix file') + threshold = traits.Range( + default=1000., + low=0.0, + argstr='--thr=%f', + position=-1, + usedefault=True, + desc='threshold') + smooth_autocorr = traits.Bool( + argstr='--sa', desc='Smooth auto corr estimates') mask_size = traits.Int(argstr='--ms=%d', desc="susan mask size") - brightness_threshold = traits.Range(low=0, argstr='--epith=%d', - desc=('susan brightness threshold, ' - 'otherwise it is estimated')) + brightness_threshold = traits.Range( + low=0, + argstr='--epith=%d', + desc=('susan brightness threshold, ' + 'otherwise it is estimated')) full_data = traits.Bool(argstr='-v', desc='output full data') - _estimate_xor = ['autocorr_estimate_only', 'fit_armodel', 'tukey_window', - 'multitaper_product', 'use_pava', 'autocorr_noestimate'] - autocorr_estimate_only = traits.Bool(argstr='--ac', xor=_estimate_xor, - desc=('perform autocorrelation ' - 'estimation only')) - fit_armodel = traits.Bool(argstr='--ar', xor=_estimate_xor, - desc=('fits autoregressive model - default is ' - 'to use tukey with M=sqrt(numvols)')) - tukey_window = traits.Int(argstr='--tukey=%d', xor=_estimate_xor, - desc='tukey window size to estimate autocorr') - multitaper_product = traits.Int(argstr='--mt=%d', xor=_estimate_xor, - desc=('multitapering with slepian tapers ' - 'and num is the time-bandwidth ' - 'product')) - use_pava = traits.Bool(argstr='--pava', - desc='estimates autocorr using PAVA') - autocorr_noestimate = traits.Bool(argstr='--noest', xor=_estimate_xor, - desc='do not estimate autocorrs') - output_pwdata = traits.Bool(argstr='--outputPWdata', - desc=('output prewhitened data and average ' - 'design matrix')) - results_dir = Directory('results', argstr='--rn=%s', usedefault=True, - desc='directory to store results in') + _estimate_xor = [ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ] + autocorr_estimate_only = traits.Bool( + argstr='--ac', + xor=_estimate_xor, + desc=('perform autocorrelation ' + 'estimation only')) + fit_armodel = traits.Bool( + argstr='--ar', + xor=_estimate_xor, + desc=('fits autoregressive model - default is ' + 'to use tukey with M=sqrt(numvols)')) + tukey_window = traits.Int( + argstr='--tukey=%d', + xor=_estimate_xor, + desc='tukey window size to estimate autocorr') + multitaper_product = traits.Int( + argstr='--mt=%d', + xor=_estimate_xor, + desc=('multitapering with slepian tapers ' + 'and num is the time-bandwidth ' + 'product')) + use_pava = traits.Bool( + argstr='--pava', desc='estimates autocorr using PAVA') + autocorr_noestimate = traits.Bool( + argstr='--noest', xor=_estimate_xor, desc='do not estimate autocorrs') + output_pwdata = traits.Bool( + argstr='--outputPWdata', + desc=('output prewhitened data and average ' + 'design matrix')) + results_dir = Directory( + 'results', + argstr='--rn=%s', + usedefault=True, + desc='directory to store results in') class FILMGLSInputSpec507(FILMGLSInputSpec505): - threshold = traits.Float(default=-1000., argstr='--thr=%f', - position=-1, usedefault=True, - desc='threshold') - tcon_file = File(exists=True, argstr='--con=%s', - desc='contrast file containing T-contrasts') - fcon_file = File(exists=True, argstr='--fcon=%s', - desc='contrast file containing F-contrasts') - mode = traits.Enum('volumetric', 'surface', argstr="--mode=%s", - desc="Type of analysis to be done") - surface = File(exists=True, argstr="--in2=%s", - desc=("input surface for autocorr smoothing in " - "surface-based analyses")) + threshold = traits.Float( + default=-1000., + argstr='--thr=%f', + position=-1, + usedefault=True, + desc='threshold') + tcon_file = File( + exists=True, + argstr='--con=%s', + desc='contrast file containing T-contrasts') + fcon_file = File( + exists=True, + argstr='--fcon=%s', + desc='contrast file containing F-contrasts') + mode = traits.Enum( + 'volumetric', + 'surface', + argstr="--mode=%s", + desc="Type of analysis to be done") + surface = File( + exists=True, + argstr="--in2=%s", + desc=("input surface for autocorr smoothing in " + "surface-based analyses")) class FILMGLSOutputSpec(TraitedSpec): - param_estimates = OutputMultiPath(File(exists=True), - desc=('Parameter estimates for each ' - 'column of the design matrix')) - residual4d = File(exists=True, - desc=('Model fit residual mean-squared error for each ' - 'time point')) + param_estimates = OutputMultiPath( + File(exists=True), + desc=('Parameter estimates for each ' + 'column of the design matrix')) + residual4d = File( + exists=True, + desc=('Model fit residual mean-squared error for each ' + 'time point')) dof_file = File(exists=True, desc='degrees of freedom') sigmasquareds = File( exists=True, desc='summary of residuals, See Woolrich, et. al., 2001') - results_dir = Directory(exists=True, - desc='directory storing model estimation output') - corrections = File(exists=True, - desc=('statistical corrections used within FILM ' - 'modeling')) - thresholdac = File(exists=True, - desc='The FILM autocorrelation parameters') - logfile = File(exists=True, - desc='FILM run logfile') + results_dir = Directory( + exists=True, desc='directory storing model estimation output') + corrections = File( + exists=True, + desc=('statistical corrections used within FILM ' + 'modeling')) + thresholdac = File(exists=True, desc='The FILM autocorrelation parameters') + logfile = File(exists=True, desc='FILM run logfile') class FILMGLSOutputSpec507(TraitedSpec): - param_estimates = OutputMultiPath(File(exists=True), - desc=('Parameter estimates for each ' - 'column of the design matrix')) - residual4d = File(exists=True, - desc=('Model fit residual mean-squared error for each ' - 'time point')) + param_estimates = OutputMultiPath( + File(exists=True), + desc=('Parameter estimates for each ' + 'column of the design matrix')) + residual4d = File( + exists=True, + desc=('Model fit residual mean-squared error for each ' + 'time point')) dof_file = File(exists=True, desc='degrees of freedom') sigmasquareds = File( exists=True, desc='summary of residuals, See Woolrich, et. al., 2001') - results_dir = Directory(exists=True, - desc='directory storing model estimation output') - thresholdac = File(exists=True, - desc='The FILM autocorrelation parameters') - logfile = File(exists=True, - desc='FILM run logfile') - copes = OutputMultiPath(File(exists=True), - desc='Contrast estimates for each contrast') - varcopes = OutputMultiPath(File(exists=True), - desc='Variance estimates for each contrast') - zstats = OutputMultiPath(File(exists=True), - desc='z-stat file for each contrast') - tstats = OutputMultiPath(File(exists=True), - desc='t-stat file for each contrast') - fstats = OutputMultiPath(File(exists=True), - desc='f-stat file for each contrast') - zfstats = OutputMultiPath(File(exists=True), - desc='z-stat file for each F contrast') + results_dir = Directory( + exists=True, desc='directory storing model estimation output') + thresholdac = File(exists=True, desc='The FILM autocorrelation parameters') + logfile = File(exists=True, desc='FILM run logfile') + copes = OutputMultiPath( + File(exists=True), desc='Contrast estimates for each contrast') + varcopes = OutputMultiPath( + File(exists=True), desc='Variance estimates for each contrast') + zstats = OutputMultiPath( + File(exists=True), desc='z-stat file for each contrast') + tstats = OutputMultiPath( + File(exists=True), desc='t-stat file for each contrast') + fstats = OutputMultiPath( + File(exists=True), desc='f-stat file for each contrast') + zfstats = OutputMultiPath( + File(exists=True), desc='z-stat file for each F contrast') class FILMGLS(FSLCommand): @@ -696,11 +761,10 @@ class FILMGLS(FSLCommand): if Info.version() and LooseVersion(Info.version()) > LooseVersion('5.0.6'): input_spec = FILMGLSInputSpec507 output_spec = FILMGLSOutputSpec507 - elif (Info.version() and - LooseVersion(Info.version()) > LooseVersion('5.0.4')): + elif (Info.version() + and LooseVersion(Info.version()) > LooseVersion('5.0.4')): input_spec = FILMGLSInputSpec505 - def _get_pe_files(self, cwd): files = None if isdefined(self.inputs.design_file): @@ -710,8 +774,8 @@ def _get_pe_files(self, cwd): numpes = int(line.split()[-1]) files = [] for i in range(numpes): - files.append(self._gen_fname('pe%d.nii' % (i + 1), - cwd=cwd)) + files.append( + self._gen_fname('pe%d.nii' % (i + 1), cwd=cwd)) break fp.close() return files @@ -745,20 +809,19 @@ def _list_outputs(self): outputs['param_estimates'] = pe_files outputs['residual4d'] = self._gen_fname('res4d.nii', cwd=results_dir) outputs['dof_file'] = os.path.join(results_dir, 'dof') - outputs['sigmasquareds'] = self._gen_fname('sigmasquareds.nii', - cwd=results_dir) - outputs['thresholdac'] = self._gen_fname('threshac1.nii', - cwd=results_dir) - if (Info.version() and - LooseVersion(Info.version()) < LooseVersion('5.0.7')): - outputs['corrections'] = self._gen_fname('corrections.nii', - cwd=results_dir) - outputs['logfile'] = self._gen_fname('logfile', - change_ext=False, - cwd=results_dir) - - if (Info.version() and - LooseVersion(Info.version()) > LooseVersion('5.0.6')): + outputs['sigmasquareds'] = self._gen_fname( + 'sigmasquareds.nii', cwd=results_dir) + outputs['thresholdac'] = self._gen_fname( + 'threshac1.nii', cwd=results_dir) + if (Info.version() + and LooseVersion(Info.version()) < LooseVersion('5.0.7')): + outputs['corrections'] = self._gen_fname( + 'corrections.nii', cwd=results_dir) + outputs['logfile'] = self._gen_fname( + 'logfile', change_ext=False, cwd=results_dir) + + if (Info.version() + and LooseVersion(Info.version()) > LooseVersion('5.0.6')): pth = results_dir numtcons, numfcons = self._get_numcons() base_contrast = 1 @@ -766,17 +829,19 @@ def _list_outputs(self): varcopes = [] zstats = [] tstats = [] - neffs = [] for i in range(numtcons): - copes.append(self._gen_fname( - 'cope%d.nii' % (base_contrast + i), cwd=pth)) + copes.append( + self._gen_fname( + 'cope%d.nii' % (base_contrast + i), cwd=pth)) varcopes.append( - self._gen_fname('varcope%d.nii' % (base_contrast + i), - cwd=pth)) - zstats.append(self._gen_fname( - 'zstat%d.nii' % (base_contrast + i), cwd=pth)) - tstats.append(self._gen_fname( - 'tstat%d.nii' % (base_contrast + i), cwd=pth)) + self._gen_fname( + 'varcope%d.nii' % (base_contrast + i), cwd=pth)) + zstats.append( + self._gen_fname( + 'zstat%d.nii' % (base_contrast + i), cwd=pth)) + tstats.append( + self._gen_fname( + 'tstat%d.nii' % (base_contrast + i), cwd=pth)) if copes: outputs['copes'] = copes outputs['varcopes'] = varcopes @@ -785,8 +850,9 @@ def _list_outputs(self): fstats = [] zfstats = [] for i in range(numfcons): - fstats.append(self._gen_fname( - 'fstat%d.nii' % (base_contrast + i), cwd=pth)) + fstats.append( + self._gen_fname( + 'fstat%d.nii' % (base_contrast + i), cwd=pth)) zfstats.append( self._gen_fname( 'zfstat%d.nii' % (base_contrast + i), cwd=pth)) @@ -798,18 +864,17 @@ def _list_outputs(self): class FEATRegisterInputSpec(BaseInterfaceInputSpec): feat_dirs = InputMultiPath( - Directory(exists=True), desc="Lower level feat dirs", - mandatory=True) + Directory(exists=True), desc="Lower level feat dirs", mandatory=True) reg_image = File( - exists=True, desc="image to register to (will be treated as standard)", + exists=True, + desc="image to register to (will be treated as standard)", mandatory=True) reg_dof = traits.Int( 12, desc="registration degrees of freedom", usedefault=True) class FEATRegisterOutputSpec(TraitedSpec): - fsf_file = File(exists=True, - desc="FSL feat specification file") + fsf_file = File(exists=True, desc="FSL feat specification file") class FEATRegister(BaseInterface): @@ -824,12 +889,13 @@ def _run_interface(self, runtime): fsf_dirs = load_template('feat_fe_featdirs.tcl') num_runs = len(self.inputs.feat_dirs) - fsf_txt = fsf_header.substitute(num_runs=num_runs, - regimage=self.inputs.reg_image, - regdof=self.inputs.reg_dof) + fsf_txt = fsf_header.substitute( + num_runs=num_runs, + regimage=self.inputs.reg_image, + regdof=self.inputs.reg_dof) for i, rundir in enumerate(filename_to_list(self.inputs.feat_dirs)): - fsf_txt += fsf_dirs.substitute(runno=i + 1, - rundir=os.path.abspath(rundir)) + fsf_txt += fsf_dirs.substitute( + runno=i + 1, rundir=os.path.abspath(rundir)) fsf_txt += fsf_footer.substitute() f = open(os.path.join(os.getcwd(), 'register.fsf'), 'wt') f.write(fsf_txt) @@ -845,78 +911,105 @@ def _list_outputs(self): class FLAMEOInputSpec(FSLCommandInputSpec): - cope_file = File(exists=True, argstr='--copefile=%s', mandatory=True, - desc='cope regressor data file') - var_cope_file = File(exists=True, argstr='--varcopefile=%s', - desc='varcope weightings data file') - dof_var_cope_file = File(exists=True, argstr='--dofvarcopefile=%s', - desc='dof data file for varcope data') - mask_file = File(exists=True, argstr='--maskfile=%s', mandatory=True, - desc='mask file') - design_file = File(exists=True, argstr='--designfile=%s', mandatory=True, - desc='design matrix file') + cope_file = File( + exists=True, + argstr='--copefile=%s', + mandatory=True, + desc='cope regressor data file') + var_cope_file = File( + exists=True, + argstr='--varcopefile=%s', + desc='varcope weightings data file') + dof_var_cope_file = File( + exists=True, + argstr='--dofvarcopefile=%s', + desc='dof data file for varcope data') + mask_file = File( + exists=True, argstr='--maskfile=%s', mandatory=True, desc='mask file') + design_file = File( + exists=True, + argstr='--designfile=%s', + mandatory=True, + desc='design matrix file') t_con_file = File( - exists=True, argstr='--tcontrastsfile=%s', mandatory=True, + exists=True, + argstr='--tcontrastsfile=%s', + mandatory=True, desc='ascii matrix specifying t-contrasts') - f_con_file = File(exists=True, argstr='--fcontrastsfile=%s', - desc='ascii matrix specifying f-contrasts') + f_con_file = File( + exists=True, + argstr='--fcontrastsfile=%s', + desc='ascii matrix specifying f-contrasts') cov_split_file = File( - exists=True, argstr='--covsplitfile=%s', mandatory=True, + exists=True, + argstr='--covsplitfile=%s', + mandatory=True, desc='ascii matrix specifying the groups the covariance is split into') run_mode = traits.Enum( - 'fe', 'ols', 'flame1', 'flame12', argstr='--runmode=%s', - mandatory=True, desc='inference to perform') + 'fe', + 'ols', + 'flame1', + 'flame12', + argstr='--runmode=%s', + mandatory=True, + desc='inference to perform') n_jumps = traits.Int( argstr='--njumps=%d', desc='number of jumps made by mcmc') - burnin = traits.Int(argstr='--burnin=%d', - desc=('number of jumps at start of mcmc to be ' - 'discarded')) - sample_every = traits.Int(argstr='--sampleevery=%d', - desc='number of jumps for each sample') + burnin = traits.Int( + argstr='--burnin=%d', + desc=('number of jumps at start of mcmc to be ' + 'discarded')) + sample_every = traits.Int( + argstr='--sampleevery=%d', desc='number of jumps for each sample') fix_mean = traits.Bool(argstr='--fixmean', desc='fix mean for tfit') - infer_outliers = traits.Bool(argstr='--inferoutliers', - desc='infer outliers - not for fe') - no_pe_outputs = traits.Bool(argstr='--nopeoutput', - desc='do not output pe files') - sigma_dofs = traits.Int(argstr='--sigma_dofs=%d', - desc=('sigma (in mm) to use for Gaussian ' - 'smoothing the DOFs in FLAME 2. Default is ' - '1mm, -1 indicates no smoothing')) - outlier_iter = traits.Int(argstr='--ioni=%d', - desc=('Number of max iterations to use when ' - 'inferring outliers. Default is 12.')) + infer_outliers = traits.Bool( + argstr='--inferoutliers', desc='infer outliers - not for fe') + no_pe_outputs = traits.Bool( + argstr='--nopeoutput', desc='do not output pe files') + sigma_dofs = traits.Int( + argstr='--sigma_dofs=%d', + desc=('sigma (in mm) to use for Gaussian ' + 'smoothing the DOFs in FLAME 2. Default is ' + '1mm, -1 indicates no smoothing')) + outlier_iter = traits.Int( + argstr='--ioni=%d', + desc=('Number of max iterations to use when ' + 'inferring outliers. Default is 12.')) log_dir = Directory("stats", argstr='--ld=%s', usedefault=True) # ohinds # no support for ven, vef class FLAMEOOutputSpec(TraitedSpec): - pes = OutputMultiPath(File(exists=True), - desc=("Parameter estimates for each column of the " - "design matrix for each voxel")) - res4d = OutputMultiPath(File(exists=True), - desc=("Model fit residual mean-squared error for " - "each time point")) - copes = OutputMultiPath(File(exists=True), - desc="Contrast estimates for each contrast") - var_copes = OutputMultiPath(File(exists=True), - desc="Variance estimates for each contrast") - zstats = OutputMultiPath(File(exists=True), - desc="z-stat file for each contrast") - tstats = OutputMultiPath(File(exists=True), - desc="t-stat file for each contrast") - zfstats = OutputMultiPath(File(exists=True), - desc="z stat file for each f contrast") - fstats = OutputMultiPath(File(exists=True), - desc="f-stat file for each contrast") - mrefvars = OutputMultiPath(File(exists=True), - desc=("mean random effect variances for each " - "contrast")) - tdof = OutputMultiPath(File(exists=True), - desc="temporal dof file for each contrast") - weights = OutputMultiPath(File(exists=True), - desc="weights file for each contrast") - stats_dir = Directory(File(exists=True), - desc="directory storing model estimation output") + pes = OutputMultiPath( + File(exists=True), + desc=("Parameter estimates for each column of the " + "design matrix for each voxel")) + res4d = OutputMultiPath( + File(exists=True), + desc=("Model fit residual mean-squared error for " + "each time point")) + copes = OutputMultiPath( + File(exists=True), desc="Contrast estimates for each contrast") + var_copes = OutputMultiPath( + File(exists=True), desc="Variance estimates for each contrast") + zstats = OutputMultiPath( + File(exists=True), desc="z-stat file for each contrast") + tstats = OutputMultiPath( + File(exists=True), desc="t-stat file for each contrast") + zfstats = OutputMultiPath( + File(exists=True), desc="z stat file for each f contrast") + fstats = OutputMultiPath( + File(exists=True), desc="f-stat file for each contrast") + mrefvars = OutputMultiPath( + File(exists=True), + desc=("mean random effect variances for each " + "contrast")) + tdof = OutputMultiPath( + File(exists=True), desc="temporal dof file for each contrast") + weights = OutputMultiPath( + File(exists=True), desc="weights file for each contrast") + stats_dir = Directory( + File(exists=True), desc="directory storing model estimation output") class FLAMEO(FSLCommand): @@ -945,27 +1038,32 @@ class FLAMEO(FSLCommand): input_spec = FLAMEOInputSpec output_spec = FLAMEOOutputSpec - references_ = [{'entry': BibTeX('@article{BeckmannJenkinsonSmith2003,' - 'author={C.F. Beckmann, M. Jenkinson, and S.M. Smith},' - 'title={General multilevel linear modeling for group analysis in FMRI.},' - 'journal={NeuroImage},' - 'volume={20},' - 'pages={1052-1063},' - 'year={2003},' - '}'), - 'tags': ['method'], - }, - {'entry': BibTeX('@article{WoolrichBehrensBeckmannJenkinsonSmith2004,' - 'author={M.W. Woolrich, T.E. Behrens, ' - 'C.F. Beckmann, M. Jenkinson, and S.M. Smith},' - 'title={Multilevel linear modelling for FMRI group analysis using Bayesian inference.},' - 'journal={NeuroImage},' - 'volume={21},' - 'pages={1732-1747},' - 'year={2004},' - '}'), - 'tags': ['method'], - }] + references_ = [{ + 'entry': + BibTeX( + '@article{BeckmannJenkinsonSmith2003,' + 'author={C.F. Beckmann, M. Jenkinson, and S.M. Smith},' + 'title={General multilevel linear modeling for group analysis in FMRI.},' + 'journal={NeuroImage},' + 'volume={20},' + 'pages={1052-1063},' + 'year={2003},' + '}'), + 'tags': ['method'], + }, { + 'entry': + BibTeX( + '@article{WoolrichBehrensBeckmannJenkinsonSmith2004,' + 'author={M.W. Woolrich, T.E. Behrens, ' + 'C.F. Beckmann, M. Jenkinson, and S.M. Smith},' + 'title={Multilevel linear modelling for FMRI group analysis using Bayesian inference.},' + 'journal={NeuroImage},' + 'volume={21},' + 'pages={1732-1747},' + 'year={2004},' + '}'), + 'tags': ['method'], + }] # ohinds: 2010-04-06 def _run_interface(self, runtime): @@ -1042,49 +1140,69 @@ def _list_outputs(self): class ContrastMgrInputSpec(FSLCommandInputSpec): - tcon_file = File(exists=True, mandatory=True, - argstr='%s', position=-1, - desc='contrast file containing T-contrasts') - fcon_file = File(exists=True, argstr='-f %s', - desc='contrast file containing F-contrasts') - param_estimates = InputMultiPath(File(exists=True), - argstr='', copyfile=False, - mandatory=True, - desc=('Parameter estimates for each ' - 'column of the design matrix')) + tcon_file = File( + exists=True, + mandatory=True, + argstr='%s', + position=-1, + desc='contrast file containing T-contrasts') + fcon_file = File( + exists=True, + argstr='-f %s', + desc='contrast file containing F-contrasts') + param_estimates = InputMultiPath( + File(exists=True), + argstr='', + copyfile=False, + mandatory=True, + desc=('Parameter estimates for each ' + 'column of the design matrix')) corrections = File( - exists=True, copyfile=False, mandatory=True, + exists=True, + copyfile=False, + mandatory=True, desc='statistical corrections used within FILM modelling') - dof_file = File(exists=True, argstr='', copyfile=False, mandatory=True, - desc='degrees of freedom') - sigmasquareds = File(exists=True, argstr='', position=-2, - copyfile=False, mandatory=True, - desc=('summary of residuals, See Woolrich, et. al., ' - '2001')) - contrast_num = traits.Range(low=1, argstr='-cope', - desc=('contrast number to start labeling ' - 'copes from')) - suffix = traits.Str(argstr='-suffix %s', - desc=('suffix to put on the end of the cope filename ' - 'before the contrast number, default is ' - 'nothing')) + dof_file = File( + exists=True, + argstr='', + copyfile=False, + mandatory=True, + desc='degrees of freedom') + sigmasquareds = File( + exists=True, + argstr='', + position=-2, + copyfile=False, + mandatory=True, + desc=('summary of residuals, See Woolrich, et. al., ' + '2001')) + contrast_num = traits.Range( + low=1, + argstr='-cope', + desc=('contrast number to start labeling ' + 'copes from')) + suffix = traits.Str( + argstr='-suffix %s', + desc=('suffix to put on the end of the cope filename ' + 'before the contrast number, default is ' + 'nothing')) class ContrastMgrOutputSpec(TraitedSpec): - copes = OutputMultiPath(File(exists=True), - desc='Contrast estimates for each contrast') - varcopes = OutputMultiPath(File(exists=True), - desc='Variance estimates for each contrast') - zstats = OutputMultiPath(File(exists=True), - desc='z-stat file for each contrast') - tstats = OutputMultiPath(File(exists=True), - desc='t-stat file for each contrast') - fstats = OutputMultiPath(File(exists=True), - desc='f-stat file for each contrast') - zfstats = OutputMultiPath(File(exists=True), - desc='z-stat file for each F contrast') - neffs = OutputMultiPath(File(exists=True), - desc='neff file ?? for each contrast') + copes = OutputMultiPath( + File(exists=True), desc='Contrast estimates for each contrast') + varcopes = OutputMultiPath( + File(exists=True), desc='Variance estimates for each contrast') + zstats = OutputMultiPath( + File(exists=True), desc='z-stat file for each contrast') + tstats = OutputMultiPath( + File(exists=True), desc='t-stat file for each contrast') + fstats = OutputMultiPath( + File(exists=True), desc='f-stat file for each contrast') + zfstats = OutputMultiPath( + File(exists=True), desc='z-stat file for each F contrast') + neffs = OutputMultiPath( + File(exists=True), desc='neff file ?? for each contrast') class ContrastMgr(FSLCommand): @@ -1094,13 +1212,13 @@ class ContrastMgr(FSLCommand): same location. This has deprecated for FSL versions 5.0.7+ as the necessary corrections file is no longer generated by FILMGLS. """ - if Info.version() and LooseVersion(Info.version()) >= LooseVersion("5.0.7"): + if Info.version() and LooseVersion( + Info.version()) >= LooseVersion("5.0.7"): DeprecationWarning("ContrastMgr is deprecated in FSL 5.0.7+") _cmd = 'contrast_mgr' input_spec = ContrastMgrInputSpec output_spec = ContrastMgrOutputSpec - def _run_interface(self, runtime): # The returncode is meaningless in ContrastMgr. So check the output # in stderr and if it's set, then update the returncode @@ -1156,17 +1274,17 @@ def _list_outputs(self): tstats = [] neffs = [] for i in range(numtcons): - copes.append(self._gen_fname('cope%d.nii' % (base_contrast + i), - cwd=pth)) + copes.append( + self._gen_fname('cope%d.nii' % (base_contrast + i), cwd=pth)) varcopes.append( - self._gen_fname('varcope%d.nii' % (base_contrast + i), - cwd=pth)) - zstats.append(self._gen_fname('zstat%d.nii' % (base_contrast + i), - cwd=pth)) - tstats.append(self._gen_fname('tstat%d.nii' % (base_contrast + i), - cwd=pth)) - neffs.append(self._gen_fname('neff%d.nii' % (base_contrast + i), - cwd=pth)) + self._gen_fname( + 'varcope%d.nii' % (base_contrast + i), cwd=pth)) + zstats.append( + self._gen_fname('zstat%d.nii' % (base_contrast + i), cwd=pth)) + tstats.append( + self._gen_fname('tstat%d.nii' % (base_contrast + i), cwd=pth)) + neffs.append( + self._gen_fname('neff%d.nii' % (base_contrast + i), cwd=pth)) if copes: outputs['copes'] = copes outputs['varcopes'] = varcopes @@ -1176,11 +1294,10 @@ def _list_outputs(self): fstats = [] zfstats = [] for i in range(numfcons): - fstats.append(self._gen_fname('fstat%d.nii' % (base_contrast + i), - cwd=pth)) + fstats.append( + self._gen_fname('fstat%d.nii' % (base_contrast + i), cwd=pth)) zfstats.append( - self._gen_fname('zfstat%d.nii' % (base_contrast + i), - cwd=pth)) + self._gen_fname('zfstat%d.nii' % (base_contrast + i), cwd=pth)) if fstats: outputs['fstats'] = fstats outputs['zfstats'] = zfstats @@ -1188,8 +1305,8 @@ def _list_outputs(self): class L2ModelInputSpec(BaseInterfaceInputSpec): - num_copes = traits.Range(low=1, mandatory=True, - desc='number of copes to be combined') + num_copes = traits.Range( + low=1, mandatory=True, desc='number of copes to be combined') class L2ModelOutputSpec(TraitedSpec): @@ -1214,37 +1331,40 @@ class L2Model(BaseInterface): def _run_interface(self, runtime): cwd = os.getcwd() - mat_txt = ['/NumWaves 1', - '/NumPoints {:d}'.format(self.inputs.num_copes), - '/PPheights 1', - '', - '/Matrix'] + mat_txt = [ + '/NumWaves 1', '/NumPoints {:d}'.format(self.inputs.num_copes), + '/PPheights 1', '', '/Matrix' + ] for i in range(self.inputs.num_copes): mat_txt += ['1'] mat_txt = '\n'.join(mat_txt) - con_txt = ['/ContrastName1 group mean', - '/NumWaves 1', - '/NumContrasts 1', - '/PPheights 1', - '/RequiredEffect 100', # XX where does this - # number come from - '', - '/Matrix', - '1'] + con_txt = [ + '/ContrastName1 group mean', + '/NumWaves 1', + '/NumContrasts 1', + '/PPheights 1', + '/RequiredEffect 100', # XX where does this + # number come from + '', + '/Matrix', + '1' + ] con_txt = '\n'.join(con_txt) - grp_txt = ['/NumWaves 1', - '/NumPoints {:d}'.format(self.inputs.num_copes), - '', - '/Matrix'] + grp_txt = [ + '/NumWaves 1', '/NumPoints {:d}'.format(self.inputs.num_copes), + '', '/Matrix' + ] for i in range(self.inputs.num_copes): grp_txt += ['1'] grp_txt = '\n'.join(grp_txt) - txt = {'design.mat': mat_txt, - 'design.con': con_txt, - 'design.grp': grp_txt} + txt = { + 'design.mat': mat_txt, + 'design.con': con_txt, + 'design.grp': grp_txt + } # write design files for i, name in enumerate(['design.mat', 'design.con', 'design.grp']): @@ -1257,39 +1377,36 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self._outputs().get() for field in list(outputs.keys()): - outputs[field] = os.path.join(os.getcwd(), - field.replace('_', '.')) + outputs[field] = os.path.join(os.getcwd(), field.replace('_', '.')) return outputs class MultipleRegressDesignInputSpec(BaseInterfaceInputSpec): contrasts = traits.List( - traits.Either(traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('F'), - traits.List(traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List( - traits.Str), - traits.List( - traits.Float)), - ))), + traits.Either( + traits.Tuple(traits.Str, traits.Enum('T'), traits.List(traits.Str), + traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('F'), + traits.List( + traits.Tuple(traits.Str, traits.Enum('T'), + traits.List(traits.Str), + traits.List(traits.Float)), ))), mandatory=True, desc="List of contrasts with each contrast being a list of the form - \ [('name', 'stat', [condition list], [weight list])]. if \ session list is None or not provided, all sessions are used. For F \ contrasts, the condition list should contain previously defined \ T-contrasts without any weight list.") - regressors = traits.Dict(traits.Str, traits.List(traits.Float), - mandatory=True, - desc=('dictionary containing named lists of ' - 'regressors')) - groups = traits.List(traits.Int, - desc=('list of group identifiers (defaults to single ' - 'group)')) + regressors = traits.Dict( + traits.Str, + traits.List(traits.Float), + mandatory=True, + desc=('dictionary containing named lists of ' + 'regressors')) + groups = traits.List( + traits.Int, + desc=('list of group identifiers (defaults to single ' + 'group)')) class MultipleRegressDesignOutputSpec(TraitedSpec): @@ -1331,8 +1448,10 @@ def _run_interface(self, runtime): ntcons = sum([1 for con in self.inputs.contrasts if con[1] == 'T']) nfcons = sum([1 for con in self.inputs.contrasts if con[1] == 'F']) # write mat file - mat_txt = ['/NumWaves %d' % nwaves, - '/NumPoints %d' % npoints] + mat_txt = [ + '/NumWaves %d' % nwaves, + '/NumPoints %d' % npoints + ] ppheights = [] for reg in regs: maxreg = np.max(self.inputs.regressors[reg]) @@ -1343,8 +1462,7 @@ def _run_interface(self, runtime): regheight = abs(maxreg - minreg) ppheights.append('%e' % regheight) mat_txt += ['/PPheights ' + ' '.join(ppheights)] - mat_txt += ['', - '/Matrix'] + mat_txt += ['', '/Matrix'] for cidx in range(npoints): mat_txt.append(' '.join( ['%e' % self.inputs.regressors[key][cidx] for key in regs])) @@ -1358,28 +1476,28 @@ def _run_interface(self, runtime): tconmap[conidx] = counter counter += 1 con_txt += ['/ContrastName%d %s' % (counter, con[0])] - con_txt += ['/NumWaves %d' % nwaves, - '/NumContrasts %d' % ntcons, - '/PPheights %s' % ' '.join( - ['%e' % 1 for i in range(counter)]), - '/RequiredEffect %s' % ' '.join( - ['%.3f' % 100 for i in range(counter)]), - '', - '/Matrix'] + con_txt += [ + '/NumWaves %d' % nwaves, + '/NumContrasts %d' % ntcons, + '/PPheights %s' % ' '.join( + ['%e' % 1 for i in range(counter)]), + '/RequiredEffect %s' % ' '.join( + ['%.3f' % 100 for i in range(counter)]), '', '/Matrix' + ] for idx in sorted(tconmap.keys()): convals = np.zeros((nwaves, 1)) for regidx, reg in enumerate(self.inputs.contrasts[idx][2]): - convals[regs.index(reg) - ] = self.inputs.contrasts[idx][3][regidx] + convals[regs.index(reg)] = self.inputs.contrasts[idx][3][ + regidx] con_txt.append(' '.join(['%e' % val for val in convals])) con_txt = '\n'.join(con_txt) + '\n' # write f-con file fcon_txt = '' if nfcons: - fcon_txt = ['/NumWaves %d' % ntcons, - '/NumContrasts %d' % nfcons, - '', - '/Matrix'] + fcon_txt = [ + '/NumWaves %d' % ntcons, + '/NumContrasts %d' % nfcons, '', '/Matrix' + ] for conidx, con in enumerate(self.inputs.contrasts): if con[1] == 'F': convals = np.zeros((ntcons, 1)) @@ -1389,10 +1507,10 @@ def _run_interface(self, runtime): fcon_txt = '\n'.join(fcon_txt) fcon_txt += '\n' # write group file - grp_txt = ['/NumWaves 1', - '/NumPoints %d' % npoints, - '', - '/Matrix'] + grp_txt = [ + '/NumWaves 1', + '/NumPoints %d' % npoints, '', '/Matrix' + ] for i in range(npoints): if isdefined(self.inputs.groups): grp_txt += ['%d' % self.inputs.groups[i]] @@ -1400,10 +1518,12 @@ def _run_interface(self, runtime): grp_txt += ['1'] grp_txt = '\n'.join(grp_txt) + '\n' - txt = {'design.mat': mat_txt, - 'design.con': con_txt, - 'design.fts': fcon_txt, - 'design.grp': grp_txt} + txt = { + 'design.mat': mat_txt, + 'design.con': con_txt, + 'design.fts': fcon_txt, + 'design.grp': grp_txt + } # write design files for key, val in list(txt.items()): @@ -1422,19 +1542,29 @@ def _list_outputs(self): for field in list(outputs.keys()): if ('fts' in field) and (nfcons == 0): continue - outputs[field] = os.path.join(os.getcwd(), - field.replace('_', '.')) + outputs[field] = os.path.join(os.getcwd(), field.replace('_', '.')) return outputs class SMMInputSpec(FSLCommandInputSpec): spatial_data_file = File( - exists=True, position=0, argstr='--sdf="%s"', mandatory=True, - desc="statistics spatial map", copyfile=False) - mask = File(exists=True, position=1, argstr='--mask="%s"', mandatory=True, - desc="mask file", copyfile=False) - no_deactivation_class = traits.Bool(position=2, argstr="--zfstatmode", - desc="enforces no deactivation class") + exists=True, + position=0, + argstr='--sdf="%s"', + mandatory=True, + desc="statistics spatial map", + copyfile=False) + mask = File( + exists=True, + position=1, + argstr='--mask="%s"', + mandatory=True, + desc="mask file", + copyfile=False) + no_deactivation_class = traits.Bool( + position=2, + argstr="--zfstatmode", + desc="enforces no deactivation class") class SMMOutputSpec(TraitedSpec): @@ -1457,12 +1587,12 @@ class SMM(FSLCommand): def _list_outputs(self): outputs = self._outputs().get() # TODO get the true logdir from the stdout - outputs['null_p_map'] = self._gen_fname(basename="w1_mean", - cwd="logdir") + outputs['null_p_map'] = self._gen_fname( + basename="w1_mean", cwd="logdir") outputs['activation_p_map'] = self._gen_fname( basename="w2_mean", cwd="logdir") - if (not isdefined(self.inputs.no_deactivation_class) or not - self.inputs.no_deactivation_class): + if (not isdefined(self.inputs.no_deactivation_class) + or not self.inputs.no_deactivation_class): outputs['deactivation_p_map'] = self._gen_fname( basename="w3_mean", cwd="logdir") return outputs @@ -1470,13 +1600,16 @@ def _list_outputs(self): class MELODICInputSpec(FSLCommandInputSpec): in_files = InputMultiPath( - File(exists=True), argstr="-i %s", mandatory=True, position=0, + File(exists=True), + argstr="-i %s", + mandatory=True, + position=0, desc="input file names (either single file name or a list)", sep=",") out_dir = Directory( argstr="-o %s", desc="output directory name", genfile=True) - mask = File(exists=True, argstr="-m %s", - desc="file name of mask for thresholding") + mask = File( + exists=True, argstr="-m %s", desc="file name of mask for thresholding") no_mask = traits.Bool(argstr="--nomask", desc="switch off masking") update_mask = traits.Bool( argstr="--update_mask", desc="switch off mask updating") @@ -1489,30 +1622,32 @@ class MELODICInputSpec(FSLCommandInputSpec): argstr="-d %d", desc=("dimensionality reduction into #num dimensions (default: " "automatic estimation)")) - dim_est = traits.Str(argstr="--dimest=%s", - desc=("use specific dim. estimation technique: lap, " - "bic, mdl, aic, mean (default: lap)")) + dim_est = traits.Str( + argstr="--dimest=%s", + desc=("use specific dim. estimation technique: lap, " + "bic, mdl, aic, mean (default: lap)")) sep_whiten = traits.Bool( argstr="--sep_whiten", desc="switch on separate whitening") sep_vn = traits.Bool( argstr="--sep_vn", desc="switch off joined variance normalization") - migp = traits.Bool( - argstr="--migp", desc="switch on MIGP data reduction") + migp = traits.Bool(argstr="--migp", desc="switch on MIGP data reduction") migpN = traits.Int( - argstr="--migpN %d", - desc="number of internal Eigenmaps") + argstr="--migpN %d", desc="number of internal Eigenmaps") migp_shuffle = traits.Bool( - argstr="--migp_shuffle", desc="randomise MIGP file order (default: TRUE)") + argstr="--migp_shuffle", + desc="randomise MIGP file order (default: TRUE)") migp_factor = traits.Int( argstr="--migp_factor %d", - desc="Internal Factor of mem-threshold relative to number of Eigenmaps (default: 2)") + desc= + "Internal Factor of mem-threshold relative to number of Eigenmaps (default: 2)" + ) num_ICs = traits.Int( argstr="-n %d", desc="number of IC's to extract (for deflation approach)") approach = traits.Str( argstr="-a %s", desc="approach for decomposition, 2D: defl, symm (default), 3D: tica " - "(default), concat") + "(default), concat") non_linearity = traits.Str( argstr="--nl=%s", desc="nonlinearity: gauss, tanh, pow3, pow4") var_norm = traits.Bool( @@ -1528,8 +1663,9 @@ class MELODICInputSpec(FSLCommandInputSpec): epsilonS = traits.Float( argstr="--epsS=%f", desc="minimum error change for rank-1 approximation in TICA") - maxit = traits.Int(argstr="--maxit=%d", - desc="maximum number of iterations before restart") + maxit = traits.Int( + argstr="--maxit=%d", + desc="maximum number of iterations before restart") max_restart = traits.Int( argstr="--maxrestart=%d", desc="maximum number of restarts") mm_thresh = traits.Float( @@ -1537,30 +1673,45 @@ class MELODICInputSpec(FSLCommandInputSpec): desc="threshold for Mixture Model based inference") no_mm = traits.Bool( argstr="--no_mm", desc="switch off mixture modelling on IC maps") - ICs = File(exists=True, argstr="--ICs=%s", - desc="filename of the IC components file for mixture modelling") - mix = File(exists=True, argstr="--mix=%s", - desc="mixing matrix for mixture modelling / filtering") - smode = File(exists=True, argstr="--smode=%s", - desc="matrix of session modes for report generation") + ICs = File( + exists=True, + argstr="--ICs=%s", + desc="filename of the IC components file for mixture modelling") + mix = File( + exists=True, + argstr="--mix=%s", + desc="mixing matrix for mixture modelling / filtering") + smode = File( + exists=True, + argstr="--smode=%s", + desc="matrix of session modes for report generation") rem_cmp = traits.List( traits.Int, argstr="-f %d", desc="component numbers to remove") report = traits.Bool(argstr="--report", desc="generate Melodic web report") bg_image = File( - exists=True, argstr="--bgimage=%s", + exists=True, + argstr="--bgimage=%s", desc="specify background image for report (default: mean image)") tr_sec = traits.Float(argstr="--tr=%f", desc="TR in seconds") log_power = traits.Bool( argstr="--logPower", desc="calculate log of power for frequency spectrum") - t_des = File(exists=True, argstr="--Tdes=%s", - desc="design matrix across time-domain") - t_con = File(exists=True, argstr="--Tcon=%s", - desc="t-contrast matrix across time-domain") - s_des = File(exists=True, argstr="--Sdes=%s", - desc="design matrix across subject-domain") - s_con = File(exists=True, argstr="--Scon=%s", - desc="t-contrast matrix across subject-domain") + t_des = File( + exists=True, + argstr="--Tdes=%s", + desc="design matrix across time-domain") + t_con = File( + exists=True, + argstr="--Tcon=%s", + desc="t-contrast matrix across time-domain") + s_des = File( + exists=True, + argstr="--Sdes=%s", + desc="design matrix across subject-domain") + s_con = File( + exists=True, + argstr="--Scon=%s", + desc="t-contrast matrix across subject-domain") out_all = traits.Bool(argstr="--Oall", desc="output everything") out_unmix = traits.Bool(argstr="--Ounmix", desc="output unmixing matrix") out_stats = traits.Bool( @@ -1620,8 +1771,7 @@ def _list_outputs(self): else: outputs['out_dir'] = self._gen_filename("out_dir") if isdefined(self.inputs.report) and self.inputs.report: - outputs['report_dir'] = os.path.join( - outputs['out_dir'], "report") + outputs['report_dir'] = os.path.join(outputs['out_dir'], "report") return outputs def _gen_filename(self, name): @@ -1630,18 +1780,23 @@ def _gen_filename(self, name): class SmoothEstimateInputSpec(FSLCommandInputSpec): - dof = traits.Int(argstr='--dof=%d', mandatory=True, - xor=['zstat_file'], - desc='number of degrees of freedom') - mask_file = File(argstr='--mask=%s', - exists=True, mandatory=True, - desc='brain mask volume') - residual_fit_file = File(argstr='--res=%s', - exists=True, requires=['dof'], - desc='residual-fit image file') - zstat_file = File(argstr='--zstat=%s', - exists=True, xor=['dof'], - desc='zstat image file') + dof = traits.Int( + argstr='--dof=%d', + mandatory=True, + xor=['zstat_file'], + desc='number of degrees of freedom') + mask_file = File( + argstr='--mask=%s', + exists=True, + mandatory=True, + desc='brain mask volume') + residual_fit_file = File( + argstr='--res=%s', + exists=True, + requires=['dof'], + desc='residual-fit image file') + zstat_file = File( + argstr='--zstat=%s', exists=True, xor=['dof'], desc='zstat image file') class SmoothEstimateOutputSpec(TraitedSpec): @@ -1678,79 +1833,110 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): class ClusterInputSpec(FSLCommandInputSpec): - in_file = File(argstr='--in=%s', mandatory=True, - exists=True, desc='input volume') - threshold = traits.Float(argstr='--thresh=%.10f', - mandatory=True, - desc='threshold for input volume') + in_file = File( + argstr='--in=%s', mandatory=True, exists=True, desc='input volume') + threshold = traits.Float( + argstr='--thresh=%.10f', + mandatory=True, + desc='threshold for input volume') out_index_file = traits.Either( - traits.Bool, File, + traits.Bool, + File, argstr='--oindex=%s', - desc='output of cluster index (in size order)', hash_files=False) - out_threshold_file = traits.Either(traits.Bool, File, - argstr='--othresh=%s', - desc='thresholded image', - hash_files=False) - out_localmax_txt_file = traits.Either(traits.Bool, File, - argstr='--olmax=%s', - desc='local maxima text file', - hash_files=False) - out_localmax_vol_file = traits.Either(traits.Bool, File, - argstr='--olmaxim=%s', - desc='output of local maxima volume', - hash_files=False) - out_size_file = traits.Either(traits.Bool, File, - argstr='--osize=%s', - desc='filename for output of size image', - hash_files=False) - out_max_file = traits.Either(traits.Bool, File, - argstr='--omax=%s', - desc='filename for output of max image', - hash_files=False) - out_mean_file = traits.Either(traits.Bool, File, - argstr='--omean=%s', - desc='filename for output of mean image', - hash_files=False) + desc='output of cluster index (in size order)', + hash_files=False) + out_threshold_file = traits.Either( + traits.Bool, + File, + argstr='--othresh=%s', + desc='thresholded image', + hash_files=False) + out_localmax_txt_file = traits.Either( + traits.Bool, + File, + argstr='--olmax=%s', + desc='local maxima text file', + hash_files=False) + out_localmax_vol_file = traits.Either( + traits.Bool, + File, + argstr='--olmaxim=%s', + desc='output of local maxima volume', + hash_files=False) + out_size_file = traits.Either( + traits.Bool, + File, + argstr='--osize=%s', + desc='filename for output of size image', + hash_files=False) + out_max_file = traits.Either( + traits.Bool, + File, + argstr='--omax=%s', + desc='filename for output of max image', + hash_files=False) + out_mean_file = traits.Either( + traits.Bool, + File, + argstr='--omean=%s', + desc='filename for output of mean image', + hash_files=False) out_pval_file = traits.Either( - traits.Bool, File, + traits.Bool, + File, argstr='--opvals=%s', desc='filename for image output of log pvals', hash_files=False) - pthreshold = traits.Float(argstr='--pthresh=%.10f', - requires=['dlh', 'volume'], - desc='p-threshold for clusters') + pthreshold = traits.Float( + argstr='--pthresh=%.10f', + requires=['dlh', 'volume'], + desc='p-threshold for clusters') peak_distance = traits.Float( argstr='--peakdist=%.10f', desc='minimum distance between local maxima/minima, in mm (default 0)') - cope_file = traits.File(argstr='--cope=%s', - desc='cope volume') - volume = traits.Int(argstr='--volume=%d', - desc='number of voxels in the mask') - dlh = traits.Float(argstr='--dlh=%.10f', - desc='smoothness estimate = sqrt(det(Lambda))') + cope_file = traits.File(argstr='--cope=%s', desc='cope volume') + volume = traits.Int( + argstr='--volume=%d', desc='number of voxels in the mask') + dlh = traits.Float( + argstr='--dlh=%.10f', desc='smoothness estimate = sqrt(det(Lambda))') fractional = traits.Bool( - False, usedefault=True, argstr='--fractional', + False, + usedefault=True, + argstr='--fractional', desc='interprets the threshold as a fraction of the robust range') - connectivity = traits.Int(argstr='--connectivity=%d', - desc='the connectivity of voxels (default 26)') - use_mm = traits.Bool(False, usedefault=True, argstr='--mm', - desc='use mm, not voxel, coordinates') - find_min = traits.Bool(False, usedefault=True, argstr='--min', - desc='find minima instead of maxima') - no_table = traits.Bool(False, usedefault=True, argstr='--no_table', - desc='suppresses printing of the table info') + connectivity = traits.Int( + argstr='--connectivity=%d', + desc='the connectivity of voxels (default 26)') + use_mm = traits.Bool( + False, + usedefault=True, + argstr='--mm', + desc='use mm, not voxel, coordinates') + find_min = traits.Bool( + False, + usedefault=True, + argstr='--min', + desc='find minima instead of maxima') + no_table = traits.Bool( + False, + usedefault=True, + argstr='--no_table', + desc='suppresses printing of the table info') minclustersize = traits.Bool( - False, usedefault=True, argstr='--minclustersize', + False, + usedefault=True, + argstr='--minclustersize', desc='prints out minimum significant cluster size') - xfm_file = File(argstr='--xfm=%s', - desc=('filename for Linear: input->standard-space ' - 'transform. Non-linear: input->highres transform')) - std_space_file = File(argstr='--stdvol=%s', - desc='filename for standard-space volume') - num_maxima = traits.Int(argstr='--num=%d', - desc='no of local maxima to report') - warpfield_file = File(argstr='--warpvol=%s', - desc='file contining warpfield') + xfm_file = File( + argstr='--xfm=%s', + desc=('filename for Linear: input->standard-space ' + 'transform. Non-linear: input->highres transform')) + std_space_file = File( + argstr='--stdvol=%s', desc='filename for standard-space volume') + num_maxima = traits.Int( + argstr='--num=%d', desc='no of local maxima to report') + warpfield_file = File( + argstr='--warpvol=%s', desc='file contining warpfield') class ClusterOutputSpec(TraitedSpec): @@ -1783,11 +1969,16 @@ class Cluster(FSLCommand): output_spec = ClusterOutputSpec _cmd = 'cluster' - filemap = {'out_index_file': 'index', 'out_threshold_file': 'threshold', - 'out_localmax_txt_file': 'localmax.txt', - 'out_localmax_vol_file': 'localmax', - 'out_size_file': 'size', 'out_max_file': 'max', - 'out_mean_file': 'mean', 'out_pval_file': 'pval'} + filemap = { + 'out_index_file': 'index', + 'out_threshold_file': 'threshold', + 'out_localmax_txt_file': 'localmax.txt', + 'out_localmax_vol_file': 'localmax', + 'out_size_file': 'size', + 'out_max_file': 'max', + 'out_mean_file': 'mean', + 'out_pval_file': 'pval' + } def _list_outputs(self): outputs = self.output_spec().get() @@ -1801,7 +1992,8 @@ def _list_outputs(self): if suffix.endswith('.txt'): change_ext = False outputs[outkey] = self._gen_fname( - self.inputs.in_file, suffix='_' + suffix, + self.inputs.in_file, + suffix='_' + suffix, change_ext=change_ext) else: outputs[outkey] = os.path.abspath(inval) @@ -1818,28 +2010,56 @@ def _format_arg(self, name, spec, value): class DualRegressionInputSpec(FSLCommandInputSpec): - in_files = InputMultiPath(File(exists=True), argstr="%s", mandatory=True, - position=-1, sep=" ", - desc="List all subjects' preprocessed, standard-space 4D datasets",) - group_IC_maps_4D = File(exists=True, argstr="%s", mandatory=True, position=1, + in_files = InputMultiPath( + File(exists=True), + argstr="%s", + mandatory=True, + position=-1, + sep=" ", + desc="List all subjects' preprocessed, standard-space 4D datasets", + ) + group_IC_maps_4D = File( + exists=True, + argstr="%s", + mandatory=True, + position=1, desc="4D image containing spatial IC maps (melodic_IC) from the " "whole-group ICA analysis") - des_norm = traits.Bool(True, argstr="%i", position=2, usedefault=True, + des_norm = traits.Bool( + True, + argstr="%i", + position=2, + usedefault=True, desc="Whether to variance-normalise the timecourses used as the " "stage-2 regressors; True is default and recommended") - one_sample_group_mean = traits.Bool(argstr="-1", position=3, + one_sample_group_mean = traits.Bool( + argstr="-1", + position=3, desc="perform 1-sample group-mean test instead of generic " "permutation test") - design_file = File(exists=True, argstr="%s", position=3, + design_file = File( + exists=True, + argstr="%s", + position=3, desc="Design matrix for final cross-subject modelling with " "randomise") - con_file = File(exists=True, argstr="%s", position=4, + con_file = File( + exists=True, + argstr="%s", + position=4, desc="Design contrasts for final cross-subject modelling with " "randomise") - n_perm = traits.Int(argstr="%i", mandatory=True, position=5, + n_perm = traits.Int( + argstr="%i", + mandatory=True, + position=5, desc="Number of permutations for randomise; set to 1 for just raw " "tstat output, set to 0 to not run randomise at all.") - out_dir = Directory("output", argstr="%s", usedefault=True, position=6, + out_dir = Directory( + "output", + argstr="%s", + usedefault=True, + position=6, desc="This directory will be created to hold all output and logfiles", genfile=True) @@ -1884,11 +2104,18 @@ def _gen_filename(self, name): class RandomiseInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, desc='4D input file', argstr='-i %s', - position=0, mandatory=True) + in_file = File( + exists=True, + desc='4D input file', + argstr='-i %s', + position=0, + mandatory=True) base_name = traits.Str( - 'randomise', desc='the rootname that all generated files will have', - argstr='-o "%s"', position=1, usedefault=True) + 'randomise', + desc='the rootname that all generated files will have', + argstr='-o "%s"', + position=1, + usedefault=True) design_mat = File( exists=True, desc='design matrix file', argstr='-d %s', position=2) tcon = File( @@ -1951,17 +2178,13 @@ class RandomiseInputSpec(FSLCommandInputSpec): class RandomiseOutputSpec(TraitedSpec): tstat_files = traits.List( - File(exists=True), - desc='t contrast raw statistic') + File(exists=True), desc='t contrast raw statistic') fstat_files = traits.List( - File(exists=True), - desc='f contrast raw statistic') + File(exists=True), desc='f contrast raw statistic') t_p_files = traits.List( - File(exists=True), - desc='f contrast uncorrected p values files') + File(exists=True), desc='f contrast uncorrected p values files') f_p_files = traits.List( - File(exists=True), - desc='f contrast uncorrected p values files') + File(exists=True), desc='f contrast uncorrected p values files') t_corrected_p_files = traits.List( File(exists=True), desc='t contrast FWE (Family-wise error) corrected p values files') @@ -1990,10 +2213,10 @@ class Randomise(FSLCommand): def _list_outputs(self): outputs = self.output_spec().get() - outputs['tstat_files'] = glob(self._gen_fname( - '%s_tstat*.nii' % self.inputs.base_name)) - outputs['fstat_files'] = glob(self._gen_fname( - '%s_fstat*.nii' % self.inputs.base_name)) + outputs['tstat_files'] = glob( + self._gen_fname('%s_tstat*.nii' % self.inputs.base_name)) + outputs['fstat_files'] = glob( + self._gen_fname('%s_fstat*.nii' % self.inputs.base_name)) prefix = False if self.inputs.tfce or self.inputs.tfce2D: prefix = 'tfce' @@ -2005,50 +2228,66 @@ def _list_outputs(self): prefix = 'clusterm' if prefix: outputs['t_p_files'] = glob( - self._gen_fname('%s_%s_p_tstat*' % ( - self.inputs.base_name, prefix))) - outputs['t_corrected_p_files'] = glob(self._gen_fname( - '%s_%s_corrp_tstat*.nii' % (self.inputs.base_name, prefix))) - - outputs['f_p_files'] = glob(self._gen_fname( - '%s_%s_p_fstat*.nii' % (self.inputs.base_name, prefix))) - outputs['f_corrected_p_files'] = glob(self._gen_fname( - '%s_%s_corrp_fstat*.nii' % (self.inputs.base_name, prefix))) + self._gen_fname('%s_%s_p_tstat*' % (self.inputs.base_name, + prefix))) + outputs['t_corrected_p_files'] = glob( + self._gen_fname('%s_%s_corrp_tstat*.nii' % + (self.inputs.base_name, prefix))) + + outputs['f_p_files'] = glob( + self._gen_fname('%s_%s_p_fstat*.nii' % (self.inputs.base_name, + prefix))) + outputs['f_corrected_p_files'] = glob( + self._gen_fname('%s_%s_corrp_fstat*.nii' % + (self.inputs.base_name, prefix))) return outputs class GLMInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr='-i %s', mandatory=True, position=1, - desc='input file name (text matrix or 3D/4D image file)') - out_file = File(name_template="%s_glm", argstr='-o %s', position=3, - desc=('filename for GLM parameter estimates' + - ' (GLM betas)'), - name_source="in_file", keep_extension=True) - design = File(exists=True, argstr='-d %s', mandatory=True, position=2, - desc=('file name of the GLM design matrix (text time' + - ' courses for temporal regression or an image' + - ' file for spatial regression)')) - contrasts = File(exists=True, argstr='-c %s', - desc=('matrix of t-statics contrasts')) - mask = File(exists=True, argstr='-m %s', - desc=('mask image file name if input is image')) - dof = traits.Int(argstr='--dof=%d', desc=('set degrees of freedom' + - ' explicitly')) - des_norm = traits.Bool(argstr='--des_norm', - desc=('switch on normalization of the design' + - ' matrix columns to unit std deviation')) + in_file = File( + exists=True, + argstr='-i %s', + mandatory=True, + position=1, + desc='input file name (text matrix or 3D/4D image file)') + out_file = File( + name_template="%s_glm", + argstr='-o %s', + position=3, + desc=('filename for GLM parameter estimates' + ' (GLM betas)'), + name_source="in_file", + keep_extension=True) + design = File( + exists=True, + argstr='-d %s', + mandatory=True, + position=2, + desc=('file name of the GLM design matrix (text time' + + ' courses for temporal regression or an image' + + ' file for spatial regression)')) + contrasts = File( + exists=True, argstr='-c %s', desc=('matrix of t-statics contrasts')) + mask = File( + exists=True, + argstr='-m %s', + desc=('mask image file name if input is image')) + dof = traits.Int( + argstr='--dof=%d', desc=('set degrees of freedom' + ' explicitly')) + des_norm = traits.Bool( + argstr='--des_norm', + desc=('switch on normalization of the design' + + ' matrix columns to unit std deviation')) dat_norm = traits.Bool( argstr='--dat_norm', desc=('switch on normalization of the data time series to unit std ' 'deviation')) var_norm = traits.Bool( - argstr='--vn', - desc=('perform MELODIC variance-normalisation on data')) + argstr='--vn', desc=('perform MELODIC variance-normalisation on data')) demean = traits.Bool( - argstr='--demean', - desc=('switch on demeaining of design and data')) - out_cope = File(argstr='--out_cope=%s', - desc='output file name for COPE (either as txt or image') + argstr='--demean', desc=('switch on demeaining of design and data')) + out_cope = File( + argstr='--out_cope=%s', + desc='output file name for COPE (either as txt or image') out_z_name = File( argstr='--out_z=%s', desc='output file name for Z-stats (either as txt or image') @@ -2059,19 +2298,21 @@ class GLMInputSpec(FSLCommandInputSpec): argstr='--out_p=%s', desc=('output file name for p-values of Z-stats (either as text file ' 'or image)')) - out_f_name = File(argstr='--out_f=%s', - desc='output file name for F-value of full model fit') - out_pf_name = File(argstr='--out_pf=%s', - desc='output file name for p-value for full model fit') - out_res_name = File(argstr='--out_res=%s', - desc='output file name for residuals') - out_varcb_name = File(argstr='--out_varcb=%s', - desc='output file name for variance of COPEs') + out_f_name = File( + argstr='--out_f=%s', + desc='output file name for F-value of full model fit') + out_pf_name = File( + argstr='--out_pf=%s', + desc='output file name for p-value for full model fit') + out_res_name = File( + argstr='--out_res=%s', desc='output file name for residuals') + out_varcb_name = File( + argstr='--out_varcb=%s', desc='output file name for variance of COPEs') out_sigsq_name = File( argstr='--out_sigsq=%s', desc=('output file name for residual noise variance sigma-square')) - out_data_name = File(argstr='--out_data=%s', - desc='output file name for pre-processed data') + out_data_name = File( + argstr='--out_data=%s', desc='output file name for pre-processed data') out_vnscales_name = File( argstr='--out_vnscales=%s', desc=('output file name for scaling factors for variance ' @@ -2080,8 +2321,7 @@ class GLMInputSpec(FSLCommandInputSpec): class GLMOutputSpec(TraitedSpec): out_file = File( - exists=True, - desc=('file name of GLM parameters (if generated)')) + exists=True, desc=('file name of GLM parameters (if generated)')) out_cope = OutputMultiPath( File(exists=True), desc=('output file name for COPEs (either as text file or image)')) @@ -2103,13 +2343,13 @@ class GLMOutputSpec(TraitedSpec): desc=('output file name for p-value for full model fit')) out_res = OutputMultiPath( File(exists=True), desc='output file name for residuals') - out_varcb = OutputMultiPath(File(exists=True), - desc='output file name for variance of COPEs') + out_varcb = OutputMultiPath( + File(exists=True), desc='output file name for variance of COPEs') out_sigsq = OutputMultiPath( File(exists=True), desc=('output file name for residual noise variance sigma-square')) - out_data = OutputMultiPath(File(exists=True), - desc='output file for preprocessed data') + out_data = OutputMultiPath( + File(exists=True), desc='output file for preprocessed data') out_vnscales = OutputMultiPath( File(exists=True), desc=('output file name for scaling factors for variance ' @@ -2186,8 +2426,9 @@ def load_template(name): """ from pkg_resources import resource_filename as pkgrf - full_fname = pkgrf( - 'nipype', os.path.join('interfaces', 'fsl', 'model_templates', name)) + full_fname = pkgrf('nipype', + os.path.join('interfaces', 'fsl', 'model_templates', + name)) with open(full_fname) as template_file: template = Template(template_file.read()) diff --git a/nipype/interfaces/fsl/possum.py b/nipype/interfaces/fsl/possum.py index 1c2b10e1d2..0adec72b8c 100644 --- a/nipype/interfaces/fsl/possum.py +++ b/nipype/interfaces/fsl/possum.py @@ -23,41 +23,73 @@ class B0CalcInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, argstr='-i %s', position=0, - desc='filename of input image (usually a tissue/air segmentation)') - out_file = File(argstr='-o %s', position=1, name_source=['in_file'], - name_template='%s_b0field', output_name='out_file', - desc='filename of B0 output volume') - - x_grad = traits.Float(0.0, argstr='--gx=%0.4f', - desc='Value for zeroth-order x-gradient field (per mm)') - y_grad = traits.Float(0.0, argstr='--gy=%0.4f', - desc='Value for zeroth-order y-gradient field (per mm)') - z_grad = traits.Float(0.0, argstr='--gz=%0.4f', - desc='Value for zeroth-order z-gradient field (per mm)') - - x_b0 = traits.Float(0.0, argstr='--b0x=%0.2f', xor=['xyz_b0'], - desc='Value for zeroth-order b0 field (x-component), in Tesla') - y_b0 = traits.Float(0.0, argstr='--b0y=%0.2f', xor=['xyz_b0'], - desc='Value for zeroth-order b0 field (y-component), in Tesla') - z_b0 = traits.Float(1.0, argstr='--b0=%0.2f', xor=['xyz_b0'], - desc='Value for zeroth-order b0 field (z-component), in Tesla') + in_file = File( + exists=True, + mandatory=True, + argstr='-i %s', + position=0, + desc='filename of input image (usually a tissue/air segmentation)') + out_file = File( + argstr='-o %s', + position=1, + name_source=['in_file'], + name_template='%s_b0field', + output_name='out_file', + desc='filename of B0 output volume') + + x_grad = traits.Float( + 0.0, + argstr='--gx=%0.4f', + desc='Value for zeroth-order x-gradient field (per mm)') + y_grad = traits.Float( + 0.0, + argstr='--gy=%0.4f', + desc='Value for zeroth-order y-gradient field (per mm)') + z_grad = traits.Float( + 0.0, + argstr='--gz=%0.4f', + desc='Value for zeroth-order z-gradient field (per mm)') + + x_b0 = traits.Float( + 0.0, + argstr='--b0x=%0.2f', + xor=['xyz_b0'], + desc='Value for zeroth-order b0 field (x-component), in Tesla') + y_b0 = traits.Float( + 0.0, + argstr='--b0y=%0.2f', + xor=['xyz_b0'], + desc='Value for zeroth-order b0 field (y-component), in Tesla') + z_b0 = traits.Float( + 1.0, + argstr='--b0=%0.2f', + xor=['xyz_b0'], + desc='Value for zeroth-order b0 field (z-component), in Tesla') xyz_b0 = traits.Tuple( - traits.Float, traits.Float, traits.Float, - argstr='--b0x=%0.2f --b0y=%0.2f --b0=%0.2f', xor=['x_b0', 'y_b0', 'z_b0'], + traits.Float, + traits.Float, + traits.Float, + argstr='--b0x=%0.2f --b0y=%0.2f --b0=%0.2f', + xor=['x_b0', 'y_b0', 'z_b0'], desc='Zeroth-order B0 field in Tesla') - delta = traits.Float(-9.45e-6, argstr='-d %e', - desc='Delta value (chi_tissue - chi_air)') + delta = traits.Float( + -9.45e-6, argstr='-d %e', desc='Delta value (chi_tissue - chi_air)') chi_air = traits.Float( 4.0e-7, argstr='--chi0=%e', desc='susceptibility of air') - compute_xyz = traits.Bool(False, argstr='--xyz', - desc='calculate and save all 3 field components (i.e. x,y,z)') - extendboundary = traits.Float(1.0, argstr='--extendboundary=%0.2f', - desc='Relative proportion to extend voxels at boundary') - directconv = traits.Bool(False, argstr='--directconv', - desc='use direct (image space) convolution, not FFT') + compute_xyz = traits.Bool( + False, + argstr='--xyz', + desc='calculate and save all 3 field components (i.e. x,y,z)') + extendboundary = traits.Float( + 1.0, + argstr='--extendboundary=%0.2f', + desc='Relative proportion to extend voxels at boundary') + directconv = traits.Bool( + False, + argstr='--directconv', + desc='use direct (image space) convolution, not FFT') class B0CalcOutputSpec(TraitedSpec): @@ -65,7 +97,6 @@ class B0CalcOutputSpec(TraitedSpec): class B0Calc(FSLCommand): - """ B0 inhomogeneities occur at interfaces of materials with different magnetic susceptibilities, such as tissue-air interfaces. These differences lead to distortion in the local magnetic field, diff --git a/nipype/interfaces/fsl/preprocess.py b/nipype/interfaces/fsl/preprocess.py index 4ffeead842..8e7b7be477 100644 --- a/nipype/interfaces/fsl/preprocess.py +++ b/nipype/interfaces/fsl/preprocess.py @@ -11,7 +11,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, open import os @@ -22,43 +23,48 @@ from nibabel import load from ...utils.filemanip import split_filename -from ..base import (TraitedSpec, File, InputMultiPath, - OutputMultiPath, Undefined, traits, - isdefined) +from ..base import (TraitedSpec, File, InputMultiPath, OutputMultiPath, + Undefined, traits, isdefined) from .base import FSLCommand, FSLCommandInputSpec, Info class BETInputSpec(FSLCommandInputSpec): # We use position args here as list indices - so a negative number # will put something on the end - in_file = File(exists=True, - desc='input file to skull strip', - argstr='%s', position=0, mandatory=True) - out_file = File(desc='name of output skull stripped image', - argstr='%s', position=1, genfile=True, hash_files=False) - outline = traits.Bool(desc='create surface outline image', - argstr='-o') - mask = traits.Bool(desc='create binary mask image', - argstr='-m') - skull = traits.Bool(desc='create skull image', - argstr='-s') - no_output = traits.Bool(argstr='-n', - desc="Don't generate segmented output") - frac = traits.Float(desc='fractional intensity threshold', - argstr='-f %.2f') + in_file = File( + exists=True, + desc='input file to skull strip', + argstr='%s', + position=0, + mandatory=True) + out_file = File( + desc='name of output skull stripped image', + argstr='%s', + position=1, + genfile=True, + hash_files=False) + outline = traits.Bool(desc='create surface outline image', argstr='-o') + mask = traits.Bool(desc='create binary mask image', argstr='-m') + skull = traits.Bool(desc='create skull image', argstr='-s') + no_output = traits.Bool( + argstr='-n', desc="Don't generate segmented output") + frac = traits.Float( + desc='fractional intensity threshold', argstr='-f %.2f') vertical_gradient = traits.Float( argstr='-g %.2f', desc='vertical gradient in fractional intensity threshold (-1, 1)') - radius = traits.Int(argstr='-r %d', units='mm', - desc="head radius") - center = traits.List(traits.Int, desc='center of gravity in voxels', - argstr='-c %s', minlen=0, maxlen=3, - units='voxels') + radius = traits.Int(argstr='-r %d', units='mm', desc="head radius") + center = traits.List( + traits.Int, + desc='center of gravity in voxels', + argstr='-c %s', + minlen=0, + maxlen=3, + units='voxels') threshold = traits.Bool( argstr='-t', desc="apply thresholding to segmented brain image and mask") - mesh = traits.Bool(argstr='-e', - desc="generate a vtk mesh brain surface") + mesh = traits.Bool(argstr='-e', desc="generate a vtk mesh brain surface") # the remaining 'options' are more like modes (mutually exclusive) that # FSL actually implements in a shell script wrapper around the bet binary. # for some combinations of them in specific order a call would not fail, @@ -68,50 +74,48 @@ class BETInputSpec(FSLCommandInputSpec): 'remove_eyes', 'surfaces', 't2_guided') robust = traits.Bool( desc='robust brain centre estimation (iterates BET several times)', - argstr='-R', xor=_xor_inputs) + argstr='-R', + xor=_xor_inputs) padding = traits.Bool( desc=('improve BET if FOV is very small in Z (by temporarily padding ' 'end slices)'), - argstr='-Z', xor=_xor_inputs) + argstr='-Z', + xor=_xor_inputs) remove_eyes = traits.Bool( desc='eye & optic nerve cleanup (can be useful in SIENA)', - argstr='-S', xor=_xor_inputs) + argstr='-S', + xor=_xor_inputs) surfaces = traits.Bool( desc=('run bet2 and then betsurf to get additional skull and scalp ' 'surfaces (includes registrations)'), - argstr='-A', xor=_xor_inputs) - t2_guided = File(desc='as with creating surfaces, when also feeding in ' - 'non-brain-extracted T2 (includes registrations)', - argstr='-A2 %s', xor=_xor_inputs) - functional = traits.Bool(argstr='-F', xor=_xor_inputs, - desc="apply to 4D fMRI data") - reduce_bias = traits.Bool(argstr='-B', xor=_xor_inputs, - desc="bias field and neck cleanup") + argstr='-A', + xor=_xor_inputs) + t2_guided = File( + desc='as with creating surfaces, when also feeding in ' + 'non-brain-extracted T2 (includes registrations)', + argstr='-A2 %s', + xor=_xor_inputs) + functional = traits.Bool( + argstr='-F', xor=_xor_inputs, desc="apply to 4D fMRI data") + reduce_bias = traits.Bool( + argstr='-B', xor=_xor_inputs, desc="bias field and neck cleanup") class BETOutputSpec(TraitedSpec): - out_file = File( - desc="path/name of skullstripped file (if generated)") - mask_file = File( - desc="path/name of binary brain mask (if generated)") - outline_file = File( - desc="path/name of outline file (if generated)") - meshfile = File( - desc="path/name of vtk mesh file (if generated)") - inskull_mask_file = File( - desc="path/name of inskull mask (if generated)") + out_file = File(desc="path/name of skullstripped file (if generated)") + mask_file = File(desc="path/name of binary brain mask (if generated)") + outline_file = File(desc="path/name of outline file (if generated)") + meshfile = File(desc="path/name of vtk mesh file (if generated)") + inskull_mask_file = File(desc="path/name of inskull mask (if generated)") inskull_mesh_file = File( desc="path/name of inskull mesh outline (if generated)") - outskull_mask_file = File( - desc="path/name of outskull mask (if generated)") + outskull_mask_file = File(desc="path/name of outskull mask (if generated)") outskull_mesh_file = File( desc="path/name of outskull mesh outline (if generated)") - outskin_mask_file = File( - desc="path/name of outskin mask (if generated)") + outskin_mask_file = File(desc="path/name of outskin mask (if generated)") outskin_mesh_file = File( desc="path/name of outskin mesh outline (if generated)") - skull_mask_file = File( - desc="path/name of skull mask (if generated)") + skull_mask_file = File(desc="path/name of skull mask (if generated)") class BET(FSLCommand): @@ -149,23 +153,21 @@ def _run_interface(self, runtime): def _gen_outfilename(self): out_file = self.inputs.out_file if not isdefined(out_file) and isdefined(self.inputs.in_file): - out_file = self._gen_fname(self.inputs.in_file, - suffix='_brain') + out_file = self._gen_fname(self.inputs.in_file, suffix='_brain') return os.path.abspath(out_file) def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = self._gen_outfilename() - if ((isdefined(self.inputs.mesh) and self.inputs.mesh) or - (isdefined(self.inputs.surfaces) and self.inputs.surfaces)): - outputs['meshfile'] = self._gen_fname(outputs['out_file'], - suffix='_mesh.vtk', - change_ext=False) + if ((isdefined(self.inputs.mesh) and self.inputs.mesh) + or (isdefined(self.inputs.surfaces) and self.inputs.surfaces)): + outputs['meshfile'] = self._gen_fname( + outputs['out_file'], suffix='_mesh.vtk', change_ext=False) if (isdefined(self.inputs.mask) and self.inputs.mask) or \ (isdefined(self.inputs.reduce_bias) and self.inputs.reduce_bias): - outputs['mask_file'] = self._gen_fname(outputs['out_file'], - suffix='_mask') + outputs['mask_file'] = self._gen_fname( + outputs['out_file'], suffix='_mask') if isdefined(self.inputs.outline) and self.inputs.outline: outputs['outline_file'] = self._gen_fname( outputs['out_file'], suffix='_overlay') @@ -196,94 +198,123 @@ def _gen_filename(self, name): class FASTInputSpec(FSLCommandInputSpec): """ Defines inputs (trait classes) for FAST """ - in_files = InputMultiPath(File(exists=True), copyfile=False, - desc='image, or multi-channel set of images, ' - 'to be segmented', - argstr='%s', position=-1, mandatory=True) - out_basename = File(desc='base name of output files', - argstr='-o %s') + in_files = InputMultiPath( + File(exists=True), + copyfile=False, + desc='image, or multi-channel set of images, ' + 'to be segmented', + argstr='%s', + position=-1, + mandatory=True) + out_basename = File(desc='base name of output files', argstr='-o %s') # ^^ uses in_file name as basename if none given - number_classes = traits.Range(low=1, high=10, argstr='-n %d', - desc='number of tissue-type classes') - output_biasfield = traits.Bool(desc='output estimated bias field', - argstr='-b') + number_classes = traits.Range( + low=1, high=10, argstr='-n %d', desc='number of tissue-type classes') + output_biasfield = traits.Bool( + desc='output estimated bias field', argstr='-b') output_biascorrected = traits.Bool( desc='output restored image (bias-corrected image)', argstr='-B') img_type = traits.Enum( (1, 2, 3), desc='int specifying type of image: (1 = T1, 2 = T2, 3 = PD)', argstr='-t %d') - bias_iters = traits.Range(low=1, high=10, argstr='-I %d', - desc='number of main-loop iterations during ' - 'bias-field removal') - bias_lowpass = traits.Range(low=4, high=40, - desc='bias field smoothing extent (FWHM) ' - 'in mm', - argstr='-l %d', units='mm') - init_seg_smooth = traits.Range(low=0.0001, high=0.1, - desc='initial segmentation spatial ' - 'smoothness (during bias field ' - 'estimation)', - argstr='-f %.3f') - segments = traits.Bool(desc='outputs a separate binary image for each ' - 'tissue type', - argstr='-g') - init_transform = File(exists=True, desc=' initialise' - ' using priors', - argstr='-a %s') + bias_iters = traits.Range( + low=1, + high=10, + argstr='-I %d', + desc='number of main-loop iterations during ' + 'bias-field removal') + bias_lowpass = traits.Range( + low=4, + high=40, + desc='bias field smoothing extent (FWHM) ' + 'in mm', + argstr='-l %d', + units='mm') + init_seg_smooth = traits.Range( + low=0.0001, + high=0.1, + desc='initial segmentation spatial ' + 'smoothness (during bias field ' + 'estimation)', + argstr='-f %.3f') + segments = traits.Bool( + desc='outputs a separate binary image for each ' + 'tissue type', + argstr='-g') + init_transform = File( + exists=True, + desc=' initialise' + ' using priors', + argstr='-a %s') other_priors = InputMultiPath( - File(exist=True), desc='alternative prior images', - argstr='-A %s', minlen=3, maxlen=3) - no_pve = traits.Bool(desc='turn off PVE (partial volume estimation)', - argstr='--nopve') - no_bias = traits.Bool(desc='do not remove bias field', - argstr='-N') - use_priors = traits.Bool(desc='use priors throughout', - argstr='-P') + File(exist=True), + desc='alternative prior images', + argstr='-A %s', + minlen=3, + maxlen=3) + no_pve = traits.Bool( + desc='turn off PVE (partial volume estimation)', argstr='--nopve') + no_bias = traits.Bool(desc='do not remove bias field', argstr='-N') + use_priors = traits.Bool(desc='use priors throughout', argstr='-P') # ^^ Must also set -a!, mutually inclusive?? No, conditional mandatory... need to figure out how to handle with traits. - segment_iters = traits.Range(low=1, high=50, - desc='number of segmentation-initialisation' - ' iterations', - argstr='-W %d') - mixel_smooth = traits.Range(low=0.0, high=1.0, - desc='spatial smoothness for mixeltype', - argstr='-R %.2f') - iters_afterbias = traits.Range(low=1, high=20, - desc='number of main-loop iterations ' - 'after bias-field removal', - argstr='-O %d') - hyper = traits.Range(low=0.0, high=1.0, - desc='segmentation spatial smoothness', - argstr='-H %.2f') - verbose = traits.Bool(desc='switch on diagnostic messages', - argstr='-v') - manual_seg = File(exists=True, desc='Filename containing intensities', - argstr='-s %s') - probability_maps = traits.Bool(desc='outputs individual probability maps', - argstr='-p') + segment_iters = traits.Range( + low=1, + high=50, + desc='number of segmentation-initialisation' + ' iterations', + argstr='-W %d') + mixel_smooth = traits.Range( + low=0.0, + high=1.0, + desc='spatial smoothness for mixeltype', + argstr='-R %.2f') + iters_afterbias = traits.Range( + low=1, + high=20, + desc='number of main-loop iterations ' + 'after bias-field removal', + argstr='-O %d') + hyper = traits.Range( + low=0.0, + high=1.0, + desc='segmentation spatial smoothness', + argstr='-H %.2f') + verbose = traits.Bool(desc='switch on diagnostic messages', argstr='-v') + manual_seg = File( + exists=True, desc='Filename containing intensities', argstr='-s %s') + probability_maps = traits.Bool( + desc='outputs individual probability maps', argstr='-p') class FASTOutputSpec(TraitedSpec): """Specify possible outputs from FAST""" - tissue_class_map = File(exists=True, - desc='path/name of binary segmented volume file' - ' one val for each class _seg') - tissue_class_files = OutputMultiPath(File( - desc=('path/name of binary segmented volumes one file for each class ' - '_seg_x'))) - restored_image = OutputMultiPath(File( - desc=('restored images (one for each input image) named according to ' - 'the input images _restore'))) + tissue_class_map = File( + exists=True, + desc='path/name of binary segmented volume file' + ' one val for each class _seg') + tissue_class_files = OutputMultiPath( + File( + desc=( + 'path/name of binary segmented volumes one file for each class ' + '_seg_x'))) + restored_image = OutputMultiPath( + File( + desc=( + 'restored images (one for each input image) named according to ' + 'the input images _restore'))) mixeltype = File(desc="path/name of mixeltype volume file _mixeltype") partial_volume_map = File(desc='path/name of partial volume file _pveseg') - partial_volume_files = OutputMultiPath(File( - desc='path/name of partial volumes files one for each class, _pve_x')) + partial_volume_files = OutputMultiPath( + File( + desc='path/name of partial volumes files one for each class, _pve_x' + )) bias_field = OutputMultiPath(File(desc='Estimated bias field _bias')) - probability_maps = OutputMultiPath(File( - desc='filenames, one for each class, for each input, prob_x')) + probability_maps = OutputMultiPath( + File(desc='filenames, one for each class, for each input, prob_x')) class FAST(FSLCommand): @@ -330,9 +361,11 @@ def _list_outputs(self): _gen_fname_opts['cwd'] = os.getcwd() else: _gen_fname_opts['basename'] = self.inputs.in_files[-1] - _gen_fname_opts['cwd'], _, _ = split_filename(_gen_fname_opts['basename']) + _gen_fname_opts['cwd'], _, _ = split_filename( + _gen_fname_opts['basename']) - outputs['tissue_class_map'] = self._gen_fname(suffix='_seg', **_gen_fname_opts) + outputs['tissue_class_map'] = self._gen_fname( + suffix='_seg', **_gen_fname_opts) if self.inputs.segments: outputs['tissue_class_files'] = [] for i in range(nclasses): @@ -346,21 +379,23 @@ def _list_outputs(self): for val, f in enumerate(self.inputs.in_files): # image numbering is 1-based outputs['restored_image'].append( - self._gen_fname(suffix='_restore_%d' % (val + 1), **_gen_fname_opts)) + self._gen_fname( + suffix='_restore_%d' % (val + 1), + **_gen_fname_opts)) else: # single image segmentation has unnumbered output image outputs['restored_image'].append( self._gen_fname(suffix='_restore', **_gen_fname_opts)) - outputs['mixeltype'] = self._gen_fname(suffix='_mixeltype', **_gen_fname_opts) + outputs['mixeltype'] = self._gen_fname( + suffix='_mixeltype', **_gen_fname_opts) if not self.inputs.no_pve: outputs['partial_volume_map'] = self._gen_fname( suffix='_pveseg', **_gen_fname_opts) outputs['partial_volume_files'] = [] for i in range(nclasses): - outputs[ - 'partial_volume_files'].append( - self._gen_fname(suffix='_pve_%d' % i, **_gen_fname_opts)) + outputs['partial_volume_files'].append( + self._gen_fname(suffix='_pve_%d' % i, **_gen_fname_opts)) if self.inputs.output_biasfield: outputs['bias_field'] = [] if len(self.inputs.in_files) > 1: @@ -369,7 +404,8 @@ def _list_outputs(self): for val, f in enumerate(self.inputs.in_files): # image numbering is 1-based outputs['bias_field'].append( - self._gen_fname(suffix='_bias_%d' % (val + 1), **_gen_fname_opts)) + self._gen_fname( + suffix='_bias_%d' % (val + 1), **_gen_fname_opts)) else: # single image segmentation has unnumbered output image outputs['bias_field'].append( @@ -384,143 +420,223 @@ def _list_outputs(self): class FLIRTInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr='-in %s', mandatory=True, - position=0, desc='input file') - reference = File(exists=True, argstr='-ref %s', mandatory=True, - position=1, desc='reference file') - out_file = File(argstr='-out %s', desc='registered output file', - name_source=['in_file'], name_template='%s_flirt', - position=2, hash_files=False) - out_matrix_file = File(argstr='-omat %s', - name_source=['in_file'], keep_extension=True, - name_template='%s_flirt.mat', - desc='output affine matrix in 4x4 asciii format', - position=3, hash_files=False) - out_log = File(name_source=['in_file'], keep_extension=True, - requires=['save_log'], - name_template='%s_flirt.log', desc='output log') + in_file = File( + exists=True, + argstr='-in %s', + mandatory=True, + position=0, + desc='input file') + reference = File( + exists=True, + argstr='-ref %s', + mandatory=True, + position=1, + desc='reference file') + out_file = File( + argstr='-out %s', + desc='registered output file', + name_source=['in_file'], + name_template='%s_flirt', + position=2, + hash_files=False) + out_matrix_file = File( + argstr='-omat %s', + name_source=['in_file'], + keep_extension=True, + name_template='%s_flirt.mat', + desc='output affine matrix in 4x4 asciii format', + position=3, + hash_files=False) + out_log = File( + name_source=['in_file'], + keep_extension=True, + requires=['save_log'], + name_template='%s_flirt.log', + desc='output log') in_matrix_file = File(argstr='-init %s', desc='input 4x4 affine matrix') apply_xfm = traits.Bool( argstr='-applyxfm', - desc=('apply transformation supplied by in_matrix_file or uses_qform to' - ' use the affine matrix stored in the reference header')) + desc=( + 'apply transformation supplied by in_matrix_file or uses_qform to' + ' use the affine matrix stored in the reference header')) apply_isoxfm = traits.Float( - argstr='-applyisoxfm %f', xor=['apply_xfm'], + argstr='-applyisoxfm %f', + xor=['apply_xfm'], desc='as applyxfm but forces isotropic resampling') - datatype = traits.Enum('char', 'short', 'int', 'float', 'double', - argstr='-datatype %s', - desc='force output data type') - cost = traits.Enum('mutualinfo', 'corratio', 'normcorr', 'normmi', - 'leastsq', 'labeldiff', 'bbr', - argstr='-cost %s', - desc='cost function') + datatype = traits.Enum( + 'char', + 'short', + 'int', + 'float', + 'double', + argstr='-datatype %s', + desc='force output data type') + cost = traits.Enum( + 'mutualinfo', + 'corratio', + 'normcorr', + 'normmi', + 'leastsq', + 'labeldiff', + 'bbr', + argstr='-cost %s', + desc='cost function') # XXX What is the difference between 'cost' and 'searchcost'? Are # these both necessary or do they map to the same variable. - cost_func = traits.Enum('mutualinfo', 'corratio', 'normcorr', 'normmi', - 'leastsq', 'labeldiff', 'bbr', - argstr='-searchcost %s', - desc='cost function') - uses_qform = traits.Bool(argstr='-usesqform', - desc='initialize using sform or qform') - display_init = traits.Bool(argstr='-displayinit', - desc='display initial matrix') - angle_rep = traits.Enum('quaternion', 'euler', - argstr='-anglerep %s', - desc='representation of rotation angles') - interp = traits.Enum('trilinear', 'nearestneighbour', 'sinc', 'spline', - argstr='-interp %s', - desc='final interpolation method used in reslicing') - sinc_width = traits.Int(argstr='-sincwidth %d', units='voxels', - desc='full-width in voxels') - sinc_window = traits.Enum('rectangular', 'hanning', 'blackman', - argstr='-sincwindow %s', - desc='sinc window') # XXX better doc + cost_func = traits.Enum( + 'mutualinfo', + 'corratio', + 'normcorr', + 'normmi', + 'leastsq', + 'labeldiff', + 'bbr', + argstr='-searchcost %s', + desc='cost function') + uses_qform = traits.Bool( + argstr='-usesqform', desc='initialize using sform or qform') + display_init = traits.Bool( + argstr='-displayinit', desc='display initial matrix') + angle_rep = traits.Enum( + 'quaternion', + 'euler', + argstr='-anglerep %s', + desc='representation of rotation angles') + interp = traits.Enum( + 'trilinear', + 'nearestneighbour', + 'sinc', + 'spline', + argstr='-interp %s', + desc='final interpolation method used in reslicing') + sinc_width = traits.Int( + argstr='-sincwidth %d', units='voxels', desc='full-width in voxels') + sinc_window = traits.Enum( + 'rectangular', + 'hanning', + 'blackman', + argstr='-sincwindow %s', + desc='sinc window') # XXX better doc bins = traits.Int(argstr='-bins %d', desc='number of histogram bins') - dof = traits.Int(argstr='-dof %d', - desc='number of transform degrees of freedom') - no_resample = traits.Bool(argstr='-noresample', - desc='do not change input sampling') - force_scaling = traits.Bool(argstr='-forcescaling', - desc='force rescaling even for low-res images') + dof = traits.Int( + argstr='-dof %d', desc='number of transform degrees of freedom') + no_resample = traits.Bool( + argstr='-noresample', desc='do not change input sampling') + force_scaling = traits.Bool( + argstr='-forcescaling', desc='force rescaling even for low-res images') min_sampling = traits.Float( - argstr='-minsampling %f', units='mm', + argstr='-minsampling %f', + units='mm', desc='set minimum voxel dimension for sampling') - padding_size = traits.Int(argstr='-paddingsize %d', units='voxels', - desc='for applyxfm: interpolates outside image ' - 'by size') - searchr_x = traits.List(traits.Int, minlen=2, maxlen=2, units='degrees', - argstr='-searchrx %s', - desc='search angles along x-axis, in degrees') - searchr_y = traits.List(traits.Int, minlen=2, maxlen=2, units='degrees', - argstr='-searchry %s', - desc='search angles along y-axis, in degrees') - searchr_z = traits.List(traits.Int, minlen=2, maxlen=2, units='degrees', - argstr='-searchrz %s', - desc='search angles along z-axis, in degrees') - no_search = traits.Bool(argstr='-nosearch', - desc='set all angular searches to ranges 0 to 0') - coarse_search = traits.Int(argstr='-coarsesearch %d', units='degrees', - desc='coarse search delta angle') - fine_search = traits.Int(argstr='-finesearch %d', units='degrees', - desc='fine search delta angle') - schedule = File(exists=True, argstr='-schedule %s', - desc='replaces default schedule') - ref_weight = File(exists=True, argstr='-refweight %s', - desc='File for reference weighting volume') - in_weight = File(exists=True, argstr='-inweight %s', - desc='File for input weighting volume') - no_clamp = traits.Bool(argstr='-noclamp', - desc='do not use intensity clamping') - no_resample_blur = traits.Bool(argstr='-noresampblur', - desc='do not use blurring on downsampling') - rigid2D = traits.Bool(argstr='-2D', - desc='use 2D rigid body mode - ignores dof') + padding_size = traits.Int( + argstr='-paddingsize %d', + units='voxels', + desc='for applyxfm: interpolates outside image ' + 'by size') + searchr_x = traits.List( + traits.Int, + minlen=2, + maxlen=2, + units='degrees', + argstr='-searchrx %s', + desc='search angles along x-axis, in degrees') + searchr_y = traits.List( + traits.Int, + minlen=2, + maxlen=2, + units='degrees', + argstr='-searchry %s', + desc='search angles along y-axis, in degrees') + searchr_z = traits.List( + traits.Int, + minlen=2, + maxlen=2, + units='degrees', + argstr='-searchrz %s', + desc='search angles along z-axis, in degrees') + no_search = traits.Bool( + argstr='-nosearch', desc='set all angular searches to ranges 0 to 0') + coarse_search = traits.Int( + argstr='-coarsesearch %d', + units='degrees', + desc='coarse search delta angle') + fine_search = traits.Int( + argstr='-finesearch %d', + units='degrees', + desc='fine search delta angle') + schedule = File( + exists=True, argstr='-schedule %s', desc='replaces default schedule') + ref_weight = File( + exists=True, + argstr='-refweight %s', + desc='File for reference weighting volume') + in_weight = File( + exists=True, + argstr='-inweight %s', + desc='File for input weighting volume') + no_clamp = traits.Bool( + argstr='-noclamp', desc='do not use intensity clamping') + no_resample_blur = traits.Bool( + argstr='-noresampblur', desc='do not use blurring on downsampling') + rigid2D = traits.Bool( + argstr='-2D', desc='use 2D rigid body mode - ignores dof') save_log = traits.Bool(desc='save to log file') - verbose = traits.Int(argstr='-verbose %d', - desc='verbose mode, 0 is least') - bgvalue = traits.Float(0, argstr='-setbackground %f', - desc=('use specified background value for points ' - 'outside FOV')) + verbose = traits.Int(argstr='-verbose %d', desc='verbose mode, 0 is least') + bgvalue = traits.Float( + 0, + argstr='-setbackground %f', + desc=('use specified background value for points ' + 'outside FOV')) # BBR options wm_seg = File( - argstr='-wmseg %s', min_ver='5.0.0', + argstr='-wmseg %s', + min_ver='5.0.0', desc='white matter segmentation volume needed by BBR cost function') wmcoords = File( - argstr='-wmcoords %s', min_ver='5.0.0', + argstr='-wmcoords %s', + min_ver='5.0.0', desc='white matter boundary coordinates for BBR cost function') wmnorms = File( - argstr='-wmnorms %s', min_ver='5.0.0', + argstr='-wmnorms %s', + min_ver='5.0.0', desc='white matter boundary normals for BBR cost function') fieldmap = File( - argstr='-fieldmap %s', min_ver='5.0.0', + argstr='-fieldmap %s', + min_ver='5.0.0', desc=('fieldmap image in rads/s - must be already registered to the ' 'reference image')) fieldmapmask = File( - argstr='-fieldmapmask %s', min_ver='5.0.0', + argstr='-fieldmapmask %s', + min_ver='5.0.0', desc='mask for fieldmap image') pedir = traits.Int( - argstr='-pedir %d', min_ver='5.0.0', + argstr='-pedir %d', + min_ver='5.0.0', desc='phase encode direction of EPI - 1/2/3=x/y/z & -1/-2/-3=-x/-y/-z') echospacing = traits.Float( - argstr='-echospacing %f', min_ver='5.0.0', + argstr='-echospacing %f', + min_ver='5.0.0', desc='value of EPI echo spacing - units of seconds') bbrtype = traits.Enum( - 'signed', 'global_abs', 'local_abs', - argstr='-bbrtype %s', min_ver='5.0.0', + 'signed', + 'global_abs', + 'local_abs', + argstr='-bbrtype %s', + min_ver='5.0.0', desc=('type of bbr cost function: signed [default], global_abs, ' 'local_abs')) bbrslope = traits.Float( - argstr='-bbrslope %f', min_ver='5.0.0', - desc='value of bbr slope') + argstr='-bbrslope %f', min_ver='5.0.0', desc='value of bbr slope') class FLIRTOutputSpec(TraitedSpec): - out_file = File(exists=True, - desc='path/name of registered file (if generated)') - out_matrix_file = File(exists=True, - desc='path/name of calculated affine transform ' - '(if generated)') + out_file = File( + exists=True, desc='path/name of registered file (if generated)') + out_matrix_file = File( + exists=True, + desc='path/name of calculated affine transform ' + '(if generated)') out_log = File(desc='path/name of output log (if generated)') @@ -565,8 +681,8 @@ def _parse_inputs(self, skip=None): skip = [] if self.inputs.save_log and not self.inputs.verbose: self.inputs.verbose = 1 - if self.inputs.apply_xfm and not (self.inputs.in_matrix_file or - self.inputs.uses_qform): + if self.inputs.apply_xfm and not (self.inputs.in_matrix_file + or self.inputs.uses_qform): raise RuntimeError('Argument apply_xfm requires in_matrix_file or ' 'uses_qform arguments to run') skip.append('save_log') @@ -575,9 +691,11 @@ def _parse_inputs(self, skip=None): class ApplyXFMInputSpec(FLIRTInputSpec): apply_xfm = traits.Bool( - True, argstr='-applyxfm', - desc=('apply transformation supplied by in_matrix_file or uses_qform to' - ' use the affine matrix stored in the reference header'), + True, + argstr='-applyxfm', + desc=( + 'apply transformation supplied by in_matrix_file or uses_qform to' + ' use the affine matrix stored in the reference header'), usedefault=True) @@ -606,14 +724,23 @@ class ApplyXFM(FLIRT): class MCFLIRTInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, position=0, argstr="-in %s", mandatory=True, - desc="timeseries to motion-correct") - out_file = File(argstr='-out %s', genfile=True, - desc="file to write", hash_files=False) + in_file = File( + exists=True, + position=0, + argstr="-in %s", + mandatory=True, + desc="timeseries to motion-correct") + out_file = File( + argstr='-out %s', genfile=True, desc="file to write", hash_files=False) cost = traits.Enum( - 'mutualinfo', 'woods', 'corratio', - 'normcorr', 'normmi', 'leastsquares', - argstr='-cost %s', desc="cost function to optimize") + 'mutualinfo', + 'woods', + 'corratio', + 'normcorr', + 'normmi', + 'leastsquares', + argstr='-cost %s', + desc="cost function to optimize") bins = traits.Int(argstr='-bins %d', desc="number of histogram bins") dof = traits.Int( argstr='-dof %d', desc="degrees of freedom for the transformation") @@ -627,10 +754,14 @@ class MCFLIRTInputSpec(FSLCommandInputSpec): stages = traits.Int( argstr='-stages %d', desc="stages (if 4, perform final search with sinc interpolation") - init = File(exists=True, argstr='-init %s', - desc="inital transformation matrix") - interpolation = traits.Enum("spline", "nn", "sinc", argstr="-%s_final", - desc="interpolation method for transformation") + init = File( + exists=True, argstr='-init %s', desc="inital transformation matrix") + interpolation = traits.Enum( + "spline", + "nn", + "sinc", + argstr="-%s_final", + desc="interpolation method for transformation") use_gradient = traits.Bool( argstr='-gdt', desc="run search on gradient images") use_contour = traits.Bool( @@ -644,20 +775,23 @@ class MCFLIRTInputSpec(FSLCommandInputSpec): argstr='-plots', desc="save transformation parameters") save_rms = traits.Bool( argstr='-rmsabs -rmsrel', desc="save rms displacement parameters") - ref_file = File(exists=True, argstr='-reffile %s', - desc="target image for motion correction") + ref_file = File( + exists=True, + argstr='-reffile %s', + desc="target image for motion correction") class MCFLIRTOutputSpec(TraitedSpec): out_file = File(exists=True, desc="motion-corrected timeseries") variance_img = File(exists=True, desc="variance image") std_img = File(exists=True, desc="standard deviation image") - mean_img = File(exists=True, desc="mean timeseries image (if mean_vol=True)") + mean_img = File( + exists=True, desc="mean timeseries image (if mean_vol=True)") par_file = File(exists=True, desc="text-file with motion parameters") - mat_file = OutputMultiPath(File( - exists=True), desc="transformation matrices") - rms_files = OutputMultiPath(File( - exists=True), + mat_file = OutputMultiPath( + File(exists=True), desc="transformation matrices") + rms_files = OutputMultiPath( + File(exists=True), desc="absolute and relative displacement parameters") @@ -698,10 +832,10 @@ def _list_outputs(self): outputs['out_file'] = self._gen_outfilename() if isdefined(self.inputs.stats_imgs) and self.inputs.stats_imgs: - outputs['variance_img'] = self._gen_fname(outputs['out_file'] + - '_variance.ext', cwd=cwd) - outputs['std_img'] = self._gen_fname(outputs['out_file'] + - '_sigma.ext', cwd=cwd) + outputs['variance_img'] = self._gen_fname( + outputs['out_file'] + '_variance.ext', cwd=cwd) + outputs['std_img'] = self._gen_fname( + outputs['out_file'] + '_sigma.ext', cwd=cwd) # The mean image created if -stats option is specified ('meanvol') # is missing the top and bottom slices. Therefore we only expose the @@ -710,8 +844,8 @@ def _list_outputs(self): # Note that the same problem holds for the std and variance image. if isdefined(self.inputs.mean_vol) and self.inputs.mean_vol: - outputs['mean_img'] = self._gen_fname(outputs['out_file'] + - '_mean_reg.ext', cwd=cwd) + outputs['mean_img'] = self._gen_fname( + outputs['out_file'] + '_mean_reg.ext', cwd=cwd) if isdefined(self.inputs.save_mats) and self.inputs.save_mats: _, filename = os.path.split(outputs['out_file']) @@ -719,8 +853,8 @@ def _list_outputs(self): _, _, _, timepoints = load(self.inputs.in_file).shape outputs['mat_file'] = [] for t in range(timepoints): - outputs['mat_file'].append(os.path.join(matpathname, - 'MAT_%04d' % t)) + outputs['mat_file'].append( + os.path.join(matpathname, 'MAT_%04d' % t)) if isdefined(self.inputs.save_plots) and self.inputs.save_plots: # Note - if e.g. out_file has .nii.gz, you get .nii.gz.par, # which is what mcflirt does! @@ -740,77 +874,116 @@ def _gen_outfilename(self): if isdefined(out_file): out_file = os.path.realpath(out_file) if not isdefined(out_file) and isdefined(self.inputs.in_file): - out_file = self._gen_fname(self.inputs.in_file, - suffix='_mcf') + out_file = self._gen_fname(self.inputs.in_file, suffix='_mcf') return os.path.abspath(out_file) class FNIRTInputSpec(FSLCommandInputSpec): - ref_file = File(exists=True, argstr='--ref=%s', mandatory=True, - desc='name of reference image') - in_file = File(exists=True, argstr='--in=%s', mandatory=True, - desc='name of input image') - affine_file = File(exists=True, argstr='--aff=%s', - desc='name of file containing affine transform') - inwarp_file = File(exists=True, argstr='--inwarp=%s', - desc='name of file containing initial non-linear warps') - in_intensitymap_file = traits.List(File(exists=True), argstr='--intin=%s', - copyfile=False, minlen=1, maxlen=2, - desc=('name of file/files containing ' - 'initial intensity mapping ' - 'usually generated by previous ' - 'fnirt run')) + ref_file = File( + exists=True, + argstr='--ref=%s', + mandatory=True, + desc='name of reference image') + in_file = File( + exists=True, + argstr='--in=%s', + mandatory=True, + desc='name of input image') + affine_file = File( + exists=True, + argstr='--aff=%s', + desc='name of file containing affine transform') + inwarp_file = File( + exists=True, + argstr='--inwarp=%s', + desc='name of file containing initial non-linear warps') + in_intensitymap_file = traits.List( + File(exists=True), + argstr='--intin=%s', + copyfile=False, + minlen=1, + maxlen=2, + desc=('name of file/files containing ' + 'initial intensity mapping ' + 'usually generated by previous ' + 'fnirt run')) fieldcoeff_file = traits.Either( - traits.Bool, File, argstr='--cout=%s', + traits.Bool, + File, + argstr='--cout=%s', desc='name of output file with field coefficients or true') - warped_file = File(argstr='--iout=%s', - desc='name of output image', genfile=True, - hash_files=False) - field_file = traits.Either(traits.Bool, File, - argstr='--fout=%s', - desc='name of output file with field or true', - hash_files=False) - jacobian_file = traits.Either(traits.Bool, File, - argstr='--jout=%s', - desc=('name of file for writing out the ' - 'Jacobian of the field (for ' - 'diagnostic or VBM purposes)'), - hash_files=False) - modulatedref_file = traits.Either(traits.Bool, File, - argstr='--refout=%s', - desc=('name of file for writing out ' - 'intensity modulated --ref (for ' - 'diagnostic purposes)'), - hash_files=False) - out_intensitymap_file = traits.Either(traits.Bool, File, - argstr='--intout=%s', - desc=('name of files for writing ' - 'information pertaining to ' - 'intensity mapping'), - hash_files=False) - log_file = File(argstr='--logout=%s', - desc='Name of log-file', genfile=True, hash_files=False) + warped_file = File( + argstr='--iout=%s', + desc='name of output image', + genfile=True, + hash_files=False) + field_file = traits.Either( + traits.Bool, + File, + argstr='--fout=%s', + desc='name of output file with field or true', + hash_files=False) + jacobian_file = traits.Either( + traits.Bool, + File, + argstr='--jout=%s', + desc=('name of file for writing out the ' + 'Jacobian of the field (for ' + 'diagnostic or VBM purposes)'), + hash_files=False) + modulatedref_file = traits.Either( + traits.Bool, + File, + argstr='--refout=%s', + desc=('name of file for writing out ' + 'intensity modulated --ref (for ' + 'diagnostic purposes)'), + hash_files=False) + out_intensitymap_file = traits.Either( + traits.Bool, + File, + argstr='--intout=%s', + desc=('name of files for writing ' + 'information pertaining to ' + 'intensity mapping'), + hash_files=False) + log_file = File( + argstr='--logout=%s', + desc='Name of log-file', + genfile=True, + hash_files=False) config_file = traits.Either( - traits.Enum("T1_2_MNI152_2mm", "FA_2_FMRIB58_1mm"), File(exists=True), + traits.Enum("T1_2_MNI152_2mm", "FA_2_FMRIB58_1mm"), + File(exists=True), argstr='--config=%s', desc='Name of config file specifying command line arguments') - refmask_file = File(exists=True, argstr='--refmask=%s', - desc='name of file with mask in reference space') - inmask_file = File(exists=True, argstr='--inmask=%s', - desc='name of file with mask in input image space') + refmask_file = File( + exists=True, + argstr='--refmask=%s', + desc='name of file with mask in reference space') + inmask_file = File( + exists=True, + argstr='--inmask=%s', + desc='name of file with mask in input image space') skip_refmask = traits.Bool( - argstr='--applyrefmask=0', xor=['apply_refmask'], + argstr='--applyrefmask=0', + xor=['apply_refmask'], desc='Skip specified refmask if set, default false') skip_inmask = traits.Bool( - argstr='--applyinmask=0', xor=['apply_inmask'], + argstr='--applyinmask=0', + xor=['apply_inmask'], desc='skip specified inmask if set, default false') apply_refmask = traits.List( - traits.Enum(0, 1), argstr='--applyrefmask=%s', xor=['skip_refmask'], + traits.Enum(0, 1), + argstr='--applyrefmask=%s', + xor=['skip_refmask'], desc=('list of iterations to use reference mask on (1 to use, 0 to ' 'skip)'), sep=",") apply_inmask = traits.List( - traits.Enum(0, 1), argstr='--applyinmask=%s', xor=['skip_inmask'], + traits.Enum(0, 1), + argstr='--applyinmask=%s', + xor=['skip_inmask'], desc='list of iterations to use input mask on (1 to use, 0 to skip)', sep=",") skip_implicit_ref_masking = traits.Bool( @@ -838,7 +1011,9 @@ class FNIRTInputSpec(FSLCommandInputSpec): desc='sub-sampling scheme, list, default [4, 2, 1, 1]', sep=",") warp_resolution = traits.Tuple( - traits.Int, traits.Int, traits.Int, + traits.Int, + traits.Int, + traits.Int, argstr='--warpres=%d,%d,%d', desc=('(approximate) resolution (in mm) of warp basis in x-, y- and ' 'z-direction, default 10, 10, 10')) @@ -846,22 +1021,26 @@ class FNIRTInputSpec(FSLCommandInputSpec): argstr='--splineorder=%d', desc='Order of spline, 2->Qadratic spline, 3->Cubic spline. Default=3') in_fwhm = traits.List( - traits.Int, argstr='--infwhm=%s', + traits.Int, + argstr='--infwhm=%s', desc=('FWHM (in mm) of gaussian smoothing kernel for input volume, ' 'default [6, 4, 2, 2]'), sep=",") ref_fwhm = traits.List( - traits.Int, argstr='--reffwhm=%s', + traits.Int, + argstr='--reffwhm=%s', desc=('FWHM (in mm) of gaussian smoothing kernel for ref volume, ' 'default [4, 2, 0, 0]'), sep=",") regularization_model = traits.Enum( - 'membrane_energy', 'bending_energy', + 'membrane_energy', + 'bending_energy', argstr='--regmod=%s', desc=('Model for regularisation of warp-field [membrane_energy ' 'bending_energy], default bending_energy')) regularization_lambda = traits.List( - traits.Float, argstr='--lambda=%s', + traits.Float, + argstr='--lambda=%s', desc=('Weight of regularisation, default depending on --ssqlambda and ' '--regmod switches. See user documetation.'), sep=",") @@ -869,7 +1048,8 @@ class FNIRTInputSpec(FSLCommandInputSpec): argstr='--ssqlambda=0', desc='If true, lambda is not weighted by current ssq, default false') jacobian_range = traits.Tuple( - traits.Float, traits.Float, + traits.Float, + traits.Float, argstr='--jacrange=%f,%f', desc='Allowed range of Jacobian determinants, default 0.01, 100.0') derive_from_ref = traits.Bool( @@ -877,15 +1057,21 @@ class FNIRTInputSpec(FSLCommandInputSpec): desc=('If true, ref image is used to calculate derivatives. ' 'Default false')) intensity_mapping_model = traits.Enum( - 'none', 'global_linear', 'global_non_linear', - 'local_linear', 'global_non_linear_with_bias', - 'local_non_linear', argstr='--intmod=%s', + 'none', + 'global_linear', + 'global_non_linear', + 'local_linear', + 'global_non_linear_with_bias', + 'local_non_linear', + argstr='--intmod=%s', desc='Model for intensity-mapping') intensity_mapping_order = traits.Int( argstr='--intorder=%d', desc='Order of poynomial for mapping intensities, default 5') biasfield_resolution = traits.Tuple( - traits.Int, traits.Int, traits.Int, + traits.Int, + traits.Int, + traits.Int, argstr='--biasres=%d,%d,%d', desc=('Resolution (in mm) of bias-field modelling local intensities, ' 'default 50, 50, 50')) @@ -893,16 +1079,20 @@ class FNIRTInputSpec(FSLCommandInputSpec): argstr='--biaslambda=%f', desc='Weight of regularisation for bias-field, default 10000') skip_intensity_mapping = traits.Bool( - argstr='--estint=0', xor=['apply_intensity_mapping'], + argstr='--estint=0', + xor=['apply_intensity_mapping'], desc='Skip estimate intensity-mapping default false') apply_intensity_mapping = traits.List( - traits.Enum(0, 1), argstr='--estint=%s', + traits.Enum(0, 1), + argstr='--estint=%s', xor=['skip_intensity_mapping'], desc=('List of subsampling levels to apply intensity mapping for ' '(0 to skip, 1 to apply)'), sep=",") hessian_precision = traits.Enum( - 'double', 'float', argstr='--numprec=%s', + 'double', + 'float', + argstr='--numprec=%s', desc=('Precision for representing Hessian, double or float. ' 'Default double')) @@ -914,7 +1104,9 @@ class FNIRTOutputSpec(TraitedSpec): jacobian_file = File(desc='file containing Jacobian of the field') modulatedref_file = File(desc='file containing intensity modulated --ref') out_intensitymap_file = traits.List( - File, minlen=2, maxlen=2, + File, + minlen=2, + maxlen=2, desc='files containing info pertaining to intensity mapping') log_file = File(desc='Name of log-file') @@ -955,13 +1147,15 @@ class FNIRT(FSLCommand): input_spec = FNIRTInputSpec output_spec = FNIRTOutputSpec - filemap = {'warped_file': 'warped', - 'field_file': 'field', - 'jacobian_file': 'field_jacobian', - 'modulatedref_file': 'modulated', - 'out_intensitymap_file': 'intmap', - 'log_file': 'log.txt', - 'fieldcoeff_file': 'fieldwarp'} + filemap = { + 'warped_file': 'warped', + 'field_file': 'field', + 'jacobian_file': 'field_jacobian', + 'modulatedref_file': 'modulated', + 'out_intensitymap_file': 'intmap', + 'log_file': 'log.txt', + 'fieldcoeff_file': 'fieldwarp' + } def _list_outputs(self): outputs = self.output_spec().get() @@ -974,15 +1168,17 @@ def _list_outputs(self): if isdefined(inval): outputs[key] = inval else: - outputs[key] = self._gen_fname(self.inputs.in_file, - suffix='_' + suffix, - change_ext=change_ext) + outputs[key] = self._gen_fname( + self.inputs.in_file, + suffix='_' + suffix, + change_ext=change_ext) elif isdefined(inval): if isinstance(inval, bool): if inval: - outputs[key] = self._gen_fname(self.inputs.in_file, - suffix='_' + suffix, - change_ext=change_ext) + outputs[key] = self._gen_fname( + self.inputs.in_file, + suffix='_' + suffix, + change_ext=change_ext) else: outputs[key] = os.path.abspath(inval) @@ -1023,7 +1219,7 @@ def write_config(self, configfile): try: fid = open(configfile, 'w+') except IOError: - print ('unable to create config_file %s' % (configfile)) + print('unable to create config_file %s' % (configfile)) for item in list(self.inputs.get().items()): fid.write('%s\n' % (item)) @@ -1042,40 +1238,71 @@ def intensitymap_file_basename(cls, f): class ApplyWarpInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr='--in=%s', - mandatory=True, position=0, - desc='image to be warped') - out_file = File(argstr='--out=%s', genfile=True, position=2, - desc='output filename', hash_files=False) - ref_file = File(exists=True, argstr='--ref=%s', - mandatory=True, position=1, - desc='reference image') - field_file = File(exists=True, argstr='--warp=%s', - desc='file containing warp field') - abswarp = traits.Bool(argstr='--abs', xor=['relwarp'], - desc="treat warp field as absolute: x' = w(x)") - relwarp = traits.Bool(argstr='--rel', xor=['abswarp'], position=-1, - desc="treat warp field as relative: x' = x + w(x)") + in_file = File( + exists=True, + argstr='--in=%s', + mandatory=True, + position=0, + desc='image to be warped') + out_file = File( + argstr='--out=%s', + genfile=True, + position=2, + desc='output filename', + hash_files=False) + ref_file = File( + exists=True, + argstr='--ref=%s', + mandatory=True, + position=1, + desc='reference image') + field_file = File( + exists=True, argstr='--warp=%s', desc='file containing warp field') + abswarp = traits.Bool( + argstr='--abs', + xor=['relwarp'], + desc="treat warp field as absolute: x' = w(x)") + relwarp = traits.Bool( + argstr='--rel', + xor=['abswarp'], + position=-1, + desc="treat warp field as relative: x' = x + w(x)") datatype = traits.Enum( - 'char', 'short', 'int', 'float', 'double', + 'char', + 'short', + 'int', + 'float', + 'double', argstr='--datatype=%s', desc='Force output data type [char short int float double].') supersample = traits.Bool( argstr='--super', desc='intermediary supersampling of output, default is off') superlevel = traits.Either( - traits.Enum('a'), traits.Int, + traits.Enum('a'), + traits.Int, argstr='--superlevel=%s', desc=("level of intermediary supersampling, a for 'automatic' or " "integer level. Default = 2")) - premat = File(exists=True, argstr='--premat=%s', - desc='filename for pre-transform (affine matrix)') - postmat = File(exists=True, argstr='--postmat=%s', - desc='filename for post-transform (affine matrix)') - mask_file = File(exists=True, argstr='--mask=%s', - desc='filename for mask image (in reference space)') + premat = File( + exists=True, + argstr='--premat=%s', + desc='filename for pre-transform (affine matrix)') + postmat = File( + exists=True, + argstr='--postmat=%s', + desc='filename for post-transform (affine matrix)') + mask_file = File( + exists=True, + argstr='--mask=%s', + desc='filename for mask image (in reference space)') interp = traits.Enum( - 'nn', 'trilinear', 'sinc', 'spline', argstr='--interp=%s', position=-2, + 'nn', + 'trilinear', + 'sinc', + 'spline', + argstr='--interp=%s', + position=-2, desc='interpolation method') @@ -1111,8 +1338,8 @@ def _format_arg(self, name, spec, value): def _list_outputs(self): outputs = self._outputs().get() if not isdefined(self.inputs.out_file): - outputs['out_file'] = self._gen_fname(self.inputs.in_file, - suffix='_warp') + outputs['out_file'] = self._gen_fname( + self.inputs.in_file, suffix='_warp') else: outputs['out_file'] = os.path.abspath(self.inputs.out_file) return outputs @@ -1124,29 +1351,40 @@ def _gen_filename(self, name): class SliceTimerInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr='--in=%s', - mandatory=True, position=0, - desc='filename of input timeseries') - out_file = File(argstr='--out=%s', genfile=True, - desc='filename of output timeseries', hash_files=False) - index_dir = traits.Bool(argstr='--down', - desc='slice indexing from top to bottom') - time_repetition = traits.Float(argstr='--repeat=%f', - desc='Specify TR of data - default is 3s') + in_file = File( + exists=True, + argstr='--in=%s', + mandatory=True, + position=0, + desc='filename of input timeseries') + out_file = File( + argstr='--out=%s', + genfile=True, + desc='filename of output timeseries', + hash_files=False) + index_dir = traits.Bool( + argstr='--down', desc='slice indexing from top to bottom') + time_repetition = traits.Float( + argstr='--repeat=%f', desc='Specify TR of data - default is 3s') slice_direction = traits.Enum( - 1, 2, 3, argstr='--direction=%d', + 1, + 2, + 3, + argstr='--direction=%d', desc='direction of slice acquisition (x=1, y=2, z=3) - default is z') - interleaved = traits.Bool(argstr='--odd', - desc='use interleaved acquisition') + interleaved = traits.Bool( + argstr='--odd', desc='use interleaved acquisition') custom_timings = File( - exists=True, argstr='--tcustom=%s', + exists=True, + argstr='--tcustom=%s', desc=('slice timings, in fractions of TR, range 0:1 (default is 0.5 = ' 'no shift)')) global_shift = traits.Float( argstr='--tglobal', desc='shift in fraction of TR, range 0:1 (default is 0.5 = no shift)') custom_order = File( - exists=True, argstr='--ocustom=%s', + exists=True, + argstr='--ocustom=%s', desc=('filename of single-column custom interleave order file (first ' 'slice is referred to as 1 not 0)')) @@ -1178,8 +1416,7 @@ def _list_outputs(self): outputs = self._outputs().get() out_file = self.inputs.out_file if not isdefined(out_file): - out_file = self._gen_fname(self.inputs.in_file, - suffix='_st') + out_file = self._gen_fname(self.inputs.in_file, suffix='_st') outputs['slice_time_corrected_file'] = os.path.abspath(out_file) return outputs @@ -1190,32 +1427,55 @@ def _gen_filename(self, name): class SUSANInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr='%s', - mandatory=True, position=1, - desc='filename of input timeseries') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=1, + desc='filename of input timeseries') brightness_threshold = traits.Float( argstr='%.10f', - position=2, mandatory=True, + position=2, + mandatory=True, desc=('brightness threshold and should be greater than noise level ' 'and less than contrast of edges to be preserved.')) fwhm = traits.Float( - argstr='%.10f', position=3, mandatory=True, + argstr='%.10f', + position=3, + mandatory=True, desc='fwhm of smoothing, in mm, gets converted using sqrt(8*log(2))') - dimension = traits.Enum(3, 2, argstr='%d', position=4, usedefault=True, - desc='within-plane (2) or fully 3D (3)') + dimension = traits.Enum( + 3, + 2, + argstr='%d', + position=4, + usedefault=True, + desc='within-plane (2) or fully 3D (3)') use_median = traits.Enum( - 1, 0, argstr='%d', position=5, usedefault=True, + 1, + 0, + argstr='%d', + position=5, + usedefault=True, desc=('whether to use a local median filter in the cases where ' 'single-point noise is detected')) usans = traits.List( - traits.Tuple(File(exists=True), traits.Float), maxlen=2, - argstr='', position=6, default=[], usedefault=True, + traits.Tuple(File(exists=True), traits.Float), + maxlen=2, + argstr='', + position=6, + default=[], + usedefault=True, desc='determines whether the smoothing area (USAN) is to be ' - 'found from secondary images (0, 1 or 2). A negative ' - 'value for any brightness threshold will auto-set the ' - 'threshold at 10% of the robust range') - out_file = File(argstr='%s', position=-1, genfile=True, - desc='output file name', hash_files=False) + 'found from secondary images (0, 1 or 2). A negative ' + 'value for any brightness threshold will auto-set the ' + 'threshold at 10% of the robust range') + out_file = File( + argstr='%s', + position=-1, + genfile=True, + desc='output file name', + hash_files=False) class SUSANOutputSpec(TraitedSpec): @@ -1262,8 +1522,7 @@ def _list_outputs(self): outputs = self._outputs().get() out_file = self.inputs.out_file if not isdefined(out_file): - out_file = self._gen_fname(self.inputs.in_file, - suffix='_smooth') + out_file = self._gen_fname(self.inputs.in_file, suffix='_smooth') outputs['smoothed_file'] = os.path.abspath(out_file) return outputs @@ -1274,25 +1533,36 @@ def _gen_filename(self, name): class FUGUEInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr='--in=%s', - desc='filename of input volume') - shift_in_file = File(exists=True, argstr='--loadshift=%s', - desc='filename for reading pixel shift volume') - phasemap_in_file = File(exists=True, argstr='--phasemap=%s', - desc='filename for input phase image') - fmap_in_file = File(exists=True, argstr='--loadfmap=%s', - desc='filename for loading fieldmap (rad/s)') - unwarped_file = File(argstr='--unwarp=%s', - desc='apply unwarping and save as filename', - xor=['warped_file'], requires=['in_file']) - warped_file = File(argstr='--warp=%s', - desc='apply forward warping and save as filename', - xor=['unwarped_file'], requires=['in_file']) + in_file = File( + exists=True, argstr='--in=%s', desc='filename of input volume') + shift_in_file = File( + exists=True, + argstr='--loadshift=%s', + desc='filename for reading pixel shift volume') + phasemap_in_file = File( + exists=True, + argstr='--phasemap=%s', + desc='filename for input phase image') + fmap_in_file = File( + exists=True, + argstr='--loadfmap=%s', + desc='filename for loading fieldmap (rad/s)') + unwarped_file = File( + argstr='--unwarp=%s', + desc='apply unwarping and save as filename', + xor=['warped_file'], + requires=['in_file']) + warped_file = File( + argstr='--warp=%s', + desc='apply forward warping and save as filename', + xor=['unwarped_file'], + requires=['in_file']) forward_warping = traits.Bool( - False, usedefault=True, + False, + usedefault=True, desc='apply forward warping instead of unwarping') - dwell_to_asym_ratio = traits.Float(argstr='--dwelltoasym=%.10f', - desc='set the dwell to asym time ratio') + dwell_to_asym_ratio = traits.Float( + argstr='--dwelltoasym=%.10f', desc='set the dwell to asym time ratio') dwell_time = traits.Float( argstr='--dwell=%.10f', desc=('set the EPI dwell time per phase-encode line - same as echo ' @@ -1300,10 +1570,10 @@ class FUGUEInputSpec(FSLCommandInputSpec): asym_se_time = traits.Float( argstr='--asym=%.10f', desc='set the fieldmap asymmetric spin echo time (sec)') - median_2dfilter = traits.Bool(argstr='--median', - desc='apply 2D median filtering') - despike_2dfilter = traits.Bool(argstr='--despike', - desc='apply a 2D de-spiking filter') + median_2dfilter = traits.Bool( + argstr='--median', desc='apply 2D median filtering') + despike_2dfilter = traits.Bool( + argstr='--despike', desc='apply a 2D de-spiking filter') no_gap_fill = traits.Bool( argstr='--nofill', desc='do not apply gap-filling measure to the fieldmap') @@ -1316,50 +1586,62 @@ class FUGUEInputSpec(FSLCommandInputSpec): smooth3d = traits.Float( argstr='--smooth3=%.2f', desc='apply 3D Gaussian smoothing of sigma N (in mm)') - poly_order = traits.Int(argstr='--poly=%d', - desc='apply polynomial fitting of order N') + poly_order = traits.Int( + argstr='--poly=%d', desc='apply polynomial fitting of order N') fourier_order = traits.Int( argstr='--fourier=%d', desc='apply Fourier (sinusoidal) fitting of order N') - pava = traits.Bool(argstr='--pava', - desc='apply monotonic enforcement via PAVA') + pava = traits.Bool( + argstr='--pava', desc='apply monotonic enforcement via PAVA') despike_threshold = traits.Float( argstr='--despikethreshold=%s', desc='specify the threshold for de-spiking (default=3.0)') unwarp_direction = traits.Enum( - 'x', 'y', 'z', 'x-', 'y-', 'z-', + 'x', + 'y', + 'z', + 'x-', + 'y-', + 'z-', argstr='--unwarpdir=%s', desc='specifies direction of warping (default y)') phase_conjugate = traits.Bool( - argstr='--phaseconj', - desc='apply phase conjugate method of unwarping') + argstr='--phaseconj', desc='apply phase conjugate method of unwarping') icorr = traits.Bool( - argstr='--icorr', requires=['shift_in_file'], + argstr='--icorr', + requires=['shift_in_file'], desc=('apply intensity correction to unwarping (pixel shift method ' 'only)')) - icorr_only = traits.Bool(argstr='--icorronly', requires=['unwarped_file'], - desc='apply intensity correction only') - mask_file = File(exists=True, argstr='--mask=%s', - desc='filename for loading valid mask') - nokspace = traits.Bool(False, argstr='--nokspace', - desc='do not use k-space forward warping') + icorr_only = traits.Bool( + argstr='--icorronly', + requires=['unwarped_file'], + desc='apply intensity correction only') + mask_file = File( + exists=True, + argstr='--mask=%s', + desc='filename for loading valid mask') + nokspace = traits.Bool( + False, argstr='--nokspace', desc='do not use k-space forward warping') # Special outputs: shift (voxel shift map, vsm) - save_shift = traits.Bool(False, xor=['save_unmasked_shift'], - desc='write pixel shift volume') - shift_out_file = File(argstr='--saveshift=%s', - desc='filename for saving pixel shift volume') + save_shift = traits.Bool( + False, xor=['save_unmasked_shift'], desc='write pixel shift volume') + shift_out_file = File( + argstr='--saveshift=%s', desc='filename for saving pixel shift volume') save_unmasked_shift = traits.Bool( - argstr='--unmaskshift', xor=['save_shift'], + argstr='--unmaskshift', + xor=['save_shift'], desc='saves the unmasked shiftmap when using --saveshift') # Special outputs: fieldmap (fmap) - save_fmap = traits.Bool(False, xor=['save_unmasked_fmap'], - desc='write field map volume') - fmap_out_file = File(argstr='--savefmap=%s', - desc='filename for saving fieldmap (rad/s)') + save_fmap = traits.Bool( + False, xor=['save_unmasked_fmap'], desc='write field map volume') + fmap_out_file = File( + argstr='--savefmap=%s', desc='filename for saving fieldmap (rad/s)') save_unmasked_fmap = traits.Bool( - False, argstr='--unmaskfmap', xor=['save_fmap'], + False, + argstr='--unmaskfmap', + xor=['save_fmap'], desc='saves the unmasked fieldmap when using --savefmap') @@ -1469,10 +1751,10 @@ def _parse_inputs(self, skip=None): # Handle shift output if not isdefined(self.inputs.shift_out_file): - vsm_save_masked = (isdefined(self.inputs.save_shift) and - self.inputs.save_shift) - vsm_save_unmasked = (isdefined(self.inputs.save_unmasked_shift) and - self.inputs.save_unmasked_shift) + vsm_save_masked = (isdefined(self.inputs.save_shift) + and self.inputs.save_shift) + vsm_save_unmasked = (isdefined(self.inputs.save_unmasked_shift) + and self.inputs.save_unmasked_shift) if (vsm_save_masked or vsm_save_unmasked): trait_spec = self.inputs.trait('shift_out_file') @@ -1498,10 +1780,10 @@ def _parse_inputs(self, skip=None): # Handle fieldmap output if not isdefined(self.inputs.fmap_out_file): - fmap_save_masked = (isdefined(self.inputs.save_fmap) and - self.inputs.save_fmap) - fmap_save_unmasked = (isdefined(self.inputs.save_unmasked_fmap) and - self.inputs.save_unmasked_fmap) + fmap_save_masked = (isdefined(self.inputs.save_fmap) + and self.inputs.save_fmap) + fmap_save_unmasked = (isdefined(self.inputs.save_unmasked_fmap) + and self.inputs.save_unmasked_fmap) if (fmap_save_masked or fmap_save_unmasked): trait_spec = self.inputs.trait('fmap_out_file') @@ -1529,54 +1811,68 @@ def _parse_inputs(self, skip=None): class PRELUDEInputSpec(FSLCommandInputSpec): - complex_phase_file = File(exists=True, argstr='--complex=%s', - mandatory=True, xor=[ - 'magnitude_file', 'phase_file'], - desc='complex phase input volume') - magnitude_file = File(exists=True, argstr='--abs=%s', - mandatory=True, - xor=['complex_phase_file'], - desc='file containing magnitude image') - phase_file = File(exists=True, argstr='--phase=%s', - mandatory=True, - xor=['complex_phase_file'], - desc='raw phase file') - unwrapped_phase_file = File(genfile=True, - argstr='--unwrap=%s', - desc='file containing unwrapepd phase', - hash_files=False) - num_partitions = traits.Int(argstr='--numphasesplit=%d', - desc='number of phase partitions to use') + complex_phase_file = File( + exists=True, + argstr='--complex=%s', + mandatory=True, + xor=['magnitude_file', 'phase_file'], + desc='complex phase input volume') + magnitude_file = File( + exists=True, + argstr='--abs=%s', + mandatory=True, + xor=['complex_phase_file'], + desc='file containing magnitude image') + phase_file = File( + exists=True, + argstr='--phase=%s', + mandatory=True, + xor=['complex_phase_file'], + desc='raw phase file') + unwrapped_phase_file = File( + genfile=True, + argstr='--unwrap=%s', + desc='file containing unwrapepd phase', + hash_files=False) + num_partitions = traits.Int( + argstr='--numphasesplit=%d', desc='number of phase partitions to use') labelprocess2d = traits.Bool( argstr='--labelslices', desc='does label processing in 2D (slice at a time)') - process2d = traits.Bool(argstr='--slices', - xor=['labelprocess2d'], - desc='does all processing in 2D (slice at a time)') - process3d = traits.Bool(argstr='--force3D', - xor=['labelprocess2d', 'process2d'], - desc='forces all processing to be full 3D') - threshold = traits.Float(argstr='--thresh=%.10f', - desc='intensity threshold for masking') - mask_file = File(exists=True, argstr='--mask=%s', - desc='filename of mask input volume') - start = traits.Int(argstr='--start=%d', - desc='first image number to process (default 0)') - end = traits.Int(argstr='--end=%d', - desc='final image number to process (default Inf)') - savemask_file = File(argstr='--savemask=%s', - desc='saving the mask volume', hash_files=False) - rawphase_file = File(argstr='--rawphase=%s', - desc='saving the raw phase output', hash_files=False) - label_file = File(argstr='--labels=%s', - desc='saving the area labels output', hash_files=False) - removeramps = traits.Bool(argstr='--removeramps', - desc='remove phase ramps during unwrapping') + process2d = traits.Bool( + argstr='--slices', + xor=['labelprocess2d'], + desc='does all processing in 2D (slice at a time)') + process3d = traits.Bool( + argstr='--force3D', + xor=['labelprocess2d', 'process2d'], + desc='forces all processing to be full 3D') + threshold = traits.Float( + argstr='--thresh=%.10f', desc='intensity threshold for masking') + mask_file = File( + exists=True, argstr='--mask=%s', desc='filename of mask input volume') + start = traits.Int( + argstr='--start=%d', desc='first image number to process (default 0)') + end = traits.Int( + argstr='--end=%d', desc='final image number to process (default Inf)') + savemask_file = File( + argstr='--savemask=%s', + desc='saving the mask volume', + hash_files=False) + rawphase_file = File( + argstr='--rawphase=%s', + desc='saving the raw phase output', + hash_files=False) + label_file = File( + argstr='--labels=%s', + desc='saving the area labels output', + hash_files=False) + removeramps = traits.Bool( + argstr='--removeramps', desc='remove phase ramps during unwrapping') class PRELUDEOutputSpec(TraitedSpec): - unwrapped_phase_file = File(exists=True, - desc='unwrapped phase file') + unwrapped_phase_file = File(exists=True, desc='unwrapped phase file') class PRELUDE(FSLCommand): @@ -1601,11 +1897,11 @@ def _list_outputs(self): out_file = self.inputs.unwrapped_phase_file if not isdefined(out_file): if isdefined(self.inputs.phase_file): - out_file = self._gen_fname(self.inputs.phase_file, - suffix='_unwrapped') + out_file = self._gen_fname( + self.inputs.phase_file, suffix='_unwrapped') elif isdefined(self.inputs.complex_phase_file): - out_file = self._gen_fname(self.inputs.complex_phase_file, - suffix='_phase_unwrapped') + out_file = self._gen_fname( + self.inputs.complex_phase_file, suffix='_phase_unwrapped') outputs['unwrapped_phase_file'] = os.path.abspath(out_file) return outputs @@ -1617,36 +1913,58 @@ def _gen_filename(self, name): class FIRSTInputSpec(FSLCommandInputSpec): in_file = File( - exists=True, mandatory=True, position=-2, copyfile=False, - argstr='-i %s', desc='input data file') + exists=True, + mandatory=True, + position=-2, + copyfile=False, + argstr='-i %s', + desc='input data file') out_file = File( - 'segmented', usedefault=True, mandatory=True, position=-1, - argstr='-o %s', desc='output data file', hash_files=False) - verbose = traits.Bool(argstr='-v', position=1, - desc="Use verbose logging.") + 'segmented', + usedefault=True, + mandatory=True, + position=-1, + argstr='-o %s', + desc='output data file', + hash_files=False) + verbose = traits.Bool(argstr='-v', position=1, desc="Use verbose logging.") brain_extracted = traits.Bool( - argstr='-b', position=2, + argstr='-b', + position=2, desc="Input structural image is already brain-extracted") no_cleanup = traits.Bool( - argstr='-d', position=3, + argstr='-d', + position=3, desc="Input structural image is already brain-extracted") method = traits.Enum( - 'auto', 'fast', 'none', xor=['method_as_numerical_threshold'], - argstr='-m %s', position=4, usedefault=True, + 'auto', + 'fast', + 'none', + xor=['method_as_numerical_threshold'], + argstr='-m %s', + position=4, + usedefault=True, desc=("Method must be one of auto, fast, none, or it can be entered " "using the 'method_as_numerical_threshold' input")) method_as_numerical_threshold = traits.Float( - argstr='-m %.4f', position=4, + argstr='-m %.4f', + position=4, desc=("Specify a numerical threshold value or use the 'method' input " "to choose auto, fast, or none")) list_of_specific_structures = traits.List( - traits.Str, argstr='-s %s', sep=',', position=5, minlen=1, + traits.Str, + argstr='-s %s', + sep=',', + position=5, + minlen=1, desc='Runs only on the specified structures (e.g. L_Hipp, R_Hipp' - 'L_Accu, R_Accu, L_Amyg, R_Amyg' - 'L_Caud, R_Caud, L_Pall, R_Pall' - 'L_Puta, R_Puta, L_Thal, R_Thal, BrStem') + 'L_Accu, R_Accu, L_Amyg, R_Amyg' + 'L_Caud, R_Caud, L_Pall, R_Pall' + 'L_Puta, R_Puta, L_Thal, R_Thal, BrStem') affine_file = File( - exists=True, position=6, argstr='-a %s', + exists=True, + position=6, + argstr='-a %s', desc=('Affine matrix to use (e.g. img2std.mat) (does not ' 're-run registration)')) @@ -1656,14 +1974,15 @@ class FIRSTOutputSpec(TraitedSpec): File(exists=True), desc='VTK format meshes for each subcortical region') bvars = OutputMultiPath( - File(exists=True), - desc='bvars for each subcortical region') + File(exists=True), desc='bvars for each subcortical region') original_segmentations = File( - exists=True, desc=('3D image file containing the segmented regions ' - 'as integer values. Uses CMA labelling')) + exists=True, + desc=('3D image file containing the segmented regions ' + 'as integer values. Uses CMA labelling')) segmentation_file = File( - exists=True, desc=('4D image file containing a single volume per ' - 'segmented region')) + exists=True, + desc=('4D image file containing a single volume per ' + 'segmented region')) class FIRST(FSLCommand): @@ -1693,14 +2012,11 @@ def _list_outputs(self): if isdefined(self.inputs.list_of_specific_structures): structures = self.inputs.list_of_specific_structures else: - structures = ['L_Hipp', 'R_Hipp', - 'L_Accu', 'R_Accu', - 'L_Amyg', 'R_Amyg', - 'L_Caud', 'R_Caud', - 'L_Pall', 'R_Pall', - 'L_Puta', 'R_Puta', - 'L_Thal', 'R_Thal', - 'BrStem'] + structures = [ + 'L_Hipp', 'R_Hipp', 'L_Accu', 'R_Accu', 'L_Amyg', 'R_Amyg', + 'L_Caud', 'R_Caud', 'L_Pall', 'R_Pall', 'L_Puta', 'R_Puta', + 'L_Thal', 'R_Thal', 'BrStem' + ] outputs['original_segmentations'] = \ self._gen_fname('original_segmentations') outputs['segmentation_file'] = self._gen_fname('segmentation_file') @@ -1715,8 +2031,8 @@ def _gen_fname(self, name): method = 'none' if isdefined(self.inputs.method) and self.inputs.method != 'none': method = 'fast' - if (self.inputs.list_of_specific_structures and - self.inputs.method == 'auto'): + if (self.inputs.list_of_specific_structures + and self.inputs.method == 'auto'): method = 'none' if isdefined(self.inputs.method_as_numerical_threshold): diff --git a/nipype/interfaces/fsl/tests/test_FILMGLS.py b/nipype/interfaces/fsl/tests/test_FILMGLS.py index 4ac8756a47..9676486751 100644 --- a/nipype/interfaces/fsl/tests/test_FILMGLS.py +++ b/nipype/interfaces/fsl/tests/test_FILMGLS.py @@ -3,47 +3,124 @@ def test_filmgls(): - input_map = dict(args=dict(argstr='%s',), - autocorr_estimate_only=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='-ac',), - autocorr_noestimate=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='-noest',), - brightness_threshold=dict(argstr='-epith %d',), - design_file=dict(argstr='%s',), - environ=dict(usedefault=True,), - fit_armodel=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='-ar',), - full_data=dict(argstr='-v',), - ignore_exception=dict(usedefault=True,), - in_file=dict(mandatory=True, argstr='%s',), - mask_size=dict(argstr='-ms %d',), - multitaper_product=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='-mt %d',), - output_pwdata=dict(argstr='-output_pwdata',), - output_type=dict(), - results_dir=dict(usedefault=True, argstr='-rn %s',), - smooth_autocorr=dict(argstr='-sa',), - threshold=dict(argstr='%f',), - tukey_window=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='-tukey %d',), - use_pava=dict(argstr='-pava',), - ) - input_map2 = dict(args=dict(argstr='%s',), - autocorr_estimate_only=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='--ac',), - autocorr_noestimate=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='--noest',), - brightness_threshold=dict(argstr='--epith=%d',), - design_file=dict(argstr='--pd=%s',), - environ=dict(usedefault=True,), - fit_armodel=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='--ar',), - full_data=dict(argstr='-v',), - ignore_exception=dict(usedefault=True,), - in_file=dict(mandatory=True, argstr='--in=%s',), - mask_size=dict(argstr='--ms=%d',), - multitaper_product=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='--mt=%d',), - output_pwdata=dict(argstr='--outputPWdata',), - output_type=dict(), - results_dir=dict(argstr='--rn=%s', usedefault=True,), - smooth_autocorr=dict(argstr='--sa',), - terminal_output=dict(), - threshold=dict(usedefault=True, argstr='--thr=%f',), - tukey_window=dict(xor=['autocorr_estimate_only', 'fit_armodel', 'tukey_window', 'multitaper_product', 'use_pava', 'autocorr_noestimate'], argstr='--tukey=%d',), - use_pava=dict(argstr='--pava',), - ) + input_map = dict( + args=dict(argstr='%s', ), + autocorr_estimate_only=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='-ac', + ), + autocorr_noestimate=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='-noest', + ), + brightness_threshold=dict(argstr='-epith %d', ), + design_file=dict(argstr='%s', ), + environ=dict(usedefault=True, ), + fit_armodel=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='-ar', + ), + full_data=dict(argstr='-v', ), + ignore_exception=dict(usedefault=True, ), + in_file=dict( + mandatory=True, + argstr='%s', + ), + mask_size=dict(argstr='-ms %d', ), + multitaper_product=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='-mt %d', + ), + output_pwdata=dict(argstr='-output_pwdata', ), + output_type=dict(), + results_dir=dict( + usedefault=True, + argstr='-rn %s', + ), + smooth_autocorr=dict(argstr='-sa', ), + threshold=dict(argstr='%f', ), + tukey_window=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='-tukey %d', + ), + use_pava=dict(argstr='-pava', ), + ) + input_map2 = dict( + args=dict(argstr='%s', ), + autocorr_estimate_only=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='--ac', + ), + autocorr_noestimate=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='--noest', + ), + brightness_threshold=dict(argstr='--epith=%d', ), + design_file=dict(argstr='--pd=%s', ), + environ=dict(usedefault=True, ), + fit_armodel=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='--ar', + ), + full_data=dict(argstr='-v', ), + ignore_exception=dict(usedefault=True, ), + in_file=dict( + mandatory=True, + argstr='--in=%s', + ), + mask_size=dict(argstr='--ms=%d', ), + multitaper_product=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='--mt=%d', + ), + output_pwdata=dict(argstr='--outputPWdata', ), + output_type=dict(), + results_dir=dict( + argstr='--rn=%s', + usedefault=True, + ), + smooth_autocorr=dict(argstr='--sa', ), + terminal_output=dict(), + threshold=dict( + usedefault=True, + argstr='--thr=%f', + ), + tukey_window=dict( + xor=[ + 'autocorr_estimate_only', 'fit_armodel', 'tukey_window', + 'multitaper_product', 'use_pava', 'autocorr_noestimate' + ], + argstr='--tukey=%d', + ), + use_pava=dict(argstr='--pava', ), + ) instance = FILMGLS() if isinstance(instance.inputs, FILMGLSInputSpec): for key, metadata in list(input_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_Level1Design_functions.py b/nipype/interfaces/fsl/tests/test_Level1Design_functions.py index b7573f7454..44c04d41d5 100644 --- a/nipype/interfaces/fsl/tests/test_Level1Design_functions.py +++ b/nipype/interfaces/fsl/tests/test_Level1Design_functions.py @@ -7,26 +7,26 @@ def test_level1design(tmpdir): old = tmpdir.chdir() l = Level1Design() - runinfo = dict(cond=[{'name': 'test_condition', 'onset': [0, 10], - 'duration':[10, 10]}],regress=[]) + runinfo = dict( + cond=[{ + 'name': 'test_condition', + 'onset': [0, 10], + 'duration': [10, 10] + }], + regress=[]) runidx = 0 contrasts = Undefined do_tempfilter = False orthogonalization = {} - basic_ev_parameters = {'temporalderiv':False} - convolution_variants = [ - ('custom', 7, {'temporalderiv':False, 'bfcustompath':'/some/path'}), - ('hrf', 3, basic_ev_parameters), - ('dgamma', 3, basic_ev_parameters), - ('gamma', 2, basic_ev_parameters), - ('none', 0, basic_ev_parameters) - ] + basic_ev_parameters = {'temporalderiv': False} + convolution_variants = [('custom', 7, { + 'temporalderiv': False, + 'bfcustompath': '/some/path' + }), ('hrf', 3, basic_ev_parameters), ('dgamma', 3, basic_ev_parameters), + ('gamma', 2, basic_ev_parameters), + ('none', 0, basic_ev_parameters)] for key, val, ev_parameters in convolution_variants: - output_num, output_txt = Level1Design._create_ev_files(l, os.getcwd(), - runinfo, runidx, - ev_parameters, - orthogonalization, - contrasts, - do_tempfilter, - key) + output_num, output_txt = Level1Design._create_ev_files( + l, os.getcwd(), runinfo, runidx, ev_parameters, orthogonalization, + contrasts, do_tempfilter, key) assert "set fmri(convolve1) {0}".format(val) in output_txt diff --git a/nipype/interfaces/fsl/tests/test_auto_AR1Image.py b/nipype/interfaces/fsl/tests/test_auto_AR1Image.py index e21844346a..45828cd552 100644 --- a/nipype/interfaces/fsl/tests/test_auto_AR1Image.py +++ b/nipype/interfaces/fsl/tests/test_auto_AR1Image.py @@ -4,52 +4,58 @@ def test_AR1Image_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%sar1', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%sar1', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AR1Image.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AR1Image_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = AR1Image.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py b/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py index dc5daa76c5..bb49910c2a 100644 --- a/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py +++ b/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py @@ -4,44 +4,49 @@ def test_AccuracyTester_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mel_icas=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=3, - ), - output_directory=dict(argstr='%s', - mandatory=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trained_wts_file=dict(argstr='%s', - mandatory=True, - position=1, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mel_icas=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=3, + ), + output_directory=dict( + argstr='%s', + mandatory=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trained_wts_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), ) inputs = AccuracyTester.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AccuracyTester_outputs(): - output_map = dict(output_directory=dict(argstr='%s', - position=1, - ), - ) + output_map = dict( + output_directory=dict( + argstr='%s', + position=1, + ), ) outputs = AccuracyTester.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py b/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py index f5bad0d6f2..673c0f17f7 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py @@ -4,52 +4,58 @@ def test_ApplyMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - mask_file=dict(argstr='-mas %s', - mandatory=True, - position=4, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + mask_file=dict( + argstr='-mas %s', + mandatory=True, + position=4, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ApplyMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyMask_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ApplyMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py b/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py index c60fc9f5de..645573a93a 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py @@ -4,57 +4,60 @@ def test_ApplyTOPUP_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - datatype=dict(argstr='-d=%s', - ), - encoding_file=dict(argstr='--datain=%s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='--imain=%s', - mandatory=True, - sep=',', - ), - in_index=dict(argstr='--inindex=%s', - sep=',', - ), - in_topup_fieldcoef=dict(argstr='--topup=%s', - copyfile=False, - requires=['in_topup_movpar'], - ), - in_topup_movpar=dict(copyfile=False, - requires=['in_topup_fieldcoef'], - ), - interp=dict(argstr='--interp=%s', - ), - method=dict(argstr='--method=%s', - ), - out_corrected=dict(argstr='--out=%s', - name_source=['in_files'], - name_template='%s_corrected', - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + datatype=dict(argstr='-d=%s', ), + encoding_file=dict( + argstr='--datain=%s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='--imain=%s', + mandatory=True, + sep=',', + ), + in_index=dict( + argstr='--inindex=%s', + sep=',', + ), + in_topup_fieldcoef=dict( + argstr='--topup=%s', + copyfile=False, + requires=['in_topup_movpar'], + ), + in_topup_movpar=dict( + copyfile=False, + requires=['in_topup_fieldcoef'], + ), + interp=dict(argstr='--interp=%s', ), + method=dict(argstr='--method=%s', ), + out_corrected=dict( + argstr='--out=%s', + name_source=['in_files'], + name_template='%s_corrected', + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ApplyTOPUP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyTOPUP_outputs(): - output_map = dict(out_corrected=dict(), - ) + output_map = dict(out_corrected=dict(), ) outputs = ApplyTOPUP.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py b/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py index 7056d1d363..8bcbf64307 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py @@ -4,67 +4,66 @@ def test_ApplyWarp_inputs(): - input_map = dict(abswarp=dict(argstr='--abs', - xor=['relwarp'], - ), - args=dict(argstr='%s', - ), - datatype=dict(argstr='--datatype=%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - field_file=dict(argstr='--warp=%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--in=%s', - mandatory=True, - position=0, - ), - interp=dict(argstr='--interp=%s', - position=-2, - ), - mask_file=dict(argstr='--mask=%s', - ), - out_file=dict(argstr='--out=%s', - genfile=True, - hash_files=False, - position=2, - ), - output_type=dict(), - postmat=dict(argstr='--postmat=%s', - ), - premat=dict(argstr='--premat=%s', - ), - ref_file=dict(argstr='--ref=%s', - mandatory=True, - position=1, - ), - relwarp=dict(argstr='--rel', - position=-1, - xor=['abswarp'], - ), - superlevel=dict(argstr='--superlevel=%s', - ), - supersample=dict(argstr='--super', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + abswarp=dict( + argstr='--abs', + xor=['relwarp'], + ), + args=dict(argstr='%s', ), + datatype=dict(argstr='--datatype=%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + field_file=dict(argstr='--warp=%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--in=%s', + mandatory=True, + position=0, + ), + interp=dict( + argstr='--interp=%s', + position=-2, + ), + mask_file=dict(argstr='--mask=%s', ), + out_file=dict( + argstr='--out=%s', + genfile=True, + hash_files=False, + position=2, + ), + output_type=dict(), + postmat=dict(argstr='--postmat=%s', ), + premat=dict(argstr='--premat=%s', ), + ref_file=dict( + argstr='--ref=%s', + mandatory=True, + position=1, + ), + relwarp=dict( + argstr='--rel', + position=-1, + xor=['abswarp'], + ), + superlevel=dict(argstr='--superlevel=%s', ), + supersample=dict(argstr='--super', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ApplyWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyWarp_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ApplyWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py b/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py index 9e8b4d0877..adb132db1c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py @@ -4,159 +4,163 @@ def test_ApplyXFM_inputs(): - input_map = dict(angle_rep=dict(argstr='-anglerep %s', - ), - apply_isoxfm=dict(argstr='-applyisoxfm %f', - xor=['apply_xfm'], - ), - apply_xfm=dict(argstr='-applyxfm', - usedefault=True, - ), - args=dict(argstr='%s', - ), - bbrslope=dict(argstr='-bbrslope %f', - min_ver='5.0.0', - ), - bbrtype=dict(argstr='-bbrtype %s', - min_ver='5.0.0', - ), - bgvalue=dict(argstr='-setbackground %f', - ), - bins=dict(argstr='-bins %d', - ), - coarse_search=dict(argstr='-coarsesearch %d', - units='degrees', - ), - cost=dict(argstr='-cost %s', - ), - cost_func=dict(argstr='-searchcost %s', - ), - datatype=dict(argstr='-datatype %s', - ), - display_init=dict(argstr='-displayinit', - ), - dof=dict(argstr='-dof %d', - ), - echospacing=dict(argstr='-echospacing %f', - min_ver='5.0.0', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fieldmap=dict(argstr='-fieldmap %s', - min_ver='5.0.0', - ), - fieldmapmask=dict(argstr='-fieldmapmask %s', - min_ver='5.0.0', - ), - fine_search=dict(argstr='-finesearch %d', - units='degrees', - ), - force_scaling=dict(argstr='-forcescaling', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - position=0, - ), - in_matrix_file=dict(argstr='-init %s', - ), - in_weight=dict(argstr='-inweight %s', - ), - interp=dict(argstr='-interp %s', - ), - min_sampling=dict(argstr='-minsampling %f', - units='mm', - ), - no_clamp=dict(argstr='-noclamp', - ), - no_resample=dict(argstr='-noresample', - ), - no_resample_blur=dict(argstr='-noresampblur', - ), - no_search=dict(argstr='-nosearch', - ), - out_file=dict(argstr='-out %s', - hash_files=False, - name_source=['in_file'], - name_template='%s_flirt', - position=2, - ), - out_log=dict(keep_extension=True, - name_source=['in_file'], - name_template='%s_flirt.log', - requires=['save_log'], - ), - out_matrix_file=dict(argstr='-omat %s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s_flirt.mat', - position=3, - ), - output_type=dict(), - padding_size=dict(argstr='-paddingsize %d', - units='voxels', - ), - pedir=dict(argstr='-pedir %d', - min_ver='5.0.0', - ), - ref_weight=dict(argstr='-refweight %s', - ), - reference=dict(argstr='-ref %s', - mandatory=True, - position=1, - ), - rigid2D=dict(argstr='-2D', - ), - save_log=dict(), - schedule=dict(argstr='-schedule %s', - ), - searchr_x=dict(argstr='-searchrx %s', - units='degrees', - ), - searchr_y=dict(argstr='-searchry %s', - units='degrees', - ), - searchr_z=dict(argstr='-searchrz %s', - units='degrees', - ), - sinc_width=dict(argstr='-sincwidth %d', - units='voxels', - ), - sinc_window=dict(argstr='-sincwindow %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uses_qform=dict(argstr='-usesqform', - ), - verbose=dict(argstr='-verbose %d', - ), - wm_seg=dict(argstr='-wmseg %s', - min_ver='5.0.0', - ), - wmcoords=dict(argstr='-wmcoords %s', - min_ver='5.0.0', - ), - wmnorms=dict(argstr='-wmnorms %s', - min_ver='5.0.0', - ), + input_map = dict( + angle_rep=dict(argstr='-anglerep %s', ), + apply_isoxfm=dict( + argstr='-applyisoxfm %f', + xor=['apply_xfm'], + ), + apply_xfm=dict( + argstr='-applyxfm', + usedefault=True, + ), + args=dict(argstr='%s', ), + bbrslope=dict( + argstr='-bbrslope %f', + min_ver='5.0.0', + ), + bbrtype=dict( + argstr='-bbrtype %s', + min_ver='5.0.0', + ), + bgvalue=dict(argstr='-setbackground %f', ), + bins=dict(argstr='-bins %d', ), + coarse_search=dict( + argstr='-coarsesearch %d', + units='degrees', + ), + cost=dict(argstr='-cost %s', ), + cost_func=dict(argstr='-searchcost %s', ), + datatype=dict(argstr='-datatype %s', ), + display_init=dict(argstr='-displayinit', ), + dof=dict(argstr='-dof %d', ), + echospacing=dict( + argstr='-echospacing %f', + min_ver='5.0.0', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fieldmap=dict( + argstr='-fieldmap %s', + min_ver='5.0.0', + ), + fieldmapmask=dict( + argstr='-fieldmapmask %s', + min_ver='5.0.0', + ), + fine_search=dict( + argstr='-finesearch %d', + units='degrees', + ), + force_scaling=dict(argstr='-forcescaling', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + position=0, + ), + in_matrix_file=dict(argstr='-init %s', ), + in_weight=dict(argstr='-inweight %s', ), + interp=dict(argstr='-interp %s', ), + min_sampling=dict( + argstr='-minsampling %f', + units='mm', + ), + no_clamp=dict(argstr='-noclamp', ), + no_resample=dict(argstr='-noresample', ), + no_resample_blur=dict(argstr='-noresampblur', ), + no_search=dict(argstr='-nosearch', ), + out_file=dict( + argstr='-out %s', + hash_files=False, + name_source=['in_file'], + name_template='%s_flirt', + position=2, + ), + out_log=dict( + keep_extension=True, + name_source=['in_file'], + name_template='%s_flirt.log', + requires=['save_log'], + ), + out_matrix_file=dict( + argstr='-omat %s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s_flirt.mat', + position=3, + ), + output_type=dict(), + padding_size=dict( + argstr='-paddingsize %d', + units='voxels', + ), + pedir=dict( + argstr='-pedir %d', + min_ver='5.0.0', + ), + ref_weight=dict(argstr='-refweight %s', ), + reference=dict( + argstr='-ref %s', + mandatory=True, + position=1, + ), + rigid2D=dict(argstr='-2D', ), + save_log=dict(), + schedule=dict(argstr='-schedule %s', ), + searchr_x=dict( + argstr='-searchrx %s', + units='degrees', + ), + searchr_y=dict( + argstr='-searchry %s', + units='degrees', + ), + searchr_z=dict( + argstr='-searchrz %s', + units='degrees', + ), + sinc_width=dict( + argstr='-sincwidth %d', + units='voxels', + ), + sinc_window=dict(argstr='-sincwindow %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uses_qform=dict(argstr='-usesqform', ), + verbose=dict(argstr='-verbose %d', ), + wm_seg=dict( + argstr='-wmseg %s', + min_ver='5.0.0', + ), + wmcoords=dict( + argstr='-wmcoords %s', + min_ver='5.0.0', + ), + wmnorms=dict( + argstr='-wmnorms %s', + min_ver='5.0.0', + ), ) inputs = ApplyXFM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyXFM_outputs(): - output_map = dict(out_file=dict(), - out_log=dict(), - out_matrix_file=dict(), + output_map = dict( + out_file=dict(), + out_log=dict(), + out_matrix_file=dict(), ) outputs = ApplyXFM.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_AvScale.py b/nipype/interfaces/fsl/tests/test_auto_AvScale.py index eb582cc783..c2c0503c6d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_AvScale.py +++ b/nipype/interfaces/fsl/tests/test_auto_AvScale.py @@ -4,45 +4,48 @@ def test_AvScale_inputs(): - input_map = dict(all_param=dict(argstr='--allparams', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mat_file=dict(argstr='%s', - position=-2, - ), - ref_file=dict(argstr='%s', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + all_param=dict(argstr='--allparams', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mat_file=dict( + argstr='%s', + position=-2, + ), + ref_file=dict( + argstr='%s', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AvScale.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AvScale_outputs(): - output_map = dict(average_scaling=dict(), - backward_half_transform=dict(), - determinant=dict(), - forward_half_transform=dict(), - left_right_orientation_preserved=dict(), - rot_angles=dict(), - rotation_translation_matrix=dict(), - scales=dict(), - skews=dict(), - translations=dict(), + output_map = dict( + average_scaling=dict(), + backward_half_transform=dict(), + determinant=dict(), + forward_half_transform=dict(), + left_right_orientation_preserved=dict(), + rot_angles=dict(), + rotation_translation_matrix=dict(), + scales=dict(), + skews=dict(), + translations=dict(), ) outputs = AvScale.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_B0Calc.py b/nipype/interfaces/fsl/tests/test_auto_B0Calc.py index a03dba1061..23a3c1a944 100644 --- a/nipype/interfaces/fsl/tests/test_auto_B0Calc.py +++ b/nipype/interfaces/fsl/tests/test_auto_B0Calc.py @@ -4,68 +4,66 @@ def test_B0Calc_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - chi_air=dict(argstr='--chi0=%e', - ), - compute_xyz=dict(argstr='--xyz', - ), - delta=dict(argstr='-d %e', - ), - directconv=dict(argstr='--directconv', - ), - environ=dict(nohash=True, - usedefault=True, - ), - extendboundary=dict(argstr='--extendboundary=%0.2f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=0, - ), - out_file=dict(argstr='-o %s', - name_source=['in_file'], - name_template='%s_b0field', - output_name='out_file', - position=1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - x_b0=dict(argstr='--b0x=%0.2f', - xor=['xyz_b0'], - ), - x_grad=dict(argstr='--gx=%0.4f', - ), - xyz_b0=dict(argstr='--b0x=%0.2f --b0y=%0.2f --b0=%0.2f', - xor=['x_b0', 'y_b0', 'z_b0'], - ), - y_b0=dict(argstr='--b0y=%0.2f', - xor=['xyz_b0'], - ), - y_grad=dict(argstr='--gy=%0.4f', - ), - z_b0=dict(argstr='--b0=%0.2f', - xor=['xyz_b0'], - ), - z_grad=dict(argstr='--gz=%0.4f', - ), + input_map = dict( + args=dict(argstr='%s', ), + chi_air=dict(argstr='--chi0=%e', ), + compute_xyz=dict(argstr='--xyz', ), + delta=dict(argstr='-d %e', ), + directconv=dict(argstr='--directconv', ), + environ=dict( + nohash=True, + usedefault=True, + ), + extendboundary=dict(argstr='--extendboundary=%0.2f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=0, + ), + out_file=dict( + argstr='-o %s', + name_source=['in_file'], + name_template='%s_b0field', + output_name='out_file', + position=1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + x_b0=dict( + argstr='--b0x=%0.2f', + xor=['xyz_b0'], + ), + x_grad=dict(argstr='--gx=%0.4f', ), + xyz_b0=dict( + argstr='--b0x=%0.2f --b0y=%0.2f --b0=%0.2f', + xor=['x_b0', 'y_b0', 'z_b0'], + ), + y_b0=dict( + argstr='--b0y=%0.2f', + xor=['xyz_b0'], + ), + y_grad=dict(argstr='--gy=%0.4f', ), + z_b0=dict( + argstr='--b0=%0.2f', + xor=['xyz_b0'], + ), + z_grad=dict(argstr='--gz=%0.4f', ), ) inputs = B0Calc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_B0Calc_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = B0Calc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py b/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py index 7e57bdea55..91a9d304fd 100644 --- a/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py +++ b/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py @@ -4,103 +4,100 @@ def test_BEDPOSTX5_inputs(): - input_map = dict(all_ard=dict(argstr='--allard', - xor=('no_ard', 'all_ard'), - ), - args=dict(argstr='%s', - ), - burn_in=dict(argstr='-b %d', - ), - burn_in_no_ard=dict(argstr='--burninnoard=%d', - ), - bvals=dict(mandatory=True, - ), - bvecs=dict(mandatory=True, - ), - cnlinear=dict(argstr='--cnonlinear', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - dwi=dict(mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - f0_ard=dict(argstr='--f0 --ardf0', - xor=['f0_noard', 'f0_ard', 'all_ard'], - ), - f0_noard=dict(argstr='--f0', - xor=['f0_noard', 'f0_ard'], - ), - force_dir=dict(argstr='--forcedir', - usedefault=True, - ), - fudge=dict(argstr='-w %d', - ), - grad_dev=dict(), - gradnonlin=dict(argstr='-g', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - logdir=dict(argstr='--logdir=%s', - ), - mask=dict(mandatory=True, - ), - model=dict(argstr='-model %d', - ), - n_fibres=dict(argstr='-n %d', - mandatory=True, - usedefault=True, - ), - n_jumps=dict(argstr='-j %d', - ), - no_ard=dict(argstr='--noard', - xor=('no_ard', 'all_ard'), - ), - no_spat=dict(argstr='--nospat', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - non_linear=dict(argstr='--nonlinear', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - out_dir=dict(argstr='%s', - mandatory=True, - position=1, - usedefault=True, - ), - output_type=dict(), - rician=dict(argstr='--rician', - ), - sample_every=dict(argstr='-s %d', - ), - seed=dict(argstr='--seed=%d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - update_proposal_every=dict(argstr='--updateproposalevery=%d', - ), - use_gpu=dict(), + input_map = dict( + all_ard=dict( + argstr='--allard', + xor=('no_ard', 'all_ard'), + ), + args=dict(argstr='%s', ), + burn_in=dict(argstr='-b %d', ), + burn_in_no_ard=dict(argstr='--burninnoard=%d', ), + bvals=dict(mandatory=True, ), + bvecs=dict(mandatory=True, ), + cnlinear=dict( + argstr='--cnonlinear', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + dwi=dict(mandatory=True, ), + environ=dict( + nohash=True, + usedefault=True, + ), + f0_ard=dict( + argstr='--f0 --ardf0', + xor=['f0_noard', 'f0_ard', 'all_ard'], + ), + f0_noard=dict( + argstr='--f0', + xor=['f0_noard', 'f0_ard'], + ), + force_dir=dict( + argstr='--forcedir', + usedefault=True, + ), + fudge=dict(argstr='-w %d', ), + grad_dev=dict(), + gradnonlin=dict(argstr='-g', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + logdir=dict(argstr='--logdir=%s', ), + mask=dict(mandatory=True, ), + model=dict(argstr='-model %d', ), + n_fibres=dict( + argstr='-n %d', + mandatory=True, + usedefault=True, + ), + n_jumps=dict(argstr='-j %d', ), + no_ard=dict( + argstr='--noard', + xor=('no_ard', 'all_ard'), + ), + no_spat=dict( + argstr='--nospat', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + non_linear=dict( + argstr='--nonlinear', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + out_dir=dict( + argstr='%s', + mandatory=True, + position=1, + usedefault=True, + ), + output_type=dict(), + rician=dict(argstr='--rician', ), + sample_every=dict(argstr='-s %d', ), + seed=dict(argstr='--seed=%d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + update_proposal_every=dict(argstr='--updateproposalevery=%d', ), + use_gpu=dict(), ) inputs = BEDPOSTX5.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BEDPOSTX5_outputs(): - output_map = dict(dyads=dict(), - dyads_dispersion=dict(), - mean_S0samples=dict(), - mean_dsamples=dict(), - mean_fsamples=dict(), - mean_phsamples=dict(), - mean_thsamples=dict(), - merged_fsamples=dict(), - merged_phsamples=dict(), - merged_thsamples=dict(), + output_map = dict( + dyads=dict(), + dyads_dispersion=dict(), + mean_S0samples=dict(), + mean_dsamples=dict(), + mean_fsamples=dict(), + mean_phsamples=dict(), + mean_thsamples=dict(), + merged_fsamples=dict(), + merged_phsamples=dict(), + merged_thsamples=dict(), ) outputs = BEDPOSTX5.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_BET.py b/nipype/interfaces/fsl/tests/test_auto_BET.py index a0ba58c88a..132e7bc402 100644 --- a/nipype/interfaces/fsl/tests/test_auto_BET.py +++ b/nipype/interfaces/fsl/tests/test_auto_BET.py @@ -4,91 +4,103 @@ def test_BET_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - center=dict(argstr='-c %s', - units='voxels', - ), - environ=dict(nohash=True, - usedefault=True, - ), - frac=dict(argstr='-f %.2f', - ), - functional=dict(argstr='-F', - xor=('functional', 'reduce_bias', 'robust', 'padding', 'remove_eyes', 'surfaces', 't2_guided'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - mask=dict(argstr='-m', - ), - mesh=dict(argstr='-e', - ), - no_output=dict(argstr='-n', - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=1, - ), - outline=dict(argstr='-o', - ), - output_type=dict(), - padding=dict(argstr='-Z', - xor=('functional', 'reduce_bias', 'robust', 'padding', 'remove_eyes', 'surfaces', 't2_guided'), - ), - radius=dict(argstr='-r %d', - units='mm', - ), - reduce_bias=dict(argstr='-B', - xor=('functional', 'reduce_bias', 'robust', 'padding', 'remove_eyes', 'surfaces', 't2_guided'), - ), - remove_eyes=dict(argstr='-S', - xor=('functional', 'reduce_bias', 'robust', 'padding', 'remove_eyes', 'surfaces', 't2_guided'), - ), - robust=dict(argstr='-R', - xor=('functional', 'reduce_bias', 'robust', 'padding', 'remove_eyes', 'surfaces', 't2_guided'), - ), - skull=dict(argstr='-s', - ), - surfaces=dict(argstr='-A', - xor=('functional', 'reduce_bias', 'robust', 'padding', 'remove_eyes', 'surfaces', 't2_guided'), - ), - t2_guided=dict(argstr='-A2 %s', - xor=('functional', 'reduce_bias', 'robust', 'padding', 'remove_eyes', 'surfaces', 't2_guided'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='-t', - ), - vertical_gradient=dict(argstr='-g %.2f', - ), + input_map = dict( + args=dict(argstr='%s', ), + center=dict( + argstr='-c %s', + units='voxels', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + frac=dict(argstr='-f %.2f', ), + functional=dict( + argstr='-F', + xor=('functional', 'reduce_bias', 'robust', 'padding', + 'remove_eyes', 'surfaces', 't2_guided'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + mask=dict(argstr='-m', ), + mesh=dict(argstr='-e', ), + no_output=dict(argstr='-n', ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=1, + ), + outline=dict(argstr='-o', ), + output_type=dict(), + padding=dict( + argstr='-Z', + xor=('functional', 'reduce_bias', 'robust', 'padding', + 'remove_eyes', 'surfaces', 't2_guided'), + ), + radius=dict( + argstr='-r %d', + units='mm', + ), + reduce_bias=dict( + argstr='-B', + xor=('functional', 'reduce_bias', 'robust', 'padding', + 'remove_eyes', 'surfaces', 't2_guided'), + ), + remove_eyes=dict( + argstr='-S', + xor=('functional', 'reduce_bias', 'robust', 'padding', + 'remove_eyes', 'surfaces', 't2_guided'), + ), + robust=dict( + argstr='-R', + xor=('functional', 'reduce_bias', 'robust', 'padding', + 'remove_eyes', 'surfaces', 't2_guided'), + ), + skull=dict(argstr='-s', ), + surfaces=dict( + argstr='-A', + xor=('functional', 'reduce_bias', 'robust', 'padding', + 'remove_eyes', 'surfaces', 't2_guided'), + ), + t2_guided=dict( + argstr='-A2 %s', + xor=('functional', 'reduce_bias', 'robust', 'padding', + 'remove_eyes', 'surfaces', 't2_guided'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='-t', ), + vertical_gradient=dict(argstr='-g %.2f', ), ) inputs = BET.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BET_outputs(): - output_map = dict(inskull_mask_file=dict(), - inskull_mesh_file=dict(), - mask_file=dict(), - meshfile=dict(), - out_file=dict(), - outline_file=dict(), - outskin_mask_file=dict(), - outskin_mesh_file=dict(), - outskull_mask_file=dict(), - outskull_mesh_file=dict(), - skull_mask_file=dict(), + output_map = dict( + inskull_mask_file=dict(), + inskull_mesh_file=dict(), + mask_file=dict(), + meshfile=dict(), + out_file=dict(), + outline_file=dict(), + outskin_mask_file=dict(), + outskin_mesh_file=dict(), + outskull_mask_file=dict(), + outskull_mesh_file=dict(), + skull_mask_file=dict(), ) outputs = BET.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py b/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py index d4c8eed2f9..28a98758d2 100644 --- a/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py @@ -4,62 +4,70 @@ def test_BinaryMaths_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - operand_file=dict(argstr='%s', - mandatory=True, - position=5, - xor=['operand_value'], - ), - operand_value=dict(argstr='%.8f', - mandatory=True, - position=5, - xor=['operand_file'], - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + operand_file=dict( + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value'], + ), + operand_value=dict( + argstr='%.8f', + mandatory=True, + position=5, + xor=['operand_file'], + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BinaryMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BinaryMaths_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = BinaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py b/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py index 2142994a08..65baf20a6d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py +++ b/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py @@ -4,49 +4,54 @@ def test_ChangeDataType_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - mandatory=True, - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + mandatory=True, + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ChangeDataType.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ChangeDataType_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ChangeDataType.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Classifier.py b/nipype/interfaces/fsl/tests/test_auto_Classifier.py index d9e8180f87..3e58078b94 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Classifier.py +++ b/nipype/interfaces/fsl/tests/test_auto_Classifier.py @@ -4,43 +4,46 @@ def test_Classifier_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - artifacts_list_file=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mel_ica=dict(argstr='%s', - copyfile=False, - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresh=dict(argstr='%d', - mandatory=True, - position=-1, - ), - trained_wts_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=2, - ), + input_map = dict( + args=dict(argstr='%s', ), + artifacts_list_file=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mel_ica=dict( + argstr='%s', + copyfile=False, + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresh=dict( + argstr='%d', + mandatory=True, + position=-1, + ), + trained_wts_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=2, + ), ) inputs = Classifier.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Classifier_outputs(): - output_map = dict(artifacts_list_file=dict(), - ) + output_map = dict(artifacts_list_file=dict(), ) outputs = Classifier.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Cleaner.py b/nipype/interfaces/fsl/tests/test_auto_Cleaner.py index 08f40263b5..4071ddc41a 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Cleaner.py +++ b/nipype/interfaces/fsl/tests/test_auto_Cleaner.py @@ -4,52 +4,59 @@ def test_Cleaner_inputs(): - input_map = dict(aggressive=dict(argstr='-A', - position=3, - ), - args=dict(argstr='%s', - ), - artifacts_list_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - cleanup_motion=dict(argstr='-m', - position=2, - ), - confound_file=dict(argstr='-x %s', - position=4, - ), - confound_file_1=dict(argstr='-x %s', - position=5, - ), - confound_file_2=dict(argstr='-x %s', - position=6, - ), - environ=dict(nohash=True, - usedefault=True, - ), - highpass=dict(argstr='-m -h %f', - position=2, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + aggressive=dict( + argstr='-A', + position=3, + ), + args=dict(argstr='%s', ), + artifacts_list_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + cleanup_motion=dict( + argstr='-m', + position=2, + ), + confound_file=dict( + argstr='-x %s', + position=4, + ), + confound_file_1=dict( + argstr='-x %s', + position=5, + ), + confound_file_2=dict( + argstr='-x %s', + position=6, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass=dict( + argstr='-m -h %f', + position=2, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Cleaner.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Cleaner_outputs(): - output_map = dict(cleaned_functional_file=dict(), - ) + output_map = dict(cleaned_functional_file=dict(), ) outputs = Cleaner.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Cluster.py b/nipype/interfaces/fsl/tests/test_auto_Cluster.py index 8085989aad..5ffd5aa485 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Cluster.py +++ b/nipype/interfaces/fsl/tests/test_auto_Cluster.py @@ -4,102 +4,111 @@ def test_Cluster_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - connectivity=dict(argstr='--connectivity=%d', - ), - cope_file=dict(argstr='--cope=%s', - ), - dlh=dict(argstr='--dlh=%.10f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - find_min=dict(argstr='--min', - usedefault=True, - ), - fractional=dict(argstr='--fractional', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--in=%s', - mandatory=True, - ), - minclustersize=dict(argstr='--minclustersize', - usedefault=True, - ), - no_table=dict(argstr='--no_table', - usedefault=True, - ), - num_maxima=dict(argstr='--num=%d', - ), - out_index_file=dict(argstr='--oindex=%s', - hash_files=False, - ), - out_localmax_txt_file=dict(argstr='--olmax=%s', - hash_files=False, - ), - out_localmax_vol_file=dict(argstr='--olmaxim=%s', - hash_files=False, - ), - out_max_file=dict(argstr='--omax=%s', - hash_files=False, - ), - out_mean_file=dict(argstr='--omean=%s', - hash_files=False, - ), - out_pval_file=dict(argstr='--opvals=%s', - hash_files=False, - ), - out_size_file=dict(argstr='--osize=%s', - hash_files=False, - ), - out_threshold_file=dict(argstr='--othresh=%s', - hash_files=False, - ), - output_type=dict(), - peak_distance=dict(argstr='--peakdist=%.10f', - ), - pthreshold=dict(argstr='--pthresh=%.10f', - requires=['dlh', 'volume'], - ), - std_space_file=dict(argstr='--stdvol=%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--thresh=%.10f', - mandatory=True, - ), - use_mm=dict(argstr='--mm', - usedefault=True, - ), - volume=dict(argstr='--volume=%d', - ), - warpfield_file=dict(argstr='--warpvol=%s', - ), - xfm_file=dict(argstr='--xfm=%s', - ), + input_map = dict( + args=dict(argstr='%s', ), + connectivity=dict(argstr='--connectivity=%d', ), + cope_file=dict(argstr='--cope=%s', ), + dlh=dict(argstr='--dlh=%.10f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + find_min=dict( + argstr='--min', + usedefault=True, + ), + fractional=dict( + argstr='--fractional', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--in=%s', + mandatory=True, + ), + minclustersize=dict( + argstr='--minclustersize', + usedefault=True, + ), + no_table=dict( + argstr='--no_table', + usedefault=True, + ), + num_maxima=dict(argstr='--num=%d', ), + out_index_file=dict( + argstr='--oindex=%s', + hash_files=False, + ), + out_localmax_txt_file=dict( + argstr='--olmax=%s', + hash_files=False, + ), + out_localmax_vol_file=dict( + argstr='--olmaxim=%s', + hash_files=False, + ), + out_max_file=dict( + argstr='--omax=%s', + hash_files=False, + ), + out_mean_file=dict( + argstr='--omean=%s', + hash_files=False, + ), + out_pval_file=dict( + argstr='--opvals=%s', + hash_files=False, + ), + out_size_file=dict( + argstr='--osize=%s', + hash_files=False, + ), + out_threshold_file=dict( + argstr='--othresh=%s', + hash_files=False, + ), + output_type=dict(), + peak_distance=dict(argstr='--peakdist=%.10f', ), + pthreshold=dict( + argstr='--pthresh=%.10f', + requires=['dlh', 'volume'], + ), + std_space_file=dict(argstr='--stdvol=%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict( + argstr='--thresh=%.10f', + mandatory=True, + ), + use_mm=dict( + argstr='--mm', + usedefault=True, + ), + volume=dict(argstr='--volume=%d', ), + warpfield_file=dict(argstr='--warpvol=%s', ), + xfm_file=dict(argstr='--xfm=%s', ), ) inputs = Cluster.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Cluster_outputs(): - output_map = dict(index_file=dict(), - localmax_txt_file=dict(), - localmax_vol_file=dict(), - max_file=dict(), - mean_file=dict(), - pval_file=dict(), - size_file=dict(), - threshold_file=dict(), + output_map = dict( + index_file=dict(), + localmax_txt_file=dict(), + localmax_vol_file=dict(), + max_file=dict(), + mean_file=dict(), + pval_file=dict(), + size_file=dict(), + threshold_file=dict(), ) outputs = Cluster.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Complex.py b/nipype/interfaces/fsl/tests/test_auto_Complex.py index 0a2133bb6f..2d2bb78508 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Complex.py +++ b/nipype/interfaces/fsl/tests/test_auto_Complex.py @@ -4,106 +4,166 @@ def test_Complex_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - complex_cartesian=dict(argstr='-complex', - position=1, - xor=['real_polar', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - complex_in_file=dict(argstr='%s', - position=2, - ), - complex_in_file2=dict(argstr='%s', - position=3, - ), - complex_merge=dict(argstr='-complexmerge', - position=1, - xor=['real_polar', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge', 'start_vol', 'end_vol'], - ), - complex_out_file=dict(argstr='%s', - genfile=True, - position=-3, - xor=['complex_out_file', 'magnitude_out_file', 'phase_out_file', 'real_out_file', 'imaginary_out_file', 'real_polar', 'real_cartesian'], - ), - complex_polar=dict(argstr='-complexpolar', - position=1, - xor=['real_polar', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - complex_split=dict(argstr='-complexsplit', - position=1, - xor=['real_polar', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - end_vol=dict(argstr='%d', - position=-1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - imaginary_in_file=dict(argstr='%s', - position=3, - ), - imaginary_out_file=dict(argstr='%s', - genfile=True, - position=-3, - xor=['complex_out_file', 'magnitude_out_file', 'phase_out_file', 'real_polar', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - magnitude_in_file=dict(argstr='%s', - position=2, - ), - magnitude_out_file=dict(argstr='%s', - genfile=True, - position=-4, - xor=['complex_out_file', 'real_out_file', 'imaginary_out_file', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - output_type=dict(), - phase_in_file=dict(argstr='%s', - position=3, - ), - phase_out_file=dict(argstr='%s', - genfile=True, - position=-3, - xor=['complex_out_file', 'real_out_file', 'imaginary_out_file', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - real_cartesian=dict(argstr='-realcartesian', - position=1, - xor=['real_polar', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - real_in_file=dict(argstr='%s', - position=2, - ), - real_out_file=dict(argstr='%s', - genfile=True, - position=-4, - xor=['complex_out_file', 'magnitude_out_file', 'phase_out_file', 'real_polar', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - real_polar=dict(argstr='-realpolar', - position=1, - xor=['real_polar', 'real_cartesian', 'complex_cartesian', 'complex_polar', 'complex_split', 'complex_merge'], - ), - start_vol=dict(argstr='%d', - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + complex_cartesian=dict( + argstr='-complex', + position=1, + xor=[ + 'real_polar', 'real_cartesian', 'complex_cartesian', + 'complex_polar', 'complex_split', 'complex_merge' + ], + ), + complex_in_file=dict( + argstr='%s', + position=2, + ), + complex_in_file2=dict( + argstr='%s', + position=3, + ), + complex_merge=dict( + argstr='-complexmerge', + position=1, + xor=[ + 'real_polar', 'real_cartesian', 'complex_cartesian', + 'complex_polar', 'complex_split', 'complex_merge', 'start_vol', + 'end_vol' + ], + ), + complex_out_file=dict( + argstr='%s', + genfile=True, + position=-3, + xor=[ + 'complex_out_file', 'magnitude_out_file', 'phase_out_file', + 'real_out_file', 'imaginary_out_file', 'real_polar', + 'real_cartesian' + ], + ), + complex_polar=dict( + argstr='-complexpolar', + position=1, + xor=[ + 'real_polar', 'real_cartesian', 'complex_cartesian', + 'complex_polar', 'complex_split', 'complex_merge' + ], + ), + complex_split=dict( + argstr='-complexsplit', + position=1, + xor=[ + 'real_polar', 'real_cartesian', 'complex_cartesian', + 'complex_polar', 'complex_split', 'complex_merge' + ], + ), + end_vol=dict( + argstr='%d', + position=-1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + imaginary_in_file=dict( + argstr='%s', + position=3, + ), + imaginary_out_file=dict( + argstr='%s', + genfile=True, + position=-3, + xor=[ + 'complex_out_file', 'magnitude_out_file', 'phase_out_file', + 'real_polar', 'complex_cartesian', 'complex_polar', + 'complex_split', 'complex_merge' + ], + ), + magnitude_in_file=dict( + argstr='%s', + position=2, + ), + magnitude_out_file=dict( + argstr='%s', + genfile=True, + position=-4, + xor=[ + 'complex_out_file', 'real_out_file', 'imaginary_out_file', + 'real_cartesian', 'complex_cartesian', 'complex_polar', + 'complex_split', 'complex_merge' + ], + ), + output_type=dict(), + phase_in_file=dict( + argstr='%s', + position=3, + ), + phase_out_file=dict( + argstr='%s', + genfile=True, + position=-3, + xor=[ + 'complex_out_file', 'real_out_file', 'imaginary_out_file', + 'real_cartesian', 'complex_cartesian', 'complex_polar', + 'complex_split', 'complex_merge' + ], + ), + real_cartesian=dict( + argstr='-realcartesian', + position=1, + xor=[ + 'real_polar', 'real_cartesian', 'complex_cartesian', + 'complex_polar', 'complex_split', 'complex_merge' + ], + ), + real_in_file=dict( + argstr='%s', + position=2, + ), + real_out_file=dict( + argstr='%s', + genfile=True, + position=-4, + xor=[ + 'complex_out_file', 'magnitude_out_file', 'phase_out_file', + 'real_polar', 'complex_cartesian', 'complex_polar', + 'complex_split', 'complex_merge' + ], + ), + real_polar=dict( + argstr='-realpolar', + position=1, + xor=[ + 'real_polar', 'real_cartesian', 'complex_cartesian', + 'complex_polar', 'complex_split', 'complex_merge' + ], + ), + start_vol=dict( + argstr='%d', + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Complex.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Complex_outputs(): - output_map = dict(complex_out_file=dict(), - imaginary_out_file=dict(), - magnitude_out_file=dict(), - phase_out_file=dict(), - real_out_file=dict(), + output_map = dict( + complex_out_file=dict(), + imaginary_out_file=dict(), + magnitude_out_file=dict(), + phase_out_file=dict(), + real_out_file=dict(), ) outputs = Complex.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py b/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py index de4296e751..b2e0ff2098 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py +++ b/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py @@ -4,61 +4,65 @@ def test_ContrastMgr_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - contrast_num=dict(argstr='-cope', - ), - corrections=dict(copyfile=False, - mandatory=True, - ), - dof_file=dict(argstr='', - copyfile=False, - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fcon_file=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - output_type=dict(), - param_estimates=dict(argstr='', - copyfile=False, - mandatory=True, - ), - sigmasquareds=dict(argstr='', - copyfile=False, - mandatory=True, - position=-2, - ), - suffix=dict(argstr='-suffix %s', - ), - tcon_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + contrast_num=dict(argstr='-cope', ), + corrections=dict( + copyfile=False, + mandatory=True, + ), + dof_file=dict( + argstr='', + copyfile=False, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fcon_file=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + output_type=dict(), + param_estimates=dict( + argstr='', + copyfile=False, + mandatory=True, + ), + sigmasquareds=dict( + argstr='', + copyfile=False, + mandatory=True, + position=-2, + ), + suffix=dict(argstr='-suffix %s', ), + tcon_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ContrastMgr.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ContrastMgr_outputs(): - output_map = dict(copes=dict(), - fstats=dict(), - neffs=dict(), - tstats=dict(), - varcopes=dict(), - zfstats=dict(), - zstats=dict(), + output_map = dict( + copes=dict(), + fstats=dict(), + neffs=dict(), + tstats=dict(), + varcopes=dict(), + zfstats=dict(), + zstats=dict(), ) outputs = ContrastMgr.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py b/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py index 4ea9b536f9..7bb4b7a760 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py @@ -4,73 +4,71 @@ def test_ConvertWarp_inputs(): - input_map = dict(abswarp=dict(argstr='--abs', - xor=['relwarp'], - ), - args=dict(argstr='%s', - ), - cons_jacobian=dict(argstr='--constrainj', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - jacobian_max=dict(argstr='--jmax=%f', - ), - jacobian_min=dict(argstr='--jmin=%f', - ), - midmat=dict(argstr='--midmat=%s', - ), - out_abswarp=dict(argstr='--absout', - xor=['out_relwarp'], - ), - out_file=dict(argstr='--out=%s', - name_source=['reference'], - name_template='%s_concatwarp', - output_name='out_file', - position=-1, - ), - out_relwarp=dict(argstr='--relout', - xor=['out_abswarp'], - ), - output_type=dict(), - postmat=dict(argstr='--postmat=%s', - ), - premat=dict(argstr='--premat=%s', - ), - reference=dict(argstr='--ref=%s', - mandatory=True, - position=1, - ), - relwarp=dict(argstr='--rel', - xor=['abswarp'], - ), - shift_direction=dict(argstr='--shiftdir=%s', - requires=['shift_in_file'], - ), - shift_in_file=dict(argstr='--shiftmap=%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp1=dict(argstr='--warp1=%s', - ), - warp2=dict(argstr='--warp2=%s', - ), + input_map = dict( + abswarp=dict( + argstr='--abs', + xor=['relwarp'], + ), + args=dict(argstr='%s', ), + cons_jacobian=dict(argstr='--constrainj', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + jacobian_max=dict(argstr='--jmax=%f', ), + jacobian_min=dict(argstr='--jmin=%f', ), + midmat=dict(argstr='--midmat=%s', ), + out_abswarp=dict( + argstr='--absout', + xor=['out_relwarp'], + ), + out_file=dict( + argstr='--out=%s', + name_source=['reference'], + name_template='%s_concatwarp', + output_name='out_file', + position=-1, + ), + out_relwarp=dict( + argstr='--relout', + xor=['out_abswarp'], + ), + output_type=dict(), + postmat=dict(argstr='--postmat=%s', ), + premat=dict(argstr='--premat=%s', ), + reference=dict( + argstr='--ref=%s', + mandatory=True, + position=1, + ), + relwarp=dict( + argstr='--rel', + xor=['abswarp'], + ), + shift_direction=dict( + argstr='--shiftdir=%s', + requires=['shift_in_file'], + ), + shift_in_file=dict(argstr='--shiftmap=%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp1=dict(argstr='--warp1=%s', ), + warp2=dict(argstr='--warp2=%s', ), ) inputs = ConvertWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ConvertWarp_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ConvertWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py b/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py index 1dad2d7d63..c62ae58546 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py +++ b/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py @@ -4,56 +4,62 @@ def test_ConvertXFM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - concat_xfm=dict(argstr='-concat', - position=-3, - requires=['in_file2'], - xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - fix_scale_skew=dict(argstr='-fixscaleskew', - position=-3, - requires=['in_file2'], - xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - in_file2=dict(argstr='%s', - position=-2, - ), - invert_xfm=dict(argstr='-inverse', - position=-3, - xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'], - ), - out_file=dict(argstr='-omat %s', - genfile=True, - hash_files=False, - position=1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + concat_xfm=dict( + argstr='-concat', + position=-3, + requires=['in_file2'], + xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fix_scale_skew=dict( + argstr='-fixscaleskew', + position=-3, + requires=['in_file2'], + xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + in_file2=dict( + argstr='%s', + position=-2, + ), + invert_xfm=dict( + argstr='-inverse', + position=-3, + xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'], + ), + out_file=dict( + argstr='-omat %s', + genfile=True, + hash_files=False, + position=1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ConvertXFM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ConvertXFM_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ConvertXFM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py b/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py index 8374c8c93d..c7d6c5f5c9 100644 --- a/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py +++ b/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py @@ -4,45 +4,48 @@ def test_CopyGeom_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dest_file=dict(argstr='%s', - copyfile=True, - mandatory=True, - name_source='dest_file', - name_template='%s', - output_name='out_file', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_dims=dict(argstr='-d', - position='-1', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dest_file=dict( + argstr='%s', + copyfile=True, + mandatory=True, + name_source='dest_file', + name_template='%s', + output_name='out_file', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_dims=dict( + argstr='-d', + position='-1', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = CopyGeom.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CopyGeom_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = CopyGeom.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_DTIFit.py b/nipype/interfaces/fsl/tests/test_auto_DTIFit.py index 02e031519e..969faf1dc3 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DTIFit.py +++ b/nipype/interfaces/fsl/tests/test_auto_DTIFit.py @@ -4,81 +4,77 @@ def test_DTIFit_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - base_name=dict(argstr='-o %s', - position=1, - usedefault=True, - ), - bvals=dict(argstr='-b %s', - mandatory=True, - position=4, - ), - bvecs=dict(argstr='-r %s', - mandatory=True, - position=3, - ), - cni=dict(argstr='--cni=%s', - ), - dwi=dict(argstr='-k %s', - mandatory=True, - position=0, - ), - environ=dict(nohash=True, - usedefault=True, - ), - gradnonlin=dict(argstr='--gradnonlin=%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - little_bit=dict(argstr='--littlebit', - ), - mask=dict(argstr='-m %s', - mandatory=True, - position=2, - ), - max_x=dict(argstr='-X %d', - ), - max_y=dict(argstr='-Y %d', - ), - max_z=dict(argstr='-Z %d', - ), - min_x=dict(argstr='-x %d', - ), - min_y=dict(argstr='-y %d', - ), - min_z=dict(argstr='-z %d', - ), - output_type=dict(), - save_tensor=dict(argstr='--save_tensor', - ), - sse=dict(argstr='--sse', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + base_name=dict( + argstr='-o %s', + position=1, + usedefault=True, + ), + bvals=dict( + argstr='-b %s', + mandatory=True, + position=4, + ), + bvecs=dict( + argstr='-r %s', + mandatory=True, + position=3, + ), + cni=dict(argstr='--cni=%s', ), + dwi=dict( + argstr='-k %s', + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradnonlin=dict(argstr='--gradnonlin=%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + little_bit=dict(argstr='--littlebit', ), + mask=dict( + argstr='-m %s', + mandatory=True, + position=2, + ), + max_x=dict(argstr='-X %d', ), + max_y=dict(argstr='-Y %d', ), + max_z=dict(argstr='-Z %d', ), + min_x=dict(argstr='-x %d', ), + min_y=dict(argstr='-y %d', ), + min_z=dict(argstr='-z %d', ), + output_type=dict(), + save_tensor=dict(argstr='--save_tensor', ), + sse=dict(argstr='--sse', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DTIFit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTIFit_outputs(): - output_map = dict(FA=dict(), - L1=dict(), - L2=dict(), - L3=dict(), - MD=dict(), - MO=dict(), - S0=dict(), - V1=dict(), - V2=dict(), - V3=dict(), - tensor=dict(), + output_map = dict( + FA=dict(), + L1=dict(), + L2=dict(), + L3=dict(), + MD=dict(), + MO=dict(), + S0=dict(), + V1=dict(), + V2=dict(), + V3=dict(), + tensor=dict(), ) outputs = DTIFit.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_DilateImage.py b/nipype/interfaces/fsl/tests/test_auto_DilateImage.py index 2b8be886a6..ad6089b877 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DilateImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_DilateImage.py @@ -4,63 +4,72 @@ def test_DilateImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - kernel_file=dict(argstr='%s', - position=5, - xor=['kernel_size'], - ), - kernel_shape=dict(argstr='-kernel %s', - position=4, - ), - kernel_size=dict(argstr='%.4f', - position=5, - xor=['kernel_file'], - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - operation=dict(argstr='-dil%s', - mandatory=True, - position=6, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + kernel_file=dict( + argstr='%s', + position=5, + xor=['kernel_size'], + ), + kernel_shape=dict( + argstr='-kernel %s', + position=4, + ), + kernel_size=dict( + argstr='%.4f', + position=5, + xor=['kernel_file'], + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + operation=dict( + argstr='-dil%s', + mandatory=True, + position=6, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DilateImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DilateImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = DilateImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py b/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py index 1b063503dc..1efc1f7e07 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py +++ b/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py @@ -4,44 +4,47 @@ def test_DistanceMap_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - distance_map=dict(argstr='--out=%s', - genfile=True, - hash_files=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--in=%s', - mandatory=True, - ), - invert_input=dict(argstr='--invert', - ), - local_max_file=dict(argstr='--localmax=%s', - hash_files=False, - ), - mask_file=dict(argstr='--mask=%s', - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + distance_map=dict( + argstr='--out=%s', + genfile=True, + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--in=%s', + mandatory=True, + ), + invert_input=dict(argstr='--invert', ), + local_max_file=dict( + argstr='--localmax=%s', + hash_files=False, + ), + mask_file=dict(argstr='--mask=%s', ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DistanceMap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DistanceMap_outputs(): - output_map = dict(distance_map=dict(), - local_max_file=dict(), + output_map = dict( + distance_map=dict(), + local_max_file=dict(), ) outputs = DistanceMap.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_DualRegression.py b/nipype/interfaces/fsl/tests/test_auto_DualRegression.py index 894a3a3ad4..cf407d634e 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DualRegression.py +++ b/nipype/interfaces/fsl/tests/test_auto_DualRegression.py @@ -4,61 +4,69 @@ def test_DualRegression_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - con_file=dict(argstr='%s', - position=4, - ), - des_norm=dict(argstr='%i', - position=2, - usedefault=True, - ), - design_file=dict(argstr='%s', - position=3, - ), - environ=dict(nohash=True, - usedefault=True, - ), - group_IC_maps_4D=dict(argstr='%s', - mandatory=True, - position=1, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=-1, - sep=' ', - ), - n_perm=dict(argstr='%i', - mandatory=True, - position=5, - ), - one_sample_group_mean=dict(argstr='-1', - position=3, - ), - out_dir=dict(argstr='%s', - genfile=True, - position=6, - usedefault=True, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + con_file=dict( + argstr='%s', + position=4, + ), + des_norm=dict( + argstr='%i', + position=2, + usedefault=True, + ), + design_file=dict( + argstr='%s', + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + group_IC_maps_4D=dict( + argstr='%s', + mandatory=True, + position=1, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-1, + sep=' ', + ), + n_perm=dict( + argstr='%i', + mandatory=True, + position=5, + ), + one_sample_group_mean=dict( + argstr='-1', + position=3, + ), + out_dir=dict( + argstr='%s', + genfile=True, + position=6, + usedefault=True, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DualRegression.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DualRegression_outputs(): - output_map = dict(out_dir=dict(), - ) + output_map = dict(out_dir=dict(), ) outputs = DualRegression.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py b/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py index 969ecfa86d..983d9d2041 100644 --- a/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py @@ -4,69 +4,78 @@ def test_EPIDeWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cleanup=dict(argstr='--cleanup', - ), - dph_file=dict(argstr='--dph %s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - epi_file=dict(argstr='--epi %s', - ), - epidw=dict(argstr='--epidw %s', - genfile=False, - ), - esp=dict(argstr='--esp %s', - usedefault=True, - ), - exf_file=dict(argstr='--exf %s', - ), - exfdw=dict(argstr='--exfdw %s', - genfile=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mag_file=dict(argstr='--mag %s', - mandatory=True, - position=0, - ), - nocleanup=dict(argstr='--nocleanup', - usedefault=True, - ), - output_type=dict(), - sigma=dict(argstr='--sigma %s', - usedefault=True, - ), - tediff=dict(argstr='--tediff %s', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tmpdir=dict(argstr='--tmpdir %s', - genfile=True, - ), - vsm=dict(argstr='--vsm %s', - genfile=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + cleanup=dict(argstr='--cleanup', ), + dph_file=dict( + argstr='--dph %s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi_file=dict(argstr='--epi %s', ), + epidw=dict( + argstr='--epidw %s', + genfile=False, + ), + esp=dict( + argstr='--esp %s', + usedefault=True, + ), + exf_file=dict(argstr='--exf %s', ), + exfdw=dict( + argstr='--exfdw %s', + genfile=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mag_file=dict( + argstr='--mag %s', + mandatory=True, + position=0, + ), + nocleanup=dict( + argstr='--nocleanup', + usedefault=True, + ), + output_type=dict(), + sigma=dict( + argstr='--sigma %s', + usedefault=True, + ), + tediff=dict( + argstr='--tediff %s', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tmpdir=dict( + argstr='--tmpdir %s', + genfile=True, + ), + vsm=dict( + argstr='--vsm %s', + genfile=True, + ), ) inputs = EPIDeWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EPIDeWarp_outputs(): - output_map = dict(exf_mask=dict(), - exfdw=dict(), - unwarped_file=dict(), - vsm_file=dict(), + output_map = dict( + exf_mask=dict(), + exfdw=dict(), + unwarped_file=dict(), + vsm_file=dict(), ) outputs = EPIDeWarp.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Eddy.py b/nipype/interfaces/fsl/tests/test_auto_Eddy.py index df4155472d..d973412fcc 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Eddy.py +++ b/nipype/interfaces/fsl/tests/test_auto_Eddy.py @@ -4,97 +4,91 @@ def test_Eddy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dont_peas=dict(argstr='--dont_peas', - ), - dont_sep_offs_move=dict(argstr='--dont_sep_offs_move', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fep=dict(argstr='--fep', - ), - field=dict(argstr='--field=%s', - ), - field_mat=dict(argstr='--field_mat=%s', - ), - flm=dict(argstr='--flm=%s', - ), - fudge_factor=dict(argstr='--ff=%s', - ), - fwhm=dict(argstr='--fwhm=%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_acqp=dict(argstr='--acqp=%s', - mandatory=True, - ), - in_bval=dict(argstr='--bvals=%s', - mandatory=True, - ), - in_bvec=dict(argstr='--bvecs=%s', - mandatory=True, - ), - in_file=dict(argstr='--imain=%s', - mandatory=True, - ), - in_index=dict(argstr='--index=%s', - mandatory=True, - ), - in_mask=dict(argstr='--mask=%s', - mandatory=True, - ), - in_topup_fieldcoef=dict(argstr='--topup=%s', - requires=['in_topup_movpar'], - ), - in_topup_movpar=dict(requires=['in_topup_fieldcoef'], - ), - interp=dict(argstr='--interp=%s', - ), - is_shelled=dict(argstr='--data_is_shelled', - ), - method=dict(argstr='--resamp=%s', - ), - niter=dict(argstr='--niter=%s', - ), - num_threads=dict(nohash=True, - usedefault=True, - ), - nvoxhp=dict(argstr='--nvoxhp=%s', - ), - out_base=dict(argstr='--out=%s', - usedefault=True, - ), - output_type=dict(), - repol=dict(argstr='--repol', - ), - session=dict(argstr='--session=%s', - ), - slm=dict(argstr='--slm=%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_cuda=dict(), + input_map = dict( + args=dict(argstr='%s', ), + dont_peas=dict(argstr='--dont_peas', ), + dont_sep_offs_move=dict(argstr='--dont_sep_offs_move', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fep=dict(argstr='--fep', ), + field=dict(argstr='--field=%s', ), + field_mat=dict(argstr='--field_mat=%s', ), + flm=dict(argstr='--flm=%s', ), + fudge_factor=dict(argstr='--ff=%s', ), + fwhm=dict(argstr='--fwhm=%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_acqp=dict( + argstr='--acqp=%s', + mandatory=True, + ), + in_bval=dict( + argstr='--bvals=%s', + mandatory=True, + ), + in_bvec=dict( + argstr='--bvecs=%s', + mandatory=True, + ), + in_file=dict( + argstr='--imain=%s', + mandatory=True, + ), + in_index=dict( + argstr='--index=%s', + mandatory=True, + ), + in_mask=dict( + argstr='--mask=%s', + mandatory=True, + ), + in_topup_fieldcoef=dict( + argstr='--topup=%s', + requires=['in_topup_movpar'], + ), + in_topup_movpar=dict(requires=['in_topup_fieldcoef'], ), + interp=dict(argstr='--interp=%s', ), + is_shelled=dict(argstr='--data_is_shelled', ), + method=dict(argstr='--resamp=%s', ), + niter=dict(argstr='--niter=%s', ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + nvoxhp=dict(argstr='--nvoxhp=%s', ), + out_base=dict( + argstr='--out=%s', + usedefault=True, + ), + output_type=dict(), + repol=dict(argstr='--repol', ), + session=dict(argstr='--session=%s', ), + slm=dict(argstr='--slm=%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_cuda=dict(), ) inputs = Eddy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Eddy_outputs(): - output_map = dict(out_corrected=dict(), - out_movement_rms=dict(), - out_outlier_report=dict(), - out_parameter=dict(), - out_restricted_movement_rms=dict(), - out_rotated_bvecs=dict(), - out_shell_alignment_parameters=dict(), + output_map = dict( + out_corrected=dict(), + out_movement_rms=dict(), + out_outlier_report=dict(), + out_parameter=dict(), + out_restricted_movement_rms=dict(), + out_rotated_bvecs=dict(), + out_shell_alignment_parameters=dict(), ) outputs = Eddy.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py b/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py index 57bf91ac79..e89747a41f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py +++ b/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py @@ -4,45 +4,48 @@ def test_EddyCorrect_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s_edc', - output_name='eddy_corrected', - position=1, - ), - output_type=dict(), - ref_num=dict(argstr='%d', - mandatory=True, - position=2, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s_edc', + output_name='eddy_corrected', + position=1, + ), + output_type=dict(), + ref_num=dict( + argstr='%d', + mandatory=True, + position=2, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = EddyCorrect.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EddyCorrect_outputs(): - output_map = dict(eddy_corrected=dict(), - ) + output_map = dict(eddy_corrected=dict(), ) outputs = EddyCorrect.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_EpiReg.py b/nipype/interfaces/fsl/tests/test_auto_EpiReg.py index 65e8134a30..67cf28d1bc 100644 --- a/nipype/interfaces/fsl/tests/test_auto_EpiReg.py +++ b/nipype/interfaces/fsl/tests/test_auto_EpiReg.py @@ -4,76 +4,75 @@ def test_EpiReg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - echospacing=dict(argstr='--echospacing=%f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - epi=dict(argstr='--epi=%s', - mandatory=True, - position=-4, - ), - fmap=dict(argstr='--fmap=%s', - ), - fmapmag=dict(argstr='--fmapmag=%s', - ), - fmapmagbrain=dict(argstr='--fmapmagbrain=%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - no_clean=dict(argstr='--noclean', - usedefault=True, - ), - no_fmapreg=dict(argstr='--nofmapreg', - ), - out_base=dict(argstr='--out=%s', - position=-1, - usedefault=True, - ), - output_type=dict(), - pedir=dict(argstr='--pedir=%s', - ), - t1_brain=dict(argstr='--t1brain=%s', - mandatory=True, - position=-2, - ), - t1_head=dict(argstr='--t1=%s', - mandatory=True, - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - weight_image=dict(argstr='--weight=%s', - ), - wmseg=dict(argstr='--wmseg=%s', - ), + input_map = dict( + args=dict(argstr='%s', ), + echospacing=dict(argstr='--echospacing=%f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi=dict( + argstr='--epi=%s', + mandatory=True, + position=-4, + ), + fmap=dict(argstr='--fmap=%s', ), + fmapmag=dict(argstr='--fmapmag=%s', ), + fmapmagbrain=dict(argstr='--fmapmagbrain=%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + no_clean=dict( + argstr='--noclean', + usedefault=True, + ), + no_fmapreg=dict(argstr='--nofmapreg', ), + out_base=dict( + argstr='--out=%s', + position=-1, + usedefault=True, + ), + output_type=dict(), + pedir=dict(argstr='--pedir=%s', ), + t1_brain=dict( + argstr='--t1brain=%s', + mandatory=True, + position=-2, + ), + t1_head=dict( + argstr='--t1=%s', + mandatory=True, + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + weight_image=dict(argstr='--weight=%s', ), + wmseg=dict(argstr='--wmseg=%s', ), ) inputs = EpiReg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EpiReg_outputs(): - output_map = dict(epi2str_inv=dict(), - epi2str_mat=dict(), - fmap2epi_mat=dict(), - fmap2str_mat=dict(), - fmap_epi=dict(), - fmap_str=dict(), - fmapmag_str=dict(), - fullwarp=dict(), - out_1vol=dict(), - out_file=dict(), - shiftmap=dict(), - wmedge=dict(), - wmseg=dict(), + output_map = dict( + epi2str_inv=dict(), + epi2str_mat=dict(), + fmap2epi_mat=dict(), + fmap2str_mat=dict(), + fmap_epi=dict(), + fmap_str=dict(), + fmapmag_str=dict(), + fullwarp=dict(), + out_1vol=dict(), + out_file=dict(), + shiftmap=dict(), + wmedge=dict(), + wmseg=dict(), ) outputs = EpiReg.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py b/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py index 015b97e59e..88a1c79657 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py @@ -4,63 +4,72 @@ def test_ErodeImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - kernel_file=dict(argstr='%s', - position=5, - xor=['kernel_size'], - ), - kernel_shape=dict(argstr='-kernel %s', - position=4, - ), - kernel_size=dict(argstr='%.4f', - position=5, - xor=['kernel_file'], - ), - minimum_filter=dict(argstr='%s', - position=6, - usedefault=True, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + kernel_file=dict( + argstr='%s', + position=5, + xor=['kernel_size'], + ), + kernel_shape=dict( + argstr='-kernel %s', + position=4, + ), + kernel_size=dict( + argstr='%.4f', + position=5, + xor=['kernel_file'], + ), + minimum_filter=dict( + argstr='%s', + position=6, + usedefault=True, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ErodeImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ErodeImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ErodeImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py b/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py index 8abad8a656..5b7189a017 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py +++ b/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py @@ -4,67 +4,81 @@ def test_ExtractROI_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - crop_list=dict(argstr='%s', - position=2, - xor=['x_min', 'x_size', 'y_min', 'y_size', 'z_min', 'z_size', 't_min', 't_size'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - output_type=dict(), - roi_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=1, - ), - t_min=dict(argstr='%d', - position=8, - ), - t_size=dict(argstr='%d', - position=9, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - x_min=dict(argstr='%d', - position=2, - ), - x_size=dict(argstr='%d', - position=3, - ), - y_min=dict(argstr='%d', - position=4, - ), - y_size=dict(argstr='%d', - position=5, - ), - z_min=dict(argstr='%d', - position=6, - ), - z_size=dict(argstr='%d', - position=7, - ), + input_map = dict( + args=dict(argstr='%s', ), + crop_list=dict( + argstr='%s', + position=2, + xor=[ + 'x_min', 'x_size', 'y_min', 'y_size', 'z_min', 'z_size', + 't_min', 't_size' + ], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + output_type=dict(), + roi_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=1, + ), + t_min=dict( + argstr='%d', + position=8, + ), + t_size=dict( + argstr='%d', + position=9, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + x_min=dict( + argstr='%d', + position=2, + ), + x_size=dict( + argstr='%d', + position=3, + ), + y_min=dict( + argstr='%d', + position=4, + ), + y_size=dict( + argstr='%d', + position=5, + ), + z_min=dict( + argstr='%d', + position=6, + ), + z_size=dict( + argstr='%d', + position=7, + ), ) inputs = ExtractROI.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ExtractROI_outputs(): - output_map = dict(roi_file=dict(), - ) + output_map = dict(roi_file=dict(), ) outputs = ExtractROI.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FAST.py b/nipype/interfaces/fsl/tests/test_auto_FAST.py index a5e54b0882..e848fb9442 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FAST.py +++ b/nipype/interfaces/fsl/tests/test_auto_FAST.py @@ -4,84 +4,68 @@ def test_FAST_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bias_iters=dict(argstr='-I %d', - ), - bias_lowpass=dict(argstr='-l %d', - units='mm', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hyper=dict(argstr='-H %.2f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - img_type=dict(argstr='-t %d', - ), - in_files=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - ), - init_seg_smooth=dict(argstr='-f %.3f', - ), - init_transform=dict(argstr='-a %s', - ), - iters_afterbias=dict(argstr='-O %d', - ), - manual_seg=dict(argstr='-s %s', - ), - mixel_smooth=dict(argstr='-R %.2f', - ), - no_bias=dict(argstr='-N', - ), - no_pve=dict(argstr='--nopve', - ), - number_classes=dict(argstr='-n %d', - ), - other_priors=dict(argstr='-A %s', - ), - out_basename=dict(argstr='-o %s', - ), - output_biascorrected=dict(argstr='-B', - ), - output_biasfield=dict(argstr='-b', - ), - output_type=dict(), - probability_maps=dict(argstr='-p', - ), - segment_iters=dict(argstr='-W %d', - ), - segments=dict(argstr='-g', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_priors=dict(argstr='-P', - ), - verbose=dict(argstr='-v', - ), + input_map = dict( + args=dict(argstr='%s', ), + bias_iters=dict(argstr='-I %d', ), + bias_lowpass=dict( + argstr='-l %d', + units='mm', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hyper=dict(argstr='-H %.2f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + img_type=dict(argstr='-t %d', ), + in_files=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + ), + init_seg_smooth=dict(argstr='-f %.3f', ), + init_transform=dict(argstr='-a %s', ), + iters_afterbias=dict(argstr='-O %d', ), + manual_seg=dict(argstr='-s %s', ), + mixel_smooth=dict(argstr='-R %.2f', ), + no_bias=dict(argstr='-N', ), + no_pve=dict(argstr='--nopve', ), + number_classes=dict(argstr='-n %d', ), + other_priors=dict(argstr='-A %s', ), + out_basename=dict(argstr='-o %s', ), + output_biascorrected=dict(argstr='-B', ), + output_biasfield=dict(argstr='-b', ), + output_type=dict(), + probability_maps=dict(argstr='-p', ), + segment_iters=dict(argstr='-W %d', ), + segments=dict(argstr='-g', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_priors=dict(argstr='-P', ), + verbose=dict(argstr='-v', ), ) inputs = FAST.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FAST_outputs(): - output_map = dict(bias_field=dict(), - mixeltype=dict(), - partial_volume_files=dict(), - partial_volume_map=dict(), - probability_maps=dict(), - restored_image=dict(), - tissue_class_files=dict(), - tissue_class_map=dict(), + output_map = dict( + bias_field=dict(), + mixeltype=dict(), + partial_volume_files=dict(), + partial_volume_map=dict(), + probability_maps=dict(), + restored_image=dict(), + tissue_class_files=dict(), + tissue_class_map=dict(), ) outputs = FAST.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FEAT.py b/nipype/interfaces/fsl/tests/test_auto_FEAT.py index bb024b4c29..5e9cfb51ce 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FEAT.py +++ b/nipype/interfaces/fsl/tests/test_auto_FEAT.py @@ -4,34 +4,35 @@ def test_FEAT_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fsf_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fsf_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FEAT.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FEAT_outputs(): - output_map = dict(feat_dir=dict(), - ) + output_map = dict(feat_dir=dict(), ) outputs = FEAT.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FEATModel.py b/nipype/interfaces/fsl/tests/test_auto_FEATModel.py index 9aa25a02d8..a66ced2f76 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FEATModel.py +++ b/nipype/interfaces/fsl/tests/test_auto_FEATModel.py @@ -4,43 +4,47 @@ def test_FEATModel_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ev_files=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=1, - ), - fsf_file=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=0, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ev_files=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=1, + ), + fsf_file=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=0, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FEATModel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FEATModel_outputs(): - output_map = dict(con_file=dict(), - design_cov=dict(), - design_file=dict(), - design_image=dict(), - fcon_file=dict(), + output_map = dict( + con_file=dict(), + design_cov=dict(), + design_file=dict(), + design_image=dict(), + fcon_file=dict(), ) outputs = FEATModel.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py b/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py index 9a46bd77c7..d09850b5d0 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py +++ b/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py @@ -4,27 +4,23 @@ def test_FEATRegister_inputs(): - input_map = dict(feat_dirs=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - reg_dof=dict(usedefault=True, - ), - reg_image=dict(mandatory=True, - ), + input_map = dict( + feat_dirs=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + reg_dof=dict(usedefault=True, ), + reg_image=dict(mandatory=True, ), ) inputs = FEATRegister.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FEATRegister_outputs(): - output_map = dict(fsf_file=dict(), - ) + output_map = dict(fsf_file=dict(), ) outputs = FEATRegister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FIRST.py b/nipype/interfaces/fsl/tests/test_auto_FIRST.py index 61f369a0f1..464bb56a24 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FIRST.py +++ b/nipype/interfaces/fsl/tests/test_auto_FIRST.py @@ -4,67 +4,78 @@ def test_FIRST_inputs(): - input_map = dict(affine_file=dict(argstr='-a %s', - position=6, - ), - args=dict(argstr='%s', - ), - brain_extracted=dict(argstr='-b', - position=2, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - copyfile=False, - mandatory=True, - position=-2, - ), - list_of_specific_structures=dict(argstr='-s %s', - position=5, - sep=',', - ), - method=dict(argstr='-m %s', - position=4, - usedefault=True, - xor=['method_as_numerical_threshold'], - ), - method_as_numerical_threshold=dict(argstr='-m %.4f', - position=4, - ), - no_cleanup=dict(argstr='-d', - position=3, - ), - out_file=dict(argstr='-o %s', - hash_files=False, - mandatory=True, - position=-1, - usedefault=True, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-v', - position=1, - ), + input_map = dict( + affine_file=dict( + argstr='-a %s', + position=6, + ), + args=dict(argstr='%s', ), + brain_extracted=dict( + argstr='-b', + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + copyfile=False, + mandatory=True, + position=-2, + ), + list_of_specific_structures=dict( + argstr='-s %s', + position=5, + sep=',', + ), + method=dict( + argstr='-m %s', + position=4, + usedefault=True, + xor=['method_as_numerical_threshold'], + ), + method_as_numerical_threshold=dict( + argstr='-m %.4f', + position=4, + ), + no_cleanup=dict( + argstr='-d', + position=3, + ), + out_file=dict( + argstr='-o %s', + hash_files=False, + mandatory=True, + position=-1, + usedefault=True, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict( + argstr='-v', + position=1, + ), ) inputs = FIRST.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FIRST_outputs(): - output_map = dict(bvars=dict(), - original_segmentations=dict(), - segmentation_file=dict(), - vtk_surfaces=dict(), + output_map = dict( + bvars=dict(), + original_segmentations=dict(), + segmentation_file=dict(), + vtk_surfaces=dict(), ) outputs = FIRST.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py b/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py index 6caf4d6d9a..2b9856ff6d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py +++ b/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py @@ -4,83 +4,81 @@ def test_FLAMEO_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - burnin=dict(argstr='--burnin=%d', - ), - cope_file=dict(argstr='--copefile=%s', - mandatory=True, - ), - cov_split_file=dict(argstr='--covsplitfile=%s', - mandatory=True, - ), - design_file=dict(argstr='--designfile=%s', - mandatory=True, - ), - dof_var_cope_file=dict(argstr='--dofvarcopefile=%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - f_con_file=dict(argstr='--fcontrastsfile=%s', - ), - fix_mean=dict(argstr='--fixmean', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - infer_outliers=dict(argstr='--inferoutliers', - ), - log_dir=dict(argstr='--ld=%s', - usedefault=True, - ), - mask_file=dict(argstr='--maskfile=%s', - mandatory=True, - ), - n_jumps=dict(argstr='--njumps=%d', - ), - no_pe_outputs=dict(argstr='--nopeoutput', - ), - outlier_iter=dict(argstr='--ioni=%d', - ), - output_type=dict(), - run_mode=dict(argstr='--runmode=%s', - mandatory=True, - ), - sample_every=dict(argstr='--sampleevery=%d', - ), - sigma_dofs=dict(argstr='--sigma_dofs=%d', - ), - t_con_file=dict(argstr='--tcontrastsfile=%s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - var_cope_file=dict(argstr='--varcopefile=%s', - ), + input_map = dict( + args=dict(argstr='%s', ), + burnin=dict(argstr='--burnin=%d', ), + cope_file=dict( + argstr='--copefile=%s', + mandatory=True, + ), + cov_split_file=dict( + argstr='--covsplitfile=%s', + mandatory=True, + ), + design_file=dict( + argstr='--designfile=%s', + mandatory=True, + ), + dof_var_cope_file=dict(argstr='--dofvarcopefile=%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + f_con_file=dict(argstr='--fcontrastsfile=%s', ), + fix_mean=dict(argstr='--fixmean', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + infer_outliers=dict(argstr='--inferoutliers', ), + log_dir=dict( + argstr='--ld=%s', + usedefault=True, + ), + mask_file=dict( + argstr='--maskfile=%s', + mandatory=True, + ), + n_jumps=dict(argstr='--njumps=%d', ), + no_pe_outputs=dict(argstr='--nopeoutput', ), + outlier_iter=dict(argstr='--ioni=%d', ), + output_type=dict(), + run_mode=dict( + argstr='--runmode=%s', + mandatory=True, + ), + sample_every=dict(argstr='--sampleevery=%d', ), + sigma_dofs=dict(argstr='--sigma_dofs=%d', ), + t_con_file=dict( + argstr='--tcontrastsfile=%s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + var_cope_file=dict(argstr='--varcopefile=%s', ), ) inputs = FLAMEO.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FLAMEO_outputs(): - output_map = dict(copes=dict(), - fstats=dict(), - mrefvars=dict(), - pes=dict(), - res4d=dict(), - stats_dir=dict(), - tdof=dict(), - tstats=dict(), - var_copes=dict(), - weights=dict(), - zfstats=dict(), - zstats=dict(), + output_map = dict( + copes=dict(), + fstats=dict(), + mrefvars=dict(), + pes=dict(), + res4d=dict(), + stats_dir=dict(), + tdof=dict(), + tstats=dict(), + var_copes=dict(), + weights=dict(), + zfstats=dict(), + zstats=dict(), ) outputs = FLAMEO.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FLIRT.py b/nipype/interfaces/fsl/tests/test_auto_FLIRT.py index bd13a2fd36..20bb8fe4c4 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FLIRT.py +++ b/nipype/interfaces/fsl/tests/test_auto_FLIRT.py @@ -4,158 +4,160 @@ def test_FLIRT_inputs(): - input_map = dict(angle_rep=dict(argstr='-anglerep %s', - ), - apply_isoxfm=dict(argstr='-applyisoxfm %f', - xor=['apply_xfm'], - ), - apply_xfm=dict(argstr='-applyxfm', - ), - args=dict(argstr='%s', - ), - bbrslope=dict(argstr='-bbrslope %f', - min_ver='5.0.0', - ), - bbrtype=dict(argstr='-bbrtype %s', - min_ver='5.0.0', - ), - bgvalue=dict(argstr='-setbackground %f', - ), - bins=dict(argstr='-bins %d', - ), - coarse_search=dict(argstr='-coarsesearch %d', - units='degrees', - ), - cost=dict(argstr='-cost %s', - ), - cost_func=dict(argstr='-searchcost %s', - ), - datatype=dict(argstr='-datatype %s', - ), - display_init=dict(argstr='-displayinit', - ), - dof=dict(argstr='-dof %d', - ), - echospacing=dict(argstr='-echospacing %f', - min_ver='5.0.0', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fieldmap=dict(argstr='-fieldmap %s', - min_ver='5.0.0', - ), - fieldmapmask=dict(argstr='-fieldmapmask %s', - min_ver='5.0.0', - ), - fine_search=dict(argstr='-finesearch %d', - units='degrees', - ), - force_scaling=dict(argstr='-forcescaling', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - position=0, - ), - in_matrix_file=dict(argstr='-init %s', - ), - in_weight=dict(argstr='-inweight %s', - ), - interp=dict(argstr='-interp %s', - ), - min_sampling=dict(argstr='-minsampling %f', - units='mm', - ), - no_clamp=dict(argstr='-noclamp', - ), - no_resample=dict(argstr='-noresample', - ), - no_resample_blur=dict(argstr='-noresampblur', - ), - no_search=dict(argstr='-nosearch', - ), - out_file=dict(argstr='-out %s', - hash_files=False, - name_source=['in_file'], - name_template='%s_flirt', - position=2, - ), - out_log=dict(keep_extension=True, - name_source=['in_file'], - name_template='%s_flirt.log', - requires=['save_log'], - ), - out_matrix_file=dict(argstr='-omat %s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s_flirt.mat', - position=3, - ), - output_type=dict(), - padding_size=dict(argstr='-paddingsize %d', - units='voxels', - ), - pedir=dict(argstr='-pedir %d', - min_ver='5.0.0', - ), - ref_weight=dict(argstr='-refweight %s', - ), - reference=dict(argstr='-ref %s', - mandatory=True, - position=1, - ), - rigid2D=dict(argstr='-2D', - ), - save_log=dict(), - schedule=dict(argstr='-schedule %s', - ), - searchr_x=dict(argstr='-searchrx %s', - units='degrees', - ), - searchr_y=dict(argstr='-searchry %s', - units='degrees', - ), - searchr_z=dict(argstr='-searchrz %s', - units='degrees', - ), - sinc_width=dict(argstr='-sincwidth %d', - units='voxels', - ), - sinc_window=dict(argstr='-sincwindow %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uses_qform=dict(argstr='-usesqform', - ), - verbose=dict(argstr='-verbose %d', - ), - wm_seg=dict(argstr='-wmseg %s', - min_ver='5.0.0', - ), - wmcoords=dict(argstr='-wmcoords %s', - min_ver='5.0.0', - ), - wmnorms=dict(argstr='-wmnorms %s', - min_ver='5.0.0', - ), + input_map = dict( + angle_rep=dict(argstr='-anglerep %s', ), + apply_isoxfm=dict( + argstr='-applyisoxfm %f', + xor=['apply_xfm'], + ), + apply_xfm=dict(argstr='-applyxfm', ), + args=dict(argstr='%s', ), + bbrslope=dict( + argstr='-bbrslope %f', + min_ver='5.0.0', + ), + bbrtype=dict( + argstr='-bbrtype %s', + min_ver='5.0.0', + ), + bgvalue=dict(argstr='-setbackground %f', ), + bins=dict(argstr='-bins %d', ), + coarse_search=dict( + argstr='-coarsesearch %d', + units='degrees', + ), + cost=dict(argstr='-cost %s', ), + cost_func=dict(argstr='-searchcost %s', ), + datatype=dict(argstr='-datatype %s', ), + display_init=dict(argstr='-displayinit', ), + dof=dict(argstr='-dof %d', ), + echospacing=dict( + argstr='-echospacing %f', + min_ver='5.0.0', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fieldmap=dict( + argstr='-fieldmap %s', + min_ver='5.0.0', + ), + fieldmapmask=dict( + argstr='-fieldmapmask %s', + min_ver='5.0.0', + ), + fine_search=dict( + argstr='-finesearch %d', + units='degrees', + ), + force_scaling=dict(argstr='-forcescaling', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + position=0, + ), + in_matrix_file=dict(argstr='-init %s', ), + in_weight=dict(argstr='-inweight %s', ), + interp=dict(argstr='-interp %s', ), + min_sampling=dict( + argstr='-minsampling %f', + units='mm', + ), + no_clamp=dict(argstr='-noclamp', ), + no_resample=dict(argstr='-noresample', ), + no_resample_blur=dict(argstr='-noresampblur', ), + no_search=dict(argstr='-nosearch', ), + out_file=dict( + argstr='-out %s', + hash_files=False, + name_source=['in_file'], + name_template='%s_flirt', + position=2, + ), + out_log=dict( + keep_extension=True, + name_source=['in_file'], + name_template='%s_flirt.log', + requires=['save_log'], + ), + out_matrix_file=dict( + argstr='-omat %s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s_flirt.mat', + position=3, + ), + output_type=dict(), + padding_size=dict( + argstr='-paddingsize %d', + units='voxels', + ), + pedir=dict( + argstr='-pedir %d', + min_ver='5.0.0', + ), + ref_weight=dict(argstr='-refweight %s', ), + reference=dict( + argstr='-ref %s', + mandatory=True, + position=1, + ), + rigid2D=dict(argstr='-2D', ), + save_log=dict(), + schedule=dict(argstr='-schedule %s', ), + searchr_x=dict( + argstr='-searchrx %s', + units='degrees', + ), + searchr_y=dict( + argstr='-searchry %s', + units='degrees', + ), + searchr_z=dict( + argstr='-searchrz %s', + units='degrees', + ), + sinc_width=dict( + argstr='-sincwidth %d', + units='voxels', + ), + sinc_window=dict(argstr='-sincwindow %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uses_qform=dict(argstr='-usesqform', ), + verbose=dict(argstr='-verbose %d', ), + wm_seg=dict( + argstr='-wmseg %s', + min_ver='5.0.0', + ), + wmcoords=dict( + argstr='-wmcoords %s', + min_ver='5.0.0', + ), + wmnorms=dict( + argstr='-wmnorms %s', + min_ver='5.0.0', + ), ) inputs = FLIRT.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FLIRT_outputs(): - output_map = dict(out_file=dict(), - out_log=dict(), - out_matrix_file=dict(), + output_map = dict( + out_file=dict(), + out_log=dict(), + out_matrix_file=dict(), ) outputs = FLIRT.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FNIRT.py b/nipype/interfaces/fsl/tests/test_auto_FNIRT.py index 19536f0913..612947e76f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FNIRT.py +++ b/nipype/interfaces/fsl/tests/test_auto_FNIRT.py @@ -4,142 +4,143 @@ def test_FNIRT_inputs(): - input_map = dict(affine_file=dict(argstr='--aff=%s', - ), - apply_inmask=dict(argstr='--applyinmask=%s', - sep=',', - xor=['skip_inmask'], - ), - apply_intensity_mapping=dict(argstr='--estint=%s', - sep=',', - xor=['skip_intensity_mapping'], - ), - apply_refmask=dict(argstr='--applyrefmask=%s', - sep=',', - xor=['skip_refmask'], - ), - args=dict(argstr='%s', - ), - bias_regularization_lambda=dict(argstr='--biaslambda=%f', - ), - biasfield_resolution=dict(argstr='--biasres=%d,%d,%d', - ), - config_file=dict(argstr='--config=%s', - ), - derive_from_ref=dict(argstr='--refderiv', - ), - environ=dict(nohash=True, - usedefault=True, - ), - field_file=dict(argstr='--fout=%s', - hash_files=False, - ), - fieldcoeff_file=dict(argstr='--cout=%s', - ), - hessian_precision=dict(argstr='--numprec=%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--in=%s', - mandatory=True, - ), - in_fwhm=dict(argstr='--infwhm=%s', - sep=',', - ), - in_intensitymap_file=dict(argstr='--intin=%s', - copyfile=False, - ), - inmask_file=dict(argstr='--inmask=%s', - ), - inmask_val=dict(argstr='--impinval=%f', - ), - intensity_mapping_model=dict(argstr='--intmod=%s', - ), - intensity_mapping_order=dict(argstr='--intorder=%d', - ), - inwarp_file=dict(argstr='--inwarp=%s', - ), - jacobian_file=dict(argstr='--jout=%s', - hash_files=False, - ), - jacobian_range=dict(argstr='--jacrange=%f,%f', - ), - log_file=dict(argstr='--logout=%s', - genfile=True, - hash_files=False, - ), - max_nonlin_iter=dict(argstr='--miter=%s', - sep=',', - ), - modulatedref_file=dict(argstr='--refout=%s', - hash_files=False, - ), - out_intensitymap_file=dict(argstr='--intout=%s', - hash_files=False, - ), - output_type=dict(), - ref_file=dict(argstr='--ref=%s', - mandatory=True, - ), - ref_fwhm=dict(argstr='--reffwhm=%s', - sep=',', - ), - refmask_file=dict(argstr='--refmask=%s', - ), - refmask_val=dict(argstr='--imprefval=%f', - ), - regularization_lambda=dict(argstr='--lambda=%s', - sep=',', - ), - regularization_model=dict(argstr='--regmod=%s', - ), - skip_implicit_in_masking=dict(argstr='--impinm=0', - ), - skip_implicit_ref_masking=dict(argstr='--imprefm=0', - ), - skip_inmask=dict(argstr='--applyinmask=0', - xor=['apply_inmask'], - ), - skip_intensity_mapping=dict(argstr='--estint=0', - xor=['apply_intensity_mapping'], - ), - skip_lambda_ssq=dict(argstr='--ssqlambda=0', - ), - skip_refmask=dict(argstr='--applyrefmask=0', - xor=['apply_refmask'], - ), - spline_order=dict(argstr='--splineorder=%d', - ), - subsampling_scheme=dict(argstr='--subsamp=%s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_resolution=dict(argstr='--warpres=%d,%d,%d', - ), - warped_file=dict(argstr='--iout=%s', - genfile=True, - hash_files=False, - ), + input_map = dict( + affine_file=dict(argstr='--aff=%s', ), + apply_inmask=dict( + argstr='--applyinmask=%s', + sep=',', + xor=['skip_inmask'], + ), + apply_intensity_mapping=dict( + argstr='--estint=%s', + sep=',', + xor=['skip_intensity_mapping'], + ), + apply_refmask=dict( + argstr='--applyrefmask=%s', + sep=',', + xor=['skip_refmask'], + ), + args=dict(argstr='%s', ), + bias_regularization_lambda=dict(argstr='--biaslambda=%f', ), + biasfield_resolution=dict(argstr='--biasres=%d,%d,%d', ), + config_file=dict(argstr='--config=%s', ), + derive_from_ref=dict(argstr='--refderiv', ), + environ=dict( + nohash=True, + usedefault=True, + ), + field_file=dict( + argstr='--fout=%s', + hash_files=False, + ), + fieldcoeff_file=dict(argstr='--cout=%s', ), + hessian_precision=dict(argstr='--numprec=%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--in=%s', + mandatory=True, + ), + in_fwhm=dict( + argstr='--infwhm=%s', + sep=',', + ), + in_intensitymap_file=dict( + argstr='--intin=%s', + copyfile=False, + ), + inmask_file=dict(argstr='--inmask=%s', ), + inmask_val=dict(argstr='--impinval=%f', ), + intensity_mapping_model=dict(argstr='--intmod=%s', ), + intensity_mapping_order=dict(argstr='--intorder=%d', ), + inwarp_file=dict(argstr='--inwarp=%s', ), + jacobian_file=dict( + argstr='--jout=%s', + hash_files=False, + ), + jacobian_range=dict(argstr='--jacrange=%f,%f', ), + log_file=dict( + argstr='--logout=%s', + genfile=True, + hash_files=False, + ), + max_nonlin_iter=dict( + argstr='--miter=%s', + sep=',', + ), + modulatedref_file=dict( + argstr='--refout=%s', + hash_files=False, + ), + out_intensitymap_file=dict( + argstr='--intout=%s', + hash_files=False, + ), + output_type=dict(), + ref_file=dict( + argstr='--ref=%s', + mandatory=True, + ), + ref_fwhm=dict( + argstr='--reffwhm=%s', + sep=',', + ), + refmask_file=dict(argstr='--refmask=%s', ), + refmask_val=dict(argstr='--imprefval=%f', ), + regularization_lambda=dict( + argstr='--lambda=%s', + sep=',', + ), + regularization_model=dict(argstr='--regmod=%s', ), + skip_implicit_in_masking=dict(argstr='--impinm=0', ), + skip_implicit_ref_masking=dict(argstr='--imprefm=0', ), + skip_inmask=dict( + argstr='--applyinmask=0', + xor=['apply_inmask'], + ), + skip_intensity_mapping=dict( + argstr='--estint=0', + xor=['apply_intensity_mapping'], + ), + skip_lambda_ssq=dict(argstr='--ssqlambda=0', ), + skip_refmask=dict( + argstr='--applyrefmask=0', + xor=['apply_refmask'], + ), + spline_order=dict(argstr='--splineorder=%d', ), + subsampling_scheme=dict( + argstr='--subsamp=%s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_resolution=dict(argstr='--warpres=%d,%d,%d', ), + warped_file=dict( + argstr='--iout=%s', + genfile=True, + hash_files=False, + ), ) inputs = FNIRT.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FNIRT_outputs(): - output_map = dict(field_file=dict(), - fieldcoeff_file=dict(), - jacobian_file=dict(), - log_file=dict(), - modulatedref_file=dict(), - out_intensitymap_file=dict(), - warped_file=dict(), + output_map = dict( + field_file=dict(), + fieldcoeff_file=dict(), + jacobian_file=dict(), + log_file=dict(), + modulatedref_file=dict(), + out_intensitymap_file=dict(), + warped_file=dict(), ) outputs = FNIRT.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py b/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py index a88daabceb..d7aa1e1832 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py +++ b/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py @@ -4,23 +4,25 @@ def test_FSLCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FSLCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py b/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py index adabb09143..bb9856338c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py +++ b/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py @@ -4,97 +4,104 @@ def test_FSLXCommand_inputs(): - input_map = dict(all_ard=dict(argstr='--allard', - xor=('no_ard', 'all_ard'), - ), - args=dict(argstr='%s', - ), - burn_in=dict(argstr='--burnin=%d', - ), - burn_in_no_ard=dict(argstr='--burninnoard=%d', - ), - bvals=dict(argstr='--bvals=%s', - mandatory=True, - ), - bvecs=dict(argstr='--bvecs=%s', - mandatory=True, - ), - cnlinear=dict(argstr='--cnonlinear', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - dwi=dict(argstr='--data=%s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - f0_ard=dict(argstr='--f0 --ardf0', - xor=['f0_noard', 'f0_ard', 'all_ard'], - ), - f0_noard=dict(argstr='--f0', - xor=['f0_noard', 'f0_ard'], - ), - force_dir=dict(argstr='--forcedir', - usedefault=True, - ), - fudge=dict(argstr='--fudge=%d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - logdir=dict(argstr='--logdir=%s', - usedefault=True, - ), - mask=dict(argstr='--mask=%s', - mandatory=True, - ), - model=dict(argstr='--model=%d', - ), - n_fibres=dict(argstr='--nfibres=%d', - mandatory=True, - usedefault=True, - ), - n_jumps=dict(argstr='--njumps=%d', - ), - no_ard=dict(argstr='--noard', - xor=('no_ard', 'all_ard'), - ), - no_spat=dict(argstr='--nospat', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - non_linear=dict(argstr='--nonlinear', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - output_type=dict(), - rician=dict(argstr='--rician', - ), - sample_every=dict(argstr='--sampleevery=%d', - ), - seed=dict(argstr='--seed=%d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - update_proposal_every=dict(argstr='--updateproposalevery=%d', - ), + input_map = dict( + all_ard=dict( + argstr='--allard', + xor=('no_ard', 'all_ard'), + ), + args=dict(argstr='%s', ), + burn_in=dict(argstr='--burnin=%d', ), + burn_in_no_ard=dict(argstr='--burninnoard=%d', ), + bvals=dict( + argstr='--bvals=%s', + mandatory=True, + ), + bvecs=dict( + argstr='--bvecs=%s', + mandatory=True, + ), + cnlinear=dict( + argstr='--cnonlinear', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + dwi=dict( + argstr='--data=%s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f0_ard=dict( + argstr='--f0 --ardf0', + xor=['f0_noard', 'f0_ard', 'all_ard'], + ), + f0_noard=dict( + argstr='--f0', + xor=['f0_noard', 'f0_ard'], + ), + force_dir=dict( + argstr='--forcedir', + usedefault=True, + ), + fudge=dict(argstr='--fudge=%d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + logdir=dict( + argstr='--logdir=%s', + usedefault=True, + ), + mask=dict( + argstr='--mask=%s', + mandatory=True, + ), + model=dict(argstr='--model=%d', ), + n_fibres=dict( + argstr='--nfibres=%d', + mandatory=True, + usedefault=True, + ), + n_jumps=dict(argstr='--njumps=%d', ), + no_ard=dict( + argstr='--noard', + xor=('no_ard', 'all_ard'), + ), + no_spat=dict( + argstr='--nospat', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + non_linear=dict( + argstr='--nonlinear', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + output_type=dict(), + rician=dict(argstr='--rician', ), + sample_every=dict(argstr='--sampleevery=%d', ), + seed=dict(argstr='--seed=%d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + update_proposal_every=dict(argstr='--updateproposalevery=%d', ), ) inputs = FSLXCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FSLXCommand_outputs(): - output_map = dict(dyads=dict(), - fsamples=dict(), - mean_S0samples=dict(), - mean_dsamples=dict(), - mean_fsamples=dict(), - mean_tausamples=dict(), - phsamples=dict(), - thsamples=dict(), + output_map = dict( + dyads=dict(), + fsamples=dict(), + mean_S0samples=dict(), + mean_dsamples=dict(), + mean_fsamples=dict(), + mean_tausamples=dict(), + phsamples=dict(), + thsamples=dict(), ) outputs = FSLXCommand.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FUGUE.py b/nipype/interfaces/fsl/tests/test_auto_FUGUE.py index f88ffd7b6f..5a98b48155 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FUGUE.py +++ b/nipype/interfaces/fsl/tests/test_auto_FUGUE.py @@ -4,104 +4,86 @@ def test_FUGUE_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - asym_se_time=dict(argstr='--asym=%.10f', - ), - despike_2dfilter=dict(argstr='--despike', - ), - despike_threshold=dict(argstr='--despikethreshold=%s', - ), - dwell_time=dict(argstr='--dwell=%.10f', - ), - dwell_to_asym_ratio=dict(argstr='--dwelltoasym=%.10f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fmap_in_file=dict(argstr='--loadfmap=%s', - ), - fmap_out_file=dict(argstr='--savefmap=%s', - ), - forward_warping=dict(usedefault=True, - ), - fourier_order=dict(argstr='--fourier=%d', - ), - icorr=dict(argstr='--icorr', - requires=['shift_in_file'], - ), - icorr_only=dict(argstr='--icorronly', - requires=['unwarped_file'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--in=%s', - ), - mask_file=dict(argstr='--mask=%s', - ), - median_2dfilter=dict(argstr='--median', - ), - no_extend=dict(argstr='--noextend', - ), - no_gap_fill=dict(argstr='--nofill', - ), - nokspace=dict(argstr='--nokspace', - ), - output_type=dict(), - pava=dict(argstr='--pava', - ), - phase_conjugate=dict(argstr='--phaseconj', - ), - phasemap_in_file=dict(argstr='--phasemap=%s', - ), - poly_order=dict(argstr='--poly=%d', - ), - save_fmap=dict(xor=['save_unmasked_fmap'], - ), - save_shift=dict(xor=['save_unmasked_shift'], - ), - save_unmasked_fmap=dict(argstr='--unmaskfmap', - xor=['save_fmap'], - ), - save_unmasked_shift=dict(argstr='--unmaskshift', - xor=['save_shift'], - ), - shift_in_file=dict(argstr='--loadshift=%s', - ), - shift_out_file=dict(argstr='--saveshift=%s', - ), - smooth2d=dict(argstr='--smooth2=%.2f', - ), - smooth3d=dict(argstr='--smooth3=%.2f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unwarp_direction=dict(argstr='--unwarpdir=%s', - ), - unwarped_file=dict(argstr='--unwarp=%s', - requires=['in_file'], - xor=['warped_file'], - ), - warped_file=dict(argstr='--warp=%s', - requires=['in_file'], - xor=['unwarped_file'], - ), + input_map = dict( + args=dict(argstr='%s', ), + asym_se_time=dict(argstr='--asym=%.10f', ), + despike_2dfilter=dict(argstr='--despike', ), + despike_threshold=dict(argstr='--despikethreshold=%s', ), + dwell_time=dict(argstr='--dwell=%.10f', ), + dwell_to_asym_ratio=dict(argstr='--dwelltoasym=%.10f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fmap_in_file=dict(argstr='--loadfmap=%s', ), + fmap_out_file=dict(argstr='--savefmap=%s', ), + forward_warping=dict(usedefault=True, ), + fourier_order=dict(argstr='--fourier=%d', ), + icorr=dict( + argstr='--icorr', + requires=['shift_in_file'], + ), + icorr_only=dict( + argstr='--icorronly', + requires=['unwarped_file'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(argstr='--in=%s', ), + mask_file=dict(argstr='--mask=%s', ), + median_2dfilter=dict(argstr='--median', ), + no_extend=dict(argstr='--noextend', ), + no_gap_fill=dict(argstr='--nofill', ), + nokspace=dict(argstr='--nokspace', ), + output_type=dict(), + pava=dict(argstr='--pava', ), + phase_conjugate=dict(argstr='--phaseconj', ), + phasemap_in_file=dict(argstr='--phasemap=%s', ), + poly_order=dict(argstr='--poly=%d', ), + save_fmap=dict(xor=['save_unmasked_fmap'], ), + save_shift=dict(xor=['save_unmasked_shift'], ), + save_unmasked_fmap=dict( + argstr='--unmaskfmap', + xor=['save_fmap'], + ), + save_unmasked_shift=dict( + argstr='--unmaskshift', + xor=['save_shift'], + ), + shift_in_file=dict(argstr='--loadshift=%s', ), + shift_out_file=dict(argstr='--saveshift=%s', ), + smooth2d=dict(argstr='--smooth2=%.2f', ), + smooth3d=dict(argstr='--smooth3=%.2f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unwarp_direction=dict(argstr='--unwarpdir=%s', ), + unwarped_file=dict( + argstr='--unwarp=%s', + requires=['in_file'], + xor=['warped_file'], + ), + warped_file=dict( + argstr='--warp=%s', + requires=['in_file'], + xor=['unwarped_file'], + ), ) inputs = FUGUE.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FUGUE_outputs(): - output_map = dict(fmap_out_file=dict(), - shift_out_file=dict(), - unwarped_file=dict(), - warped_file=dict(), + output_map = dict( + fmap_out_file=dict(), + shift_out_file=dict(), + unwarped_file=dict(), + warped_file=dict(), ) outputs = FUGUE.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py b/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py index 69565fa7c8..a4b8060c2d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py +++ b/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py @@ -4,36 +4,39 @@ def test_FeatureExtractor_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mel_ica=dict(argstr='%s', - copyfile=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mel_ica=dict( + argstr='%s', + copyfile=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FeatureExtractor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FeatureExtractor_outputs(): - output_map = dict(mel_ica=dict(argstr='%s', - copyfile=False, - position=-1, - ), - ) + output_map = dict( + mel_ica=dict( + argstr='%s', + copyfile=False, + position=-1, + ), ) outputs = FeatureExtractor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py b/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py index 576b7ea3ee..7e13a4bb85 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py +++ b/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py @@ -4,59 +4,61 @@ def test_FilterRegressor_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - design_file=dict(argstr='-d %s', - mandatory=True, - position=3, - ), - environ=dict(nohash=True, - usedefault=True, - ), - filter_all=dict(argstr="-f '%s'", - mandatory=True, - position=4, - xor=['filter_columns'], - ), - filter_columns=dict(argstr="-f '%s'", - mandatory=True, - position=4, - xor=['filter_all'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=1, - ), - mask=dict(argstr='-m %s', - ), - out_file=dict(argstr='-o %s', - genfile=True, - hash_files=False, - position=2, - ), - out_vnscales=dict(argstr='--out_vnscales', - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - var_norm=dict(argstr='--vn', - ), + input_map = dict( + args=dict(argstr='%s', ), + design_file=dict( + argstr='-d %s', + mandatory=True, + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filter_all=dict( + argstr="-f '%s'", + mandatory=True, + position=4, + xor=['filter_columns'], + ), + filter_columns=dict( + argstr="-f '%s'", + mandatory=True, + position=4, + xor=['filter_all'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=1, + ), + mask=dict(argstr='-m %s', ), + out_file=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + position=2, + ), + out_vnscales=dict(argstr='--out_vnscales', ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + var_norm=dict(argstr='--vn', ), ) inputs = FilterRegressor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FilterRegressor_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = FilterRegressor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py b/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py index cb5b925f15..9e70f50838 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py +++ b/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py @@ -4,40 +4,41 @@ def test_FindTheBiggest_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=0, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=2, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=0, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=2, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FindTheBiggest.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FindTheBiggest_outputs(): - output_map = dict(out_file=dict(argstr='%s', - ), - ) + output_map = dict(out_file=dict(argstr='%s', ), ) outputs = FindTheBiggest.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_GLM.py b/nipype/interfaces/fsl/tests/test_auto_GLM.py index 846e3f4854..86e0ec995f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_GLM.py +++ b/nipype/interfaces/fsl/tests/test_auto_GLM.py @@ -4,90 +4,77 @@ def test_GLM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - contrasts=dict(argstr='-c %s', - ), - dat_norm=dict(argstr='--dat_norm', - ), - demean=dict(argstr='--demean', - ), - des_norm=dict(argstr='--des_norm', - ), - design=dict(argstr='-d %s', - mandatory=True, - position=2, - ), - dof=dict(argstr='--dof=%d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=1, - ), - mask=dict(argstr='-m %s', - ), - out_cope=dict(argstr='--out_cope=%s', - ), - out_data_name=dict(argstr='--out_data=%s', - ), - out_f_name=dict(argstr='--out_f=%s', - ), - out_file=dict(argstr='-o %s', - keep_extension=True, - name_source='in_file', - name_template='%s_glm', - position=3, - ), - out_p_name=dict(argstr='--out_p=%s', - ), - out_pf_name=dict(argstr='--out_pf=%s', - ), - out_res_name=dict(argstr='--out_res=%s', - ), - out_sigsq_name=dict(argstr='--out_sigsq=%s', - ), - out_t_name=dict(argstr='--out_t=%s', - ), - out_varcb_name=dict(argstr='--out_varcb=%s', - ), - out_vnscales_name=dict(argstr='--out_vnscales=%s', - ), - out_z_name=dict(argstr='--out_z=%s', - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - var_norm=dict(argstr='--vn', - ), + input_map = dict( + args=dict(argstr='%s', ), + contrasts=dict(argstr='-c %s', ), + dat_norm=dict(argstr='--dat_norm', ), + demean=dict(argstr='--demean', ), + des_norm=dict(argstr='--des_norm', ), + design=dict( + argstr='-d %s', + mandatory=True, + position=2, + ), + dof=dict(argstr='--dof=%d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=1, + ), + mask=dict(argstr='-m %s', ), + out_cope=dict(argstr='--out_cope=%s', ), + out_data_name=dict(argstr='--out_data=%s', ), + out_f_name=dict(argstr='--out_f=%s', ), + out_file=dict( + argstr='-o %s', + keep_extension=True, + name_source='in_file', + name_template='%s_glm', + position=3, + ), + out_p_name=dict(argstr='--out_p=%s', ), + out_pf_name=dict(argstr='--out_pf=%s', ), + out_res_name=dict(argstr='--out_res=%s', ), + out_sigsq_name=dict(argstr='--out_sigsq=%s', ), + out_t_name=dict(argstr='--out_t=%s', ), + out_varcb_name=dict(argstr='--out_varcb=%s', ), + out_vnscales_name=dict(argstr='--out_vnscales=%s', ), + out_z_name=dict(argstr='--out_z=%s', ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + var_norm=dict(argstr='--vn', ), ) inputs = GLM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GLM_outputs(): - output_map = dict(out_cope=dict(), - out_data=dict(), - out_f=dict(), - out_file=dict(), - out_p=dict(), - out_pf=dict(), - out_res=dict(), - out_sigsq=dict(), - out_t=dict(), - out_varcb=dict(), - out_vnscales=dict(), - out_z=dict(), + output_map = dict( + out_cope=dict(), + out_data=dict(), + out_f=dict(), + out_file=dict(), + out_p=dict(), + out_pf=dict(), + out_res=dict(), + out_sigsq=dict(), + out_t=dict(), + out_varcb=dict(), + out_vnscales=dict(), + out_z=dict(), ) outputs = GLM.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py b/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py index 3a04429b2c..6d5851c918 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py +++ b/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py @@ -4,64 +4,73 @@ def test_ICA_AROMA_inputs(): - input_map = dict(TR=dict(argstr='-tr %.3f', - ), - args=dict(argstr='%s', - ), - denoise_type=dict(argstr='-den %s', - mandatory=True, - usedefault=True, - ), - dim=dict(argstr='-dim %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - feat_dir=dict(argstr='-feat %s', - mandatory=True, - xor=['in_file', 'mat_file', 'fnirt_warp_file', 'motion_parameters'], - ), - fnirt_warp_file=dict(argstr='-warp %s', - xor=['feat_dir'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - xor=['feat_dir'], - ), - mask=dict(argstr='-m %s', - xor=['feat_dir'], - ), - mat_file=dict(argstr='-affmat %s', - xor=['feat_dir'], - ), - melodic_dir=dict(argstr='-meldir %s', - ), - motion_parameters=dict(argstr='-mc %s', - mandatory=True, - xor=['feat_dir'], - ), - out_dir=dict(argstr='-o %s', - genfile=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + TR=dict(argstr='-tr %.3f', ), + args=dict(argstr='%s', ), + denoise_type=dict( + argstr='-den %s', + mandatory=True, + usedefault=True, + ), + dim=dict(argstr='-dim %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + feat_dir=dict( + argstr='-feat %s', + mandatory=True, + xor=[ + 'in_file', 'mat_file', 'fnirt_warp_file', 'motion_parameters' + ], + ), + fnirt_warp_file=dict( + argstr='-warp %s', + xor=['feat_dir'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + xor=['feat_dir'], + ), + mask=dict( + argstr='-m %s', + xor=['feat_dir'], + ), + mat_file=dict( + argstr='-affmat %s', + xor=['feat_dir'], + ), + melodic_dir=dict(argstr='-meldir %s', ), + motion_parameters=dict( + argstr='-mc %s', + mandatory=True, + xor=['feat_dir'], + ), + out_dir=dict( + argstr='-o %s', + genfile=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ICA_AROMA.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ICA_AROMA_outputs(): - output_map = dict(aggr_denoised_file=dict(), - nonaggr_denoised_file=dict(), - out_dir=dict(), + output_map = dict( + aggr_denoised_file=dict(), + nonaggr_denoised_file=dict(), + out_dir=dict(), ) outputs = ICA_AROMA.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py b/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py index bbff7e8b42..d17a13bd99 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py @@ -4,49 +4,54 @@ def test_ImageMaths_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - in_file2=dict(argstr='%s', - position=3, - ), - op_string=dict(argstr='%s', - position=2, - ), - out_data_type=dict(argstr='-odt %s', - position=5, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=4, - ), - output_type=dict(), - suffix=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + in_file2=dict( + argstr='%s', + position=3, + ), + op_string=dict( + argstr='%s', + position=2, + ), + out_data_type=dict( + argstr='-odt %s', + position=5, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=4, + ), + output_type=dict(), + suffix=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ImageMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ImageMaths_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ImageMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py b/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py index 2991a45c9b..be411b577c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py +++ b/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py @@ -4,55 +4,51 @@ def test_ImageMeants_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - eig=dict(argstr='--eig', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=0, - ), - mask=dict(argstr='-m %s', - ), - nobin=dict(argstr='--no_bin', - ), - order=dict(argstr='--order=%d', - usedefault=True, - ), - out_file=dict(argstr='-o %s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - show_all=dict(argstr='--showall', - ), - spatial_coord=dict(argstr='-c %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transpose=dict(argstr='--transpose', - ), - use_mm=dict(argstr='--usemm', - ), + input_map = dict( + args=dict(argstr='%s', ), + eig=dict(argstr='--eig', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=0, + ), + mask=dict(argstr='-m %s', ), + nobin=dict(argstr='--no_bin', ), + order=dict( + argstr='--order=%d', + usedefault=True, + ), + out_file=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + show_all=dict(argstr='--showall', ), + spatial_coord=dict(argstr='-c %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transpose=dict(argstr='--transpose', ), + use_mm=dict(argstr='--usemm', ), ) inputs = ImageMeants.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ImageMeants_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ImageMeants.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ImageStats.py b/nipype/interfaces/fsl/tests/test_auto_ImageStats.py index 0a97eb2e21..173e16d9ad 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ImageStats.py +++ b/nipype/interfaces/fsl/tests/test_auto_ImageStats.py @@ -4,43 +4,45 @@ def test_ImageStats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - mask_file=dict(argstr='', - ), - op_string=dict(argstr='%s', - mandatory=True, - position=3, - ), - output_type=dict(), - split_4d=dict(argstr='-t', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + mask_file=dict(argstr='', ), + op_string=dict( + argstr='%s', + mandatory=True, + position=3, + ), + output_type=dict(), + split_4d=dict( + argstr='-t', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ImageStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ImageStats_outputs(): - output_map = dict(out_stat=dict(), - ) + output_map = dict(out_stat=dict(), ) outputs = ImageStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_InvWarp.py b/nipype/interfaces/fsl/tests/test_auto_InvWarp.py index 0d96f46d4d..3651e2ec5f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_InvWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_InvWarp.py @@ -4,57 +4,57 @@ def test_InvWarp_inputs(): - input_map = dict(absolute=dict(argstr='--abs', - xor=['relative'], - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inverse_warp=dict(argstr='--out=%s', - hash_files=False, - name_source=['warp'], - name_template='%s_inverse', - ), - jacobian_max=dict(argstr='--jmax=%f', - ), - jacobian_min=dict(argstr='--jmin=%f', - ), - niter=dict(argstr='--niter=%d', - ), - noconstraint=dict(argstr='--noconstraint', - ), - output_type=dict(), - reference=dict(argstr='--ref=%s', - mandatory=True, - ), - regularise=dict(argstr='--regularise=%f', - ), - relative=dict(argstr='--rel', - xor=['absolute'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp=dict(argstr='--warp=%s', - mandatory=True, - ), + input_map = dict( + absolute=dict( + argstr='--abs', + xor=['relative'], + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inverse_warp=dict( + argstr='--out=%s', + hash_files=False, + name_source=['warp'], + name_template='%s_inverse', + ), + jacobian_max=dict(argstr='--jmax=%f', ), + jacobian_min=dict(argstr='--jmin=%f', ), + niter=dict(argstr='--niter=%d', ), + noconstraint=dict(argstr='--noconstraint', ), + output_type=dict(), + reference=dict( + argstr='--ref=%s', + mandatory=True, + ), + regularise=dict(argstr='--regularise=%f', ), + relative=dict( + argstr='--rel', + xor=['absolute'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp=dict( + argstr='--warp=%s', + mandatory=True, + ), ) inputs = InvWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_InvWarp_outputs(): - output_map = dict(inverse_warp=dict(), - ) + output_map = dict(inverse_warp=dict(), ) outputs = InvWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py b/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py index bc02253720..65d2ab3c1c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py +++ b/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py @@ -4,58 +4,65 @@ def test_IsotropicSmooth_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm=dict(argstr='-s %.5f', - mandatory=True, - position=4, - xor=['sigma'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - sigma=dict(argstr='-s %.5f', - mandatory=True, - position=4, - xor=['fwhm'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr='-s %.5f', + mandatory=True, + position=4, + xor=['sigma'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + sigma=dict( + argstr='-s %.5f', + mandatory=True, + position=4, + xor=['fwhm'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = IsotropicSmooth.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_IsotropicSmooth_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = IsotropicSmooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_L2Model.py b/nipype/interfaces/fsl/tests/test_auto_L2Model.py index ef86a37e0e..f174668168 100644 --- a/nipype/interfaces/fsl/tests/test_auto_L2Model.py +++ b/nipype/interfaces/fsl/tests/test_auto_L2Model.py @@ -4,24 +4,24 @@ def test_L2Model_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - num_copes=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + num_copes=dict(mandatory=True, ), ) inputs = L2Model.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_L2Model_outputs(): - output_map = dict(design_con=dict(), - design_grp=dict(), - design_mat=dict(), + output_map = dict( + design_con=dict(), + design_grp=dict(), + design_mat=dict(), ) outputs = L2Model.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Level1Design.py b/nipype/interfaces/fsl/tests/test_auto_Level1Design.py index c15f8e055a..13100792c5 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Level1Design.py +++ b/nipype/interfaces/fsl/tests/test_auto_Level1Design.py @@ -4,31 +4,28 @@ def test_Level1Design_inputs(): - input_map = dict(bases=dict(mandatory=True, - ), - contrasts=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interscan_interval=dict(mandatory=True, - ), - model_serial_correlations=dict(mandatory=True, - ), - orthogonalization=dict(), - session_info=dict(mandatory=True, - ), + input_map = dict( + bases=dict(mandatory=True, ), + contrasts=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interscan_interval=dict(mandatory=True, ), + model_serial_correlations=dict(mandatory=True, ), + orthogonalization=dict(), + session_info=dict(mandatory=True, ), ) inputs = Level1Design.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Level1Design_outputs(): - output_map = dict(ev_files=dict(), - fsf_files=dict(), + output_map = dict( + ev_files=dict(), + fsf_files=dict(), ) outputs = Level1Design.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py b/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py index 07ecdc9094..c7ad885daf 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py +++ b/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py @@ -4,79 +4,65 @@ def test_MCFLIRT_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bins=dict(argstr='-bins %d', - ), - cost=dict(argstr='-cost %s', - ), - dof=dict(argstr='-dof %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - position=0, - ), - init=dict(argstr='-init %s', - ), - interpolation=dict(argstr='-%s_final', - ), - mean_vol=dict(argstr='-meanvol', - ), - out_file=dict(argstr='-out %s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - ref_file=dict(argstr='-reffile %s', - ), - ref_vol=dict(argstr='-refvol %d', - ), - rotation=dict(argstr='-rotation %d', - ), - save_mats=dict(argstr='-mats', - ), - save_plots=dict(argstr='-plots', - ), - save_rms=dict(argstr='-rmsabs -rmsrel', - ), - scaling=dict(argstr='-scaling %.2f', - ), - smooth=dict(argstr='-smooth %.2f', - ), - stages=dict(argstr='-stages %d', - ), - stats_imgs=dict(argstr='-stats', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_contour=dict(argstr='-edge', - ), - use_gradient=dict(argstr='-gdt', - ), + input_map = dict( + args=dict(argstr='%s', ), + bins=dict(argstr='-bins %d', ), + cost=dict(argstr='-cost %s', ), + dof=dict(argstr='-dof %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + position=0, + ), + init=dict(argstr='-init %s', ), + interpolation=dict(argstr='-%s_final', ), + mean_vol=dict(argstr='-meanvol', ), + out_file=dict( + argstr='-out %s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + ref_file=dict(argstr='-reffile %s', ), + ref_vol=dict(argstr='-refvol %d', ), + rotation=dict(argstr='-rotation %d', ), + save_mats=dict(argstr='-mats', ), + save_plots=dict(argstr='-plots', ), + save_rms=dict(argstr='-rmsabs -rmsrel', ), + scaling=dict(argstr='-scaling %.2f', ), + smooth=dict(argstr='-smooth %.2f', ), + stages=dict(argstr='-stages %d', ), + stats_imgs=dict(argstr='-stats', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_contour=dict(argstr='-edge', ), + use_gradient=dict(argstr='-gdt', ), ) inputs = MCFLIRT.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MCFLIRT_outputs(): - output_map = dict(mat_file=dict(), - mean_img=dict(), - out_file=dict(), - par_file=dict(), - rms_files=dict(), - std_img=dict(), - variance_img=dict(), + output_map = dict( + mat_file=dict(), + mean_img=dict(), + out_file=dict(), + par_file=dict(), + rms_files=dict(), + std_img=dict(), + variance_img=dict(), ) outputs = MCFLIRT.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_MELODIC.py b/nipype/interfaces/fsl/tests/test_auto_MELODIC.py index 5e009e701d..ecfbbf8fd0 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MELODIC.py +++ b/nipype/interfaces/fsl/tests/test_auto_MELODIC.py @@ -4,130 +4,88 @@ def test_MELODIC_inputs(): - input_map = dict(ICs=dict(argstr='--ICs=%s', - ), - approach=dict(argstr='-a %s', - ), - args=dict(argstr='%s', - ), - bg_image=dict(argstr='--bgimage=%s', - ), - bg_threshold=dict(argstr='--bgthreshold=%f', - ), - cov_weight=dict(argstr='--covarweight=%f', - ), - dim=dict(argstr='-d %d', - ), - dim_est=dict(argstr='--dimest=%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - epsilon=dict(argstr='--eps=%f', - ), - epsilonS=dict(argstr='--epsS=%f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='-i %s', - mandatory=True, - position=0, - sep=',', - ), - log_power=dict(argstr='--logPower', - ), - mask=dict(argstr='-m %s', - ), - max_restart=dict(argstr='--maxrestart=%d', - ), - maxit=dict(argstr='--maxit=%d', - ), - migp=dict(argstr='--migp', - ), - migpN=dict(argstr='--migpN %d', - ), - migp_factor=dict(argstr='--migp_factor %d', - ), - migp_shuffle=dict(argstr='--migp_shuffle', - ), - mix=dict(argstr='--mix=%s', - ), - mm_thresh=dict(argstr='--mmthresh=%f', - ), - no_bet=dict(argstr='--nobet', - ), - no_mask=dict(argstr='--nomask', - ), - no_mm=dict(argstr='--no_mm', - ), - non_linearity=dict(argstr='--nl=%s', - ), - num_ICs=dict(argstr='-n %d', - ), - out_all=dict(argstr='--Oall', - ), - out_dir=dict(argstr='-o %s', - genfile=True, - ), - out_mean=dict(argstr='--Omean', - ), - out_orig=dict(argstr='--Oorig', - ), - out_pca=dict(argstr='--Opca', - ), - out_stats=dict(argstr='--Ostats', - ), - out_unmix=dict(argstr='--Ounmix', - ), - out_white=dict(argstr='--Owhite', - ), - output_type=dict(), - pbsc=dict(argstr='--pbsc', - ), - rem_cmp=dict(argstr='-f %d', - ), - remove_deriv=dict(argstr='--remove_deriv', - ), - report=dict(argstr='--report', - ), - report_maps=dict(argstr='--report_maps=%s', - ), - s_con=dict(argstr='--Scon=%s', - ), - s_des=dict(argstr='--Sdes=%s', - ), - sep_vn=dict(argstr='--sep_vn', - ), - sep_whiten=dict(argstr='--sep_whiten', - ), - smode=dict(argstr='--smode=%s', - ), - t_con=dict(argstr='--Tcon=%s', - ), - t_des=dict(argstr='--Tdes=%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tr_sec=dict(argstr='--tr=%f', - ), - update_mask=dict(argstr='--update_mask', - ), - var_norm=dict(argstr='--vn', - ), + input_map = dict( + ICs=dict(argstr='--ICs=%s', ), + approach=dict(argstr='-a %s', ), + args=dict(argstr='%s', ), + bg_image=dict(argstr='--bgimage=%s', ), + bg_threshold=dict(argstr='--bgthreshold=%f', ), + cov_weight=dict(argstr='--covarweight=%f', ), + dim=dict(argstr='-d %d', ), + dim_est=dict(argstr='--dimest=%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epsilon=dict(argstr='--eps=%f', ), + epsilonS=dict(argstr='--epsS=%f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='-i %s', + mandatory=True, + position=0, + sep=',', + ), + log_power=dict(argstr='--logPower', ), + mask=dict(argstr='-m %s', ), + max_restart=dict(argstr='--maxrestart=%d', ), + maxit=dict(argstr='--maxit=%d', ), + migp=dict(argstr='--migp', ), + migpN=dict(argstr='--migpN %d', ), + migp_factor=dict(argstr='--migp_factor %d', ), + migp_shuffle=dict(argstr='--migp_shuffle', ), + mix=dict(argstr='--mix=%s', ), + mm_thresh=dict(argstr='--mmthresh=%f', ), + no_bet=dict(argstr='--nobet', ), + no_mask=dict(argstr='--nomask', ), + no_mm=dict(argstr='--no_mm', ), + non_linearity=dict(argstr='--nl=%s', ), + num_ICs=dict(argstr='-n %d', ), + out_all=dict(argstr='--Oall', ), + out_dir=dict( + argstr='-o %s', + genfile=True, + ), + out_mean=dict(argstr='--Omean', ), + out_orig=dict(argstr='--Oorig', ), + out_pca=dict(argstr='--Opca', ), + out_stats=dict(argstr='--Ostats', ), + out_unmix=dict(argstr='--Ounmix', ), + out_white=dict(argstr='--Owhite', ), + output_type=dict(), + pbsc=dict(argstr='--pbsc', ), + rem_cmp=dict(argstr='-f %d', ), + remove_deriv=dict(argstr='--remove_deriv', ), + report=dict(argstr='--report', ), + report_maps=dict(argstr='--report_maps=%s', ), + s_con=dict(argstr='--Scon=%s', ), + s_des=dict(argstr='--Sdes=%s', ), + sep_vn=dict(argstr='--sep_vn', ), + sep_whiten=dict(argstr='--sep_whiten', ), + smode=dict(argstr='--smode=%s', ), + t_con=dict(argstr='--Tcon=%s', ), + t_des=dict(argstr='--Tdes=%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tr_sec=dict(argstr='--tr=%f', ), + update_mask=dict(argstr='--update_mask', ), + var_norm=dict(argstr='--vn', ), ) inputs = MELODIC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MELODIC_outputs(): - output_map = dict(out_dir=dict(), - report_dir=dict(), + output_map = dict( + out_dir=dict(), + report_dir=dict(), ) outputs = MELODIC.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py b/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py index 447be7025e..70c536022d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py +++ b/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py @@ -4,49 +4,56 @@ def test_MakeDyadicVectors_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask=dict(argstr='%s', - position=2, - ), - output=dict(argstr='%s', - hash_files=False, - position=3, - usedefault=True, - ), - output_type=dict(), - perc=dict(argstr='%f', - position=4, - ), - phi_vol=dict(argstr='%s', - mandatory=True, - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - theta_vol=dict(argstr='%s', - mandatory=True, - position=0, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask=dict( + argstr='%s', + position=2, + ), + output=dict( + argstr='%s', + hash_files=False, + position=3, + usedefault=True, + ), + output_type=dict(), + perc=dict( + argstr='%f', + position=4, + ), + phi_vol=dict( + argstr='%s', + mandatory=True, + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + theta_vol=dict( + argstr='%s', + mandatory=True, + position=0, + ), ) inputs = MakeDyadicVectors.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MakeDyadicVectors_outputs(): - output_map = dict(dispersion=dict(), - dyads=dict(), + output_map = dict( + dispersion=dict(), + dyads=dict(), ) outputs = MakeDyadicVectors.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py b/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py index 224bc3ee75..62d91100e0 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py +++ b/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py @@ -4,48 +4,53 @@ def test_MathsCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MathsCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MathsCommand_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MathsCommand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MaxImage.py b/nipype/interfaces/fsl/tests/test_auto_MaxImage.py index 536a44bccf..54e2e48f48 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MaxImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MaxImage.py @@ -4,52 +4,58 @@ def test_MaxImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%smax', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%smax', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MaxImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MaxImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MaxImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py b/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py index 09aec304d8..786e2370ff 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py @@ -4,52 +4,58 @@ def test_MaxnImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%smaxn', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%smaxn', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MaxnImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MaxnImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MaxnImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MeanImage.py b/nipype/interfaces/fsl/tests/test_auto_MeanImage.py index c444c296ad..7129923ed2 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MeanImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MeanImage.py @@ -4,52 +4,58 @@ def test_MeanImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%smean', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%smean', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MeanImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MeanImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MeanImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MedianImage.py b/nipype/interfaces/fsl/tests/test_auto_MedianImage.py index b398d50975..ec21fd00c5 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MedianImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MedianImage.py @@ -4,52 +4,58 @@ def test_MedianImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%smedian', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%smedian', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MedianImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedianImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MedianImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Merge.py b/nipype/interfaces/fsl/tests/test_auto_Merge.py index 0638326c65..15d66dc07b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Merge.py +++ b/nipype/interfaces/fsl/tests/test_auto_Merge.py @@ -4,47 +4,51 @@ def test_Merge_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%s', - mandatory=True, - position=0, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=2, - ), - merged_file=dict(argstr='%s', - hash_files=False, - name_source='in_files', - name_template='%s_merged', - position=1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tr=dict(argstr='%.2f', - position=-1, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%s', + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=2, + ), + merged_file=dict( + argstr='%s', + hash_files=False, + name_source='in_files', + name_template='%s_merged', + position=1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tr=dict( + argstr='%.2f', + position=-1, + ), ) inputs = Merge.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Merge_outputs(): - output_map = dict(merged_file=dict(), - ) + output_map = dict(merged_file=dict(), ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MinImage.py b/nipype/interfaces/fsl/tests/test_auto_MinImage.py index f2216fb083..2237aec45d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MinImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MinImage.py @@ -4,52 +4,58 @@ def test_MinImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%smin', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%smin', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MinImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MinImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MinImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py b/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py index 7921e1031c..272017a155 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py +++ b/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py @@ -4,62 +4,63 @@ def test_MotionOutliers_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dummy=dict(argstr='--dummy=%d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - ), - mask=dict(argstr='-m %s', - ), - metric=dict(argstr='--%s', - ), - no_motion_correction=dict(argstr='--nomoco', - ), - out_file=dict(argstr='-o %s', - hash_files=False, - keep_extension=True, - name_source='in_file', - name_template='%s_outliers.txt', - ), - out_metric_plot=dict(argstr='-p %s', - hash_files=False, - keep_extension=True, - name_source='in_file', - name_template='%s_metrics.png', - ), - out_metric_values=dict(argstr='-s %s', - hash_files=False, - keep_extension=True, - name_source='in_file', - name_template='%s_metrics.txt', - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--thresh=%g', - ), + input_map = dict( + args=dict(argstr='%s', ), + dummy=dict(argstr='--dummy=%d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + ), + mask=dict(argstr='-m %s', ), + metric=dict(argstr='--%s', ), + no_motion_correction=dict(argstr='--nomoco', ), + out_file=dict( + argstr='-o %s', + hash_files=False, + keep_extension=True, + name_source='in_file', + name_template='%s_outliers.txt', + ), + out_metric_plot=dict( + argstr='-p %s', + hash_files=False, + keep_extension=True, + name_source='in_file', + name_template='%s_metrics.png', + ), + out_metric_values=dict( + argstr='-s %s', + hash_files=False, + keep_extension=True, + name_source='in_file', + name_template='%s_metrics.txt', + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='--thresh=%g', ), ) inputs = MotionOutliers.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MotionOutliers_outputs(): - output_map = dict(out_file=dict(), - out_metric_plot=dict(), - out_metric_values=dict(), + output_map = dict( + out_file=dict(), + out_metric_plot=dict(), + out_metric_values=dict(), ) outputs = MotionOutliers.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py b/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py index 4a67036b55..5d6af66596 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py @@ -4,54 +4,59 @@ def test_MultiImageMaths_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - op_string=dict(argstr='%s', - mandatory=True, - position=4, - ), - operand_files=dict(mandatory=True, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + op_string=dict( + argstr='%s', + mandatory=True, + position=4, + ), + operand_files=dict(mandatory=True, ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MultiImageMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MultiImageMaths_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MultiImageMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py b/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py index c0bd71f12a..52a36111e7 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py +++ b/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py @@ -4,28 +4,27 @@ def test_MultipleRegressDesign_inputs(): - input_map = dict(contrasts=dict(mandatory=True, - ), - groups=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - regressors=dict(mandatory=True, - ), + input_map = dict( + contrasts=dict(mandatory=True, ), + groups=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + regressors=dict(mandatory=True, ), ) inputs = MultipleRegressDesign.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MultipleRegressDesign_outputs(): - output_map = dict(design_con=dict(), - design_fts=dict(), - design_grp=dict(), - design_mat=dict(), + output_map = dict( + design_con=dict(), + design_fts=dict(), + design_grp=dict(), + design_mat=dict(), ) outputs = MultipleRegressDesign.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Overlay.py b/nipype/interfaces/fsl/tests/test_auto_Overlay.py index 91b09fdd7a..133e75ac56 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Overlay.py +++ b/nipype/interfaces/fsl/tests/test_auto_Overlay.py @@ -4,84 +4,97 @@ def test_Overlay_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - auto_thresh_bg=dict(argstr='-a', - mandatory=True, - position=5, - xor=('auto_thresh_bg', 'full_bg_range', 'bg_thresh'), - ), - background_image=dict(argstr='%s', - mandatory=True, - position=4, - ), - bg_thresh=dict(argstr='%.3f %.3f', - mandatory=True, - position=5, - xor=('auto_thresh_bg', 'full_bg_range', 'bg_thresh'), - ), - environ=dict(nohash=True, - usedefault=True, - ), - full_bg_range=dict(argstr='-A', - mandatory=True, - position=5, - xor=('auto_thresh_bg', 'full_bg_range', 'bg_thresh'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-1, - ), - out_type=dict(argstr='%s', - position=2, - usedefault=True, - ), - output_type=dict(), - show_negative_stats=dict(argstr='%s', - position=8, - xor=['stat_image2'], - ), - stat_image=dict(argstr='%s', - mandatory=True, - position=6, - ), - stat_image2=dict(argstr='%s', - position=9, - xor=['show_negative_stats'], - ), - stat_thresh=dict(argstr='%.2f %.2f', - mandatory=True, - position=7, - ), - stat_thresh2=dict(argstr='%.2f %.2f', - position=10, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transparency=dict(argstr='%s', - position=1, - usedefault=True, - ), - use_checkerboard=dict(argstr='-c', - position=3, - ), + input_map = dict( + args=dict(argstr='%s', ), + auto_thresh_bg=dict( + argstr='-a', + mandatory=True, + position=5, + xor=('auto_thresh_bg', 'full_bg_range', 'bg_thresh'), + ), + background_image=dict( + argstr='%s', + mandatory=True, + position=4, + ), + bg_thresh=dict( + argstr='%.3f %.3f', + mandatory=True, + position=5, + xor=('auto_thresh_bg', 'full_bg_range', 'bg_thresh'), + ), + environ=dict( + nohash=True, + usedefault=True, + ), + full_bg_range=dict( + argstr='-A', + mandatory=True, + position=5, + xor=('auto_thresh_bg', 'full_bg_range', 'bg_thresh'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-1, + ), + out_type=dict( + argstr='%s', + position=2, + usedefault=True, + ), + output_type=dict(), + show_negative_stats=dict( + argstr='%s', + position=8, + xor=['stat_image2'], + ), + stat_image=dict( + argstr='%s', + mandatory=True, + position=6, + ), + stat_image2=dict( + argstr='%s', + position=9, + xor=['show_negative_stats'], + ), + stat_thresh=dict( + argstr='%.2f %.2f', + mandatory=True, + position=7, + ), + stat_thresh2=dict( + argstr='%.2f %.2f', + position=10, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transparency=dict( + argstr='%s', + position=1, + usedefault=True, + ), + use_checkerboard=dict( + argstr='-c', + position=3, + ), ) inputs = Overlay.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Overlay_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Overlay.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py b/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py index 98b8d69889..fd1b59f91a 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py +++ b/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py @@ -4,75 +4,77 @@ def test_PRELUDE_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - complex_phase_file=dict(argstr='--complex=%s', - mandatory=True, - xor=['magnitude_file', 'phase_file'], - ), - end=dict(argstr='--end=%d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - label_file=dict(argstr='--labels=%s', - hash_files=False, - ), - labelprocess2d=dict(argstr='--labelslices', - ), - magnitude_file=dict(argstr='--abs=%s', - mandatory=True, - xor=['complex_phase_file'], - ), - mask_file=dict(argstr='--mask=%s', - ), - num_partitions=dict(argstr='--numphasesplit=%d', - ), - output_type=dict(), - phase_file=dict(argstr='--phase=%s', - mandatory=True, - xor=['complex_phase_file'], - ), - process2d=dict(argstr='--slices', - xor=['labelprocess2d'], - ), - process3d=dict(argstr='--force3D', - xor=['labelprocess2d', 'process2d'], - ), - rawphase_file=dict(argstr='--rawphase=%s', - hash_files=False, - ), - removeramps=dict(argstr='--removeramps', - ), - savemask_file=dict(argstr='--savemask=%s', - hash_files=False, - ), - start=dict(argstr='--start=%d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--thresh=%.10f', - ), - unwrapped_phase_file=dict(argstr='--unwrap=%s', - genfile=True, - hash_files=False, - ), + input_map = dict( + args=dict(argstr='%s', ), + complex_phase_file=dict( + argstr='--complex=%s', + mandatory=True, + xor=['magnitude_file', 'phase_file'], + ), + end=dict(argstr='--end=%d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + label_file=dict( + argstr='--labels=%s', + hash_files=False, + ), + labelprocess2d=dict(argstr='--labelslices', ), + magnitude_file=dict( + argstr='--abs=%s', + mandatory=True, + xor=['complex_phase_file'], + ), + mask_file=dict(argstr='--mask=%s', ), + num_partitions=dict(argstr='--numphasesplit=%d', ), + output_type=dict(), + phase_file=dict( + argstr='--phase=%s', + mandatory=True, + xor=['complex_phase_file'], + ), + process2d=dict( + argstr='--slices', + xor=['labelprocess2d'], + ), + process3d=dict( + argstr='--force3D', + xor=['labelprocess2d', 'process2d'], + ), + rawphase_file=dict( + argstr='--rawphase=%s', + hash_files=False, + ), + removeramps=dict(argstr='--removeramps', ), + savemask_file=dict( + argstr='--savemask=%s', + hash_files=False, + ), + start=dict(argstr='--start=%d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='--thresh=%.10f', ), + unwrapped_phase_file=dict( + argstr='--unwrap=%s', + genfile=True, + hash_files=False, + ), ) inputs = PRELUDE.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PRELUDE_outputs(): - output_map = dict(unwrapped_phase_file=dict(), - ) + output_map = dict(unwrapped_phase_file=dict(), ) outputs = PRELUDE.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py b/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py index 36fd550b23..f04ce1aa84 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py @@ -4,56 +4,63 @@ def test_PercentileImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%sperc', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - perc=dict(argstr='%f', - position=5, - usedefault=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%sperc', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + perc=dict( + argstr='%f', + position=5, + usedefault=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = PercentileImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PercentileImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = PercentileImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py b/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py index e910f7e173..9825583ef9 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py +++ b/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py @@ -4,45 +4,46 @@ def test_PlotMotionParams_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - in_source=dict(mandatory=True, - ), - out_file=dict(argstr='-o %s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - plot_size=dict(argstr='%s', - ), - plot_type=dict(argstr='%s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + in_source=dict(mandatory=True, ), + out_file=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + plot_size=dict(argstr='%s', ), + plot_type=dict( + argstr='%s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = PlotMotionParams.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PlotMotionParams_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = PlotMotionParams.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py b/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py index feaa9d8449..a17f89769e 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py +++ b/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py @@ -4,71 +4,74 @@ def test_PlotTimeSeries_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - labels=dict(argstr='%s', - ), - legend_file=dict(argstr='--legend=%s', - ), - out_file=dict(argstr='-o %s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - plot_finish=dict(argstr='--finish=%d', - xor=('plot_range',), - ), - plot_range=dict(argstr='%s', - xor=('plot_start', 'plot_finish'), - ), - plot_size=dict(argstr='%s', - ), - plot_start=dict(argstr='--start=%d', - xor=('plot_range',), - ), - sci_notation=dict(argstr='--sci', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - title=dict(argstr='%s', - ), - x_precision=dict(argstr='--precision=%d', - ), - x_units=dict(argstr='-u %d', - usedefault=True, - ), - y_max=dict(argstr='--ymax=%.2f', - xor=('y_range',), - ), - y_min=dict(argstr='--ymin=%.2f', - xor=('y_range',), - ), - y_range=dict(argstr='%s', - xor=('y_min', 'y_max'), - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + labels=dict(argstr='%s', ), + legend_file=dict(argstr='--legend=%s', ), + out_file=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + plot_finish=dict( + argstr='--finish=%d', + xor=('plot_range', ), + ), + plot_range=dict( + argstr='%s', + xor=('plot_start', 'plot_finish'), + ), + plot_size=dict(argstr='%s', ), + plot_start=dict( + argstr='--start=%d', + xor=('plot_range', ), + ), + sci_notation=dict(argstr='--sci', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + title=dict(argstr='%s', ), + x_precision=dict(argstr='--precision=%d', ), + x_units=dict( + argstr='-u %d', + usedefault=True, + ), + y_max=dict( + argstr='--ymax=%.2f', + xor=('y_range', ), + ), + y_min=dict( + argstr='--ymin=%.2f', + xor=('y_range', ), + ), + y_range=dict( + argstr='%s', + xor=('y_min', 'y_max'), + ), ) inputs = PlotTimeSeries.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PlotTimeSeries_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = PlotTimeSeries.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py b/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py index 409c8bfee6..a09b8e6683 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py +++ b/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py @@ -4,39 +4,41 @@ def test_PowerSpectrum_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = PowerSpectrum.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PowerSpectrum_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = PowerSpectrum.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py b/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py index b9bf8c1c94..33ddb4cd09 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py +++ b/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py @@ -4,54 +4,60 @@ def test_PrepareFieldmap_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - delta_TE=dict(argstr='%f', - mandatory=True, - position=-2, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_magnitude=dict(argstr='%s', - mandatory=True, - position=3, - ), - in_phase=dict(argstr='%s', - mandatory=True, - position=2, - ), - nocheck=dict(argstr='--nocheck', - position=-1, - usedefault=True, - ), - out_fieldmap=dict(argstr='%s', - position=4, - ), - output_type=dict(), - scanner=dict(argstr='%s', - position=1, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + delta_TE=dict( + argstr='%f', + mandatory=True, + position=-2, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_magnitude=dict( + argstr='%s', + mandatory=True, + position=3, + ), + in_phase=dict( + argstr='%s', + mandatory=True, + position=2, + ), + nocheck=dict( + argstr='--nocheck', + position=-1, + usedefault=True, + ), + out_fieldmap=dict( + argstr='%s', + position=4, + ), + output_type=dict(), + scanner=dict( + argstr='%s', + position=1, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = PrepareFieldmap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PrepareFieldmap_outputs(): - output_map = dict(out_fieldmap=dict(), - ) + output_map = dict(out_fieldmap=dict(), ) outputs = PrepareFieldmap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py index 12352f4a38..ef5dc6b288 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py +++ b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py @@ -4,113 +4,95 @@ def test_ProbTrackX_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - avoid_mp=dict(argstr='--avoid=%s', - ), - c_thresh=dict(argstr='--cthr=%.3f', - ), - correct_path_distribution=dict(argstr='--pd', - ), - dist_thresh=dict(argstr='--distthresh=%.3f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fibst=dict(argstr='--fibst=%d', - ), - force_dir=dict(argstr='--forcedir', - usedefault=True, - ), - fsamples=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inv_xfm=dict(argstr='--invxfm=%s', - ), - loop_check=dict(argstr='--loopcheck', - ), - mask=dict(argstr='-m %s', - mandatory=True, - ), - mask2=dict(argstr='--mask2=%s', - ), - mesh=dict(argstr='--mesh=%s', - ), - mod_euler=dict(argstr='--modeuler', - ), - mode=dict(argstr='--mode=%s', - genfile=True, - ), - n_samples=dict(argstr='--nsamples=%d', - usedefault=True, - ), - n_steps=dict(argstr='--nsteps=%d', - ), - network=dict(argstr='--network', - ), - opd=dict(argstr='--opd', - usedefault=True, - ), - os2t=dict(argstr='--os2t', - ), - out_dir=dict(argstr='--dir=%s', - genfile=True, - ), - output_type=dict(), - phsamples=dict(mandatory=True, - ), - rand_fib=dict(argstr='--randfib=%d', - ), - random_seed=dict(argstr='--rseed', - ), - s2tastext=dict(argstr='--s2tastext', - ), - sample_random_points=dict(argstr='--sampvox', - ), - samples_base_name=dict(argstr='--samples=%s', - usedefault=True, - ), - seed=dict(argstr='--seed=%s', - mandatory=True, - ), - seed_ref=dict(argstr='--seedref=%s', - ), - step_length=dict(argstr='--steplength=%.3f', - ), - stop_mask=dict(argstr='--stop=%s', - ), - target_masks=dict(argstr='--targetmasks=%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thsamples=dict(mandatory=True, - ), - use_anisotropy=dict(argstr='--usef', - ), - verbose=dict(argstr='--verbose=%d', - ), - waypoints=dict(argstr='--waypoints=%s', - ), - xfm=dict(argstr='--xfm=%s', - ), + input_map = dict( + args=dict(argstr='%s', ), + avoid_mp=dict(argstr='--avoid=%s', ), + c_thresh=dict(argstr='--cthr=%.3f', ), + correct_path_distribution=dict(argstr='--pd', ), + dist_thresh=dict(argstr='--distthresh=%.3f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fibst=dict(argstr='--fibst=%d', ), + force_dir=dict( + argstr='--forcedir', + usedefault=True, + ), + fsamples=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inv_xfm=dict(argstr='--invxfm=%s', ), + loop_check=dict(argstr='--loopcheck', ), + mask=dict( + argstr='-m %s', + mandatory=True, + ), + mask2=dict(argstr='--mask2=%s', ), + mesh=dict(argstr='--mesh=%s', ), + mod_euler=dict(argstr='--modeuler', ), + mode=dict( + argstr='--mode=%s', + genfile=True, + ), + n_samples=dict( + argstr='--nsamples=%d', + usedefault=True, + ), + n_steps=dict(argstr='--nsteps=%d', ), + network=dict(argstr='--network', ), + opd=dict( + argstr='--opd', + usedefault=True, + ), + os2t=dict(argstr='--os2t', ), + out_dir=dict( + argstr='--dir=%s', + genfile=True, + ), + output_type=dict(), + phsamples=dict(mandatory=True, ), + rand_fib=dict(argstr='--randfib=%d', ), + random_seed=dict(argstr='--rseed', ), + s2tastext=dict(argstr='--s2tastext', ), + sample_random_points=dict(argstr='--sampvox', ), + samples_base_name=dict( + argstr='--samples=%s', + usedefault=True, + ), + seed=dict( + argstr='--seed=%s', + mandatory=True, + ), + seed_ref=dict(argstr='--seedref=%s', ), + step_length=dict(argstr='--steplength=%.3f', ), + stop_mask=dict(argstr='--stop=%s', ), + target_masks=dict(argstr='--targetmasks=%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thsamples=dict(mandatory=True, ), + use_anisotropy=dict(argstr='--usef', ), + verbose=dict(argstr='--verbose=%d', ), + waypoints=dict(argstr='--waypoints=%s', ), + xfm=dict(argstr='--xfm=%s', ), ) inputs = ProbTrackX.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ProbTrackX_outputs(): - output_map = dict(fdt_paths=dict(), - log=dict(), - particle_files=dict(), - targets=dict(), - way_total=dict(), + output_map = dict( + fdt_paths=dict(), + log=dict(), + particle_files=dict(), + targets=dict(), + way_total=dict(), ) outputs = ProbTrackX.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py index 249bc87777..975fbb5ac5 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py +++ b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py @@ -4,148 +4,120 @@ def test_ProbTrackX2_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - avoid_mp=dict(argstr='--avoid=%s', - ), - c_thresh=dict(argstr='--cthr=%.3f', - ), - colmask4=dict(argstr='--colmask4=%s', - ), - correct_path_distribution=dict(argstr='--pd', - ), - dist_thresh=dict(argstr='--distthresh=%.3f', - ), - distthresh1=dict(argstr='--distthresh1=%.3f', - ), - distthresh3=dict(argstr='--distthresh3=%.3f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fibst=dict(argstr='--fibst=%d', - ), - fopd=dict(argstr='--fopd=%s', - ), - force_dir=dict(argstr='--forcedir', - usedefault=True, - ), - fsamples=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inv_xfm=dict(argstr='--invxfm=%s', - ), - loop_check=dict(argstr='--loopcheck', - ), - lrtarget3=dict(argstr='--lrtarget3=%s', - ), - mask=dict(argstr='-m %s', - mandatory=True, - ), - meshspace=dict(argstr='--meshspace=%s', - ), - mod_euler=dict(argstr='--modeuler', - ), - n_samples=dict(argstr='--nsamples=%d', - usedefault=True, - ), - n_steps=dict(argstr='--nsteps=%d', - ), - network=dict(argstr='--network', - ), - omatrix1=dict(argstr='--omatrix1', - ), - omatrix2=dict(argstr='--omatrix2', - requires=['target2'], - ), - omatrix3=dict(argstr='--omatrix3', - requires=['target3', 'lrtarget3'], - ), - omatrix4=dict(argstr='--omatrix4', - ), - onewaycondition=dict(argstr='--onewaycondition', - ), - opd=dict(argstr='--opd', - usedefault=True, - ), - os2t=dict(argstr='--os2t', - ), - out_dir=dict(argstr='--dir=%s', - genfile=True, - ), - output_type=dict(), - phsamples=dict(mandatory=True, - ), - rand_fib=dict(argstr='--randfib=%d', - ), - random_seed=dict(argstr='--rseed', - ), - s2tastext=dict(argstr='--s2tastext', - ), - sample_random_points=dict(argstr='--sampvox', - ), - samples_base_name=dict(argstr='--samples=%s', - usedefault=True, - ), - seed=dict(argstr='--seed=%s', - mandatory=True, - ), - seed_ref=dict(argstr='--seedref=%s', - ), - simple=dict(argstr='--simple', - usedefault=False, - ), - step_length=dict(argstr='--steplength=%.3f', - ), - stop_mask=dict(argstr='--stop=%s', - ), - target2=dict(argstr='--target2=%s', - ), - target3=dict(argstr='--target3=%s', - ), - target4=dict(argstr='--target4=%s', - ), - target_masks=dict(argstr='--targetmasks=%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thsamples=dict(mandatory=True, - ), - use_anisotropy=dict(argstr='--usef', - ), - verbose=dict(argstr='--verbose=%d', - ), - waycond=dict(argstr='--waycond=%s', - ), - wayorder=dict(argstr='--wayorder', - ), - waypoints=dict(argstr='--waypoints=%s', - ), - xfm=dict(argstr='--xfm=%s', - ), + input_map = dict( + args=dict(argstr='%s', ), + avoid_mp=dict(argstr='--avoid=%s', ), + c_thresh=dict(argstr='--cthr=%.3f', ), + colmask4=dict(argstr='--colmask4=%s', ), + correct_path_distribution=dict(argstr='--pd', ), + dist_thresh=dict(argstr='--distthresh=%.3f', ), + distthresh1=dict(argstr='--distthresh1=%.3f', ), + distthresh3=dict(argstr='--distthresh3=%.3f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fibst=dict(argstr='--fibst=%d', ), + fopd=dict(argstr='--fopd=%s', ), + force_dir=dict( + argstr='--forcedir', + usedefault=True, + ), + fsamples=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inv_xfm=dict(argstr='--invxfm=%s', ), + loop_check=dict(argstr='--loopcheck', ), + lrtarget3=dict(argstr='--lrtarget3=%s', ), + mask=dict( + argstr='-m %s', + mandatory=True, + ), + meshspace=dict(argstr='--meshspace=%s', ), + mod_euler=dict(argstr='--modeuler', ), + n_samples=dict( + argstr='--nsamples=%d', + usedefault=True, + ), + n_steps=dict(argstr='--nsteps=%d', ), + network=dict(argstr='--network', ), + omatrix1=dict(argstr='--omatrix1', ), + omatrix2=dict( + argstr='--omatrix2', + requires=['target2'], + ), + omatrix3=dict( + argstr='--omatrix3', + requires=['target3', 'lrtarget3'], + ), + omatrix4=dict(argstr='--omatrix4', ), + onewaycondition=dict(argstr='--onewaycondition', ), + opd=dict( + argstr='--opd', + usedefault=True, + ), + os2t=dict(argstr='--os2t', ), + out_dir=dict( + argstr='--dir=%s', + genfile=True, + ), + output_type=dict(), + phsamples=dict(mandatory=True, ), + rand_fib=dict(argstr='--randfib=%d', ), + random_seed=dict(argstr='--rseed', ), + s2tastext=dict(argstr='--s2tastext', ), + sample_random_points=dict(argstr='--sampvox', ), + samples_base_name=dict( + argstr='--samples=%s', + usedefault=True, + ), + seed=dict( + argstr='--seed=%s', + mandatory=True, + ), + seed_ref=dict(argstr='--seedref=%s', ), + simple=dict( + argstr='--simple', + usedefault=False, + ), + step_length=dict(argstr='--steplength=%.3f', ), + stop_mask=dict(argstr='--stop=%s', ), + target2=dict(argstr='--target2=%s', ), + target3=dict(argstr='--target3=%s', ), + target4=dict(argstr='--target4=%s', ), + target_masks=dict(argstr='--targetmasks=%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thsamples=dict(mandatory=True, ), + use_anisotropy=dict(argstr='--usef', ), + verbose=dict(argstr='--verbose=%d', ), + waycond=dict(argstr='--waycond=%s', ), + wayorder=dict(argstr='--wayorder', ), + waypoints=dict(argstr='--waypoints=%s', ), + xfm=dict(argstr='--xfm=%s', ), ) inputs = ProbTrackX2.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ProbTrackX2_outputs(): - output_map = dict(fdt_paths=dict(), - log=dict(), - lookup_tractspace=dict(), - matrix1_dot=dict(), - matrix2_dot=dict(), - matrix3_dot=dict(), - network_matrix=dict(), - particle_files=dict(), - targets=dict(), - way_total=dict(), + output_map = dict( + fdt_paths=dict(), + log=dict(), + lookup_tractspace=dict(), + matrix1_dot=dict(), + matrix2_dot=dict(), + matrix3_dot=dict(), + network_matrix=dict(), + particle_files=dict(), + targets=dict(), + way_total=dict(), ) outputs = ProbTrackX2.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py b/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py index 37648d5a2b..c1010e49b8 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py +++ b/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py @@ -4,38 +4,40 @@ def test_ProjThresh_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=0, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='%d', - mandatory=True, - position=1, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=0, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict( + argstr='%d', + mandatory=True, + position=1, + ), ) inputs = ProjThresh.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ProjThresh_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = ProjThresh.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Randomise.py b/nipype/interfaces/fsl/tests/test_auto_Randomise.py index 432455e4a8..52a4cac3bf 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Randomise.py +++ b/nipype/interfaces/fsl/tests/test_auto_Randomise.py @@ -4,94 +4,77 @@ def test_Randomise_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - base_name=dict(argstr='-o "%s"', - position=1, - usedefault=True, - ), - c_thresh=dict(argstr='-c %.1f', - ), - cm_thresh=dict(argstr='-C %.1f', - ), - demean=dict(argstr='-D', - ), - design_mat=dict(argstr='-d %s', - position=2, - ), - environ=dict(nohash=True, - usedefault=True, - ), - f_c_thresh=dict(argstr='-F %.2f', - ), - f_cm_thresh=dict(argstr='-S %.2f', - ), - f_only=dict(argstr='--f_only', - ), - fcon=dict(argstr='-f %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=0, - ), - mask=dict(argstr='-m %s', - ), - num_perm=dict(argstr='-n %d', - ), - one_sample_group_mean=dict(argstr='-1', - ), - output_type=dict(), - p_vec_n_dist_files=dict(argstr='-P', - ), - raw_stats_imgs=dict(argstr='-R', - ), - seed=dict(argstr='--seed=%d', - ), - show_info_parallel_mode=dict(argstr='-Q', - ), - show_total_perms=dict(argstr='-q', - ), - tcon=dict(argstr='-t %s', - position=3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tfce=dict(argstr='-T', - ), - tfce2D=dict(argstr='--T2', - ), - tfce_C=dict(argstr='--tfce_C=%.2f', - ), - tfce_E=dict(argstr='--tfce_E=%.2f', - ), - tfce_H=dict(argstr='--tfce_H=%.2f', - ), - var_smooth=dict(argstr='-v %d', - ), - vox_p_values=dict(argstr='-x', - ), - x_block_labels=dict(argstr='-e %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + base_name=dict( + argstr='-o "%s"', + position=1, + usedefault=True, + ), + c_thresh=dict(argstr='-c %.1f', ), + cm_thresh=dict(argstr='-C %.1f', ), + demean=dict(argstr='-D', ), + design_mat=dict( + argstr='-d %s', + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f_c_thresh=dict(argstr='-F %.2f', ), + f_cm_thresh=dict(argstr='-S %.2f', ), + f_only=dict(argstr='--f_only', ), + fcon=dict(argstr='-f %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=0, + ), + mask=dict(argstr='-m %s', ), + num_perm=dict(argstr='-n %d', ), + one_sample_group_mean=dict(argstr='-1', ), + output_type=dict(), + p_vec_n_dist_files=dict(argstr='-P', ), + raw_stats_imgs=dict(argstr='-R', ), + seed=dict(argstr='--seed=%d', ), + show_info_parallel_mode=dict(argstr='-Q', ), + show_total_perms=dict(argstr='-q', ), + tcon=dict( + argstr='-t %s', + position=3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tfce=dict(argstr='-T', ), + tfce2D=dict(argstr='--T2', ), + tfce_C=dict(argstr='--tfce_C=%.2f', ), + tfce_E=dict(argstr='--tfce_E=%.2f', ), + tfce_H=dict(argstr='--tfce_H=%.2f', ), + var_smooth=dict(argstr='-v %d', ), + vox_p_values=dict(argstr='-x', ), + x_block_labels=dict(argstr='-e %s', ), ) inputs = Randomise.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Randomise_outputs(): - output_map = dict(f_corrected_p_files=dict(), - f_p_files=dict(), - fstat_files=dict(), - t_corrected_p_files=dict(), - t_p_files=dict(), - tstat_files=dict(), + output_map = dict( + f_corrected_p_files=dict(), + f_p_files=dict(), + fstat_files=dict(), + t_corrected_p_files=dict(), + t_p_files=dict(), + tstat_files=dict(), ) outputs = Randomise.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py b/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py index 0062b7d489..6b4d4fe372 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py +++ b/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py @@ -4,37 +4,39 @@ def test_Reorient2Std_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Reorient2Std.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Reorient2Std_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Reorient2Std.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py b/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py index 6b547109e1..ad1c5bfeda 100644 --- a/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py +++ b/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py @@ -4,46 +4,50 @@ def test_RobustFOV_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - brainsize=dict(argstr='-b %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=0, - ), - out_roi=dict(argstr='-r %s', - hash_files=False, - name_source=['in_file'], - name_template='%s_ROI', - ), - out_transform=dict(argstr='-m %s', - hash_files=False, - name_source=['in_file'], - name_template='%s_to_ROI', - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + brainsize=dict(argstr='-b %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=0, + ), + out_roi=dict( + argstr='-r %s', + hash_files=False, + name_source=['in_file'], + name_template='%s_ROI', + ), + out_transform=dict( + argstr='-m %s', + hash_files=False, + name_source=['in_file'], + name_template='%s_to_ROI', + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = RobustFOV.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RobustFOV_outputs(): - output_map = dict(out_roi=dict(), - out_transform=dict(), + output_map = dict( + out_roi=dict(), + out_transform=dict(), ) outputs = RobustFOV.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_SMM.py b/nipype/interfaces/fsl/tests/test_auto_SMM.py index f6ed7d4fd2..6509764023 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SMM.py +++ b/nipype/interfaces/fsl/tests/test_auto_SMM.py @@ -4,44 +4,49 @@ def test_SMM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask=dict(argstr='--mask="%s"', - copyfile=False, - mandatory=True, - position=1, - ), - no_deactivation_class=dict(argstr='--zfstatmode', - position=2, - ), - output_type=dict(), - spatial_data_file=dict(argstr='--sdf="%s"', - copyfile=False, - mandatory=True, - position=0, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask=dict( + argstr='--mask="%s"', + copyfile=False, + mandatory=True, + position=1, + ), + no_deactivation_class=dict( + argstr='--zfstatmode', + position=2, + ), + output_type=dict(), + spatial_data_file=dict( + argstr='--sdf="%s"', + copyfile=False, + mandatory=True, + position=0, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SMM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SMM_outputs(): - output_map = dict(activation_p_map=dict(), - deactivation_p_map=dict(), - null_p_map=dict(), + output_map = dict( + activation_p_map=dict(), + deactivation_p_map=dict(), + null_p_map=dict(), ) outputs = SMM.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_SUSAN.py b/nipype/interfaces/fsl/tests/test_auto_SUSAN.py index e3da09dadf..4fa56ce58a 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SUSAN.py +++ b/nipype/interfaces/fsl/tests/test_auto_SUSAN.py @@ -4,59 +4,66 @@ def test_SUSAN_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - brightness_threshold=dict(argstr='%.10f', - mandatory=True, - position=2, - ), - dimension=dict(argstr='%d', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm=dict(argstr='%.10f', - mandatory=True, - position=3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - usans=dict(argstr='', - position=6, - usedefault=True, - ), - use_median=dict(argstr='%d', - position=5, - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + brightness_threshold=dict( + argstr='%.10f', + mandatory=True, + position=2, + ), + dimension=dict( + argstr='%d', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr='%.10f', + mandatory=True, + position=3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + usans=dict( + argstr='', + position=6, + usedefault=True, + ), + use_median=dict( + argstr='%d', + position=5, + usedefault=True, + ), ) inputs = SUSAN.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SUSAN_outputs(): - output_map = dict(smoothed_file=dict(), - ) + output_map = dict(smoothed_file=dict(), ) outputs = SUSAN.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SigLoss.py b/nipype/interfaces/fsl/tests/test_auto_SigLoss.py index d7caee328e..d55f250774 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SigLoss.py +++ b/nipype/interfaces/fsl/tests/test_auto_SigLoss.py @@ -4,42 +4,41 @@ def test_SigLoss_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - echo_time=dict(argstr='--te=%f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - ), - mask_file=dict(argstr='-m %s', - ), - out_file=dict(argstr='-s %s', - genfile=True, - ), - output_type=dict(), - slice_direction=dict(argstr='-d %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + echo_time=dict(argstr='--te=%f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + ), + mask_file=dict(argstr='-m %s', ), + out_file=dict( + argstr='-s %s', + genfile=True, + ), + output_type=dict(), + slice_direction=dict(argstr='-d %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SigLoss.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SigLoss_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SigLoss.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py b/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py index 99d0b7215b..4d5ec0777b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py +++ b/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py @@ -4,52 +4,47 @@ def test_SliceTimer_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - custom_order=dict(argstr='--ocustom=%s', - ), - custom_timings=dict(argstr='--tcustom=%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - global_shift=dict(argstr='--tglobal', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--in=%s', - mandatory=True, - position=0, - ), - index_dir=dict(argstr='--down', - ), - interleaved=dict(argstr='--odd', - ), - out_file=dict(argstr='--out=%s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - slice_direction=dict(argstr='--direction=%d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - time_repetition=dict(argstr='--repeat=%f', - ), + input_map = dict( + args=dict(argstr='%s', ), + custom_order=dict(argstr='--ocustom=%s', ), + custom_timings=dict(argstr='--tcustom=%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + global_shift=dict(argstr='--tglobal', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--in=%s', + mandatory=True, + position=0, + ), + index_dir=dict(argstr='--down', ), + interleaved=dict(argstr='--odd', ), + out_file=dict( + argstr='--out=%s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + slice_direction=dict(argstr='--direction=%d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + time_repetition=dict(argstr='--repeat=%f', ), ) inputs = SliceTimer.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SliceTimer_outputs(): - output_map = dict(slice_time_corrected_file=dict(), - ) + output_map = dict(slice_time_corrected_file=dict(), ) outputs = SliceTimer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Slicer.py b/nipype/interfaces/fsl/tests/test_auto_Slicer.py index 6108b5f702..1f149e8e7c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Slicer.py +++ b/nipype/interfaces/fsl/tests/test_auto_Slicer.py @@ -4,93 +4,110 @@ def test_Slicer_inputs(): - input_map = dict(all_axial=dict(argstr='-A', - position=10, - requires=['image_width'], - xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), - ), - args=dict(argstr='%s', - ), - colour_map=dict(argstr='-l %s', - position=4, - ), - dither_edges=dict(argstr='-t', - position=7, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_edges=dict(argstr='%s', - position=2, - ), - image_width=dict(argstr='%d', - position=-2, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - intensity_range=dict(argstr='-i %.3f %.3f', - position=5, - ), - label_slices=dict(argstr='-L', - position=3, - usedefault=True, - ), - middle_slices=dict(argstr='-a', - position=10, - xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), - ), - nearest_neighbour=dict(argstr='-n', - position=8, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-1, - ), - output_type=dict(), - sample_axial=dict(argstr='-S %d', - position=10, - requires=['image_width'], - xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), - ), - scaling=dict(argstr='-s %f', - position=0, - ), - show_orientation=dict(argstr='%s', - position=9, - usedefault=True, - ), - single_slice=dict(argstr='-%s', - position=10, - requires=['slice_number'], - xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), - ), - slice_number=dict(argstr='-%d', - position=11, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold_edges=dict(argstr='-e %.3f', - position=6, - ), + input_map = dict( + all_axial=dict( + argstr='-A', + position=10, + requires=['image_width'], + xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), + ), + args=dict(argstr='%s', ), + colour_map=dict( + argstr='-l %s', + position=4, + ), + dither_edges=dict( + argstr='-t', + position=7, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_edges=dict( + argstr='%s', + position=2, + ), + image_width=dict( + argstr='%d', + position=-2, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + intensity_range=dict( + argstr='-i %.3f %.3f', + position=5, + ), + label_slices=dict( + argstr='-L', + position=3, + usedefault=True, + ), + middle_slices=dict( + argstr='-a', + position=10, + xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), + ), + nearest_neighbour=dict( + argstr='-n', + position=8, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-1, + ), + output_type=dict(), + sample_axial=dict( + argstr='-S %d', + position=10, + requires=['image_width'], + xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), + ), + scaling=dict( + argstr='-s %f', + position=0, + ), + show_orientation=dict( + argstr='%s', + position=9, + usedefault=True, + ), + single_slice=dict( + argstr='-%s', + position=10, + requires=['slice_number'], + xor=('single_slice', 'middle_slices', 'all_axial', 'sample_axial'), + ), + slice_number=dict( + argstr='-%d', + position=11, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold_edges=dict( + argstr='-e %.3f', + position=6, + ), ) inputs = Slicer.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Slicer_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Slicer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Smooth.py b/nipype/interfaces/fsl/tests/test_auto_Smooth.py index d653e4d7cb..e1ac043f5f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Smooth.py +++ b/nipype/interfaces/fsl/tests/test_auto_Smooth.py @@ -4,50 +4,54 @@ def test_Smooth_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm=dict(argstr='-kernel gauss %.03f -fmean', - mandatory=True, - position=1, - xor=['sigma'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - output_type=dict(), - sigma=dict(argstr='-kernel gauss %.03f -fmean', - mandatory=True, - position=1, - xor=['fwhm'], - ), - smoothed_file=dict(argstr='%s', - hash_files=False, - name_source=['in_file'], - name_template='%s_smooth', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr='-kernel gauss %.03f -fmean', + mandatory=True, + position=1, + xor=['sigma'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + output_type=dict(), + sigma=dict( + argstr='-kernel gauss %.03f -fmean', + mandatory=True, + position=1, + xor=['fwhm'], + ), + smoothed_file=dict( + argstr='%s', + hash_files=False, + name_source=['in_file'], + name_template='%s_smooth', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Smooth.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Smooth_outputs(): - output_map = dict(smoothed_file=dict(), - ) + output_map = dict(smoothed_file=dict(), ) outputs = Smooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py b/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py index c98830c384..4637f59ca1 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py +++ b/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py @@ -4,44 +4,50 @@ def test_SmoothEstimate_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dof=dict(argstr='--dof=%d', - mandatory=True, - xor=['zstat_file'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask_file=dict(argstr='--mask=%s', - mandatory=True, - ), - output_type=dict(), - residual_fit_file=dict(argstr='--res=%s', - requires=['dof'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - zstat_file=dict(argstr='--zstat=%s', - xor=['dof'], - ), + input_map = dict( + args=dict(argstr='%s', ), + dof=dict( + argstr='--dof=%d', + mandatory=True, + xor=['zstat_file'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask_file=dict( + argstr='--mask=%s', + mandatory=True, + ), + output_type=dict(), + residual_fit_file=dict( + argstr='--res=%s', + requires=['dof'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + zstat_file=dict( + argstr='--zstat=%s', + xor=['dof'], + ), ) inputs = SmoothEstimate.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SmoothEstimate_outputs(): - output_map = dict(dlh=dict(), - resels=dict(), - volume=dict(), + output_map = dict( + dlh=dict(), + resels=dict(), + volume=dict(), ) outputs = SmoothEstimate.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py b/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py index be3772926f..e6a1ef0481 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py +++ b/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py @@ -4,63 +4,72 @@ def test_SpatialFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - kernel_file=dict(argstr='%s', - position=5, - xor=['kernel_size'], - ), - kernel_shape=dict(argstr='-kernel %s', - position=4, - ), - kernel_size=dict(argstr='%.4f', - position=5, - xor=['kernel_file'], - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - operation=dict(argstr='-f%s', - mandatory=True, - position=6, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + kernel_file=dict( + argstr='%s', + position=5, + xor=['kernel_size'], + ), + kernel_shape=dict( + argstr='-kernel %s', + position=4, + ), + kernel_size=dict( + argstr='%.4f', + position=5, + xor=['kernel_file'], + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + operation=dict( + argstr='-f%s', + mandatory=True, + position=6, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SpatialFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SpatialFilter_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SpatialFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Split.py b/nipype/interfaces/fsl/tests/test_auto_Split.py index efe176be46..e04e0a0288 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Split.py +++ b/nipype/interfaces/fsl/tests/test_auto_Split.py @@ -4,41 +4,44 @@ def test_Split_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%s', - mandatory=True, - position=2, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=0, - ), - out_base_name=dict(argstr='%s', - position=1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%s', + mandatory=True, + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=0, + ), + out_base_name=dict( + argstr='%s', + position=1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Split.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Split_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = Split.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_StdImage.py b/nipype/interfaces/fsl/tests/test_auto_StdImage.py index 8675590d07..6255163bb1 100644 --- a/nipype/interfaces/fsl/tests/test_auto_StdImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_StdImage.py @@ -4,52 +4,58 @@ def test_StdImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(argstr='-%sstd', - position=4, - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict( + argstr='-%sstd', + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = StdImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_StdImage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = StdImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py b/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py index c225c37ab0..3dba8ffe44 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py +++ b/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py @@ -4,41 +4,44 @@ def test_SwapDimensions_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position='1', - ), - new_dims=dict(argstr='%s %s %s', - mandatory=True, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position='1', + ), + new_dims=dict( + argstr='%s %s %s', + mandatory=True, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SwapDimensions.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SwapDimensions_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SwapDimensions.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_TOPUP.py b/nipype/interfaces/fsl/tests/test_auto_TOPUP.py index fd04dadcbc..5d39a78524 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TOPUP.py +++ b/nipype/interfaces/fsl/tests/test_auto_TOPUP.py @@ -4,117 +4,117 @@ def test_TOPUP_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - config=dict(argstr='--config=%s', - usedefault=True, - ), - encoding_direction=dict(argstr='--datain=%s', - mandatory=True, - requires=['readout_times'], - xor=['encoding_file'], - ), - encoding_file=dict(argstr='--datain=%s', - mandatory=True, - xor=['encoding_direction'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - estmov=dict(argstr='--estmov=%d', - ), - fwhm=dict(argstr='--fwhm=%f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--imain=%s', - mandatory=True, - ), - interp=dict(argstr='--interp=%s', - ), - max_iter=dict(argstr='--miter=%d', - ), - minmet=dict(argstr='--minmet=%d', - ), - numprec=dict(argstr='--numprec=%s', - ), - out_base=dict(argstr='--out=%s', - hash_files=False, - name_source=['in_file'], - name_template='%s_base', - ), - out_corrected=dict(argstr='--iout=%s', - hash_files=False, - name_source=['in_file'], - name_template='%s_corrected', - ), - out_field=dict(argstr='--fout=%s', - hash_files=False, - name_source=['in_file'], - name_template='%s_field', - ), - out_jac_prefix=dict(argstr='--jacout=%s', - hash_files=False, - usedefault=True, - ), - out_logfile=dict(argstr='--logout=%s', - hash_files=False, - keep_extension=True, - name_source=['in_file'], - name_template='%s_topup.log', - ), - out_mat_prefix=dict(argstr='--rbmout=%s', - hash_files=False, - usedefault=True, - ), - out_warp_prefix=dict(argstr='--dfout=%s', - hash_files=False, - usedefault=True, - ), - output_type=dict(), - readout_times=dict(mandatory=True, - requires=['encoding_direction'], - xor=['encoding_file'], - ), - reg_lambda=dict(argstr='--miter=%0.f', - ), - regmod=dict(argstr='--regmod=%s', - ), - regrid=dict(argstr='--regrid=%d', - ), - scale=dict(argstr='--scale=%d', - ), - splineorder=dict(argstr='--splineorder=%d', - ), - ssqlambda=dict(argstr='--ssqlambda=%d', - ), - subsamp=dict(argstr='--subsamp=%d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_res=dict(argstr='--warpres=%f', - ), + input_map = dict( + args=dict(argstr='%s', ), + config=dict( + argstr='--config=%s', + usedefault=True, + ), + encoding_direction=dict( + argstr='--datain=%s', + mandatory=True, + requires=['readout_times'], + xor=['encoding_file'], + ), + encoding_file=dict( + argstr='--datain=%s', + mandatory=True, + xor=['encoding_direction'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + estmov=dict(argstr='--estmov=%d', ), + fwhm=dict(argstr='--fwhm=%f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--imain=%s', + mandatory=True, + ), + interp=dict(argstr='--interp=%s', ), + max_iter=dict(argstr='--miter=%d', ), + minmet=dict(argstr='--minmet=%d', ), + numprec=dict(argstr='--numprec=%s', ), + out_base=dict( + argstr='--out=%s', + hash_files=False, + name_source=['in_file'], + name_template='%s_base', + ), + out_corrected=dict( + argstr='--iout=%s', + hash_files=False, + name_source=['in_file'], + name_template='%s_corrected', + ), + out_field=dict( + argstr='--fout=%s', + hash_files=False, + name_source=['in_file'], + name_template='%s_field', + ), + out_jac_prefix=dict( + argstr='--jacout=%s', + hash_files=False, + usedefault=True, + ), + out_logfile=dict( + argstr='--logout=%s', + hash_files=False, + keep_extension=True, + name_source=['in_file'], + name_template='%s_topup.log', + ), + out_mat_prefix=dict( + argstr='--rbmout=%s', + hash_files=False, + usedefault=True, + ), + out_warp_prefix=dict( + argstr='--dfout=%s', + hash_files=False, + usedefault=True, + ), + output_type=dict(), + readout_times=dict( + mandatory=True, + requires=['encoding_direction'], + xor=['encoding_file'], + ), + reg_lambda=dict(argstr='--miter=%0.f', ), + regmod=dict(argstr='--regmod=%s', ), + regrid=dict(argstr='--regrid=%d', ), + scale=dict(argstr='--scale=%d', ), + splineorder=dict(argstr='--splineorder=%d', ), + ssqlambda=dict(argstr='--ssqlambda=%d', ), + subsamp=dict(argstr='--subsamp=%d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_res=dict(argstr='--warpres=%f', ), ) inputs = TOPUP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TOPUP_outputs(): - output_map = dict(out_corrected=dict(), - out_enc_file=dict(), - out_field=dict(), - out_fieldcoef=dict(), - out_jacs=dict(), - out_logfile=dict(), - out_mats=dict(), - out_movpar=dict(), - out_warps=dict(), + output_map = dict( + out_corrected=dict(), + out_enc_file=dict(), + out_field=dict(), + out_fieldcoef=dict(), + out_jacs=dict(), + out_logfile=dict(), + out_mats=dict(), + out_movpar=dict(), + out_warps=dict(), ) outputs = TOPUP.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py b/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py index 4f5bb4d84e..e089c2d7e8 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py +++ b/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py @@ -4,56 +4,63 @@ def test_TemporalFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - highpass_sigma=dict(argstr='-bptf %.6f', - position=4, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - lowpass_sigma=dict(argstr='%.6f', - position=5, - usedefault=True, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass_sigma=dict( + argstr='-bptf %.6f', + position=4, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + lowpass_sigma=dict( + argstr='%.6f', + position=5, + usedefault=True, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TemporalFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TemporalFilter_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TemporalFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Threshold.py b/nipype/interfaces/fsl/tests/test_auto_Threshold.py index 923deff51d..fe2a5e3012 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Threshold.py +++ b/nipype/interfaces/fsl/tests/test_auto_Threshold.py @@ -4,57 +4,61 @@ def test_Threshold_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - direction=dict(usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresh=dict(argstr='%s', - mandatory=True, - position=4, - ), - use_nonzero_voxels=dict(requires=['use_robust_range'], - ), - use_robust_range=dict(), + input_map = dict( + args=dict(argstr='%s', ), + direction=dict(usedefault=True, ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresh=dict( + argstr='%s', + mandatory=True, + position=4, + ), + use_nonzero_voxels=dict(requires=['use_robust_range'], ), + use_robust_range=dict(), ) inputs = Threshold.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Threshold_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Threshold.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py b/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py index 0c5634d731..fa15f89f2c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py +++ b/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py @@ -4,51 +4,52 @@ def test_TractSkeleton_inputs(): - input_map = dict(alt_data_file=dict(argstr='-a %s', - ), - alt_skeleton=dict(argstr='-s %s', - ), - args=dict(argstr='%s', - ), - data_file=dict(), - distance_map=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - ), - output_type=dict(), - project_data=dict(argstr='-p %.3f %s %s %s %s', - requires=['threshold', 'distance_map', 'data_file'], - ), - projected_data=dict(), - search_mask_file=dict(xor=['use_cingulum_mask'], - ), - skeleton_file=dict(argstr='-o %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(), - use_cingulum_mask=dict(usedefault=True, - xor=['search_mask_file'], - ), + input_map = dict( + alt_data_file=dict(argstr='-a %s', ), + alt_skeleton=dict(argstr='-s %s', ), + args=dict(argstr='%s', ), + data_file=dict(), + distance_map=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + ), + output_type=dict(), + project_data=dict( + argstr='-p %.3f %s %s %s %s', + requires=['threshold', 'distance_map', 'data_file'], + ), + projected_data=dict(), + search_mask_file=dict(xor=['use_cingulum_mask'], ), + skeleton_file=dict(argstr='-o %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(), + use_cingulum_mask=dict( + usedefault=True, + xor=['search_mask_file'], + ), ) inputs = TractSkeleton.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TractSkeleton_outputs(): - output_map = dict(projected_data=dict(), - skeleton_file=dict(), + output_map = dict( + projected_data=dict(), + skeleton_file=dict(), ) outputs = TractSkeleton.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Training.py b/nipype/interfaces/fsl/tests/test_auto_Training.py index 5d4d965951..3d988c28f8 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Training.py +++ b/nipype/interfaces/fsl/tests/test_auto_Training.py @@ -4,39 +4,42 @@ def test_Training_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - loo=dict(argstr='-l', - position=2, - ), - mel_icas=dict(argstr='%s', - copyfile=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trained_wts_filestem=dict(argstr='%s', - position=1, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + loo=dict( + argstr='-l', + position=2, + ), + mel_icas=dict( + argstr='%s', + copyfile=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trained_wts_filestem=dict( + argstr='%s', + position=1, + ), ) inputs = Training.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Training_outputs(): - output_map = dict(trained_wts_file=dict(), - ) + output_map = dict(trained_wts_file=dict(), ) outputs = Training.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py b/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py index 370e89fdf4..362bc171bd 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py +++ b/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py @@ -4,28 +4,30 @@ def test_TrainingSetCreator_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mel_icas_in=dict(argstr='%s', - copyfile=False, - position=-1, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mel_icas_in=dict( + argstr='%s', + copyfile=False, + position=-1, + ), ) inputs = TrainingSetCreator.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TrainingSetCreator_outputs(): - output_map = dict(mel_icas_out=dict(argstr='%s', - copyfile=False, - position=-1, - ), - ) + output_map = dict( + mel_icas_out=dict( + argstr='%s', + copyfile=False, + position=-1, + ), ) outputs = TrainingSetCreator.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py b/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py index eb43d00aaf..abd4547450 100644 --- a/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py @@ -4,52 +4,58 @@ def test_UnaryMaths_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - internal_datatype=dict(argstr='-dt %s', - position=1, - ), - nan2zeros=dict(argstr='-nan', - position=3, - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - out_file=dict(argstr='%s', - genfile=True, - hash_files=False, - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-1, - ), - output_type=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr='-dt %s', + position=1, + ), + nan2zeros=dict( + argstr='-nan', + position=3, + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + out_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-1, + ), + output_type=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = UnaryMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_UnaryMaths_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = UnaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_VecReg.py b/nipype/interfaces/fsl/tests/test_auto_VecReg.py index 2308c13b04..77084111cd 100644 --- a/nipype/interfaces/fsl/tests/test_auto_VecReg.py +++ b/nipype/interfaces/fsl/tests/test_auto_VecReg.py @@ -4,54 +4,50 @@ def test_VecReg_inputs(): - input_map = dict(affine_mat=dict(argstr='-t %s', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - ), - interpolation=dict(argstr='--interp=%s', - ), - mask=dict(argstr='-m %s', - ), - out_file=dict(argstr='-o %s', - genfile=True, - hash_files=False, - ), - output_type=dict(), - ref_mask=dict(argstr='--refmask=%s', - ), - ref_vol=dict(argstr='-r %s', - mandatory=True, - ), - rotation_mat=dict(argstr='--rotmat=%s', - ), - rotation_warp=dict(argstr='--rotwarp=%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_field=dict(argstr='-w %s', - ), + input_map = dict( + affine_mat=dict(argstr='-t %s', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + ), + interpolation=dict(argstr='--interp=%s', ), + mask=dict(argstr='-m %s', ), + out_file=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + ), + output_type=dict(), + ref_mask=dict(argstr='--refmask=%s', ), + ref_vol=dict( + argstr='-r %s', + mandatory=True, + ), + rotation_mat=dict(argstr='--rotmat=%s', ), + rotation_warp=dict(argstr='--rotwarp=%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_field=dict(argstr='-w %s', ), ) inputs = VecReg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VecReg_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = VecReg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py b/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py index cc8f9f9ce8..5cc782a04b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py @@ -4,55 +4,63 @@ def test_WarpPoints_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - coord_mm=dict(argstr='-mm', - xor=['coord_vox'], - ), - coord_vox=dict(argstr='-vox', - xor=['coord_mm'], - ), - dest_file=dict(argstr='-dest %s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_coords=dict(argstr='%s', - mandatory=True, - position=-1, - ), - out_file=dict(name_source='in_coords', - name_template='%s_warped', - output_name='out_file', - ), - src_file=dict(argstr='-src %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_file=dict(argstr='-warp %s', - xor=['xfm_file'], - ), - xfm_file=dict(argstr='-xfm %s', - xor=['warp_file'], - ), + input_map = dict( + args=dict(argstr='%s', ), + coord_mm=dict( + argstr='-mm', + xor=['coord_vox'], + ), + coord_vox=dict( + argstr='-vox', + xor=['coord_mm'], + ), + dest_file=dict( + argstr='-dest %s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_coords=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + out_file=dict( + name_source='in_coords', + name_template='%s_warped', + output_name='out_file', + ), + src_file=dict( + argstr='-src %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_file=dict( + argstr='-warp %s', + xor=['xfm_file'], + ), + xfm_file=dict( + argstr='-xfm %s', + xor=['warp_file'], + ), ) inputs = WarpPoints.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WarpPoints_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = WarpPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py b/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py index 0824beae24..addec3fffa 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py @@ -4,51 +4,58 @@ def test_WarpPointsFromStd_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - coord_mm=dict(argstr='-mm', - xor=['coord_vox'], - ), - coord_vox=dict(argstr='-vox', - xor=['coord_mm'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - img_file=dict(argstr='-img %s', - mandatory=True, - ), - in_coords=dict(argstr='%s', - mandatory=True, - position=-2, - ), - std_file=dict(argstr='-std %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_file=dict(argstr='-warp %s', - xor=['xfm_file'], - ), - xfm_file=dict(argstr='-xfm %s', - xor=['warp_file'], - ), + input_map = dict( + args=dict(argstr='%s', ), + coord_mm=dict( + argstr='-mm', + xor=['coord_vox'], + ), + coord_vox=dict( + argstr='-vox', + xor=['coord_mm'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + img_file=dict( + argstr='-img %s', + mandatory=True, + ), + in_coords=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + std_file=dict( + argstr='-std %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_file=dict( + argstr='-warp %s', + xor=['xfm_file'], + ), + xfm_file=dict( + argstr='-xfm %s', + xor=['warp_file'], + ), ) inputs = WarpPointsFromStd.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WarpPointsFromStd_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = WarpPointsFromStd.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py b/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py index ac7f73031b..c2eabbaa75 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py @@ -4,57 +4,64 @@ def test_WarpPointsToStd_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - coord_mm=dict(argstr='-mm', - xor=['coord_vox'], - ), - coord_vox=dict(argstr='-vox', - xor=['coord_mm'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - img_file=dict(argstr='-img %s', - mandatory=True, - ), - in_coords=dict(argstr='%s', - mandatory=True, - position=-1, - ), - out_file=dict(name_source='in_coords', - name_template='%s_warped', - output_name='out_file', - ), - premat_file=dict(argstr='-premat %s', - ), - std_file=dict(argstr='-std %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_file=dict(argstr='-warp %s', - xor=['xfm_file'], - ), - xfm_file=dict(argstr='-xfm %s', - xor=['warp_file'], - ), + input_map = dict( + args=dict(argstr='%s', ), + coord_mm=dict( + argstr='-mm', + xor=['coord_vox'], + ), + coord_vox=dict( + argstr='-vox', + xor=['coord_mm'], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + img_file=dict( + argstr='-img %s', + mandatory=True, + ), + in_coords=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + out_file=dict( + name_source='in_coords', + name_template='%s_warped', + output_name='out_file', + ), + premat_file=dict(argstr='-premat %s', ), + std_file=dict( + argstr='-std %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_file=dict( + argstr='-warp %s', + xor=['xfm_file'], + ), + xfm_file=dict( + argstr='-xfm %s', + xor=['warp_file'], + ), ) inputs = WarpPointsToStd.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WarpPointsToStd_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = WarpPointsToStd.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py b/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py index 2361a8f7e4..f0ada6ab67 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py @@ -4,54 +4,55 @@ def test_WarpUtils_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='--in=%s', - mandatory=True, - ), - knot_space=dict(argstr='--knotspace=%d,%d,%d', - ), - out_file=dict(argstr='--out=%s', - name_source=['in_file'], - output_name='out_file', - position=-1, - ), - out_format=dict(argstr='--outformat=%s', - ), - out_jacobian=dict(argstr='--jac=%s', - ), - output_type=dict(), - reference=dict(argstr='--ref=%s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_resolution=dict(argstr='--warpres=%0.4f,%0.4f,%0.4f', - ), - with_affine=dict(argstr='--withaff', - ), - write_jacobian=dict(mandatory=True, - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='--in=%s', + mandatory=True, + ), + knot_space=dict(argstr='--knotspace=%d,%d,%d', ), + out_file=dict( + argstr='--out=%s', + name_source=['in_file'], + output_name='out_file', + position=-1, + ), + out_format=dict(argstr='--outformat=%s', ), + out_jacobian=dict(argstr='--jac=%s', ), + output_type=dict(), + reference=dict( + argstr='--ref=%s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_resolution=dict(argstr='--warpres=%0.4f,%0.4f,%0.4f', ), + with_affine=dict(argstr='--withaff', ), + write_jacobian=dict( + mandatory=True, + usedefault=True, + ), ) inputs = WarpUtils.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WarpUtils_outputs(): - output_map = dict(out_file=dict(), - out_jacobian=dict(), + output_map = dict( + out_file=dict(), + out_jacobian=dict(), ) outputs = WarpUtils.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_XFibres5.py b/nipype/interfaces/fsl/tests/test_auto_XFibres5.py index f84b0b9ae8..77e8b06013 100644 --- a/nipype/interfaces/fsl/tests/test_auto_XFibres5.py +++ b/nipype/interfaces/fsl/tests/test_auto_XFibres5.py @@ -4,99 +4,105 @@ def test_XFibres5_inputs(): - input_map = dict(all_ard=dict(argstr='--allard', - xor=('no_ard', 'all_ard'), - ), - args=dict(argstr='%s', - ), - burn_in=dict(argstr='--burnin=%d', - ), - burn_in_no_ard=dict(argstr='--burninnoard=%d', - ), - bvals=dict(argstr='--bvals=%s', - mandatory=True, - ), - bvecs=dict(argstr='--bvecs=%s', - mandatory=True, - ), - cnlinear=dict(argstr='--cnonlinear', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - dwi=dict(argstr='--data=%s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - f0_ard=dict(argstr='--f0 --ardf0', - xor=['f0_noard', 'f0_ard', 'all_ard'], - ), - f0_noard=dict(argstr='--f0', - xor=['f0_noard', 'f0_ard'], - ), - force_dir=dict(argstr='--forcedir', - usedefault=True, - ), - fudge=dict(argstr='--fudge=%d', - ), - gradnonlin=dict(argstr='--gradnonlin=%s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - logdir=dict(argstr='--logdir=%s', - usedefault=True, - ), - mask=dict(argstr='--mask=%s', - mandatory=True, - ), - model=dict(argstr='--model=%d', - ), - n_fibres=dict(argstr='--nfibres=%d', - mandatory=True, - usedefault=True, - ), - n_jumps=dict(argstr='--njumps=%d', - ), - no_ard=dict(argstr='--noard', - xor=('no_ard', 'all_ard'), - ), - no_spat=dict(argstr='--nospat', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - non_linear=dict(argstr='--nonlinear', - xor=('no_spat', 'non_linear', 'cnlinear'), - ), - output_type=dict(), - rician=dict(argstr='--rician', - ), - sample_every=dict(argstr='--sampleevery=%d', - ), - seed=dict(argstr='--seed=%d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - update_proposal_every=dict(argstr='--updateproposalevery=%d', - ), + input_map = dict( + all_ard=dict( + argstr='--allard', + xor=('no_ard', 'all_ard'), + ), + args=dict(argstr='%s', ), + burn_in=dict(argstr='--burnin=%d', ), + burn_in_no_ard=dict(argstr='--burninnoard=%d', ), + bvals=dict( + argstr='--bvals=%s', + mandatory=True, + ), + bvecs=dict( + argstr='--bvecs=%s', + mandatory=True, + ), + cnlinear=dict( + argstr='--cnonlinear', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + dwi=dict( + argstr='--data=%s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f0_ard=dict( + argstr='--f0 --ardf0', + xor=['f0_noard', 'f0_ard', 'all_ard'], + ), + f0_noard=dict( + argstr='--f0', + xor=['f0_noard', 'f0_ard'], + ), + force_dir=dict( + argstr='--forcedir', + usedefault=True, + ), + fudge=dict(argstr='--fudge=%d', ), + gradnonlin=dict(argstr='--gradnonlin=%s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + logdir=dict( + argstr='--logdir=%s', + usedefault=True, + ), + mask=dict( + argstr='--mask=%s', + mandatory=True, + ), + model=dict(argstr='--model=%d', ), + n_fibres=dict( + argstr='--nfibres=%d', + mandatory=True, + usedefault=True, + ), + n_jumps=dict(argstr='--njumps=%d', ), + no_ard=dict( + argstr='--noard', + xor=('no_ard', 'all_ard'), + ), + no_spat=dict( + argstr='--nospat', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + non_linear=dict( + argstr='--nonlinear', + xor=('no_spat', 'non_linear', 'cnlinear'), + ), + output_type=dict(), + rician=dict(argstr='--rician', ), + sample_every=dict(argstr='--sampleevery=%d', ), + seed=dict(argstr='--seed=%d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + update_proposal_every=dict(argstr='--updateproposalevery=%d', ), ) inputs = XFibres5.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_XFibres5_outputs(): - output_map = dict(dyads=dict(), - fsamples=dict(), - mean_S0samples=dict(), - mean_dsamples=dict(), - mean_fsamples=dict(), - mean_tausamples=dict(), - phsamples=dict(), - thsamples=dict(), + output_map = dict( + dyads=dict(), + fsamples=dict(), + mean_S0samples=dict(), + mean_dsamples=dict(), + mean_fsamples=dict(), + mean_tausamples=dict(), + phsamples=dict(), + thsamples=dict(), ) outputs = XFibres5.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_base.py b/nipype/interfaces/fsl/tests/test_base.py index 030306e929..71022997b6 100644 --- a/nipype/interfaces/fsl/tests/test_base.py +++ b/nipype/interfaces/fsl/tests/test_base.py @@ -9,6 +9,7 @@ import pytest + @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_fslversion(): ver = fsl.Info.version() @@ -60,13 +61,36 @@ def test_FSLCommand2(): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") -@pytest.mark.parametrize("args, desired_name", - [({}, {"file": 'foo.nii.gz'}), # just the filename - ({"suffix": '_brain'}, {"file": 'foo_brain.nii.gz'}), # filename with suffix - ({"suffix": '_brain', "cwd": '/data'}, - {"dir": '/data', "file": 'foo_brain.nii.gz'}), # filename with suffix and working directory - ({"suffix": '_brain.mat', "change_ext": False}, {"file": 'foo_brain.mat'}) # filename with suffix and no file extension change - ]) +@pytest.mark.parametrize( + "args, desired_name", + [ + ({}, { + "file": 'foo.nii.gz' + }), # just the filename + # filename with suffix + ({ + "suffix": '_brain' + }, { + "file": 'foo_brain.nii.gz' + }), + ( + { + "suffix": '_brain', + "cwd": '/data' + }, + # filename with suffix and working directory + { + "dir": '/data', + "file": 'foo_brain.nii.gz' + }), + # filename with suffix and no file extension change + ({ + "suffix": '_brain.mat', + "change_ext": False + }, { + "file": 'foo_brain.mat' + }) + ]) def test_gen_fname(args, desired_name): # Test _gen_fname method of FSLCommand cmd = fsl.FSLCommand(command='junk', output_type='NIFTI_GZ') @@ -77,4 +101,3 @@ def test_gen_fname(args, desired_name): else: desired = os.path.join(pth, desired_name["file"]) assert fname == desired - diff --git a/nipype/interfaces/fsl/tests/test_dti.py b/nipype/interfaces/fsl/tests/test_dti.py index dab4d825ae..cd76766dd8 100644 --- a/nipype/interfaces/fsl/tests/test_dti.py +++ b/nipype/interfaces/fsl/tests/test_dti.py @@ -41,7 +41,8 @@ def test_dtifit2(create_files_in_directory): filelist[1]) -@pytest.mark.xfail(reason="These tests are skipped until we clean up some of this code") +@pytest.mark.xfail( + reason="These tests are skipped until we clean up some of this code") def test_randomise2(): rand = fsl.Randomise() @@ -65,11 +66,12 @@ def test_randomise2(): assert actualCmdline == desiredCmdline # .run based parameter setting - rand2 = fsl.Randomise(input_4D='infile2', - output_rootname='outfile2', - f_contrast='infile.f', - one_sample_gmean=True, - int_seed=4) + rand2 = fsl.Randomise( + input_4D='infile2', + output_rootname='outfile2', + f_contrast='infile.f', + one_sample_gmean=True, + int_seed=4) actualCmdline = sorted(rand2.cmdline.split()) cmd = 'randomise -i infile2 -o outfile2 -1 -f infile.f --seed=4' @@ -77,48 +79,52 @@ def test_randomise2(): assert actualCmdline == desiredCmdline rand3 = fsl.Randomise() - results = rand3.run(input_4D='infile3', - output_rootname='outfile3') + results = rand3.run(input_4D='infile3', output_rootname='outfile3') assert results.runtime.cmdline == \ 'randomise -i infile3 -o outfile3' # test arguments for opt_map - opt_map = {'demean_data': ('-D', True), - 'one_sample_gmean': ('-1', True), - 'mask_image': ('-m inp_mask', 'inp_mask'), - 'design_matrix': ('-d design.mat', 'design.mat'), - 't_contrast': ('-t input.con', 'input.con'), - 'f_contrast': ('-f input.fts', 'input.fts'), - 'xchange_block_labels': ('-e design.grp', 'design.grp'), - 'print_unique_perm': ('-q', True), - 'print_info_parallelMode': ('-Q', True), - 'num_permutations': ('-n 10', 10), - 'vox_pvalus': ('-x', True), - 'fstats_only': ('--fonly', True), - 'thresh_free_cluster': ('-T', True), - 'thresh_free_cluster_2Dopt': ('--T2', True), - 'cluster_thresholding': ('-c 0.20', 0.20), - 'cluster_mass_thresholding': ('-C 0.40', 0.40), - 'fcluster_thresholding': ('-F 0.10', 0.10), - 'fcluster_mass_thresholding': ('-S 0.30', 0.30), - 'variance_smoothing': ('-v 0.20', 0.20), - 'diagnostics_off': ('--quiet', True), - 'output_raw': ('-R', True), - 'output_perm_vect': ('-P', True), - 'int_seed': ('--seed=20', 20), - 'TFCE_height_param': ('--tfce_H=0.11', 0.11), - 'TFCE_extent_param': ('--tfce_E=0.50', 0.50), - 'TFCE_connectivity': ('--tfce_C=0.30', 0.30), - 'list_num_voxel_EVs_pos': ('--vxl=1,2,3,4', '1,2,3,4'), - 'list_img_voxel_EVs': ('--vxf=6,7,8,9,3', '6,7,8,9,3')} + opt_map = { + 'demean_data': ('-D', True), + 'one_sample_gmean': ('-1', True), + 'mask_image': ('-m inp_mask', 'inp_mask'), + 'design_matrix': ('-d design.mat', 'design.mat'), + 't_contrast': ('-t input.con', 'input.con'), + 'f_contrast': ('-f input.fts', 'input.fts'), + 'xchange_block_labels': ('-e design.grp', 'design.grp'), + 'print_unique_perm': ('-q', True), + 'print_info_parallelMode': ('-Q', True), + 'num_permutations': ('-n 10', 10), + 'vox_pvalus': ('-x', True), + 'fstats_only': ('--fonly', True), + 'thresh_free_cluster': ('-T', True), + 'thresh_free_cluster_2Dopt': ('--T2', True), + 'cluster_thresholding': ('-c 0.20', 0.20), + 'cluster_mass_thresholding': ('-C 0.40', 0.40), + 'fcluster_thresholding': ('-F 0.10', 0.10), + 'fcluster_mass_thresholding': ('-S 0.30', 0.30), + 'variance_smoothing': ('-v 0.20', 0.20), + 'diagnostics_off': ('--quiet', True), + 'output_raw': ('-R', True), + 'output_perm_vect': ('-P', True), + 'int_seed': ('--seed=20', 20), + 'TFCE_height_param': ('--tfce_H=0.11', 0.11), + 'TFCE_extent_param': ('--tfce_E=0.50', 0.50), + 'TFCE_connectivity': ('--tfce_C=0.30', 0.30), + 'list_num_voxel_EVs_pos': ('--vxl=1,2,3,4', '1,2,3,4'), + 'list_img_voxel_EVs': ('--vxf=6,7,8,9,3', '6,7,8,9,3') + } for name, settings in list(opt_map.items()): - rand4 = fsl.Randomise(input_4D='infile', output_rootname='root', - **{name: settings[1]}) + rand4 = fsl.Randomise( + input_4D='infile', output_rootname='root', **{ + name: settings[1] + }) assert rand4.cmdline == rand4.cmd + ' -i infile -o root ' + settings[0] -@pytest.mark.xfail(reason="These tests are skipped until we clean up some of this code") +@pytest.mark.xfail( + reason="These tests are skipped until we clean up some of this code") def test_Randomise_parallel(): rand = fsl.Randomise_parallel() @@ -142,11 +148,12 @@ def test_Randomise_parallel(): assert actualCmdline == desiredCmdline # .run based parameter setting - rand2 = fsl.Randomise_parallel(input_4D='infile2', - output_rootname='outfile2', - f_contrast='infile.f', - one_sample_gmean=True, - int_seed=4) + rand2 = fsl.Randomise_parallel( + input_4D='infile2', + output_rootname='outfile2', + f_contrast='infile.f', + one_sample_gmean=True, + int_seed=4) actualCmdline = sorted(rand2.cmdline.split()) cmd = 'randomise_parallel -i infile2 -o outfile2 -1 -f infile.f --seed=4' @@ -154,52 +161,55 @@ def test_Randomise_parallel(): assert actualCmdline == desiredCmdline rand3 = fsl.Randomise_parallel() - results = rand3.run(input_4D='infile3', - output_rootname='outfile3') + results = rand3.run(input_4D='infile3', output_rootname='outfile3') assert results.runtime.cmdline == \ 'randomise_parallel -i infile3 -o outfile3' # test arguments for opt_map - opt_map = {'demean_data': ('-D', True), - 'one_sample_gmean': ('-1', True), - 'mask_image': ('-m inp_mask', 'inp_mask'), - 'design_matrix': ('-d design.mat', 'design.mat'), - 't_contrast': ('-t input.con', 'input.con'), - 'f_contrast': ('-f input.fts', 'input.fts'), - 'xchange_block_labels': ('-e design.grp', 'design.grp'), - 'print_unique_perm': ('-q', True), - 'print_info_parallelMode': ('-Q', True), - 'num_permutations': ('-n 10', 10), - 'vox_pvalus': ('-x', True), - 'fstats_only': ('--fonly', True), - 'thresh_free_cluster': ('-T', True), - 'thresh_free_cluster_2Dopt': ('--T2', True), - 'cluster_thresholding': ('-c 0.20', 0.20), - 'cluster_mass_thresholding': ('-C 0.40', 0.40), - 'fcluster_thresholding': ('-F 0.10', 0.10), - 'fcluster_mass_thresholding': ('-S 0.30', 0.30), - 'variance_smoothing': ('-v 0.20', 0.20), - 'diagnostics_off': ('--quiet', True), - 'output_raw': ('-R', True), - 'output_perm_vect': ('-P', True), - 'int_seed': ('--seed=20', 20), - 'TFCE_height_param': ('--tfce_H=0.11', 0.11), - 'TFCE_extent_param': ('--tfce_E=0.50', 0.50), - 'TFCE_connectivity': ('--tfce_C=0.30', 0.30), - 'list_num_voxel_EVs_pos': ('--vxl=' + repr([1, 2, 3, 4]), - repr([1, 2, 3, 4])), - 'list_img_voxel_EVs': ('--vxf=' + repr([6, 7, 8, 9, 3]), - repr([6, 7, 8, 9, 3]))} + opt_map = { + 'demean_data': ('-D', True), + 'one_sample_gmean': ('-1', True), + 'mask_image': ('-m inp_mask', 'inp_mask'), + 'design_matrix': ('-d design.mat', 'design.mat'), + 't_contrast': ('-t input.con', 'input.con'), + 'f_contrast': ('-f input.fts', 'input.fts'), + 'xchange_block_labels': ('-e design.grp', 'design.grp'), + 'print_unique_perm': ('-q', True), + 'print_info_parallelMode': ('-Q', True), + 'num_permutations': ('-n 10', 10), + 'vox_pvalus': ('-x', True), + 'fstats_only': ('--fonly', True), + 'thresh_free_cluster': ('-T', True), + 'thresh_free_cluster_2Dopt': ('--T2', True), + 'cluster_thresholding': ('-c 0.20', 0.20), + 'cluster_mass_thresholding': ('-C 0.40', 0.40), + 'fcluster_thresholding': ('-F 0.10', 0.10), + 'fcluster_mass_thresholding': ('-S 0.30', 0.30), + 'variance_smoothing': ('-v 0.20', 0.20), + 'diagnostics_off': ('--quiet', True), + 'output_raw': ('-R', True), + 'output_perm_vect': ('-P', True), + 'int_seed': ('--seed=20', 20), + 'TFCE_height_param': ('--tfce_H=0.11', 0.11), + 'TFCE_extent_param': ('--tfce_E=0.50', 0.50), + 'TFCE_connectivity': ('--tfce_C=0.30', 0.30), + 'list_num_voxel_EVs_pos': ('--vxl=' + repr([1, 2, 3, 4]), + repr([1, 2, 3, 4])), + 'list_img_voxel_EVs': ('--vxf=' + repr([6, 7, 8, 9, 3]), + repr([6, 7, 8, 9, 3])) + } for name, settings in list(opt_map.items()): - rand4 = fsl.Randomise_parallel(input_4D='infile', - output_rootname='root', - **{name: settings[1]}) + rand4 = fsl.Randomise_parallel( + input_4D='infile', output_rootname='root', **{ + name: settings[1] + }) assert rand4.cmdline == rand4.cmd + ' -i infile -o root ' + settings[0] # test proj_thresh -@pytest.mark.xfail(reason="These tests are skipped until we clean up some of this code") +@pytest.mark.xfail( + reason="These tests are skipped until we clean up some of this code") def test_Proj_thresh(): proj = fsl.ProjThresh() @@ -223,7 +233,7 @@ def test_Proj_thresh(): results = proj3.run(volumes=['inp1', 'inp3', 'inp2'], threshold=2) assert results.runtime.cmdline == 'proj_thresh inp1 inp3 inp2 2' assert results.runtime.returncode != 0 - assert isinstance(results.interface.inputs.volumes, list) == True + assert isinstance(results.interface.inputs.volumes, list) assert results.interface.inputs.threshold == 2 # test arguments for opt_map @@ -231,7 +241,8 @@ def test_Proj_thresh(): # test vec_reg -@pytest.mark.xfail(reason="These tests are skipped until we clean up some of this code") +@pytest.mark.xfail( + reason="These tests are skipped until we clean up some of this code") def test_Vec_reg(): vrg = fsl.VecReg() @@ -251,11 +262,12 @@ def test_Vec_reg(): assert vrg.cmdline == 'vecreg -i infile -o outfile -r MNI152 -t tmat.mat' # .run based parameter setting - vrg2 = fsl.VecReg(infile='infile2', - outfile='outfile2', - refVolName='MNI152', - affineTmat='tmat2.mat', - brainMask='nodif_brain_mask') + vrg2 = fsl.VecReg( + infile='infile2', + outfile='outfile2', + refVolName='MNI152', + affineTmat='tmat2.mat', + brainMask='nodif_brain_mask') actualCmdline = sorted(vrg2.cmdline.split()) cmd = 'vecreg -i infile2 -o outfile2 -r MNI152 -t tmat2.mat -m nodif_brain_mask' @@ -263,10 +275,12 @@ def test_Vec_reg(): assert actualCmdline == desiredCmdline vrg3 = fsl.VecReg() - results = vrg3.run(infile='infile3', - outfile='outfile3', - refVolName='MNI152', - affineTmat='tmat3.mat',) + results = vrg3.run( + infile='infile3', + outfile='outfile3', + refVolName='MNI152', + affineTmat='tmat3.mat', + ) assert results.runtime.cmdline == \ 'vecreg -i infile3 -o outfile3 -r MNI152 -t tmat3.mat' @@ -277,23 +291,31 @@ def test_Vec_reg(): assert results.interface.inputs.affineTmat == 'tmat3.mat' # test arguments for opt_map - opt_map = {'verbose': ('-v', True), - 'helpDoc': ('-h', True), - 'tensor': ('--tensor', True), - 'affineTmat': ('-t Tmat', 'Tmat'), - 'warpFile': ('-w wrpFile', 'wrpFile'), - 'interpolation': ('--interp=sinc', 'sinc'), - 'brainMask': ('-m mask', 'mask')} + opt_map = { + 'verbose': ('-v', True), + 'helpDoc': ('-h', True), + 'tensor': ('--tensor', True), + 'affineTmat': ('-t Tmat', 'Tmat'), + 'warpFile': ('-w wrpFile', 'wrpFile'), + 'interpolation': ('--interp=sinc', 'sinc'), + 'brainMask': ('-m mask', 'mask') + } for name, settings in list(opt_map.items()): - vrg4 = fsl.VecReg(infile='infile', outfile='outfile', - refVolName='MNI152', **{name: settings[1]}) + vrg4 = fsl.VecReg( + infile='infile', + outfile='outfile', + refVolName='MNI152', + **{ + name: settings[1] + }) assert vrg4.cmdline == vrg4.cmd + \ ' -i infile -o outfile -r MNI152 ' + settings[0] # test find_the_biggest -@pytest.mark.xfail(reason="These tests are skipped until we clean up some of this code") +@pytest.mark.xfail( + reason="These tests are skipped until we clean up some of this code") def test_Find_the_biggest(): fbg = fsl.FindTheBiggest() @@ -387,7 +409,8 @@ def test_distancemap(create_files_in_directory): mapper.inputs.in_file = "a.nii" # It should - assert mapper.cmdline == "distancemap --out=%s --in=a.nii" % os.path.join(newdir, "a_dstmap.nii") + assert mapper.cmdline == "distancemap --out=%s --in=a.nii" % os.path.join( + newdir, "a_dstmap.nii") # And we should be able to write out a maxima map mapper.inputs.local_max_file = True @@ -399,4 +422,3 @@ def test_distancemap(create_files_in_directory): mapper.inputs.local_max_file = "max.nii" assert mapper.cmdline == \ "distancemap --out=%s --in=a.nii --localmax=max.nii" % os.path.join(newdir, "a_dstmap.nii") - diff --git a/nipype/interfaces/fsl/tests/test_epi.py b/nipype/interfaces/fsl/tests/test_epi.py index 17958426af..bf025e991d 100644 --- a/nipype/interfaces/fsl/tests/test_epi.py +++ b/nipype/interfaces/fsl/tests/test_epi.py @@ -30,7 +30,8 @@ def test_eddy_correct2(create_files_in_directory): assert eddy.cmdline == 'eddy_correct %s foo_eddc.nii 100' % filelist[0] # .run based parameter setting - eddy2 = fsl.EddyCorrect(in_file=filelist[0], out_file='foo_ec.nii', ref_num=20) + eddy2 = fsl.EddyCorrect( + in_file=filelist[0], out_file='foo_ec.nii', ref_num=20) assert eddy2.cmdline == 'eddy_correct %s foo_ec.nii 20' % filelist[0] # test arguments for opt_map diff --git a/nipype/interfaces/fsl/tests/test_maths.py b/nipype/interfaces/fsl/tests/test_maths.py index 408a74712f..b8aa41dc6b 100644 --- a/nipype/interfaces/fsl/tests/test_maths.py +++ b/nipype/interfaces/fsl/tests/test_maths.py @@ -34,19 +34,23 @@ def test_maths_base(create_files_in_directory_plus_output_type): out_file = "a_maths{}".format(out_ext) # Now test the most basic command line - assert maths.cmdline == "fslmaths a.nii {}".format(os.path.join(testdir, out_file)) + assert maths.cmdline == "fslmaths a.nii {}".format( + os.path.join(testdir, out_file)) # Now test that we can set the various data types dtypes = ["float", "char", "int", "short", "double", "input"] int_cmdline = "fslmaths -dt {} a.nii " + os.path.join(testdir, out_file) - out_cmdline = "fslmaths a.nii " + os.path.join(testdir, out_file) + " -odt {}" - duo_cmdline = "fslmaths -dt {} a.nii " + os.path.join(testdir, out_file) + " -odt {}" + out_cmdline = "fslmaths a.nii " + os.path.join(testdir, + out_file) + " -odt {}" + duo_cmdline = "fslmaths -dt {} a.nii " + os.path.join( + testdir, out_file) + " -odt {}" for dtype in dtypes: foo = fsl.MathsCommand(in_file="a.nii", internal_datatype=dtype) assert foo.cmdline == int_cmdline.format(dtype) bar = fsl.MathsCommand(in_file="a.nii", output_datatype=dtype) assert bar.cmdline == out_cmdline.format(dtype) - foobar = fsl.MathsCommand(in_file="a.nii", internal_datatype=dtype, output_datatype=dtype) + foobar = fsl.MathsCommand( + in_file="a.nii", internal_datatype=dtype, output_datatype=dtype) assert foobar.cmdline == duo_cmdline.format(dtype, dtype) # Test that we can ask for an outfile name @@ -80,7 +84,8 @@ def test_changedt(create_files_in_directory_plus_output_type): dtypes = ["float", "char", "int", "short", "double", "input"] cmdline = "fslmaths a.nii b.nii -odt {}" for dtype in dtypes: - foo = fsl.MathsCommand(in_file="a.nii", out_file="b.nii", output_datatype=dtype) + foo = fsl.MathsCommand( + in_file="a.nii", out_file="b.nii", output_datatype=dtype) assert foo.cmdline == cmdline.format(dtype) @@ -105,11 +110,13 @@ def test_threshold(create_files_in_directory_plus_output_type): assert thresh.cmdline == cmdline.format("-thr {:.10f}".format(val)) val = "{:.10f}".format(42) - thresh = fsl.Threshold(in_file="a.nii", out_file="b.nii", thresh=42, use_robust_range=True) + thresh = fsl.Threshold( + in_file="a.nii", out_file="b.nii", thresh=42, use_robust_range=True) assert thresh.cmdline == cmdline.format("-thrp " + val) thresh.inputs.use_nonzero_voxels = True assert thresh.cmdline == cmdline.format("-thrP " + val) - thresh = fsl.Threshold(in_file="a.nii", out_file="b.nii", thresh=42, direction="above") + thresh = fsl.Threshold( + in_file="a.nii", out_file="b.nii", thresh=42, direction="above") assert thresh.cmdline == cmdline.format("-uthr " + val) thresh.inputs.use_robust_range = True assert thresh.cmdline == cmdline.format("-uthrp " + val) @@ -138,7 +145,8 @@ def test_meanimage(create_files_in_directory_plus_output_type): # Test the auto naming meaner = fsl.MeanImage(in_file="a.nii") - assert meaner.cmdline == "fslmaths a.nii -Tmean {}".format(os.path.join(testdir, "a_mean{}".format(out_ext))) + assert meaner.cmdline == "fslmaths a.nii -Tmean {}".format( + os.path.join(testdir, "a_mean{}".format(out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -146,7 +154,7 @@ def test_stdimage(create_files_in_directory_plus_output_type): files, testdir, out_ext = create_files_in_directory_plus_output_type # Get the command - stder = fsl.StdImage(in_file="a.nii",out_file="b.nii") + stder = fsl.StdImage(in_file="a.nii", out_file="b.nii") # Test the underlying command assert stder.cmd == "fslmaths" @@ -156,13 +164,14 @@ def test_stdimage(create_files_in_directory_plus_output_type): # Test the other dimensions cmdline = "fslmaths a.nii -{}std b.nii" - for dim in ["X","Y","Z","T"]: - stder.inputs.dimension=dim + for dim in ["X", "Y", "Z", "T"]: + stder.inputs.dimension = dim assert stder.cmdline == cmdline.format(dim) # Test the auto naming stder = fsl.StdImage(in_file="a.nii", output_type='NIFTI') - assert stder.cmdline == "fslmaths a.nii -Tstd {}".format(os.path.join(testdir, "a_std.nii")) + assert stder.cmdline == "fslmaths a.nii -Tstd {}".format( + os.path.join(testdir, "a_std.nii")) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -186,7 +195,8 @@ def test_maximage(create_files_in_directory_plus_output_type): # Test the auto naming maxer = fsl.MaxImage(in_file="a.nii") - assert maxer.cmdline == "fslmaths a.nii -Tmax {}".format(os.path.join(testdir, "a_max{}".format(out_ext))) + assert maxer.cmdline == "fslmaths a.nii -Tmax {}".format( + os.path.join(testdir, "a_max{}".format(out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -206,15 +216,18 @@ def test_smooth(create_files_in_directory_plus_output_type): # Test smoothing kernels cmdline = "fslmaths a.nii -s {:.5f} b.nii" for val in [0, 1., 1, 25, 0.5, 8 / 3.]: - smoother = fsl.IsotropicSmooth(in_file="a.nii", out_file="b.nii", sigma=val) + smoother = fsl.IsotropicSmooth( + in_file="a.nii", out_file="b.nii", sigma=val) assert smoother.cmdline == cmdline.format(val) - smoother = fsl.IsotropicSmooth(in_file="a.nii", out_file="b.nii", fwhm=val) + smoother = fsl.IsotropicSmooth( + in_file="a.nii", out_file="b.nii", fwhm=val) val = float(val) / np.sqrt(8 * np.log(2)) assert smoother.cmdline == cmdline.format(val) # Test automatic naming smoother = fsl.IsotropicSmooth(in_file="a.nii", sigma=5) - assert smoother.cmdline == "fslmaths a.nii -s {:.5f} {}".format(5, os.path.join(testdir, "a_smooth{}".format(out_ext))) + assert smoother.cmdline == "fslmaths a.nii -s {:.5f} {}".format( + 5, os.path.join(testdir, "a_smooth{}".format(out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -237,7 +250,8 @@ def test_mask(create_files_in_directory_plus_output_type): # Test auto name generation masker = fsl.ApplyMask(in_file="a.nii", mask_file="b.nii") - assert masker.cmdline == "fslmaths a.nii -mas b.nii " + os.path.join(testdir, "a_masked{}".format(out_ext)) + assert masker.cmdline == "fslmaths a.nii -mas b.nii " + os.path.join( + testdir, "a_masked{}".format(out_ext)) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -265,7 +279,8 @@ def test_dilation(create_files_in_directory_plus_output_type): for size in [1, 1.5, 5]: diller.inputs.kernel_shape = k diller.inputs.kernel_size = size - assert diller.cmdline == "fslmaths a.nii -kernel {} {:.4f} -dilF b.nii".format(k, size) + assert diller.cmdline == "fslmaths a.nii -kernel {} {:.4f} -dilF b.nii".format( + k, size) # Test that we can use a file kernel f = open("kernel.txt", "w").close() @@ -277,7 +292,8 @@ def test_dilation(create_files_in_directory_plus_output_type): # Test that we don't need to request an out name dil = fsl.DilateImage(in_file="a.nii", operation="max") - assert dil.cmdline == "fslmaths a.nii -dilF {}".format(os.path.join(testdir, "a_dil{}".format(out_ext))) + assert dil.cmdline == "fslmaths a.nii -dilF {}".format( + os.path.join(testdir, "a_dil{}".format(out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -299,7 +315,8 @@ def test_erosion(create_files_in_directory_plus_output_type): # Test that we don't need to request an out name erode = fsl.ErodeImage(in_file="a.nii") - assert erode.cmdline == "fslmaths a.nii -ero {}".format(os.path.join(testdir, "a_ero{}".format(out_ext))) + assert erode.cmdline == "fslmaths a.nii -ero {}".format( + os.path.join(testdir, "a_ero{}".format(out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -323,7 +340,8 @@ def test_spatial_filter(create_files_in_directory_plus_output_type): # Test that we don't need to ask for an out name filter = fsl.SpatialFilter(in_file="a.nii", operation="mean") - assert filter.cmdline == "fslmaths a.nii -fmean {}".format(os.path.join(testdir, "a_filt{}".format(out_ext))) + assert filter.cmdline == "fslmaths a.nii -fmean {}".format( + os.path.join(testdir, "a_filt{}".format(out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -341,7 +359,10 @@ def test_unarymaths(create_files_in_directory_plus_output_type): maths.run() # Test the different operations - ops = ["exp", "log", "sin", "cos", "sqr", "sqrt", "recip", "abs", "bin", "index"] + ops = [ + "exp", "log", "sin", "cos", "sqr", "sqrt", "recip", "abs", "bin", + "index" + ] for op in ops: maths.inputs.operation = op assert maths.cmdline == "fslmaths a.nii -{} b.nii".format(op) @@ -349,7 +370,8 @@ def test_unarymaths(create_files_in_directory_plus_output_type): # Test that we don't need to ask for an out file for op in ops: maths = fsl.UnaryMaths(in_file="a.nii", operation=op) - assert maths.cmdline == "fslmaths a.nii -{} {}".format(op, os.path.join(testdir, "a_{}{}".format(op, out_ext))) + assert maths.cmdline == "fslmaths a.nii -{} {}".format( + op, os.path.join(testdir, "a_{}{}".format(op, out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -371,18 +393,23 @@ def test_binarymaths(create_files_in_directory_plus_output_type): operands = ["b.nii", -2, -0.5, 0, .123456, np.pi, 500] for op in ops: for ent in operands: - maths = fsl.BinaryMaths(in_file="a.nii", out_file="c.nii", operation=op) + maths = fsl.BinaryMaths( + in_file="a.nii", out_file="c.nii", operation=op) if ent == "b.nii": maths.inputs.operand_file = ent - assert maths.cmdline == "fslmaths a.nii -{} b.nii c.nii".format(op) + assert maths.cmdline == "fslmaths a.nii -{} b.nii c.nii".format( + op) else: maths.inputs.operand_value = ent - assert maths.cmdline == "fslmaths a.nii -{} {:.8f} c.nii".format(op, ent) + assert maths.cmdline == "fslmaths a.nii -{} {:.8f} c.nii".format( + op, ent) # Test that we don't need to ask for an out file for op in ops: - maths = fsl.BinaryMaths(in_file="a.nii", operation=op, operand_file="b.nii") - assert maths.cmdline == "fslmaths a.nii -{} b.nii {}".format(op, os.path.join(testdir, "a_maths{}".format(out_ext))) + maths = fsl.BinaryMaths( + in_file="a.nii", operation=op, operand_file="b.nii") + assert maths.cmdline == "fslmaths a.nii -{} b.nii {}".format( + op, os.path.join(testdir, "a_maths{}".format(out_ext))) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -401,15 +428,17 @@ def test_multimaths(create_files_in_directory_plus_output_type): # Test a few operations maths.inputs.operand_files = ["a.nii", "b.nii"] - opstrings = ["-add %s -div %s", - "-max 1 -sub %s -min %s", - "-mas %s -add %s"] + opstrings = [ + "-add %s -div %s", "-max 1 -sub %s -min %s", "-mas %s -add %s" + ] for ostr in opstrings: maths.inputs.op_string = ostr - assert maths.cmdline == "fslmaths a.nii %s c.nii" % ostr % ("a.nii", "b.nii") + assert maths.cmdline == "fslmaths a.nii %s c.nii" % ostr % ("a.nii", + "b.nii") # Test that we don't need to ask for an out file - maths = fsl.MultiImageMaths(in_file="a.nii", op_string="-add %s -mul 5", operand_files=["b.nii"]) + maths = fsl.MultiImageMaths( + in_file="a.nii", op_string="-add %s -mul 5", operand_files=["b.nii"]) assert maths.cmdline == \ "fslmaths a.nii -add b.nii -mul 5 %s" % os.path.join(testdir, "a_maths%s" % out_ext) @@ -432,12 +461,10 @@ def test_tempfilt(create_files_in_directory_plus_output_type): for win in windows: filt.inputs.highpass_sigma = win[0] filt.inputs.lowpass_sigma = win[1] - assert filt.cmdline == "fslmaths a.nii -bptf {:.6f} {:.6f} b.nii".format(win[0], win[1]) + assert filt.cmdline == "fslmaths a.nii -bptf {:.6f} {:.6f} b.nii".format( + win[0], win[1]) # Test that we don't need to ask for an out file filt = fsl.TemporalFilter(in_file="a.nii", highpass_sigma=64) assert filt.cmdline == \ "fslmaths a.nii -bptf 64.000000 -1.000000 {}".format(os.path.join(testdir, "a_filt{}".format(out_ext))) - - - diff --git a/nipype/interfaces/fsl/tests/test_model.py b/nipype/interfaces/fsl/tests/test_model.py index b2e3f8571c..8b8d0b7b40 100644 --- a/nipype/interfaces/fsl/tests/test_model.py +++ b/nipype/interfaces/fsl/tests/test_model.py @@ -15,14 +15,16 @@ def test_MultipleRegressDesign(tmpdir): tmpdir.chdir() foo = fsl.MultipleRegressDesign() - foo.inputs.regressors = dict(voice_stenght=[1, 1, 1], age=[0.2, 0.4, 0.5], BMI=[1, -1, 2]) + foo.inputs.regressors = dict( + voice_stenght=[1, 1, 1], age=[0.2, 0.4, 0.5], BMI=[1, -1, 2]) con1 = ['voice_and_age', 'T', ['age', 'voice_stenght'], [0.5, 0.5]] con2 = ['just_BMI', 'T', ['BMI'], [1]] foo.inputs.contrasts = [con1, con2, ['con3', 'F', [con1, con2]]] res = foo.run() for ii in ["mat", "con", "fts", "grp"]: - assert getattr(res.outputs, "design_"+ii) == tmpdir.join('design.'+ii).strpath + assert getattr(res.outputs, + "design_" + ii) == tmpdir.join('design.' + ii).strpath design_mat_expected_content = """/NumWaves 3 /NumPoints 3 @@ -62,6 +64,5 @@ def test_MultipleRegressDesign(tmpdir): 1 """ for ii in ["mat", "con", "fts", "grp"]: - assert tmpdir.join('design.'+ii).read() == eval("design_"+ii+"_expected_content") - - + assert tmpdir.join('design.' + ii).read() == eval( + "design_" + ii + "_expected_content") diff --git a/nipype/interfaces/fsl/tests/test_preprocess.py b/nipype/interfaces/fsl/tests/test_preprocess.py index 3d75d514a6..bd75234c62 100644 --- a/nipype/interfaces/fsl/tests/test_preprocess.py +++ b/nipype/interfaces/fsl/tests/test_preprocess.py @@ -3,12 +3,13 @@ from builtins import str # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from builtins import open, open +from builtins import open import os from copy import deepcopy -import pytest, pdb +import pytest +import pdb from nipype.utils.filemanip import split_filename, filename_to_list from .. import preprocess as fsl from nipype.interfaces.fsl import Info @@ -56,6 +57,7 @@ def test_bet(setup_infile): # infile foo.nii doesn't exist def func(): better.run(in_file='foo2.nii', out_file='bar.nii') + with pytest.raises(TraitError): func() @@ -89,6 +91,7 @@ def func(): realcmd = ' '.join([better.cmd, tmp_infile, outpath, settings[0]]) assert better.cmdline == realcmd + # test fast @@ -101,7 +104,7 @@ def test_fast(setup_infile): fasted2 = fsl.FAST(in_files=[tmp_infile, tmp_infile], verbose=True) assert faster.cmd == 'fast' - assert faster.inputs.verbose == True + assert faster.inputs.verbose assert faster.inputs.manual_seg == Undefined assert faster.inputs != fasted.inputs assert fasted.cmdline == 'fast -v -S 1 %s' % (tmp_infile) @@ -115,38 +118,40 @@ def test_fast(setup_infile): # Our options and some test values for them # Should parallel the opt_map structure in the class for clarity - opt_map = {'number_classes': ('-n 4', 4), - 'bias_iters': ('-I 5', 5), - 'bias_lowpass': ('-l 15', 15), - 'img_type': ('-t 2', 2), - 'init_seg_smooth': ('-f 0.035', 0.035), - 'segments': ('-g', True), - 'init_transform': ('-a %s' % (tmp_infile), '%s' % (tmp_infile)), - 'other_priors': ('-A %s %s %s' % (tmp_infile, tmp_infile, - tmp_infile), - (['%s' % (tmp_infile), - '%s' % (tmp_infile), - '%s' % (tmp_infile)])), - 'no_pve': ('--nopve', True), - 'output_biasfield': ('-b', True), - 'output_biascorrected': ('-B', True), - 'no_bias': ('-N', True), - 'out_basename': ('-o fasted', 'fasted'), - 'use_priors': ('-P', True), - 'segment_iters': ('-W 14', 14), - 'mixel_smooth': ('-R 0.25', 0.25), - 'iters_afterbias': ('-O 3', 3), - 'hyper': ('-H 0.15', 0.15), - 'verbose': ('-v', True), - 'manual_seg': ('-s %s' % (tmp_infile), '%s' % (tmp_infile)), - 'probability_maps': ('-p', True), - } + opt_map = { + 'number_classes': ('-n 4', 4), + 'bias_iters': ('-I 5', 5), + 'bias_lowpass': ('-l 15', 15), + 'img_type': ('-t 2', 2), + 'init_seg_smooth': ('-f 0.035', 0.035), + 'segments': ('-g', True), + 'init_transform': ('-a %s' % (tmp_infile), '%s' % (tmp_infile)), + 'other_priors': + ('-A %s %s %s' % (tmp_infile, tmp_infile, tmp_infile), + (['%s' % (tmp_infile), + '%s' % (tmp_infile), + '%s' % (tmp_infile)])), + 'no_pve': ('--nopve', True), + 'output_biasfield': ('-b', True), + 'output_biascorrected': ('-B', True), + 'no_bias': ('-N', True), + 'out_basename': ('-o fasted', 'fasted'), + 'use_priors': ('-P', True), + 'segment_iters': ('-W 14', 14), + 'mixel_smooth': ('-R 0.25', 0.25), + 'iters_afterbias': ('-O 3', 3), + 'hyper': ('-H 0.15', 0.15), + 'verbose': ('-v', True), + 'manual_seg': ('-s %s' % (tmp_infile), '%s' % (tmp_infile)), + 'probability_maps': ('-p', True), + } # test each of our arguments for name, settings in list(opt_map.items()): faster = fsl.FAST(in_files=tmp_infile, **{name: settings[1]}) - assert faster.cmdline == ' '.join([faster.cmd, settings[0], - "-S 1 %s" % tmp_infile]) + assert faster.cmdline == ' '.join( + [faster.cmd, settings[0], + "-S 1 %s" % tmp_infile]) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -154,12 +159,14 @@ def test_fast_list_outputs(setup_infile, tmpdir): ''' By default (no -o), FSL's fast command outputs files into the same directory as the input files. If the flag -o is set, it outputs files into the cwd ''' + def _run_and_test(opts, output_base): outputs = fsl.FAST(**opts)._list_outputs() for output in outputs.values(): if output: for filename in filename_to_list(output): - assert os.path.realpath(filename).startswith(os.path.realpath(output_base)) + assert os.path.realpath(filename).startswith( + os.path.realpath(output_base)) # set up tmp_infile, indir = setup_infile @@ -180,9 +187,9 @@ def _run_and_test(opts, output_base): @pytest.fixture() def setup_flirt(tmpdir): ext = Info.output_type_to_ext(Info.output_type()) - infile = tmpdir.join("infile"+ext) + infile = tmpdir.join("infile" + ext) infile.open("w") - reffile = tmpdir.join("reffile"+ext) + reffile = tmpdir.join("reffile" + ext) reffile.open("w") return (tmpdir, infile.strpath, reffile.strpath) @@ -198,15 +205,20 @@ def test_flirt(setup_flirt): flirter.inputs.bins = 256 flirter.inputs.cost = 'mutualinfo' - flirted = fsl.FLIRT(in_file=infile, reference=reffile, - out_file='outfile', out_matrix_file='outmat.mat', - bins=256, - cost='mutualinfo') - - flirt_est = fsl.FLIRT(in_file=infile, reference=reffile, - out_matrix_file='outmat.mat', - bins=256, - cost='mutualinfo') + flirted = fsl.FLIRT( + in_file=infile, + reference=reffile, + out_file='outfile', + out_matrix_file='outmat.mat', + bins=256, + cost='mutualinfo') + + flirt_est = fsl.FLIRT( + in_file=infile, + reference=reffile, + out_matrix_file='outmat.mat', + bins=256, + cost='mutualinfo') assert flirter.inputs != flirted.inputs assert flirted.inputs != flirt_est.inputs @@ -238,7 +250,8 @@ def test_flirt(setup_flirt): axfm = deepcopy(flirter) axfm.inputs.apply_xfm = True # in_matrix_file or uses_qform must be defined - with pytest.raises(RuntimeError): axfm.cmdline + with pytest.raises(RuntimeError): + axfm.cmdline axfm2 = deepcopy(axfm) # test uses_qform axfm.inputs.uses_qform = True @@ -355,15 +368,11 @@ def test_mcflirt_opt(setup_flirt): instr = '-in %s' % (infile) outstr = '-out %s' % (outfile) if name in ('init', 'cost', 'dof', 'mean_vol', 'bins'): - assert fnt.cmdline == ' '.join([fnt.cmd, - instr, - settings[0], - outstr]) + assert fnt.cmdline == ' '.join( + [fnt.cmd, instr, settings[0], outstr]) else: - assert fnt.cmdline == ' '.join([fnt.cmd, - instr, - outstr, - settings[0]]) + assert fnt.cmdline == ' '.join( + [fnt.cmd, instr, outstr, settings[0]]) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -372,7 +381,9 @@ def test_mcflirt_noinput(): fnt = fsl.MCFLIRT() with pytest.raises(ValueError) as excinfo: fnt.run() - assert str(excinfo.value).startswith("MCFLIRT requires a value for input 'in_file'") + assert str(excinfo.value).startswith( + "MCFLIRT requires a value for input 'in_file'") + # test fnirt @@ -386,18 +397,19 @@ def test_fnirt(setup_flirt): assert fnirt.cmd == 'fnirt' # Test list parameters - params = [('subsampling_scheme', '--subsamp', [4, 2, 2, 1], '4,2,2,1'), - ('max_nonlin_iter', '--miter', [4, 4, 4, 2], '4,4,4,2'), - ('ref_fwhm', '--reffwhm', [4, 2, 2, 0], '4,2,2,0'), - ('in_fwhm', '--infwhm', [4, 2, 2, 0], '4,2,2,0'), - ('apply_refmask', '--applyrefmask', [0, 0, 1, 1], '0,0,1,1'), - ('apply_inmask', '--applyinmask', [0, 0, 0, 1], '0,0,0,1'), - ('regularization_lambda', '--lambda', [0.5, 0.75], '0.5,0.75'), - ('intensity_mapping_model', '--intmod', 'global_non_linear', 'global_non_linear')] + params = [('subsampling_scheme', '--subsamp', [4, 2, 2, 1], + '4,2,2,1'), ('max_nonlin_iter', '--miter', [4, 4, 4, 2], + '4,4,4,2'), ('ref_fwhm', '--reffwhm', [4, 2, 2, 0], + '4,2,2,0'), ('in_fwhm', '--infwhm', + [4, 2, 2, 0], '4,2,2,0'), + ('apply_refmask', '--applyrefmask', [0, 0, 1, 1], + '0,0,1,1'), ('apply_inmask', '--applyinmask', [0, 0, 0, 1], + '0,0,0,1'), ('regularization_lambda', '--lambda', + [0.5, 0.75], '0.5,0.75'), + ('intensity_mapping_model', '--intmod', 'global_non_linear', + 'global_non_linear')] for item, flag, val, strval in params: - fnirt = fsl.FNIRT(in_file=infile, - ref_file=reffile, - **{item: val}) + fnirt = fsl.FNIRT(in_file=infile, ref_file=reffile, **{item: val}) log = fnirt._gen_fname(infile, suffix='_log.txt', change_ext=False) iout = fnirt._gen_fname(infile, suffix='_warped') if item in ('max_nonlin_iter'): @@ -434,7 +446,8 @@ def test_fnirt(setup_flirt): fnirt.run() fnirt.inputs.in_file = infile fnirt.inputs.ref_file = reffile - intmap_basename = '%s_intmap' % fsl.FNIRT.intensitymap_file_basename(infile) + intmap_basename = '%s_intmap' % fsl.FNIRT.intensitymap_file_basename( + infile) intmap_image = fsl_name(fnirt, intmap_basename) intmap_txt = '%s.txt' % intmap_basename # doing this to create the file to pass tests for file existence @@ -444,31 +457,31 @@ def test_fnirt(setup_flirt): pass # test files - opt_map = [ - ('affine_file', '--aff=%s' % infile, infile), - ('inwarp_file', '--inwarp=%s' % infile, infile), - ('in_intensitymap_file', '--intin=%s' % intmap_basename, [intmap_image]), - ('in_intensitymap_file', - '--intin=%s' % intmap_basename, - [intmap_image, intmap_txt]), - ('config_file', '--config=%s' % infile, infile), - ('refmask_file', '--refmask=%s' % infile, infile), - ('inmask_file', '--inmask=%s' % infile, infile), - ('field_file', '--fout=%s' % infile, infile), - ('jacobian_file', '--jout=%s' % infile, infile), - ('modulatedref_file', '--refout=%s' % infile, infile), - ('out_intensitymap_file', - '--intout=%s' % intmap_basename, True), - ('out_intensitymap_file', '--intout=%s' % intmap_basename, intmap_image), - ('fieldcoeff_file', '--cout=%s' % infile, infile), - ('log_file', '--logout=%s' % infile, infile)] + opt_map = [('affine_file', '--aff=%s' % infile, + infile), ('inwarp_file', '--inwarp=%s' % infile, infile), + ('in_intensitymap_file', '--intin=%s' % intmap_basename, + [intmap_image]), ('in_intensitymap_file', + '--intin=%s' % intmap_basename, + [intmap_image, intmap_txt]), + ('config_file', '--config=%s' % infile, + infile), ('refmask_file', '--refmask=%s' % infile, + infile), ('inmask_file', '--inmask=%s' % infile, + infile), ('field_file', + '--fout=%s' % infile, infile), + ('jacobian_file', '--jout=%s' % infile, + infile), ('modulatedref_file', '--refout=%s' % infile, + infile), ('out_intensitymap_file', + '--intout=%s' % intmap_basename, True), + ('out_intensitymap_file', '--intout=%s' % intmap_basename, + intmap_image), ('fieldcoeff_file', '--cout=%s' % infile, + infile), ('log_file', '--logout=%s' % infile, + infile)] for (name, settings, arg) in opt_map: - fnirt = fsl.FNIRT(in_file=infile, - ref_file=reffile, - **{name: arg}) + fnirt = fsl.FNIRT(in_file=infile, ref_file=reffile, **{name: arg}) - if name in ('config_file', 'affine_file', 'field_file', 'fieldcoeff_file'): + if name in ('config_file', 'affine_file', 'field_file', + 'fieldcoeff_file'): cmd = 'fnirt %s --in=%s '\ '--logout=%s '\ '--ref=%s --iout=%s' % (settings, infile, log, @@ -481,7 +494,8 @@ def test_fnirt(setup_flirt): reffile, settings, iout) - elif name in ('in_intensitymap_file', 'inwarp_file', 'inmask_file', 'jacobian_file'): + elif name in ('in_intensitymap_file', 'inwarp_file', 'inmask_file', + 'jacobian_file'): cmd = 'fnirt --in=%s '\ '%s '\ '--logout=%s --ref=%s '\ @@ -508,7 +522,9 @@ def test_fnirt(setup_flirt): if name == 'out_intensitymap_file': assert fnirt._list_outputs()['out_intensitymap_file'] == [ - intmap_image, intmap_txt] + intmap_image, intmap_txt + ] + @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_applywarp(setup_flirt): @@ -521,10 +537,13 @@ def test_applywarp(setup_flirt): # in_file, ref_file, field_file mandatory for name, settings in list(opt_map.items()): - awarp = fsl.ApplyWarp(in_file=infile, - ref_file=reffile, - field_file=reffile, - **{name: settings[1]}) + awarp = fsl.ApplyWarp( + in_file=infile, + ref_file=reffile, + field_file=reffile, + **{ + name: settings[1] + }) if name == 'out_file': realcmd = 'applywarp --in=%s '\ '--ref=%s --out=%s '\ @@ -554,25 +573,36 @@ def setup_fugue(tmpdir): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") -@pytest.mark.parametrize("attr, out_file", [ - ({"save_unmasked_fmap":True, "fmap_in_file":"infile", "mask_file":"infile", "output_type":"NIFTI_GZ"}, - 'fmap_out_file'), - ({"save_unmasked_shift":True, "fmap_in_file":"infile", "dwell_time":1.e-3, "mask_file":"infile", "output_type": "NIFTI_GZ"}, - "shift_out_file"), - ({"in_file":"infile", "mask_file":"infile", "shift_in_file":"infile", "output_type":"NIFTI_GZ"}, - 'unwarped_file') - ]) +@pytest.mark.parametrize("attr, out_file", [({ + "save_unmasked_fmap": True, + "fmap_in_file": "infile", + "mask_file": "infile", + "output_type": "NIFTI_GZ" +}, 'fmap_out_file'), ({ + "save_unmasked_shift": True, + "fmap_in_file": "infile", + "dwell_time": 1.e-3, + "mask_file": "infile", + "output_type": "NIFTI_GZ" +}, "shift_out_file"), ({ + "in_file": "infile", + "mask_file": "infile", + "shift_in_file": "infile", + "output_type": "NIFTI_GZ" +}, 'unwarped_file')]) def test_fugue(setup_fugue, attr, out_file): import os.path as op tmpdir, infile = setup_fugue fugue = fsl.FUGUE() for key, value in attr.items(): - if value == "infile": setattr(fugue.inputs, key, infile) - else: setattr(fugue.inputs, key, value) + if value == "infile": + setattr(fugue.inputs, key, infile) + else: + setattr(fugue.inputs, key, value) res = fugue.run() - assert isdefined(getattr(res.outputs,out_file)) + assert isdefined(getattr(res.outputs, out_file)) trait_spec = fugue.inputs.trait(out_file) out_name = trait_spec.name_template % 'dumbfile' out_name += '.nii.gz' diff --git a/nipype/interfaces/fsl/tests/test_utils.py b/nipype/interfaces/fsl/tests/test_utils.py index 66b91cf96f..5df6d88a49 100644 --- a/nipype/interfaces/fsl/tests/test_utils.py +++ b/nipype/interfaces/fsl/tests/test_utils.py @@ -35,12 +35,17 @@ def test_fslroi(create_files_in_directory_plus_output_type): assert roi.cmdline == 'fslroi %s foo_roi.nii 10 20' % filelist[0] # .run based parameter setting - roi2 = fsl.ExtractROI(in_file=filelist[0], - roi_file='foo2_roi.nii', - t_min=20, t_size=40, - x_min=3, x_size=30, - y_min=40, y_size=10, - z_min=5, z_size=20) + roi2 = fsl.ExtractROI( + in_file=filelist[0], + roi_file='foo2_roi.nii', + t_min=20, + t_size=40, + x_min=3, + x_size=30, + y_min=40, + y_size=10, + z_min=5, + z_size=20) assert roi2.cmdline == \ 'fslroi %s foo2_roi.nii 3 30 40 10 5 20 20 40' % filelist[0] @@ -66,18 +71,21 @@ def test_fslmerge(create_files_in_directory_plus_output_type): merger.inputs.merged_file = 'foo_merged.nii' merger.inputs.dimension = 't' merger.inputs.output_type = 'NIFTI' - assert merger.cmdline == 'fslmerge -t foo_merged.nii %s' % ' '.join(filelist) + assert merger.cmdline == 'fslmerge -t foo_merged.nii %s' % ' '.join( + filelist) # verify that providing a tr value updates the dimension to tr merger.inputs.tr = 2.25 - assert merger.cmdline == 'fslmerge -tr foo_merged.nii %s %.2f' % (' '.join(filelist), 2.25) + assert merger.cmdline == 'fslmerge -tr foo_merged.nii %s %.2f' % ( + ' '.join(filelist), 2.25) # .run based parameter setting - merger2 = fsl.Merge(in_files=filelist, - merged_file='foo_merged.nii', - dimension='t', - output_type='NIFTI', - tr=2.25) + merger2 = fsl.Merge( + in_files=filelist, + merged_file='foo_merged.nii', + dimension='t', + output_type='NIFTI', + tr=2.25) assert merger2.cmdline == \ 'fslmerge -tr foo_merged.nii %s %.2f' % (' '.join(filelist), 2.25) @@ -85,6 +93,7 @@ def test_fslmerge(create_files_in_directory_plus_output_type): # test arguments for opt_map # Fslmerge class doesn't have a filled opt_map{} + # test fslmath @@ -108,13 +117,14 @@ def test_fslmaths(create_files_in_directory_plus_output_type): 'fslmaths %s -add 2.5 -mul input_volume2 foo_math.nii' % filelist[0] # .run based parameter setting - math2 = fsl.ImageMaths(in_file=filelist[0], op_string='-add 2.5', - out_file='foo2_math.nii') + math2 = fsl.ImageMaths( + in_file=filelist[0], op_string='-add 2.5', out_file='foo2_math.nii') assert math2.cmdline == 'fslmaths %s -add 2.5 foo2_math.nii' % filelist[0] # test arguments for opt_map # Fslmath class doesn't have opt_map{} + # test overlay @@ -142,9 +152,12 @@ def test_overlay(create_files_in_directory_plus_output_type): filelist[1], filelist[0], filelist[0]) # .run based parameter setting - overlay2 = fsl.Overlay(stat_image=filelist[0], stat_thresh=(2.5, 10), - background_image=filelist[1], auto_thresh_bg=True, - out_file='foo2_overlay.nii') + overlay2 = fsl.Overlay( + stat_image=filelist[0], + stat_thresh=(2.5, 10), + background_image=filelist[1], + auto_thresh_bg=True, + out_file='foo2_overlay.nii') assert overlay2.cmdline == 'overlay 1 0 %s -a %s 2.50 10.00 foo2_overlay.nii' % ( filelist[1], filelist[0]) @@ -177,7 +190,9 @@ def test_slicer(create_files_in_directory_plus_output_type): # .run based parameter setting slicer2 = fsl.Slicer( - in_file=filelist[0], middle_slices=True, label_slices=False, + in_file=filelist[0], + middle_slices=True, + label_slices=False, out_file='foo_bar2.png') assert slicer2.cmdline == 'slicer %s -a foo_bar2.png' % (filelist[0]) @@ -187,6 +202,7 @@ def create_parfiles(): np.savetxt('b.par', np.random.rand(6, 3)) return ['a.par', 'b.par'] + # test fsl_tsplot @@ -215,7 +231,9 @@ def test_plottimeseries(create_files_in_directory_plus_output_type): # .run based parameter setting plotter2 = fsl.PlotTimeSeries( - in_file=parfiles, title='test2 plot', plot_range=(2, 5), + in_file=parfiles, + title='test2 plot', + plot_range=(2, 5), out_file='bar.png') assert plotter2.cmdline == \ 'fsl_tsplot -i %s,%s -o bar.png --start=2 --finish=5 -t \'test2 plot\' -u 1' % tuple( @@ -246,7 +264,9 @@ def test_plotmotionparams(create_files_in_directory_plus_output_type): # .run based parameter setting plotter2 = fsl.PlotMotionParams( - in_file=parfiles[1], in_source='spm', plot_type='translations', + in_file=parfiles[1], + in_source='spm', + plot_type='translations', out_file='bar.png') assert plotter2.cmdline == \ ('fsl_tsplot -i %s -o bar.png -t \'Realign estimated translations (mm)\' ' @@ -273,7 +293,9 @@ def test_convertxfm(create_files_in_directory_plus_output_type): # constructor based parameter setting cvt2 = fsl.ConvertXFM( - in_file=filelist[0], in_file2=filelist[1], concat_xfm=True, + in_file=filelist[0], + in_file2=filelist[1], + concat_xfm=True, out_file="bar.mat") assert cvt2.cmdline == \ "convert_xfm -omat bar.mat -concat %s %s" % (filelist[1], filelist[0]) @@ -297,9 +319,9 @@ def test_swapdims(create_files_in_directory_plus_output_type): # Now test a basic command line swap.inputs.in_file = files[0] swap.inputs.new_dims = ("x", "y", "z") - assert swap.cmdline == "fslswapdim a.nii x y z %s" % os.path.realpath(os.path.join(testdir, "a_newdims%s" % out_ext)) + assert swap.cmdline == "fslswapdim a.nii x y z %s" % os.path.realpath( + os.path.join(testdir, "a_newdims%s" % out_ext)) # Test that we can set an output name swap.inputs.out_file = "b.nii" assert swap.cmdline == "fslswapdim a.nii x y z b.nii" - diff --git a/nipype/interfaces/fsl/utils.py b/nipype/interfaces/fsl/utils.py index b28a4df425..159e884a7c 100644 --- a/nipype/interfaces/fsl/utils.py +++ b/nipype/interfaces/fsl/utils.py @@ -16,7 +16,8 @@ datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import map, range import os @@ -29,20 +30,30 @@ from ...utils.filemanip import (load_json, save_json, split_filename, fname_presuffix) -from ..base import (traits, TraitedSpec, OutputMultiPath, File, - CommandLine, CommandLineInputSpec, isdefined) +from ..base import (traits, TraitedSpec, OutputMultiPath, File, CommandLine, + CommandLineInputSpec, isdefined) from .base import FSLCommand, FSLCommandInputSpec, Info class CopyGeomInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, argstr="%s", position=0, - desc="source image") - dest_file = File(exists=True, mandatory=True, argstr="%s", position=1, - desc="destination image", copyfile=True, - output_name='out_file', - name_source='dest_file', name_template='%s') - ignore_dims = traits.Bool(desc='Do not copy image dimensions', - argstr='-d', position="-1") + in_file = File( + exists=True, + mandatory=True, + argstr="%s", + position=0, + desc="source image") + dest_file = File( + exists=True, + mandatory=True, + argstr="%s", + position=1, + desc="destination image", + copyfile=True, + output_name='out_file', + name_source='dest_file', + name_template='%s') + ignore_dims = traits.Bool( + desc='Do not copy image dimensions', argstr='-d', position="-1") class CopyGeomOutputSpec(TraitedSpec): @@ -64,27 +75,37 @@ class CopyGeom(FSLCommand): class RobustFOVInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, - desc='input filename', - argstr='-i %s', position=0, mandatory=True) - out_roi = File(desc="ROI volume output name", argstr="-r %s", - name_source=['in_file'], hash_files=False, - name_template='%s_ROI') - brainsize = traits.Int(desc=('size of brain in z-dimension (default ' - '170mm/150mm)'), - argstr='-b %d') - out_transform = File(desc=("Transformation matrix in_file to out_roi " - "output name"), - argstr="-m %s", - name_source=['in_file'], hash_files=False, - name_template='%s_to_ROI') + in_file = File( + exists=True, + desc='input filename', + argstr='-i %s', + position=0, + mandatory=True) + out_roi = File( + desc="ROI volume output name", + argstr="-r %s", + name_source=['in_file'], + hash_files=False, + name_template='%s_ROI') + brainsize = traits.Int( + desc=('size of brain in z-dimension (default ' + '170mm/150mm)'), + argstr='-b %d') + out_transform = File( + desc=("Transformation matrix in_file to out_roi " + "output name"), + argstr="-m %s", + name_source=['in_file'], + hash_files=False, + name_template='%s_to_ROI') class RobustFOVOutputSpec(TraitedSpec): out_roi = File(exists=True, desc="ROI volume output name") - out_transform = File(exists=True, - desc=("Transformation matrix in_file to out_roi " - "output name")) + out_transform = File( + exists=True, + desc=("Transformation matrix in_file to out_roi " + "output name")) class RobustFOV(FSLCommand): @@ -100,28 +121,44 @@ class RobustFOV(FSLCommand): class ImageMeantsInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, - desc='input file for computing the average timeseries', - argstr='-i %s', position=0, mandatory=True) - out_file = File(desc='name of output text matrix', - argstr='-o %s', genfile=True, hash_files=False) + in_file = File( + exists=True, + desc='input file for computing the average timeseries', + argstr='-i %s', + position=0, + mandatory=True) + out_file = File( + desc='name of output text matrix', + argstr='-o %s', + genfile=True, + hash_files=False) mask = File(exists=True, desc='input 3D mask', argstr='-m %s') - spatial_coord = traits.List(traits.Int, - desc=(' requested spatial coordinate ' - '(instead of mask)'), - argstr='-c %s') - use_mm = traits.Bool(desc=('use mm instead of voxel coordinates (for -c ' - 'option)'), argstr='--usemm') - show_all = traits.Bool(desc=('show all voxel time series (within mask) ' - 'instead of averaging'), argstr='--showall') + spatial_coord = traits.List( + traits.Int, + desc=(' requested spatial coordinate ' + '(instead of mask)'), + argstr='-c %s') + use_mm = traits.Bool( + desc=('use mm instead of voxel coordinates (for -c ' + 'option)'), + argstr='--usemm') + show_all = traits.Bool( + desc=('show all voxel time series (within mask) ' + 'instead of averaging'), + argstr='--showall') eig = traits.Bool( desc=('calculate Eigenvariate(s) instead of mean (output will have 0 ' 'mean)'), argstr='--eig') - order = traits.Int(1, desc='select number of Eigenvariates', - argstr='--order=%d', usedefault=True) - nobin = traits.Bool(desc=('do not binarise the mask for calculation of ' - 'Eigenvariates'), argstr='--no_bin') + order = traits.Int( + 1, + desc='select number of Eigenvariates', + argstr='--order=%d', + usedefault=True) + nobin = traits.Bool( + desc=('do not binarise the mask for calculation of ' + 'Eigenvariates'), + argstr='--no_bin') transpose = traits.Bool( desc=('output results in transpose format (one row per voxel/mean)'), argstr='--transpose') @@ -145,10 +182,8 @@ def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = self.inputs.out_file if not isdefined(outputs['out_file']): - outputs['out_file'] = self._gen_fname(self.inputs.in_file, - suffix='_ts', - ext='.txt', - change_ext=True) + outputs['out_file'] = self._gen_fname( + self.inputs.in_file, suffix='_ts', ext='.txt', change_ext=True) outputs['out_file'] = os.path.abspath(outputs['out_file']) return outputs @@ -161,17 +196,24 @@ def _gen_filename(self, name): class SmoothInputSpec(FSLCommandInputSpec): in_file = File(exists=True, argstr="%s", position=0, mandatory=True) sigma = traits.Float( - argstr="-kernel gauss %.03f -fmean", position=1, xor=['fwhm'], + argstr="-kernel gauss %.03f -fmean", + position=1, + xor=['fwhm'], mandatory=True, desc='gaussian kernel sigma in mm (not voxels)') fwhm = traits.Float( - argstr="-kernel gauss %.03f -fmean", position=1, xor=['sigma'], + argstr="-kernel gauss %.03f -fmean", + position=1, + xor=['sigma'], mandatory=True, desc=('gaussian kernel fwhm, will be converted to sigma in mm ' '(not voxels)')) smoothed_file = File( - argstr="%s", position=2, name_source=['in_file'], - name_template='%s_smooth', hash_files=False) + argstr="%s", + position=2, + name_source=['in_file'], + name_template='%s_smooth', + hash_files=False) class SmoothOutputSpec(TraitedSpec): @@ -228,17 +270,30 @@ def _format_arg(self, name, trait_spec, value): class MergeInputSpec(FSLCommandInputSpec): - in_files = traits.List(File(exists=True), argstr="%s", position=2, - mandatory=True) - dimension = traits.Enum('t', 'x', 'y', 'z', 'a', argstr="-%s", position=0, - desc=("dimension along which to merge, optionally " - "set tr input when dimension is t"), - mandatory=True) - tr = traits.Float(position=-1, argstr='%.2f', - desc=('use to specify TR in seconds (default is 1.00 ' - 'sec), overrides dimension and sets it to tr')) - merged_file = File(argstr="%s", position=1, name_source='in_files', - name_template='%s_merged', hash_files=False) + in_files = traits.List( + File(exists=True), argstr="%s", position=2, mandatory=True) + dimension = traits.Enum( + 't', + 'x', + 'y', + 'z', + 'a', + argstr="-%s", + position=0, + desc=("dimension along which to merge, optionally " + "set tr input when dimension is t"), + mandatory=True) + tr = traits.Float( + position=-1, + argstr='%.2f', + desc=('use to specify TR in seconds (default is 1.00 ' + 'sec), overrides dimension and sets it to tr')) + merged_file = File( + argstr="%s", + position=1, + name_source='in_files', + name_template='%s_merged', + hash_files=False) class MergeOutputSpec(TraitedSpec): @@ -289,10 +344,18 @@ def _format_arg(self, name, spec, value): class ExtractROIInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr="%s", - position=0, desc="input file", mandatory=True) - roi_file = File(argstr="%s", position=1, - desc="output file", genfile=True, hash_files=False) + in_file = File( + exists=True, + argstr="%s", + position=0, + desc="input file", + mandatory=True) + roi_file = File( + argstr="%s", + position=1, + desc="output file", + genfile=True, + hash_files=False) x_min = traits.Int(argstr="%d", position=2) x_size = traits.Int(argstr="%d", position=3) y_min = traits.Int(argstr="%d", position=4) @@ -301,11 +364,16 @@ class ExtractROIInputSpec(FSLCommandInputSpec): z_size = traits.Int(argstr="%d", position=7) t_min = traits.Int(argstr="%d", position=8) t_size = traits.Int(argstr="%d", position=9) - _crop_xor = ['x_min', 'x_size', 'y_min', - 'y_size', 'z_min', 'z_size', 't_min', 't_size'] - crop_list = traits.List(traits.Tuple(traits.Int, traits.Int), - argstr="%s", position=2, xor=_crop_xor, - desc="list of two tuples specifying crop options") + _crop_xor = [ + 'x_min', 'x_size', 'y_min', 'y_size', 'z_min', 'z_size', 't_min', + 't_size' + ] + crop_list = traits.List( + traits.Tuple(traits.Int, traits.Int), + argstr="%s", + position=2, + xor=_crop_xor, + desc="list of two tuples specifying crop options") class ExtractROIOutputSpec(TraitedSpec): @@ -368,8 +436,8 @@ def _list_outputs(self): outputs = self._outputs().get() outputs['roi_file'] = self.inputs.roi_file if not isdefined(outputs['roi_file']): - outputs['roi_file'] = self._gen_fname(self.inputs.in_file, - suffix='_roi') + outputs['roi_file'] = self._gen_fname( + self.inputs.in_file, suffix='_roi') outputs['roi_file'] = os.path.abspath(outputs['roi_file']) return outputs @@ -380,11 +448,20 @@ def _gen_filename(self, name): class SplitInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr="%s", position=0, mandatory=True, - desc="input filename") + in_file = File( + exists=True, + argstr="%s", + position=0, + mandatory=True, + desc="input filename") out_base_name = traits.Str(argstr="%s", position=1, desc="outputs prefix") dimension = traits.Enum( - 't', 'x', 'y', 'z', argstr="-%s", position=2, + 't', + 'x', + 'y', + 'z', + argstr="-%s", + position=2, mandatory=True, desc="dimension along which the file will be split") @@ -422,8 +499,8 @@ def _list_outputs(self): outbase = 'vol*' if isdefined(self.inputs.out_base_name): outbase = '%s*' % self.inputs.out_base_name - outputs['out_files'] = sorted(glob(os.path.join(os.getcwd(), - outbase + ext))) + outputs['out_files'] = sorted( + glob(os.path.join(os.getcwd(), outbase + ext))) return outputs @@ -431,13 +508,22 @@ class ImageMathsInputSpec(FSLCommandInputSpec): in_file = File(exists=True, argstr="%s", mandatory=True, position=1) in_file2 = File(exists=True, argstr="%s", position=3) out_file = File(argstr="%s", position=4, genfile=True, hash_files=False) - op_string = traits.Str(argstr="%s", position=2, - desc="string defining the operation, i. e. -add") + op_string = traits.Str( + argstr="%s", + position=2, + desc="string defining the operation, i. e. -add") suffix = traits.Str(desc="out_file suffix") - out_data_type = traits.Enum('char', 'short', 'int', 'float', 'double', - 'input', argstr="-odt %s", position=5, - desc=("output datatype, one of (char, short, " - "int, float, double, input)")) + out_data_type = traits.Enum( + 'char', + 'short', + 'int', + 'float', + 'double', + 'input', + argstr="-odt %s", + position=5, + desc=("output datatype, one of (char, short, " + "int, float, double, input)")) class ImageMathsOutputSpec(TraitedSpec): @@ -481,37 +567,53 @@ def _list_outputs(self): outputs = self._outputs().get() outputs['out_file'] = self.inputs.out_file if not isdefined(outputs['out_file']): - outputs['out_file'] = self._gen_fname(self.inputs.in_file, - suffix=suffix) + outputs['out_file'] = self._gen_fname( + self.inputs.in_file, suffix=suffix) outputs['out_file'] = os.path.abspath(outputs['out_file']) return outputs class FilterRegressorInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, argstr="-i %s", - desc="input file name (4D image)", mandatory=True, - position=1) - out_file = File(argstr="-o %s", - desc="output file name for the filtered data", - genfile=True, position=2, hash_files=False) - design_file = File(exists=True, argstr="-d %s", position=3, mandatory=True, - desc=("name of the matrix with time courses (e.g. GLM " - "design or MELODIC mixing matrix)")) + in_file = File( + exists=True, + argstr="-i %s", + desc="input file name (4D image)", + mandatory=True, + position=1) + out_file = File( + argstr="-o %s", + desc="output file name for the filtered data", + genfile=True, + position=2, + hash_files=False) + design_file = File( + exists=True, + argstr="-d %s", + position=3, + mandatory=True, + desc=("name of the matrix with time courses (e.g. GLM " + "design or MELODIC mixing matrix)")) filter_columns = traits.List( - traits.Int, argstr="-f '%s'", - xor=["filter_all"], mandatory=True, + traits.Int, + argstr="-f '%s'", + xor=["filter_all"], + mandatory=True, position=4, desc=("(1-based) column indices to filter out of the data")) - filter_all = traits.Bool(mandatory=True, argstr="-f '%s'", - xor=["filter_columns"], position=4, - desc=("use all columns in the design file in " - "denoising")) + filter_all = traits.Bool( + mandatory=True, + argstr="-f '%s'", + xor=["filter_columns"], + position=4, + desc=("use all columns in the design file in " + "denoising")) mask = File(exists=True, argstr="-m %s", desc="mask image file name") - var_norm = traits.Bool(argstr="--vn", - desc="perform variance-normalization on data") - out_vnscales = traits.Bool(argstr="--out_vnscales", - desc=("output scaling factors for variance " - "normalization")) + var_norm = traits.Bool( + argstr="--vn", desc="perform variance-normalization on data") + out_vnscales = traits.Bool( + argstr="--out_vnscales", + desc=("output scaling factors for variance " + "normalization")) class FilterRegressorOutputSpec(TraitedSpec): @@ -557,18 +659,27 @@ def _gen_filename(self, name): class ImageStatsInputSpec(FSLCommandInputSpec): - split_4d = traits.Bool(argstr='-t', position=1, - desc=('give a separate output line for each 3D ' - 'volume of a 4D timeseries')) - in_file = File(exists=True, argstr="%s", mandatory=True, position=2, - desc='input file to generate stats of') - op_string = traits.Str(argstr="%s", mandatory=True, position=3, - desc=("string defining the operation, options are " - "applied in order, e.g. -M -l 10 -M will " - "report the non-zero mean, apply a threshold " - "and then report the new nonzero mean")) - mask_file = File(exists=True, argstr="", - desc='mask file used for option -k %s') + split_4d = traits.Bool( + argstr='-t', + position=1, + desc=('give a separate output line for each 3D ' + 'volume of a 4D timeseries')) + in_file = File( + exists=True, + argstr="%s", + mandatory=True, + position=2, + desc='input file to generate stats of') + op_string = traits.Str( + argstr="%s", + mandatory=True, + position=3, + desc=("string defining the operation, options are " + "applied in order, e.g. -M -l 10 -M will " + "report the non-zero mean, apply a threshold " + "and then report the new nonzero mean")) + mask_file = File( + exists=True, argstr="", desc='mask file used for option -k %s') class ImageStatsOutputSpec(TraitedSpec): @@ -636,10 +747,13 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): class AvScaleInputSpec(CommandLineInputSpec): all_param = traits.Bool(False, argstr='--allparams') - mat_file = File(exists=True, argstr='%s', - desc='mat file to read', position=-2) - ref_file = File(exists=True, argstr='%s', position=-1, - desc='reference file to get center of rotation') + mat_file = File( + exists=True, argstr='%s', desc='mat file to read', position=-2) + ref_file = File( + exists=True, + argstr='%s', + position=-1, + desc='reference file to get center of rotation') class AvScaleOutputSpec(TraitedSpec): @@ -695,27 +809,30 @@ def _run_interface(self, runtime): out = expr.search(runtime.stdout).groupdict() outputs = {} outputs['rotation_translation_matrix'] = [[ - float(v) for v in r.strip().split(' ')] - for r in out['rot_tran_mat'].strip().split('\n')] + float(v) for v in r.strip().split(' ') + ] for r in out['rot_tran_mat'].strip().split('\n')] outputs['scales'] = [ - float(s) for s in out['scales'].strip().split(' ')] + float(s) for s in out['scales'].strip().split(' ') + ] outputs['skews'] = [float(s) for s in out['skews'].strip().split(' ')] outputs['average_scaling'] = float(out['avg_scaling'].strip()) outputs['determinant'] = float(out['determinant'].strip()) outputs['left_right_orientation_preserved'] = out[ 'lr_orientation'].strip() == 'preserved' outputs['forward_half_transform'] = [[ - float(v) for v in r.strip().split(' ')] - for r in out['fwd_half_xfm'].strip().split('\n')] + float(v) for v in r.strip().split(' ') + ] for r in out['fwd_half_xfm'].strip().split('\n')] outputs['backward_half_transform'] = [[ - float(v) for v in r.strip().split(' ')] - for r in out['bwd_half_xfm'].strip().split('\n')] + float(v) for v in r.strip().split(' ') + ] for r in out['bwd_half_xfm'].strip().split('\n')] if self.inputs.all_param: outputs['rot_angles'] = [ - float(r) for r in out['rot_angles'].strip().split(' ')] + float(r) for r in out['rot_angles'].strip().split(' ') + ] outputs['translations'] = [ - float(r) for r in out['translations'].strip().split(' ')] + float(r) for r in out['translations'].strip().split(' ') + ] setattr(self, '_results', outputs) return runtime @@ -725,47 +842,87 @@ def _list_outputs(self): class OverlayInputSpec(FSLCommandInputSpec): - transparency = traits.Bool(desc='make overlay colors semi-transparent', - position=1, argstr='%s', usedefault=True, - default_value=True) - out_type = traits.Enum('float', 'int', position=2, usedefault=True, - argstr='%s', - desc='write output with float or int') - use_checkerboard = traits.Bool(desc='use checkerboard mask for overlay', - argstr='-c', position=3) - background_image = File(exists=True, position=4, mandatory=True, - argstr='%s', desc='image to use as background') + transparency = traits.Bool( + desc='make overlay colors semi-transparent', + position=1, + argstr='%s', + usedefault=True, + default_value=True) + out_type = traits.Enum( + 'float', + 'int', + position=2, + usedefault=True, + argstr='%s', + desc='write output with float or int') + use_checkerboard = traits.Bool( + desc='use checkerboard mask for overlay', argstr='-c', position=3) + background_image = File( + exists=True, + position=4, + mandatory=True, + argstr='%s', + desc='image to use as background') _xor_inputs = ('auto_thresh_bg', 'full_bg_range', 'bg_thresh') auto_thresh_bg = traits.Bool( desc=('automatically threshold the background image'), - argstr='-a', position=5, - xor=_xor_inputs, mandatory=True) - full_bg_range = traits.Bool(desc='use full range of background image', - argstr='-A', position=5, xor=_xor_inputs, - mandatory=True) + argstr='-a', + position=5, + xor=_xor_inputs, + mandatory=True) + full_bg_range = traits.Bool( + desc='use full range of background image', + argstr='-A', + position=5, + xor=_xor_inputs, + mandatory=True) bg_thresh = traits.Tuple( - traits.Float, traits.Float, argstr='%.3f %.3f', + traits.Float, + traits.Float, + argstr='%.3f %.3f', position=5, desc='min and max values for background intensity', - xor=_xor_inputs, mandatory=True) - stat_image = File(exists=True, position=6, mandatory=True, argstr='%s', - desc='statistical image to overlay in color') - stat_thresh = traits.Tuple(traits.Float, traits.Float, position=7, - mandatory=True, argstr='%.2f %.2f', - desc=('min and max values for the statistical ' - 'overlay')) - show_negative_stats = traits.Bool(desc=('display negative statistics in ' - 'overlay'), xor=['stat_image2'], - argstr='%s', position=8) - stat_image2 = File(exists=True, position=9, xor=['show_negative_stats'], - argstr='%s', - desc='second statistical image to overlay in color') - stat_thresh2 = traits.Tuple(traits.Float, traits.Float, position=10, - desc=('min and max values for second ' - 'statistical overlay'), - argstr='%.2f %.2f') - out_file = File(desc='combined image volume', - position=-1, argstr='%s', genfile=True, hash_files=False) + xor=_xor_inputs, + mandatory=True) + stat_image = File( + exists=True, + position=6, + mandatory=True, + argstr='%s', + desc='statistical image to overlay in color') + stat_thresh = traits.Tuple( + traits.Float, + traits.Float, + position=7, + mandatory=True, + argstr='%.2f %.2f', + desc=('min and max values for the statistical ' + 'overlay')) + show_negative_stats = traits.Bool( + desc=('display negative statistics in ' + 'overlay'), + xor=['stat_image2'], + argstr='%s', + position=8) + stat_image2 = File( + exists=True, + position=9, + xor=['show_negative_stats'], + argstr='%s', + desc='second statistical image to overlay in color') + stat_thresh2 = traits.Tuple( + traits.Float, + traits.Float, + position=10, + desc=('min and max values for second ' + 'statistical overlay'), + argstr='%.2f %.2f') + out_file = File( + desc='combined image volume', + position=-1, + argstr='%s', + genfile=True, + hash_files=False) class OverlayOutputSpec(TraitedSpec): @@ -817,8 +974,8 @@ def _list_outputs(self): out_file = self.inputs.out_file if not isdefined(out_file): if isdefined(self.inputs.stat_image2) and ( - not isdefined(self.inputs.show_negative_stats) or not - self.inputs.show_negative_stats): + not isdefined(self.inputs.show_negative_stats) + or not self.inputs.show_negative_stats): stem = "%s_and_%s" % ( split_filename(self.inputs.stat_image)[1], split_filename(self.inputs.stat_image2)[1]) @@ -835,53 +992,94 @@ def _gen_filename(self, name): class SlicerInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, position=1, argstr='%s', mandatory=True, - desc='input volume') - image_edges = File(exists=True, position=2, argstr='%s', - desc=('volume to display edge overlay for (useful for ' - 'checking registration')) + in_file = File( + exists=True, + position=1, + argstr='%s', + mandatory=True, + desc='input volume') + image_edges = File( + exists=True, + position=2, + argstr='%s', + desc=('volume to display edge overlay for (useful for ' + 'checking registration')) label_slices = traits.Bool( - position=3, argstr='-L', desc='display slice number', - usedefault=True, default_value=True) - colour_map = File(exists=True, position=4, argstr='-l %s', - desc=('use different colour map from that stored in ' - 'nifti header')) - intensity_range = traits.Tuple(traits.Float, traits.Float, position=5, - argstr='-i %.3f %.3f', - desc='min and max intensities to display') - threshold_edges = traits.Float(position=6, argstr='-e %.3f', - desc='use threshold for edges') - dither_edges = traits.Bool(position=7, argstr='-t', - desc=('produce semi-transparent (dithered) ' - 'edges')) - nearest_neighbour = traits.Bool(position=8, argstr='-n', - desc=('use nearest neighbor interpolation ' - 'for output')) - show_orientation = traits.Bool(position=9, argstr='%s', usedefault=True, - default_value=True, - desc='label left-right orientation') + position=3, + argstr='-L', + desc='display slice number', + usedefault=True, + default_value=True) + colour_map = File( + exists=True, + position=4, + argstr='-l %s', + desc=('use different colour map from that stored in ' + 'nifti header')) + intensity_range = traits.Tuple( + traits.Float, + traits.Float, + position=5, + argstr='-i %.3f %.3f', + desc='min and max intensities to display') + threshold_edges = traits.Float( + position=6, argstr='-e %.3f', desc='use threshold for edges') + dither_edges = traits.Bool( + position=7, + argstr='-t', + desc=('produce semi-transparent (dithered) ' + 'edges')) + nearest_neighbour = traits.Bool( + position=8, + argstr='-n', + desc=('use nearest neighbor interpolation ' + 'for output')) + show_orientation = traits.Bool( + position=9, + argstr='%s', + usedefault=True, + default_value=True, + desc='label left-right orientation') _xor_options = ('single_slice', 'middle_slices', 'all_axial', 'sample_axial') single_slice = traits.Enum( - 'x', 'y', 'z', position=10, argstr='-%s', - xor=_xor_options, requires=['slice_number'], + 'x', + 'y', + 'z', + position=10, + argstr='-%s', + xor=_xor_options, + requires=['slice_number'], desc=('output picture of single slice in the x, y, or z plane')) - slice_number = traits.Int(position=11, argstr='-%d', - desc='slice number to save in picture') - middle_slices = traits.Bool(position=10, argstr='-a', xor=_xor_options, - desc=('output picture of mid-sagittal, axial, ' - 'and coronal slices')) - all_axial = traits.Bool(position=10, argstr='-A', xor=_xor_options, - requires=['image_width'], - desc='output all axial slices into one picture') - sample_axial = traits.Int(position=10, argstr='-S %d', - xor=_xor_options, requires=['image_width'], - desc=('output every n axial slices into one ' - 'picture')) + slice_number = traits.Int( + position=11, argstr='-%d', desc='slice number to save in picture') + middle_slices = traits.Bool( + position=10, + argstr='-a', + xor=_xor_options, + desc=('output picture of mid-sagittal, axial, ' + 'and coronal slices')) + all_axial = traits.Bool( + position=10, + argstr='-A', + xor=_xor_options, + requires=['image_width'], + desc='output all axial slices into one picture') + sample_axial = traits.Int( + position=10, + argstr='-S %d', + xor=_xor_options, + requires=['image_width'], + desc=('output every n axial slices into one ' + 'picture')) image_width = traits.Int( position=-2, argstr='%d', desc='max picture width') - out_file = File(position=-1, genfile=True, argstr='%s', - desc='picture to write', hash_files=False) + out_file = File( + position=-1, + genfile=True, + argstr='%s', + desc='picture to write', + hash_files=False) scaling = traits.Float(position=0, argstr='-s %f', desc='image scale') @@ -939,40 +1137,62 @@ def _gen_filename(self, name): class PlotTimeSeriesInputSpec(FSLCommandInputSpec): - in_file = traits.Either(File(exists=True), traits.List(File(exists=True)), - mandatory=True, argstr="%s", position=1, - desc=("file or list of files with columns of " - "timecourse information")) - plot_start = traits.Int(argstr="--start=%d", xor=("plot_range",), - desc="first column from in-file to plot") - plot_finish = traits.Int(argstr="--finish=%d", xor=("plot_range",), - desc="final column from in-file to plot") - plot_range = traits.Tuple(traits.Int, traits.Int, argstr="%s", - xor=("plot_start", "plot_finish"), - desc=("first and last columns from the in-file " - "to plot")) + in_file = traits.Either( + File(exists=True), + traits.List(File(exists=True)), + mandatory=True, + argstr="%s", + position=1, + desc=("file or list of files with columns of " + "timecourse information")) + plot_start = traits.Int( + argstr="--start=%d", + xor=("plot_range", ), + desc="first column from in-file to plot") + plot_finish = traits.Int( + argstr="--finish=%d", + xor=("plot_range", ), + desc="final column from in-file to plot") + plot_range = traits.Tuple( + traits.Int, + traits.Int, + argstr="%s", + xor=("plot_start", "plot_finish"), + desc=("first and last columns from the in-file " + "to plot")) title = traits.Str(argstr="%s", desc="plot title") legend_file = File(exists=True, argstr="--legend=%s", desc="legend file") - labels = traits.Either(traits.Str, traits.List(traits.Str), - argstr="%s", desc="label or list of labels") - y_min = traits.Float(argstr="--ymin=%.2f", desc="minumum y value", - xor=("y_range",)) - y_max = traits.Float(argstr="--ymax=%.2f", desc="maximum y value", - xor=("y_range",)) - y_range = traits.Tuple(traits.Float, traits.Float, argstr="%s", - xor=("y_min", "y_max"), - desc="min and max y axis values") + labels = traits.Either( + traits.Str, + traits.List(traits.Str), + argstr="%s", + desc="label or list of labels") + y_min = traits.Float( + argstr="--ymin=%.2f", desc="minumum y value", xor=("y_range", )) + y_max = traits.Float( + argstr="--ymax=%.2f", desc="maximum y value", xor=("y_range", )) + y_range = traits.Tuple( + traits.Float, + traits.Float, + argstr="%s", + xor=("y_min", "y_max"), + desc="min and max y axis values") x_units = traits.Int( - argstr="-u %d", usedefault=True, default_value=1, + argstr="-u %d", + usedefault=True, + default_value=1, desc=("scaling units for x-axis (between 1 and length of in file)")) - plot_size = traits.Tuple(traits.Int, traits.Int, argstr="%s", - desc="plot image height and width") - x_precision = traits.Int(argstr="--precision=%d", - desc="precision of x-axis labels") - sci_notation = traits.Bool(argstr="--sci", - desc="switch on scientific notation") - out_file = File(argstr="-o %s", genfile=True, - desc="image to write", hash_files=False) + plot_size = traits.Tuple( + traits.Int, + traits.Int, + argstr="%s", + desc="plot image height and width") + x_precision = traits.Int( + argstr="--precision=%d", desc="precision of x-axis labels") + sci_notation = traits.Bool( + argstr="--sci", desc="switch on scientific notation") + out_file = File( + argstr="-o %s", genfile=True, desc="image to write", hash_files=False) class PlotTimeSeriesOutputSpec(TraitedSpec): @@ -1042,20 +1262,34 @@ def _gen_filename(self, name): class PlotMotionParamsInputSpec(FSLCommandInputSpec): - in_file = traits.Either(File(exists=True), traits.List(File(exists=True)), - mandatory=True, argstr="%s", position=1, - desc="file with motion parameters") - in_source = traits.Enum("spm", "fsl", mandatory=True, - desc=("which program generated the motion " - "parameter file - fsl, spm")) - plot_type = traits.Enum("rotations", "translations", "displacement", - argstr="%s", mandatory=True, - desc=("which motion type to plot - rotations, " - "translations, displacement")) - plot_size = traits.Tuple(traits.Int, traits.Int, argstr="%s", - desc="plot image height and width") - out_file = File(argstr="-o %s", genfile=True, - desc="image to write", hash_files=False) + in_file = traits.Either( + File(exists=True), + traits.List(File(exists=True)), + mandatory=True, + argstr="%s", + position=1, + desc="file with motion parameters") + in_source = traits.Enum( + "spm", + "fsl", + mandatory=True, + desc=("which program generated the motion " + "parameter file - fsl, spm")) + plot_type = traits.Enum( + "rotations", + "translations", + "displacement", + argstr="%s", + mandatory=True, + desc=("which motion type to plot - rotations, " + "translations, displacement")) + plot_size = traits.Tuple( + traits.Int, + traits.Int, + argstr="%s", + desc="plot image height and width") + out_file = File( + argstr="-o %s", genfile=True, desc="image to write", hash_files=False) class PlotMotionParamsOutputSpec(TraitedSpec): @@ -1106,17 +1340,17 @@ def _format_arg(self, name, spec, value): # Get the right starting and ending position depending on source # package - sfdict = dict(fsl_rot=(1, 3), fsl_tra=( - 4, 6), spm_rot=(4, 6), spm_tra=(1, 3)) + sfdict = dict( + fsl_rot=(1, 3), fsl_tra=(4, 6), spm_rot=(4, 6), spm_tra=(1, 3)) # Format the title properly - sfstr = "--start=%d --finish=%d" % sfdict[ - "%s_%s" % (source, value[:3])] + sfstr = "--start=%d --finish=%d" % sfdict["%s_%s" % (source, + value[:3])] titledict = dict(fsl="MCFLIRT", spm="Realign") unitdict = dict(rot="radians", tra="mm") - title = "\'%s estimated %s (%s)\'" % ( - titledict[source], value, unitdict[value[:3]]) + title = "\'%s estimated %s (%s)\'" % (titledict[source], value, + unitdict[value[:3]]) return "-t %s %s -a x,y,z" % (title, sfstr) elif name == "plot_size": @@ -1138,8 +1372,8 @@ def _list_outputs(self): infile = self.inputs.in_file[0] else: infile = self.inputs.in_file - plttype = dict(rot="rot", tra="trans", dis="disp")[ - self.inputs.plot_type[:3]] + plttype = dict( + rot="rot", tra="trans", dis="disp")[self.inputs.plot_type[:3]] out_file = fname_presuffix( infile, suffix="_%s.png" % plttype, use_ext=False) outputs['out_file'] = os.path.abspath(out_file) @@ -1152,24 +1386,43 @@ def _gen_filename(self, name): class ConvertXFMInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, argstr="%s", position=-1, - desc="input transformation matrix") + in_file = File( + exists=True, + mandatory=True, + argstr="%s", + position=-1, + desc="input transformation matrix") in_file2 = File( - exists=True, argstr="%s", position=-2, + exists=True, + argstr="%s", + position=-2, desc="second input matrix (for use with fix_scale_skew or concat_xfm)") _options = ["invert_xfm", "concat_xfm", "fix_scale_skew"] - invert_xfm = traits.Bool(argstr="-inverse", position=-3, xor=_options, - desc="invert input transformation") - concat_xfm = traits.Bool(argstr="-concat", position=-3, xor=_options, - requires=["in_file2"], - desc=("write joint transformation of two input " - "matrices")) - fix_scale_skew = traits.Bool(argstr="-fixscaleskew", position=-3, - xor=_options, requires=["in_file2"], - desc=("use secondary matrix to fix scale and " - "skew")) - out_file = File(genfile=True, argstr="-omat %s", position=1, - desc="final transformation matrix", hash_files=False) + invert_xfm = traits.Bool( + argstr="-inverse", + position=-3, + xor=_options, + desc="invert input transformation") + concat_xfm = traits.Bool( + argstr="-concat", + position=-3, + xor=_options, + requires=["in_file2"], + desc=("write joint transformation of two input " + "matrices")) + fix_scale_skew = traits.Bool( + argstr="-fixscaleskew", + position=-3, + xor=_options, + requires=["in_file2"], + desc=("use secondary matrix to fix scale and " + "skew")) + out_file = File( + genfile=True, + argstr="-omat %s", + position=1, + desc="final transformation matrix", + hash_files=False) class ConvertXFMOutputSpec(TraitedSpec): @@ -1203,22 +1456,25 @@ def _list_outputs(self): if not isdefined(outfile): _, infile1, _ = split_filename(self.inputs.in_file) if self.inputs.invert_xfm: - outfile = fname_presuffix(infile1, - suffix="_inv.mat", - newpath=os.getcwd(), - use_ext=False) + outfile = fname_presuffix( + infile1, + suffix="_inv.mat", + newpath=os.getcwd(), + use_ext=False) else: if self.inputs.concat_xfm: _, infile2, _ = split_filename(self.inputs.in_file2) - outfile = fname_presuffix("%s_%s" % (infile1, infile2), - suffix=".mat", - newpath=os.getcwd(), - use_ext=False) + outfile = fname_presuffix( + "%s_%s" % (infile1, infile2), + suffix=".mat", + newpath=os.getcwd(), + use_ext=False) else: - outfile = fname_presuffix(infile1, - suffix="_fix.mat", - newpath=os.getcwd(), - use_ext=False) + outfile = fname_presuffix( + infile1, + suffix="_fix.mat", + newpath=os.getcwd(), + use_ext=False) outputs["out_file"] = os.path.abspath(outfile) return outputs @@ -1230,16 +1486,24 @@ def _gen_filename(self, name): class SwapDimensionsInputSpec(FSLCommandInputSpec): - in_file = File(exists=True, mandatory=True, argstr="%s", position="1", - desc="input image") - _dims = ["x", "-x", "y", "-y", "z", - "-z", "RL", "LR", "AP", "PA", "IS", "SI"] - new_dims = traits.Tuple(traits.Enum(_dims), traits.Enum(_dims), - traits.Enum(_dims), argstr="%s %s %s", - mandatory=True, - desc="3-tuple of new dimension order") - out_file = File(genfile=True, argstr="%s", - desc="image to write", hash_files=False) + in_file = File( + exists=True, + mandatory=True, + argstr="%s", + position="1", + desc="input image") + _dims = [ + "x", "-x", "y", "-y", "z", "-z", "RL", "LR", "AP", "PA", "IS", "SI" + ] + new_dims = traits.Tuple( + traits.Enum(_dims), + traits.Enum(_dims), + traits.Enum(_dims), + argstr="%s %s %s", + mandatory=True, + desc="3-tuple of new dimension order") + out_file = File( + genfile=True, argstr="%s", desc="image to write", hash_files=False) class SwapDimensionsOutputSpec(TraitedSpec): @@ -1264,8 +1528,8 @@ def _list_outputs(self): outputs = self._outputs().get() outputs["out_file"] = self.inputs.out_file if not isdefined(self.inputs.out_file): - outputs["out_file"] = self._gen_fname(self.inputs.in_file, - suffix='_newdims') + outputs["out_file"] = self._gen_fname( + self.inputs.in_file, suffix='_newdims') outputs["out_file"] = os.path.abspath(outputs["out_file"]) return outputs @@ -1278,11 +1542,18 @@ def _gen_filename(self, name): class PowerSpectrumInputSpec(FSLCommandInputSpec): # We use position args here as list indices - so a negative number # will put something on the end - in_file = File(exists=True, - desc="input 4D file to estimate the power spectrum", - argstr='%s', position=0, mandatory=True) - out_file = File(desc='name of output 4D file for power spectrum', - argstr='%s', position=1, genfile=True, hash_files=False) + in_file = File( + exists=True, + desc="input 4D file to estimate the power spectrum", + argstr='%s', + position=0, + mandatory=True) + out_file = File( + desc='name of output 4D file for power spectrum', + argstr='%s', + position=1, + genfile=True, + hash_files=False) class PowerSpectrumOutputSpec(TraitedSpec): @@ -1311,8 +1582,7 @@ class PowerSpectrum(FSLCommand): def _gen_outfilename(self): out_file = self.inputs.out_file if not isdefined(out_file) and isdefined(self.inputs.in_file): - out_file = self._gen_fname(self.inputs.in_file, - suffix='_ps') + out_file = self._gen_fname(self.inputs.in_file, suffix='_ps') return out_file def _list_outputs(self): @@ -1327,27 +1597,19 @@ def _gen_filename(self, name): class SigLossInputSpec(FSLCommandInputSpec): - in_file = File(mandatory=True, - exists=True, - argstr='-i %s', - desc='b0 fieldmap file') - out_file = File(argstr='-s %s', - desc='output signal loss estimate file', - genfile=True) - - mask_file = File(exists=True, - argstr='-m %s', - desc='brain mask file') - echo_time = traits.Float(argstr='--te=%f', - desc='echo time in seconds') - slice_direction = traits.Enum('x', 'y', 'z', - argstr='-d %s', - desc='slicing direction') + in_file = File( + mandatory=True, exists=True, argstr='-i %s', desc='b0 fieldmap file') + out_file = File( + argstr='-s %s', desc='output signal loss estimate file', genfile=True) + + mask_file = File(exists=True, argstr='-m %s', desc='brain mask file') + echo_time = traits.Float(argstr='--te=%f', desc='echo time in seconds') + slice_direction = traits.Enum( + 'x', 'y', 'z', argstr='-d %s', desc='slicing direction') class SigLossOuputSpec(TraitedSpec): - out_file = File(exists=True, - desc='signal loss estimate file') + out_file = File(exists=True, desc='signal loss estimate file') class SigLoss(FSLCommand): @@ -1372,8 +1634,8 @@ def _list_outputs(self): outputs['out_file'] = self.inputs.out_file if not isdefined(outputs['out_file']) and \ isdefined(self.inputs.in_file): - outputs['out_file'] = self._gen_fname(self.inputs.in_file, - suffix='_sigloss') + outputs['out_file'] = self._gen_fname( + self.inputs.in_file, suffix='_sigloss') return outputs def _gen_filename(self, name): @@ -1411,8 +1673,7 @@ class Reorient2Std(FSLCommand): def _gen_filename(self, name): if name == 'out_file': - return self._gen_fname(self.inputs.in_file, - suffix="_reoriented") + return self._gen_fname(self.inputs.in_file, suffix="_reoriented") return None def _list_outputs(self): @@ -1425,58 +1686,76 @@ def _list_outputs(self): class InvWarpInputSpec(FSLCommandInputSpec): - warp = File(exists=True, argstr='--warp=%s', mandatory=True, - desc=('Name of file containing warp-coefficients/fields. This ' - 'would typically be the output from the --cout switch of' - ' fnirt (but can also use fields, like the output from ' - '--fout).')) - reference = File(exists=True, argstr='--ref=%s', mandatory=True, - desc=('Name of a file in target space. Note that the ' - 'target space is now different from the target ' - 'space that was used to create the --warp file. It ' - 'would typically be the file that was specified ' - 'with the --in argument when running fnirt.')) - inverse_warp = File(argstr='--out=%s', name_source=['warp'], - hash_files=False, name_template='%s_inverse', - desc=('Name of output file, containing warps that are ' - 'the "reverse" of those in --warp. This will be ' - 'a field-file (rather than a file of spline ' - 'coefficients), and it will have any affine ' - 'component included as part of the ' - 'displacements.')) - absolute = traits.Bool(argstr='--abs', xor=['relative'], - desc=('If set it indicates that the warps in --warp' - ' should be interpreted as absolute, provided' - ' that it is not created by fnirt (which ' - 'always uses relative warps). If set it also ' - 'indicates that the output --out should be ' - 'absolute.')) - relative = traits.Bool(argstr='--rel', xor=['absolute'], - desc=('If set it indicates that the warps in --warp' - ' should be interpreted as relative. I.e. the' - ' values in --warp are displacements from the' - ' coordinates in the --ref space. If set it ' - 'also indicates that the output --out should ' - 'be relative.')) - niter = traits.Int(argstr='--niter=%d', - desc=('Determines how many iterations of the ' - 'gradient-descent search that should be run.')) - regularise = traits.Float(argstr='--regularise=%f', - desc='Regularization strength (deafult=1.0).') - noconstraint = traits.Bool(argstr='--noconstraint', - desc='Do not apply Jacobian constraint') - jacobian_min = traits.Float(argstr='--jmin=%f', - desc=('Minimum acceptable Jacobian value for ' - 'constraint (default 0.01)')) - jacobian_max = traits.Float(argstr='--jmax=%f', - desc=('Maximum acceptable Jacobian value for ' - 'constraint (default 100.0)')) + warp = File( + exists=True, + argstr='--warp=%s', + mandatory=True, + desc=('Name of file containing warp-coefficients/fields. This ' + 'would typically be the output from the --cout switch of' + ' fnirt (but can also use fields, like the output from ' + '--fout).')) + reference = File( + exists=True, + argstr='--ref=%s', + mandatory=True, + desc=('Name of a file in target space. Note that the ' + 'target space is now different from the target ' + 'space that was used to create the --warp file. It ' + 'would typically be the file that was specified ' + 'with the --in argument when running fnirt.')) + inverse_warp = File( + argstr='--out=%s', + name_source=['warp'], + hash_files=False, + name_template='%s_inverse', + desc=('Name of output file, containing warps that are ' + 'the "reverse" of those in --warp. This will be ' + 'a field-file (rather than a file of spline ' + 'coefficients), and it will have any affine ' + 'component included as part of the ' + 'displacements.')) + absolute = traits.Bool( + argstr='--abs', + xor=['relative'], + desc=('If set it indicates that the warps in --warp' + ' should be interpreted as absolute, provided' + ' that it is not created by fnirt (which ' + 'always uses relative warps). If set it also ' + 'indicates that the output --out should be ' + 'absolute.')) + relative = traits.Bool( + argstr='--rel', + xor=['absolute'], + desc=('If set it indicates that the warps in --warp' + ' should be interpreted as relative. I.e. the' + ' values in --warp are displacements from the' + ' coordinates in the --ref space. If set it ' + 'also indicates that the output --out should ' + 'be relative.')) + niter = traits.Int( + argstr='--niter=%d', + desc=('Determines how many iterations of the ' + 'gradient-descent search that should be run.')) + regularise = traits.Float( + argstr='--regularise=%f', + desc='Regularization strength (deafult=1.0).') + noconstraint = traits.Bool( + argstr='--noconstraint', desc='Do not apply Jacobian constraint') + jacobian_min = traits.Float( + argstr='--jmin=%f', + desc=('Minimum acceptable Jacobian value for ' + 'constraint (default 0.01)')) + jacobian_max = traits.Float( + argstr='--jmax=%f', + desc=('Maximum acceptable Jacobian value for ' + 'constraint (default 100.0)')) class InvWarpOutputSpec(TraitedSpec): - inverse_warp = File(exists=True, - desc=('Name of output file, containing warps that are ' - 'the "reverse" of those in --warp.')) + inverse_warp = File( + exists=True, + desc=('Name of output file, containing warps that are ' + 'the "reverse" of those in --warp.')) class InvWarp(FSLCommand): @@ -1514,46 +1793,83 @@ class ComplexInputSpec(FSLCommandInputSpec): magnitude_in_file = File(exists=True, argstr="%s", position=2) phase_in_file = File(exists=True, argstr='%s', position=3) - _ofs = ['complex_out_file', - 'magnitude_out_file', 'phase_out_file', - 'real_out_file', 'imaginary_out_file'] - _conversion = ['real_polar', 'real_cartesian', - 'complex_cartesian', 'complex_polar', - 'complex_split', 'complex_merge', ] - - complex_out_file = File(genfile=True, argstr="%s", position=-3, - xor=_ofs + _conversion[:2]) - magnitude_out_file = File(genfile=True, argstr="%s", position=-4, - xor=_ofs[:1] + _ofs[3:] + _conversion[1:]) - phase_out_file = File(genfile=True, argstr="%s", position=-3, - xor=_ofs[:1] + _ofs[3:] + _conversion[1:]) - real_out_file = File(genfile=True, argstr="%s", position=-4, - xor=_ofs[:3] + _conversion[:1] + _conversion[2:]) - imaginary_out_file = File(genfile=True, argstr="%s", position=-3, - xor=_ofs[:3] + _conversion[:1] + _conversion[2:]) + _ofs = [ + 'complex_out_file', 'magnitude_out_file', 'phase_out_file', + 'real_out_file', 'imaginary_out_file' + ] + _conversion = [ + 'real_polar', + 'real_cartesian', + 'complex_cartesian', + 'complex_polar', + 'complex_split', + 'complex_merge', + ] + + complex_out_file = File( + genfile=True, argstr="%s", position=-3, xor=_ofs + _conversion[:2]) + magnitude_out_file = File( + genfile=True, + argstr="%s", + position=-4, + xor=_ofs[:1] + _ofs[3:] + _conversion[1:]) + phase_out_file = File( + genfile=True, + argstr="%s", + position=-3, + xor=_ofs[:1] + _ofs[3:] + _conversion[1:]) + real_out_file = File( + genfile=True, + argstr="%s", + position=-4, + xor=_ofs[:3] + _conversion[:1] + _conversion[2:]) + imaginary_out_file = File( + genfile=True, + argstr="%s", + position=-3, + xor=_ofs[:3] + _conversion[:1] + _conversion[2:]) start_vol = traits.Int(position=-2, argstr='%d') end_vol = traits.Int(position=-1, argstr='%d') real_polar = traits.Bool( - argstr='-realpolar', xor=_conversion, position=1,) -# requires=['complex_in_file','magnitude_out_file','phase_out_file']) + argstr='-realpolar', + xor=_conversion, + position=1, + ) + # requires=['complex_in_file','magnitude_out_file','phase_out_file']) real_cartesian = traits.Bool( - argstr='-realcartesian', xor=_conversion, position=1,) -# requires=['complex_in_file','real_out_file','imaginary_out_file']) + argstr='-realcartesian', + xor=_conversion, + position=1, + ) + # requires=['complex_in_file','real_out_file','imaginary_out_file']) complex_cartesian = traits.Bool( - argstr='-complex', xor=_conversion, position=1,) -# requires=['real_in_file','imaginary_in_file','complex_out_file']) + argstr='-complex', + xor=_conversion, + position=1, + ) + # requires=['real_in_file','imaginary_in_file','complex_out_file']) complex_polar = traits.Bool( - argstr='-complexpolar', xor=_conversion, position=1,) -# requires=['magnitude_in_file','phase_in_file', -# 'magnitude_out_file','phase_out_file']) + argstr='-complexpolar', + xor=_conversion, + position=1, + ) + # requires=['magnitude_in_file','phase_in_file', + # 'magnitude_out_file','phase_out_file']) complex_split = traits.Bool( - argstr='-complexsplit', xor=_conversion, position=1,) -# requires=['complex_in_file','complex_out_file']) + argstr='-complexsplit', + xor=_conversion, + position=1, + ) + # requires=['complex_in_file','complex_out_file']) complex_merge = traits.Bool( - argstr='-complexmerge', xor=_conversion + ['start_vol', 'end_vol'], - position=1,) + argstr='-complexmerge', + xor=_conversion + ['start_vol', 'end_vol'], + position=1, + ) + + # requires=['complex_in_file','complex_in_file2','complex_out_file']) @@ -1639,26 +1955,35 @@ def _list_outputs(self): class WarpUtilsInputSpec(FSLCommandInputSpec): in_file = File( - exists=True, argstr='--in=%s', mandatory=True, + exists=True, + argstr='--in=%s', + mandatory=True, desc=('Name of file containing warp-coefficients/fields. This ' 'would typically be the output from the --cout switch of ' 'fnirt (but can also use fields, like the output from ' '--fout).')) - reference = File(exists=True, argstr='--ref=%s', mandatory=True, - desc=('Name of a file in target space. Note that the ' - 'target space is now different from the target ' - 'space that was used to create the --warp file. It ' - 'would typically be the file that was specified ' - 'with the --in argument when running fnirt.')) + reference = File( + exists=True, + argstr='--ref=%s', + mandatory=True, + desc=('Name of a file in target space. Note that the ' + 'target space is now different from the target ' + 'space that was used to create the --warp file. It ' + 'would typically be the file that was specified ' + 'with the --in argument when running fnirt.')) out_format = traits.Enum( - 'spline', 'field', argstr='--outformat=%s', + 'spline', + 'field', + argstr='--outformat=%s', desc=('Specifies the output format. If set to field (default) ' 'the output will be a (4D) field-file. If set to spline ' 'the format will be a (4D) file of spline coefficients.')) warp_resolution = traits.Tuple( - traits.Float, traits.Float, traits.Float, + traits.Float, + traits.Float, + traits.Float, argstr='--warpres=%0.4f,%0.4f,%0.4f', desc=('Specifies the resolution/knot-spacing of the splines pertaining' ' to the coefficients in the --out file. This parameter is only ' @@ -1671,13 +1996,17 @@ class WarpUtilsInputSpec(FSLCommandInputSpec): 'size.')) knot_space = traits.Tuple( - traits.Int, traits.Int, traits.Int, + traits.Int, + traits.Int, + traits.Int, argstr='--knotspace=%d,%d,%d', desc=('Alternative (to --warpres) specification of the resolution of ' 'the output spline-field.')) out_file = File( - argstr='--out=%s', position=-1, name_source=['in_file'], + argstr='--out=%s', + position=-1, + name_source=['in_file'], output_name='out_file', desc=('Name of output file. The format of the output depends on what ' 'other parameters are set. The default format is a (4D) ' @@ -1685,7 +2014,9 @@ class WarpUtilsInputSpec(FSLCommandInputSpec): 'will be a (4D) file of spline coefficients.')) write_jacobian = traits.Bool( - False, mandatory=True, usedefault=True, + False, + mandatory=True, + usedefault=True, desc='Switch on --jac flag with automatically generated filename') out_jacobian = File( @@ -1695,7 +2026,8 @@ class WarpUtilsInputSpec(FSLCommandInputSpec): 'filename.')) with_affine = traits.Bool( - False, argstr='--withaff', + False, + argstr='--withaff', desc=('Specifies that the affine transform (i.e. that which was ' 'specified for the --aff parameter in fnirt) should be ' 'included as displacements in the --out file. That can be ' @@ -1745,8 +2077,8 @@ def _parse_inputs(self, skip=None): skip = [] suffix = 'field' - if (isdefined(self.inputs.out_format) and - self.inputs.out_format == 'spline'): + if (isdefined(self.inputs.out_format) + and self.inputs.out_format == 'spline'): suffix = 'coeffs' trait_spec = self.inputs.trait('out_file') @@ -1767,103 +2099,131 @@ def _parse_inputs(self, skip=None): class ConvertWarpInputSpec(FSLCommandInputSpec): reference = File( - exists=True, argstr='--ref=%s', mandatory=True, position=1, + exists=True, + argstr='--ref=%s', + mandatory=True, + position=1, desc='Name of a file in target space of the full transform.') out_file = File( - argstr='--out=%s', position=-1, name_source=['reference'], - name_template='%s_concatwarp', output_name='out_file', + argstr='--out=%s', + position=-1, + name_source=['reference'], + name_template='%s_concatwarp', + output_name='out_file', desc=('Name of output file, containing warps that are the combination ' 'of all those given as arguments. The format of this will be a ' 'field-file (rather than spline coefficients) with any affine ' 'components included.')) - premat = File(exists=True, argstr='--premat=%s', - desc='filename for pre-transform (affine matrix)') + premat = File( + exists=True, + argstr='--premat=%s', + desc='filename for pre-transform (affine matrix)') - warp1 = File(exists=True, argstr='--warp1=%s', - desc='Name of file containing initial ' - 'warp-fields/coefficients (follows premat). This could ' - 'e.g. be a fnirt-transform from a subjects structural ' - 'scan to an average of a group of subjects.') + warp1 = File( + exists=True, + argstr='--warp1=%s', + desc='Name of file containing initial ' + 'warp-fields/coefficients (follows premat). This could ' + 'e.g. be a fnirt-transform from a subjects structural ' + 'scan to an average of a group of subjects.') - midmat = File(exists=True, argstr="--midmat=%s", - desc="Name of file containing mid-warp-affine transform") + midmat = File( + exists=True, + argstr="--midmat=%s", + desc="Name of file containing mid-warp-affine transform") warp2 = File( - exists=True, argstr='--warp2=%s', + exists=True, + argstr='--warp2=%s', desc='Name of file containing secondary warp-fields/coefficients ' - '(after warp1/midmat but before postmat). This could e.g. be a ' - 'fnirt-transform from the average of a group of subjects to some ' - 'standard space (e.g. MNI152).') + '(after warp1/midmat but before postmat). This could e.g. be a ' + 'fnirt-transform from the average of a group of subjects to some ' + 'standard space (e.g. MNI152).') postmat = File( - exists=True, argstr='--postmat=%s', + exists=True, + argstr='--postmat=%s', desc='Name of file containing an affine transform (applied last). It ' - 'could e.g. be an affine transform that maps the MNI152-space ' - 'into a better approximation to the Talairach-space (if indeed ' - 'there is one).') + 'could e.g. be an affine transform that maps the MNI152-space ' + 'into a better approximation to the Talairach-space (if indeed ' + 'there is one).') shift_in_file = File( - exists=True, argstr='--shiftmap=%s', + exists=True, + argstr='--shiftmap=%s', desc='Name of file containing a "shiftmap", a non-linear transform ' - 'with displacements only in one direction (applied first, before ' - 'premat). This would typically be a fieldmap that has been ' - 'pre-processed using fugue that maps a subjects functional (EPI) ' - 'data onto an undistorted space (i.e. a space that corresponds ' - 'to his/her true anatomy).') + 'with displacements only in one direction (applied first, before ' + 'premat). This would typically be a fieldmap that has been ' + 'pre-processed using fugue that maps a subjects functional (EPI) ' + 'data onto an undistorted space (i.e. a space that corresponds ' + 'to his/her true anatomy).') shift_direction = traits.Enum( - 'y-', 'y', 'x', 'x-', 'z', 'z-', - argstr="--shiftdir=%s", requires=['shift_in_file'], + 'y-', + 'y', + 'x', + 'x-', + 'z', + 'z-', + argstr="--shiftdir=%s", + requires=['shift_in_file'], desc='Indicates the direction that the distortions from ' - '--shiftmap goes. It depends on the direction and ' - 'polarity of the phase-encoding in the EPI sequence.') + '--shiftmap goes. It depends on the direction and ' + 'polarity of the phase-encoding in the EPI sequence.') cons_jacobian = traits.Bool( - False, argstr='--constrainj', + False, + argstr='--constrainj', desc='Constrain the Jacobian of the warpfield to lie within specified ' - 'min/max limits.') + 'min/max limits.') - jacobian_min = traits.Float(argstr='--jmin=%f', - desc='Minimum acceptable Jacobian value for ' - 'constraint (default 0.01)') - jacobian_max = traits.Float(argstr='--jmax=%f', - desc='Maximum acceptable Jacobian value for ' - 'constraint (default 100.0)') + jacobian_min = traits.Float( + argstr='--jmin=%f', + desc='Minimum acceptable Jacobian value for ' + 'constraint (default 0.01)') + jacobian_max = traits.Float( + argstr='--jmax=%f', + desc='Maximum acceptable Jacobian value for ' + 'constraint (default 100.0)') abswarp = traits.Bool( - argstr='--abs', xor=['relwarp'], + argstr='--abs', + xor=['relwarp'], desc='If set it indicates that the warps in --warp1 and --warp2 should' - ' be interpreted as absolute. I.e. the values in --warp1/2 are ' - 'the coordinates in the next space, rather than displacements. ' - 'This flag is ignored if --warp1/2 was created by fnirt, which ' - 'always creates relative displacements.') + ' be interpreted as absolute. I.e. the values in --warp1/2 are ' + 'the coordinates in the next space, rather than displacements. ' + 'This flag is ignored if --warp1/2 was created by fnirt, which ' + 'always creates relative displacements.') relwarp = traits.Bool( - argstr='--rel', xor=['abswarp'], + argstr='--rel', + xor=['abswarp'], desc='If set it indicates that the warps in --warp1/2 should be ' - 'interpreted as relative. I.e. the values in --warp1/2 are ' - 'displacements from the coordinates in the next space.') + 'interpreted as relative. I.e. the values in --warp1/2 are ' + 'displacements from the coordinates in the next space.') out_abswarp = traits.Bool( - argstr='--absout', xor=['out_relwarp'], + argstr='--absout', + xor=['out_relwarp'], desc='If set it indicates that the warps in --out should be absolute, ' - 'i.e. the values in --out are displacements from the coordinates ' - 'in --ref.') + 'i.e. the values in --out are displacements from the coordinates ' + 'in --ref.') out_relwarp = traits.Bool( - argstr='--relout', xor=['out_abswarp'], + argstr='--relout', + xor=['out_abswarp'], desc='If set it indicates that the warps in --out should be relative, ' - 'i.e. the values in --out are displacements from the coordinates ' - 'in --ref.') + 'i.e. the values in --out are displacements from the coordinates ' + 'in --ref.') class ConvertWarpOutputSpec(TraitedSpec): out_file = File( exists=True, desc='Name of output file, containing the warp as field or ' - 'coefficients.') + 'coefficients.') class ConvertWarp(FSLCommand): @@ -1893,34 +2253,55 @@ class ConvertWarp(FSLCommand): class WarpPointsBaseInputSpec(CommandLineInputSpec): - in_coords = File(exists=True, position=-1, argstr='%s', mandatory=True, - desc='filename of file containing coordinates') - xfm_file = File(exists=True, argstr='-xfm %s', xor=['warp_file'], - desc='filename of affine transform (e.g. source2dest.mat)') - warp_file = File(exists=True, argstr='-warp %s', xor=['xfm_file'], - desc='filename of warpfield (e.g. ' - 'intermediate2dest_warp.nii.gz)') - coord_vox = traits.Bool(True, argstr='-vox', xor=['coord_mm'], - desc='all coordinates in voxels - default') - coord_mm = traits.Bool(False, argstr='-mm', xor=['coord_vox'], - desc='all coordinates in mm') - out_file = File(name_source='in_coords', - name_template='%s_warped', output_name='out_file', - desc='output file name') + in_coords = File( + exists=True, + position=-1, + argstr='%s', + mandatory=True, + desc='filename of file containing coordinates') + xfm_file = File( + exists=True, + argstr='-xfm %s', + xor=['warp_file'], + desc='filename of affine transform (e.g. source2dest.mat)') + warp_file = File( + exists=True, + argstr='-warp %s', + xor=['xfm_file'], + desc='filename of warpfield (e.g. ' + 'intermediate2dest_warp.nii.gz)') + coord_vox = traits.Bool( + True, + argstr='-vox', + xor=['coord_mm'], + desc='all coordinates in voxels - default') + coord_mm = traits.Bool( + False, argstr='-mm', xor=['coord_vox'], desc='all coordinates in mm') + out_file = File( + name_source='in_coords', + name_template='%s_warped', + output_name='out_file', + desc='output file name') class WarpPointsInputSpec(WarpPointsBaseInputSpec): - src_file = File(exists=True, argstr='-src %s', mandatory=True, - desc='filename of source image') - dest_file = File(exists=True, argstr='-dest %s', mandatory=True, - desc='filename of destination image') + src_file = File( + exists=True, + argstr='-src %s', + mandatory=True, + desc='filename of source image') + dest_file = File( + exists=True, + argstr='-dest %s', + mandatory=True, + desc='filename of destination image') class WarpPointsOutputSpec(TraitedSpec): out_file = File( exists=True, desc='Name of output file, containing the warp as field or ' - 'coefficients.') + 'coefficients.') class WarpPoints(CommandLine): @@ -1969,8 +2350,8 @@ def _parse_inputs(self, skip=None): fname, ext = op.splitext(self.inputs.in_coords) setattr(self, '_in_file', fname) setattr(self, '_outformat', ext[1:]) - first_args = super(WarpPoints, self)._parse_inputs( - skip=['in_coords', 'out_file']) + first_args = super(WarpPoints, + self)._parse_inputs(skip=['in_coords', 'out_file']) second_args = fname + '.txt' @@ -2072,13 +2453,21 @@ def _run_interface(self, runtime): class WarpPointsToStdInputSpec(WarpPointsBaseInputSpec): - img_file = File(exists=True, argstr='-img %s', mandatory=True, - desc=('filename of input image')) - std_file = File(exists=True, argstr='-std %s', mandatory=True, - desc=('filename of destination image')) - premat_file = File(exists=True, argstr='-premat %s', - desc=('filename of pre-warp affine transform ' - '(e.g. example_func2highres.mat)')) + img_file = File( + exists=True, + argstr='-img %s', + mandatory=True, + desc=('filename of input image')) + std_file = File( + exists=True, + argstr='-std %s', + mandatory=True, + desc=('filename of destination image')) + premat_file = File( + exists=True, + argstr='-premat %s', + desc=('filename of pre-warp affine transform ' + '(e.g. example_func2highres.mat)')) class WarpPointsToStd(WarpPoints): @@ -2114,21 +2503,40 @@ class WarpPointsToStd(WarpPoints): class WarpPointsFromStdInputSpec(CommandLineInputSpec): - img_file = File(exists=True, argstr='-img %s', mandatory=True, - desc='filename of a destination image') - std_file = File(exists=True, argstr='-std %s', mandatory=True, - desc='filename of the image in standard space') - in_coords = File(exists=True, position=-2, argstr='%s', mandatory=True, - desc='filename of file containing coordinates') - xfm_file = File(exists=True, argstr='-xfm %s', xor=['warp_file'], - desc='filename of affine transform (e.g. source2dest.mat)') - warp_file = File(exists=True, argstr='-warp %s', xor=['xfm_file'], - desc='filename of warpfield (e.g. ' - 'intermediate2dest_warp.nii.gz)') - coord_vox = traits.Bool(True, argstr='-vox', xor=['coord_mm'], - desc='all coordinates in voxels - default') - coord_mm = traits.Bool(False, argstr='-mm', xor=['coord_vox'], - desc='all coordinates in mm') + img_file = File( + exists=True, + argstr='-img %s', + mandatory=True, + desc='filename of a destination image') + std_file = File( + exists=True, + argstr='-std %s', + mandatory=True, + desc='filename of the image in standard space') + in_coords = File( + exists=True, + position=-2, + argstr='%s', + mandatory=True, + desc='filename of file containing coordinates') + xfm_file = File( + exists=True, + argstr='-xfm %s', + xor=['warp_file'], + desc='filename of affine transform (e.g. source2dest.mat)') + warp_file = File( + exists=True, + argstr='-warp %s', + xor=['xfm_file'], + desc='filename of warpfield (e.g. ' + 'intermediate2dest_warp.nii.gz)') + coord_vox = traits.Bool( + True, + argstr='-vox', + xor=['coord_mm'], + desc='all coordinates in voxels - default') + coord_mm = traits.Bool( + False, argstr='-mm', xor=['coord_vox'], desc='all coordinates in mm') class WarpPointsFromStd(CommandLine): @@ -2167,39 +2575,52 @@ def _list_outputs(self): class MotionOutliersInputSpec(FSLCommandInputSpec): in_file = File( - exists=True, mandatory=True, desc="unfiltered 4D image", + exists=True, + mandatory=True, + desc="unfiltered 4D image", argstr="-i %s") - out_file = File(argstr="-o %s", name_source='in_file', - name_template='%s_outliers.txt', - keep_extension=True, desc='output outlier file name', - hash_files=False) + out_file = File( + argstr="-o %s", + name_source='in_file', + name_template='%s_outliers.txt', + keep_extension=True, + desc='output outlier file name', + hash_files=False) mask = File( exists=True, argstr="-m %s", desc="mask image for calculating metric") metric = traits.Enum( - 'refrms', ['refrms', 'dvars', 'refmse', 'fd', 'fdrms'], argstr="--%s", + 'refrms', ['refrms', 'dvars', 'refmse', 'fd', 'fdrms'], + argstr="--%s", desc='metrics: refrms - RMS intensity difference to reference volume ' - 'as metric [default metric], refmse - Mean Square Error version ' - 'of refrms (used in original version of fsl_motion_outliers), ' - 'dvars - DVARS, fd - frame displacement, fdrms - FD with RMS ' - 'matrix calculation') - threshold = traits.Float(argstr="--thresh=%g", - desc=("specify absolute threshold value " - "(otherwise use box-plot cutoff = P75 + " - "1.5*IQR)")) + 'as metric [default metric], refmse - Mean Square Error version ' + 'of refrms (used in original version of fsl_motion_outliers), ' + 'dvars - DVARS, fd - frame displacement, fdrms - FD with RMS ' + 'matrix calculation') + threshold = traits.Float( + argstr="--thresh=%g", + desc=("specify absolute threshold value " + "(otherwise use box-plot cutoff = P75 + " + "1.5*IQR)")) no_motion_correction = traits.Bool( argstr="--nomoco", desc="do not run motion correction (assumed already done)") dummy = traits.Int( argstr="--dummy=%d", desc='number of dummy scans to delete (before running anything and ' - 'creating EVs)') + 'creating EVs)') out_metric_values = File( - argstr="-s %s", name_source='in_file', name_template='%s_metrics.txt', + argstr="-s %s", + name_source='in_file', + name_template='%s_metrics.txt', keep_extension=True, - desc='output metric values (DVARS etc.) file name', hash_files=False) + desc='output metric values (DVARS etc.) file name', + hash_files=False) out_metric_plot = File( - argstr="-p %s", name_source='in_file', name_template='%s_metrics.png', - hash_files=False, keep_extension=True, + argstr="-p %s", + name_source='in_file', + name_template='%s_metrics.png', + hash_files=False, + keep_extension=True, desc='output metric values plot (DVARS etc.) file name') diff --git a/nipype/interfaces/io.py b/nipype/interfaces/io.py index 0793b955bd..fc36170369 100644 --- a/nipype/interfaces/io.py +++ b/nipype/interfaces/io.py @@ -18,7 +18,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object, zip, filter, range, open, str import glob @@ -37,9 +38,9 @@ from .. import config, logging from ..utils.filemanip import copyfile, list_to_filename, filename_to_list from ..utils.misc import human_order_sorted, str2bool -from .base import ( - TraitedSpec, traits, Str, File, Directory, BaseInterface, InputMultiPath, - isdefined, OutputMultiPath, DynamicTraitedSpec, Undefined, BaseInterfaceInputSpec) +from .base import (TraitedSpec, traits, Str, File, Directory, BaseInterface, + InputMultiPath, isdefined, OutputMultiPath, + DynamicTraitedSpec, Undefined, BaseInterfaceInputSpec) from .bids_utils import BIDSDataGrabber try: @@ -60,6 +61,7 @@ iflogger = logging.getLogger('interface') + def copytree(src, dst, use_hardlink=False): """Recursively copy a directory tree using nipype.utils.filemanip.copyfile() @@ -84,8 +86,12 @@ def copytree(src, dst, use_hardlink=False): if os.path.isdir(srcname): copytree(srcname, dstname, use_hardlink) else: - copyfile(srcname, dstname, True, hashmethod='content', - use_hardlink=use_hardlink) + copyfile( + srcname, + dstname, + True, + hashmethod='content', + use_hardlink=use_hardlink) except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can @@ -115,7 +121,6 @@ def add_traits(base, names, trait_type=None): class IOBase(BaseInterface): - def _run_interface(self, runtime): return runtime @@ -181,30 +186,31 @@ class DataSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): desc='Path to the base directory for storing data.') container = Str( desc='Folder within base directory in which to store output') - parameterization = traits.Bool(True, usedefault=True, - desc='store output in parametrized structure') + parameterization = traits.Bool( + True, usedefault=True, desc='store output in parametrized structure') strip_dir = Directory(desc='path to strip out of filename') - substitutions = InputMultiPath(traits.Tuple(Str, Str), - desc=('List of 2-tuples reflecting string ' - 'to substitute and string to replace ' - 'it with')) + substitutions = InputMultiPath( + traits.Tuple(Str, Str), + desc=('List of 2-tuples reflecting string ' + 'to substitute and string to replace ' + 'it with')) regexp_substitutions = \ InputMultiPath(traits.Tuple(Str, Str), - desc=('List of 2-tuples reflecting a pair of a '\ - 'Python regexp pattern and a replacement '\ + desc=('List of 2-tuples reflecting a pair of a ' + 'Python regexp pattern and a replacement ' 'string. Invoked after string `substitutions`')) _outputs = traits.Dict(Str, value={}, usedefault=True) - remove_dest_dir = traits.Bool(False, usedefault=True, - desc='remove dest directory when copying dirs') + remove_dest_dir = traits.Bool( + False, usedefault=True, desc='remove dest directory when copying dirs') # AWS S3 data attributes - creds_path = Str(desc='Filepath to AWS credentials file for S3 bucket '\ - 'access; if not specified, the credentials will '\ - 'be taken from the AWS_ACCESS_KEY_ID and '\ - 'AWS_SECRET_ACCESS_KEY environment variables') - encrypt_bucket_keys = traits.Bool(desc='Flag indicating whether to use S3 '\ - 'server-side AES-256 encryption') + creds_path = Str(desc='Filepath to AWS credentials file for S3 bucket ' + 'access; if not specified, the credentials will ' + 'be taken from the AWS_ACCESS_KEY_ID and ' + 'AWS_SECRET_ACCESS_KEY environment variables') + encrypt_bucket_keys = traits.Bool(desc='Flag indicating whether to use S3 ' + 'server-side AES-256 encryption') # Set this if user wishes to override the bucket with their own bucket = traits.Any(desc='Boto3 S3 bucket for manual override of bucket') # Set this if user wishes to have local copy of files as well @@ -329,8 +335,10 @@ def _get_dst(self, src): dst = path if isdefined(self.inputs.strip_dir): dst = dst.replace(self.inputs.strip_dir, '') - folders = [folder for folder in dst.split(os.path.sep) if - folder.startswith('_')] + folders = [ + folder for folder in dst.split(os.path.sep) + if folder.startswith('_') + ] dst = os.path.sep.join(folders) if fname: dst = os.path.join(dst, fname) @@ -457,8 +465,11 @@ def _return_aws_keys(self): raise Exception(err_msg) # Strip any carriage return/line feeds - aws_access_key_id = aws_access_key_id.replace('\r', '').replace('\n', '') - aws_secret_access_key = aws_secret_access_key.replace('\r', '').replace('\n', '') + aws_access_key_id = aws_access_key_id.replace('\r', '').replace( + '\n', '') + aws_secret_access_key = aws_secret_access_key.replace('\r', + '').replace( + '\n', '') else: aws_access_key_id = os.getenv('AWS_ACCESS_KEY_ID') aws_secret_access_key = os.getenv('AWS_SECRET_ACCESS_KEY') @@ -519,8 +530,9 @@ def _fetch_bucket(self, bucket_name): # Use individual session for each instance of DataSink # Better when datasinks are being used in multi-threading, see: # http://boto3.readthedocs.org/en/latest/guide/resources.html#multithreading - session = boto3.session.Session(aws_access_key_id=aws_access_key_id, - aws_secret_access_key=aws_secret_access_key) + session = boto3.session.Session( + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key) s3_resource = session.resource('s3', use_ssl=True) # Otherwise, connect anonymously @@ -528,8 +540,8 @@ def _fetch_bucket(self, bucket_name): iflogger.info('Connecting to AWS: %s anonymously...', bucket_name) session = boto3.session.Session() s3_resource = session.resource('s3', use_ssl=True) - s3_resource.meta.client.meta.events.register('choose-signer.s3.*', - botocore.handlers.disable_signing) + s3_resource.meta.client.meta.events.register( + 'choose-signer.s3.*', botocore.handlers.disable_signing) # Explicitly declare a secure SSL connection for bucket object bucket = s3_resource.Bucket(bucket_name) @@ -588,8 +600,10 @@ def _upload_to_s3(self, bucket, src, dst): for root, dirs, files in os.walk(src): src_files.extend([os.path.join(root, fil) for fil in files]) # Make the dst files have the dst folder as base dir - dst_files = [os.path.join(dst, src_f.split(src)[1]) \ - for src_f in src_files] + dst_files = [ + os.path.join(dst, + src_f.split(src)[1]) for src_f in src_files + ] else: src_files = [src] dst_files = [dst] @@ -610,7 +624,8 @@ def _upload_to_s3(self, bucket, src, dst): src_md5 = hashlib.md5(src_read).hexdigest() # Move to next loop iteration if dst_md5 == src_md5: - iflogger.info('File %s already exists on S3, skipping...', dst_f) + iflogger.info('File %s already exists on S3, skipping...', + dst_f) continue else: iflogger.info('Overwriting previous S3 file...') @@ -622,11 +637,14 @@ def _upload_to_s3(self, bucket, src, dst): iflogger.info('Uploading %s to S3 bucket, %s, as %s...', src_f, bucket.name, dst_f) if self.inputs.encrypt_bucket_keys: - extra_args = {'ServerSideEncryption' : 'AES256'} + extra_args = {'ServerSideEncryption': 'AES256'} else: extra_args = {} - bucket.upload_file(src_f, dst_k, ExtraArgs=extra_args, - Callback=ProgressPercentage(src_f)) + bucket.upload_file( + src_f, + dst_k, + ExtraArgs=extra_args, + Callback=ProgressPercentage(src_f)) # List outputs, main run routine def _list_outputs(self): @@ -638,7 +656,8 @@ def _list_outputs(self): outputs = self.output_spec().get() out_files = [] # Use hardlink - use_hardlink = str2bool(config.get('execution', 'try_hard_link_datasink')) + use_hardlink = str2bool( + config.get('execution', 'try_hard_link_datasink')) # Set local output directory if specified if isdefined(self.inputs.local_copy): @@ -665,12 +684,14 @@ def _list_outputs(self): except Exception as exc: s3dir = '' if not isdefined(self.inputs.local_copy): - local_out_exception = os.path.join(os.path.expanduser('~'), - 's3_datasink_' + bucket_name) + local_out_exception = os.path.join( + os.path.expanduser('~'), + 's3_datasink_' + bucket_name) outdir = local_out_exception # Log local copying directory - iflogger.info('Access to S3 failed! Storing outputs locally at: '\ - '%s\nError: %s', outdir, exc) + iflogger.info( + 'Access to S3 failed! Storing outputs locally at: ' + '%s\nError: %s', outdir, exc) else: s3dir = '' @@ -690,7 +711,7 @@ def _list_outputs(self): if 'File exists' in inst.strerror: pass else: - raise(inst) + raise (inst) # Iterate through outputs attributes {key : path(s)} for key, files in list(self.inputs._outputs.items()): @@ -741,12 +762,16 @@ def _list_outputs(self): if 'File exists' in inst.strerror: pass else: - raise(inst) + raise (inst) # If src is a file, copy it to dst if os.path.isfile(src): iflogger.debug('copyfile: %s %s', src, dst) - copyfile(src, dst, copy=True, hashmethod='content', - use_hardlink=use_hardlink) + copyfile( + src, + dst, + copy=True, + hashmethod='content', + use_hardlink=use_hardlink) out_files.append(dst) # If src is a directory, copy entire contents to dst dir elif os.path.isdir(src): @@ -764,28 +789,39 @@ def _list_outputs(self): class S3DataGrabberInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - anon = traits.Bool(False, usedefault=True, - desc='Use anonymous connection to s3. If this is set to True, boto may print' + - ' a urlopen error, but this does not prevent data from being downloaded.') - region = Str('us-east-1', usedefault=True, - desc='Region of s3 bucket') - bucket = Str(mandatory=True, - desc='Amazon S3 bucket where your data is stored') - bucket_path = Str('', usedefault=True, - desc='Location within your bucket for subject data.') - local_directory = Directory(exists=True, - desc='Path to the local directory for subject data to be downloaded ' - 'and accessed. Should be on HDFS for Spark jobs.') - raise_on_empty = traits.Bool(True, usedefault=True, - desc='Generate exception if list is empty for a given field') - sort_filelist = traits.Bool(mandatory=True, - desc='Sort the filelist that matches the template') - template = Str(mandatory=True, - desc='Layout used to get files. Relative to bucket_path if defined.' - 'Uses regex rather than glob style formatting.') - template_args = traits.Dict(key_trait=Str, - value_trait=traits.List(traits.List), - desc='Information to plug into template') + anon = traits.Bool( + False, + usedefault=True, + desc= + 'Use anonymous connection to s3. If this is set to True, boto may print' + + + ' a urlopen error, but this does not prevent data from being downloaded.' + ) + region = Str('us-east-1', usedefault=True, desc='Region of s3 bucket') + bucket = Str( + mandatory=True, desc='Amazon S3 bucket where your data is stored') + bucket_path = Str( + '', + usedefault=True, + desc='Location within your bucket for subject data.') + local_directory = Directory( + exists=True, + desc='Path to the local directory for subject data to be downloaded ' + 'and accessed. Should be on HDFS for Spark jobs.') + raise_on_empty = traits.Bool( + True, + usedefault=True, + desc='Generate exception if list is empty for a given field') + sort_filelist = traits.Bool( + mandatory=True, desc='Sort the filelist that matches the template') + template = Str( + mandatory=True, + desc='Layout used to get files. Relative to bucket_path if defined.' + 'Uses regex rather than glob style formatting.') + template_args = traits.Dict( + key_trait=Str, + value_trait=traits.List(traits.List), + desc='Information to plug into template') class S3DataGrabber(IOBase): @@ -831,8 +867,9 @@ def __init__(self, infields=None, outfields=None, **kwargs): undefined_traits[key] = Undefined # add ability to insert field specific templates self.inputs.add_trait('field_template', - traits.Dict(traits.Enum(outfields), - desc="arguments that fit into template")) + traits.Dict( + traits.Enum(outfields), + desc="arguments that fit into template")) undefined_traits['field_template'] = Undefined if not isdefined(self.inputs.template_args): self.inputs.template_args = {} @@ -869,7 +906,8 @@ def _list_outputs(self): # get list of all files in s3 bucket conn = boto.connect_s3(anon=self.inputs.anon) bkt = conn.get_bucket(self.inputs.bucket) - bkt_files = list(k.key for k in bkt.list(prefix=self.inputs.bucket_path)) + bkt_files = list( + k.key for k in bkt.list(prefix=self.inputs.bucket_path)) # keys are outfields, args are template args for the outfield for key, args in list(self.inputs.template_args.items()): @@ -878,7 +916,8 @@ def _list_outputs(self): if hasattr(self.inputs, 'field_template') and \ isdefined(self.inputs.field_template) and \ key in self.inputs.field_template: - template = self.inputs.field_template[key] # template override for multiple outfields + template = self.inputs.field_template[ + key] # template override for multiple outfields if isdefined(self.inputs.bucket_path): template = os.path.join(self.inputs.bucket_path, template) if not args: @@ -900,18 +939,22 @@ def _list_outputs(self): for argnum, arglist in enumerate(args): maxlen = 1 for arg in arglist: - if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): + if isinstance(arg, + (str, bytes)) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): - raise ValueError('incompatible number of arguments for %s' % key) + raise ValueError( + 'incompatible number of arguments for %s' % + key) if len(arg) > maxlen: maxlen = len(arg) outfiles = [] for i in range(maxlen): argtuple = [] for arg in arglist: - if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): + if isinstance(arg, (str, bytes)) and hasattr( + self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): argtuple.append(arg[i]) @@ -922,13 +965,17 @@ def _list_outputs(self): try: filledtemplate = template % tuple(argtuple) except TypeError as e: - raise TypeError(e.message + ": Template %s failed to convert with args %s" % (template, str(tuple(argtuple)))) + raise TypeError( + e.message + + ": Template %s failed to convert with args %s" + % (template, str(tuple(argtuple)))) outfiles = [] for fname in bkt_files: if re.match(filledtemplate, fname): outfiles.append(fname) if len(outfiles) == 0: - msg = 'Output key: %s Template: %s returned no files' % (key, filledtemplate) + msg = 'Output key: %s Template: %s returned no files' % ( + key, filledtemplate) if self.inputs.raise_on_empty: raise IOError(msg) else: @@ -947,13 +994,13 @@ def _list_outputs(self): # Outputs are currently stored as locations on S3. # We must convert to the local location specified # and download the files. - for key,val in outputs.items(): + for key, val in outputs.items(): # This will basically be either list-like or string-like: # if it's an instance of a list, we'll iterate through it. # If it isn't, it's string-like (string, unicode), we # convert that value directly. if isinstance(val, (list, tuple, set)): - for i,path in enumerate(val): + for i, path in enumerate(val): outputs[key][i] = self.s3tolocal(path, bkt) else: outputs[key] = self.s3tolocal(val, bkt) @@ -971,7 +1018,8 @@ def s3tolocal(self, s3path, bkt): if self.inputs.template[0] == '/': self.inputs.template = self.inputs.template[1:] - localpath = s3path.replace(self.inputs.bucket_path, self.inputs.local_directory) + localpath = s3path.replace(self.inputs.bucket_path, + self.inputs.local_directory) localdir = os.path.split(localpath)[0] if not os.path.exists(localdir): os.makedirs(localdir) @@ -982,17 +1030,22 @@ def s3tolocal(self, s3path, bkt): class DataGrabberInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - base_directory = Directory(exists=True, - desc='Path to the base directory consisting of subject data.') - raise_on_empty = traits.Bool(True, usedefault=True, - desc='Generate exception if list is empty for a given field') - sort_filelist = traits.Bool(mandatory=True, - desc='Sort the filelist that matches the template') - template = Str(mandatory=True, - desc='Layout used to get files. relative to base directory if defined') - template_args = traits.Dict(key_trait=Str, - value_trait=traits.List(traits.List), - desc='Information to plug into template') + base_directory = Directory( + exists=True, + desc='Path to the base directory consisting of subject data.') + raise_on_empty = traits.Bool( + True, + usedefault=True, + desc='Generate exception if list is empty for a given field') + sort_filelist = traits.Bool( + mandatory=True, desc='Sort the filelist that matches the template') + template = Str( + mandatory=True, + desc='Layout used to get files. relative to base directory if defined') + template_args = traits.Dict( + key_trait=Str, + value_trait=traits.List(traits.List), + desc='Information to plug into template') class DataGrabber(IOBase): @@ -1076,8 +1129,9 @@ def __init__(self, infields=None, outfields=None, **kwargs): undefined_traits[key] = Undefined # add ability to insert field specific templates self.inputs.add_trait('field_template', - traits.Dict(traits.Enum(outfields), - desc="arguments that fit into template")) + traits.Dict( + traits.Enum(outfields), + desc="arguments that fit into template")) undefined_traits['field_template'] = Undefined if not isdefined(self.inputs.template_args): self.inputs.template_args = {} @@ -1138,18 +1192,22 @@ def _list_outputs(self): for argnum, arglist in enumerate(args): maxlen = 1 for arg in arglist: - if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): + if isinstance(arg, + (str, bytes)) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): - raise ValueError('incompatible number of arguments for %s' % key) + raise ValueError( + 'incompatible number of arguments for %s' % + key) if len(arg) > maxlen: maxlen = len(arg) outfiles = [] for i in range(maxlen): argtuple = [] for arg in arglist: - if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): + if isinstance(arg, (str, bytes)) and hasattr( + self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): argtuple.append(arg[i]) @@ -1160,10 +1218,14 @@ def _list_outputs(self): try: filledtemplate = template % tuple(argtuple) except TypeError as e: - raise TypeError(e.message + ": Template %s failed to convert with args %s" % (template, str(tuple(argtuple)))) + raise TypeError( + e.message + + ": Template %s failed to convert with args %s" + % (template, str(tuple(argtuple)))) outfiles = glob.glob(filledtemplate) if len(outfiles) == 0: - msg = 'Output key: %s Template: %s returned no files' % (key, filledtemplate) + msg = 'Output key: %s Template: %s returned no files' % ( + key, filledtemplate) if self.inputs.raise_on_empty: raise IOError(msg) else: @@ -1184,21 +1246,28 @@ def _list_outputs(self): class SelectFilesInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - base_directory = Directory(exists=True, - desc="Root path common to templates.") - sort_filelist = traits.Bool(True, usedefault=True, - desc="When matching mutliple files, return them" - " in sorted order.") - raise_on_empty = traits.Bool(True, usedefault=True, - desc="Raise an exception if a template pattern " - "matches no files.") - force_lists = traits.Either(traits.Bool(), traits.List(Str()), - default=False, usedefault=True, - desc=("Whether to return outputs as a list even" - " when only one file matches the template. " - "Either a boolean that applies to all output " - "fields or a list of output field names to " - "coerce to a list")) + base_directory = Directory( + exists=True, desc="Root path common to templates.") + sort_filelist = traits.Bool( + True, + usedefault=True, + desc="When matching mutliple files, return them" + " in sorted order.") + raise_on_empty = traits.Bool( + True, + usedefault=True, + desc="Raise an exception if a template pattern " + "matches no files.") + force_lists = traits.Either( + traits.Bool(), + traits.List(Str()), + default=False, + usedefault=True, + desc=("Whether to return outputs as a list even" + " when only one file matches the template. " + "Either a boolean that applies to all output " + "fields or a list of output field names to " + "coerce to a list")) class SelectFiles(IOBase): @@ -1302,8 +1371,8 @@ def _list_outputs(self): # Build the full template path if isdefined(self.inputs.base_directory): - template = op.abspath(op.join( - self.inputs.base_directory, template)) + template = op.abspath( + op.join(self.inputs.base_directory, template)) else: template = op.abspath(template) @@ -1338,24 +1407,25 @@ def _list_outputs(self): class DataFinderInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - root_paths = traits.Either(traits.List(), - Str(), - mandatory=True,) - match_regex = Str('(.+)', - usedefault=True, - desc=("Regular expression for matching " - "paths.")) - ignore_regexes = traits.List(desc=("List of regular expressions, " - "if any match the path it will be " - "ignored.") - ) + root_paths = traits.Either( + traits.List(), + Str(), + mandatory=True, + ) + match_regex = Str( + '(.+)', + usedefault=True, + desc=("Regular expression for matching paths.")) + ignore_regexes = traits.List( + desc=("List of regular expressions, " + "if any match the path it will be " + "ignored.")) max_depth = traits.Int(desc="The maximum depth to search beneath " "the root_paths") min_depth = traits.Int(desc="The minimum depth to search beneath " "the root paths") - unpack_single = traits.Bool(False, - usedefault=True, - desc="Unpack single results from list") + unpack_single = traits.Bool( + False, usedefault=True, desc="Unpack single results from list") class DataFinder(IOBase): @@ -1436,7 +1506,8 @@ def _run_interface(self, runtime): self.result = None for root_path in self.inputs.root_paths: # Handle tilda/env variables and remove extra seperators - root_path = os.path.normpath(os.path.expandvars(os.path.expanduser(root_path))) + root_path = os.path.normpath( + os.path.expandvars(os.path.expanduser(root_path))) # Check if the root_path is a file if os.path.isfile(root_path): if min_depth == 0: @@ -1445,8 +1516,7 @@ def _run_interface(self, runtime): # Walk through directory structure checking paths for curr_dir, sub_dirs, files in os.walk(root_path): # Determine the current depth from the root_path - curr_depth = (curr_dir.count(os.sep) - - root_path.count(os.sep)) + curr_depth = (curr_dir.count(os.sep) - root_path.count(os.sep)) # If the max path depth has been reached, clear sub_dirs # and files if max_depth is not None and curr_depth >= max_depth: @@ -1459,8 +1529,7 @@ def _run_interface(self, runtime): for infile in files: full_path = os.path.join(curr_dir, infile) self._match_path(full_path) - if (self.inputs.unpack_single and - len(self.result['out_paths']) == 1): + if (self.inputs.unpack_single and len(self.result['out_paths']) == 1): for key, vals in list(self.result.items()): self.result[key] = vals[0] else: @@ -1468,10 +1537,11 @@ def _run_interface(self, runtime): for key in list(self.result.keys()): if key == "out_paths": continue - sort_tuples = human_order_sorted(list(zip(self.result["out_paths"], - self.result[key]))) + sort_tuples = human_order_sorted( + list(zip(self.result["out_paths"], self.result[key]))) self.result[key] = [x for (_, x) in sort_tuples] - self.result["out_paths"] = human_order_sorted(self.result["out_paths"]) + self.result["out_paths"] = human_order_sorted( + self.result["out_paths"]) if not self.result: raise RuntimeError("Regular expression did not match any files!") @@ -1485,19 +1555,24 @@ def _list_outputs(self): class FSSourceInputSpec(BaseInterfaceInputSpec): - subjects_dir = Directory(mandatory=True, - desc='Freesurfer subjects directory.') - subject_id = Str(mandatory=True, - desc='Subject name for whom to retrieve data') - hemi = traits.Enum('both', 'lh', 'rh', usedefault=True, - desc='Selects hemisphere specific outputs') + subjects_dir = Directory( + mandatory=True, desc='Freesurfer subjects directory.') + subject_id = Str( + mandatory=True, desc='Subject name for whom to retrieve data') + hemi = traits.Enum( + 'both', + 'lh', + 'rh', + usedefault=True, + desc='Selects hemisphere specific outputs') class FSSourceOutputSpec(TraitedSpec): T1 = File( exists=True, desc='Intensity normalized whole-head volume', loc='mri') aseg = File( - exists=True, loc='mri', + exists=True, + loc='mri', desc='Volumetric map of regions from automatic segmentation') brain = File( exists=True, desc='Intensity normalized brain-only volume', loc='mri') @@ -1506,87 +1581,126 @@ class FSSourceOutputSpec(TraitedSpec): filled = File(exists=True, desc='Subcortical mass volume', loc='mri') norm = File( exists=True, desc='Normalized skull-stripped volume', loc='mri') - nu = File(exists=True, - desc='Non-uniformity corrected whole-head volume', loc='mri') - orig = File(exists=True, desc='Base image conformed to Freesurfer space', - loc='mri') - rawavg = File(exists=True, desc='Volume formed by averaging input images', - loc='mri') + nu = File( + exists=True, + desc='Non-uniformity corrected whole-head volume', + loc='mri') + orig = File( + exists=True, + desc='Base image conformed to Freesurfer space', + loc='mri') + rawavg = File( + exists=True, desc='Volume formed by averaging input images', loc='mri') ribbon = OutputMultiPath( - File(exists=True), desc='Volumetric maps of cortical ribbons', - loc='mri', altkey='*ribbon') + File(exists=True), + desc='Volumetric maps of cortical ribbons', + loc='mri', + altkey='*ribbon') wm = File(exists=True, desc='Segmented white-matter volume', loc='mri') wmparc = File( - exists=True, loc='mri', + exists=True, + loc='mri', desc='Aparc parcellation projected into subcortical white matter') - curv = OutputMultiPath(File(exists=True), desc='Maps of surface curvature', - loc='surf') + curv = OutputMultiPath( + File(exists=True), desc='Maps of surface curvature', loc='surf') avg_curv = OutputMultiPath( - File(exists=True), desc='Average atlas curvature, sampled to subject', + File(exists=True), + desc='Average atlas curvature, sampled to subject', loc='surf') inflated = OutputMultiPath( - File(exists=True), desc='Inflated surface meshes', - loc='surf') + File(exists=True), desc='Inflated surface meshes', loc='surf') pial = OutputMultiPath( - File(exists=True), desc='Gray matter/pia mater surface meshes', + File(exists=True), + desc='Gray matter/pia mater surface meshes', loc='surf') area_pial = OutputMultiPath( File(exists=True), desc='Mean area of triangles each vertex on the pial surface is ' 'associated with', - loc='surf', altkey='area.pial') + loc='surf', + altkey='area.pial') curv_pial = OutputMultiPath( - File(exists=True), desc='Curvature of pial surface', - loc='surf', altkey='curv.pial') - smoothwm = OutputMultiPath(File(exists=True), loc='surf', - desc='Smoothed original surface meshes') + File(exists=True), + desc='Curvature of pial surface', + loc='surf', + altkey='curv.pial') + smoothwm = OutputMultiPath( + File(exists=True), loc='surf', desc='Smoothed original surface meshes') sphere = OutputMultiPath( - File(exists=True), desc='Spherical surface meshes', - loc='surf') + File(exists=True), desc='Spherical surface meshes', loc='surf') sulc = OutputMultiPath( File(exists=True), desc='Surface maps of sulcal depth', loc='surf') - thickness = OutputMultiPath(File(exists=True), loc='surf', - desc='Surface maps of cortical thickness') + thickness = OutputMultiPath( + File(exists=True), + loc='surf', + desc='Surface maps of cortical thickness') volume = OutputMultiPath( File(exists=True), desc='Surface maps of cortical volume', loc='surf') white = OutputMultiPath( - File(exists=True), desc='White/gray matter surface meshes', - loc='surf') + File(exists=True), desc='White/gray matter surface meshes', loc='surf') jacobian_white = OutputMultiPath( File(exists=True), desc='Distortion required to register to spherical atlas', loc='surf') graymid = OutputMultiPath( - File(exists=True), desc='Graymid/midthickness surface meshes', - loc='surf', altkey=['graymid', 'midthickness']) + File(exists=True), + desc='Graymid/midthickness surface meshes', + loc='surf', + altkey=['graymid', 'midthickness']) label = OutputMultiPath( - File(exists=True), desc='Volume and surface label files', - loc='label', altkey='*label') - annot = OutputMultiPath(File(exists=True), desc='Surface annotation files', - loc='label', altkey='*annot') + File(exists=True), + desc='Volume and surface label files', + loc='label', + altkey='*label') + annot = OutputMultiPath( + File(exists=True), + desc='Surface annotation files', + loc='label', + altkey='*annot') aparc_aseg = OutputMultiPath( - File(exists=True), loc='mri', altkey='aparc*aseg', + File(exists=True), + loc='mri', + altkey='aparc*aseg', desc='Aparc parcellation projected into aseg volume') sphere_reg = OutputMultiPath( - File(exists=True), loc='surf', altkey='sphere.reg', + File(exists=True), + loc='surf', + altkey='sphere.reg', desc='Spherical registration file') - aseg_stats = OutputMultiPath(File(exists=True), loc='stats', altkey='aseg', - desc='Automated segmentation statistics file') + aseg_stats = OutputMultiPath( + File(exists=True), + loc='stats', + altkey='aseg', + desc='Automated segmentation statistics file') wmparc_stats = OutputMultiPath( - File(exists=True), loc='stats', altkey='wmparc', + File(exists=True), + loc='stats', + altkey='wmparc', desc='White matter parcellation statistics file') aparc_stats = OutputMultiPath( - File(exists=True), loc='stats', altkey='aparc', + File(exists=True), + loc='stats', + altkey='aparc', desc='Aparc parcellation statistics files') - BA_stats = OutputMultiPath(File(exists=True), loc='stats', altkey='BA', - desc='Brodmann Area statistics files') + BA_stats = OutputMultiPath( + File(exists=True), + loc='stats', + altkey='BA', + desc='Brodmann Area statistics files') aparc_a2009s_stats = OutputMultiPath( - File(exists=True), loc='stats', altkey='aparc.a2009s', + File(exists=True), + loc='stats', + altkey='aparc.a2009s', desc='Aparc a2009s parcellation statistics files') - curv_stats = OutputMultiPath(File(exists=True), loc='stats', altkey='curv', - desc='Curvature statistics files') + curv_stats = OutputMultiPath( + File(exists=True), + loc='stats', + altkey='curv', + desc='Curvature statistics files') entorhinal_exvivo_stats = OutputMultiPath( - File(exists=True), loc='stats', altkey='entorhinal_exvivo', + File(exists=True), + loc='stats', + altkey='entorhinal_exvivo', desc='Entorhinal exvivo statistics files') @@ -1631,11 +1745,12 @@ def _get_files(self, path, key, dirval, altkey=None): else: globprefix = '*' keys = filename_to_list(altkey) if altkey else [key] - globfmt = os.path.join(path, dirval, - ''.join((globprefix, '{}', globsuffix))) - return [os.path.abspath(f) - for key in keys - for f in glob.glob(globfmt.format(key))] + globfmt = os.path.join(path, dirval, ''.join((globprefix, '{}', + globsuffix))) + return [ + os.path.abspath(f) for key in keys + for f in glob.glob(globfmt.format(key)) + ] def _list_outputs(self): subjects_dir = self.inputs.subjects_dir @@ -1656,21 +1771,16 @@ class XNATSourceInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): query_template = Str( mandatory=True, desc=('Layout used to get files. Relative to base ' - 'directory if defined') - ) + 'directory if defined')) query_template_args = traits.Dict( Str, traits.List(traits.List), - value=dict(outfiles=[]), usedefault=True, - desc='Information to plug into template' - ) + value=dict(outfiles=[]), + usedefault=True, + desc='Information to plug into template') - server = Str( - mandatory=True, - requires=['user', 'pwd'], - xor=['config'] - ) + server = Str(mandatory=True, requires=['user', 'pwd'], xor=['config']) user = Str() pwd = traits.Password() @@ -1741,9 +1851,9 @@ def __init__(self, infields=None, outfields=None, **kwargs): # add ability to insert field specific templates self.inputs.add_trait( 'field_template', - traits.Dict(traits.Enum(outfields), - desc="arguments that fit into query_template") - ) + traits.Dict( + traits.Enum(outfields), + desc="arguments that fit into query_template")) undefined_traits['field_template'] = Undefined # self.inputs.remove_trait('query_template_args') outdict = {} @@ -1769,11 +1879,8 @@ def _list_outputs(self): if self.inputs.config: xnat = pyxnat.Interface(config=self.inputs.config) else: - xnat = pyxnat.Interface(self.inputs.server, - self.inputs.user, - self.inputs.pwd, - cache_dir - ) + xnat = pyxnat.Interface(self.inputs.server, self.inputs.user, + self.inputs.pwd, cache_dir) if self._infields: for key in self._infields: @@ -1781,8 +1888,7 @@ def _list_outputs(self): if not isdefined(value): msg = ("%s requires a value for input '%s' " "because it was listed in 'infields'" % - (self.__class__.__name__, key) - ) + (self.__class__.__name__, key)) raise ValueError(msg) outputs = {} @@ -1796,24 +1902,21 @@ def _list_outputs(self): if not args: file_objects = xnat.select(template).get('obj') if file_objects == []: - raise IOError('Template %s returned no files' - % template - ) - outputs[key] = list_to_filename( - [str(file_object.get()) - for file_object in file_objects - if file_object.exists() - ]) + raise IOError('Template %s returned no files' % template) + outputs[key] = list_to_filename([ + str(file_object.get()) for file_object in file_objects + if file_object.exists() + ]) for argnum, arglist in enumerate(args): maxlen = 1 for arg in arglist: - if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): + if isinstance(arg, + (str, bytes)) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): raise ValueError('incompatible number ' - 'of arguments for %s' % key - ) + 'of arguments for %s' % key) if len(arg) > maxlen: maxlen = len(arg) outfiles = [] @@ -1833,29 +1936,25 @@ def _list_outputs(self): if file_objects == []: raise IOError('Template %s ' - 'returned no files' % target - ) - - outfiles = list_to_filename( - [str(file_object.get()) - for file_object in file_objects - if file_object.exists() - ] - ) + 'returned no files' % target) + + outfiles = list_to_filename([ + str(file_object.get()) + for file_object in file_objects + if file_object.exists() + ]) else: file_objects = xnat.select(template).get('obj') if file_objects == []: raise IOError('Template %s ' - 'returned no files' % template - ) + 'returned no files' % template) - outfiles = list_to_filename( - [str(file_object.get()) - for file_object in file_objects - if file_object.exists() - ] - ) + outfiles = list_to_filename([ + str(file_object.get()) + for file_object in file_objects + if file_object.exists() + ]) outputs[key].insert(i, outfiles) if len(outputs[key]) == 0: @@ -1869,10 +1968,7 @@ class XNATSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): _outputs = traits.Dict(Str, value={}, usedefault=True) - server = Str(mandatory=True, - requires=['user', 'pwd'], - xor=['config'] - ) + server = Str(mandatory=True, requires=['user', 'pwd'], xor=['config']) user = Str() pwd = traits.Password() @@ -1882,30 +1978,26 @@ class XNATSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): project_id = Str( desc='Project in which to store the outputs', mandatory=True) - subject_id = Str( - desc='Set to subject id', mandatory=True) + subject_id = Str(desc='Set to subject id', mandatory=True) - experiment_id = Str( - desc='Set to workflow name', mandatory=True) + experiment_id = Str(desc='Set to workflow name', mandatory=True) assessor_id = Str( desc=('Option to customize ouputs representation in XNAT - ' 'assessor level will be used with specified id'), - xor=['reconstruction_id'] - ) + xor=['reconstruction_id']) reconstruction_id = Str( desc=('Option to customize ouputs representation in XNAT - ' 'reconstruction level will be used with specified id'), - xor=['assessor_id'] - ) + xor=['assessor_id']) - share = traits.Bool(False, - desc=('Option to share the subjects from the original project' - 'instead of creating new ones when possible - the created ' - 'experiments are then shared back to the original project' - ), - usedefault=True) + share = traits.Bool( + False, + desc=('Option to share the subjects from the original project' + 'instead of creating new ones when possible - the created ' + 'experiments are then shared back to the original project'), + usedefault=True) def __setattr__(self, key, value): if key not in self.copyable_trait_names(): @@ -1931,29 +2023,23 @@ def _list_outputs(self): if self.inputs.config: xnat = pyxnat.Interface(config=self.inputs.config) else: - xnat = pyxnat.Interface(self.inputs.server, - self.inputs.user, - self.inputs.pwd, - cache_dir - ) + xnat = pyxnat.Interface(self.inputs.server, self.inputs.user, + self.inputs.pwd, cache_dir) # if possible share the subject from the original project if self.inputs.share: subject_id = self.inputs.subject_id result = xnat.select( 'xnat:subjectData', - ['xnat:subjectData/PROJECT', - 'xnat:subjectData/SUBJECT_ID'] - ).where('xnat:subjectData/SUBJECT_ID = %s AND' % subject_id) + ['xnat:subjectData/PROJECT', 'xnat:subjectData/SUBJECT_ID' + ]).where('xnat:subjectData/SUBJECT_ID = %s AND' % subject_id) # subject containing raw data exists on the server if (result.data and isinstance(result.data[0], dict)): result = result.data[0] shared = xnat.select('/project/%s/subject/%s' % (self.inputs.project_id, - self.inputs.subject_id - ) - ) + self.inputs.subject_id)) if not shared.exists(): # subject not in share project @@ -1964,8 +2050,7 @@ def _list_outputs(self): share_project.insert() subject = xnat.select('/project/%(project)s' - '/subject/%(subject_id)s' % result - ) + '/subject/%(subject_id)s' % result) subject.share(str(self.inputs.project_id)) @@ -1979,9 +2064,11 @@ def _list_outputs(self): uri_template_args['original_project'] = result['project'] if self.inputs.assessor_id: - uri_template_args['assessor_id'] = quote_id(self.inputs.assessor_id) + uri_template_args['assessor_id'] = quote_id( + self.inputs.assessor_id) elif self.inputs.reconstruction_id: - uri_template_args['reconstruction_id'] = quote_id(self.inputs.reconstruction_id) + uri_template_args['reconstruction_id'] = quote_id( + self.inputs.reconstruction_id) # gather outputs and upload them for key, files in list(self.inputs._outputs.items()): @@ -1990,10 +2077,8 @@ def _list_outputs(self): if isinstance(name, list): for i, file_name in enumerate(name): - push_file(self, xnat, file_name, - '%s_' % i + key, - uri_template_args - ) + push_file(self, xnat, file_name, '%s_' % i + key, + uri_template_args) else: push_file(self, xnat, name, key, uri_template_args) @@ -2009,11 +2094,11 @@ def unquote_id(string): def push_file(self, xnat, file_name, out_key, uri_template_args): # grab info from output file names - val_list = [unquote_id(val) - for part in os.path.split(file_name)[0].split(os.sep) - for val in part.split('_')[1:] - if part.startswith('_') and len(part.split('_')) % 2 - ] + val_list = [ + unquote_id(val) for part in os.path.split(file_name)[0].split(os.sep) + for val in part.split('_')[1:] + if part.startswith('_') and len(part.split('_')) % 2 + ] keymap = dict(list(zip(val_list[1::2], val_list[2::2]))) @@ -2034,22 +2119,18 @@ def push_file(self, xnat, file_name, out_key, uri_template_args): uri_template_args['container_type'] = 'reconstruction' uri_template_args['container_id'] = unquote_id( - uri_template_args['experiment_id'] - ) + uri_template_args['experiment_id']) if _label: uri_template_args['container_id'] += ( - '_results_%s' % '_'.join(_label) - ) + '_results_%s' % '_'.join(_label)) else: uri_template_args['container_id'] += '_results' # define resource level - uri_template_args['resource_label'] = ( - '%s_%s' % (uri_template_args['container_id'], - out_key.split('.')[0] - ) - ) + uri_template_args['resource_label'] = ('%s_%s' % + (uri_template_args['container_id'], + out_key.split('.')[0])) # define file level uri_template_args['file_name'] = os.path.split( @@ -2058,8 +2139,7 @@ def push_file(self, xnat, file_name, out_key, uri_template_args): uri_template = ( '/project/%(project_id)s/subject/%(subject_id)s' '/experiment/%(experiment_id)s/%(container_type)s/%(container_id)s' - '/out/resource/%(resource_label)s/file/%(file_name)s' - ) + '/out/resource/%(resource_label)s/file/%(file_name)s') # unquote values before uploading for key in list(uri_template_args.keys()): @@ -2067,21 +2147,18 @@ def push_file(self, xnat, file_name, out_key, uri_template_args): # upload file remote_file = xnat.select(uri_template % uri_template_args) - remote_file.insert(file_name, - experiments='xnat:imageSessionData', - use_label=True - ) + remote_file.insert( + file_name, experiments='xnat:imageSessionData', use_label=True) # shares the experiment back to the original project if relevant if 'original_project' in uri_template_args: experiment_template = ( '/project/%(original_project)s' - '/subject/%(subject_id)s/experiment/%(experiment_id)s' - ) + '/subject/%(subject_id)s/experiment/%(experiment_id)s') - xnat.select(experiment_template % uri_template_args - ).share(uri_template_args['original_project']) + xnat.select(experiment_template % uri_template_args).share( + uri_template_args['original_project']) def capture_provenance(): @@ -2128,8 +2205,8 @@ def __init__(self, input_names, **inputs): def _list_outputs(self): """Execute this module. """ - conn = sqlite3.connect(self.inputs.database_file, - check_same_thread=False) + conn = sqlite3.connect( + self.inputs.database_file, check_same_thread=False) c = conn.cursor() c.execute("INSERT OR REPLACE INTO %s (" % self.inputs.table_name + ",".join(self._input_names) + ") VALUES (" + @@ -2141,11 +2218,16 @@ def _list_outputs(self): class MySQLSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - host = Str('localhost', mandatory=True, - requires=['username', 'password'], - xor=['config'], usedefault=True) - config = File(mandatory=True, xor=['host'], - desc="MySQL Options File (same format as my.cnf)") + host = Str( + 'localhost', + mandatory=True, + requires=['username', 'password'], + xor=['config'], + usedefault=True) + config = File( + mandatory=True, + xor=['host'], + desc="MySQL Options File (same format as my.cnf)") database_name = Str( mandatory=True, desc='Otherwise known as the schema name') table_name = Str(mandatory=True) @@ -2183,13 +2265,15 @@ def _list_outputs(self): """ import MySQLdb if isdefined(self.inputs.config): - conn = MySQLdb.connect(db=self.inputs.database_name, - read_default_file=self.inputs.config) + conn = MySQLdb.connect( + db=self.inputs.database_name, + read_default_file=self.inputs.config) else: - conn = MySQLdb.connect(host=self.inputs.host, - user=self.inputs.username, - passwd=self.inputs.password, - db=self.inputs.database_name) + conn = MySQLdb.connect( + host=self.inputs.host, + user=self.inputs.username, + passwd=self.inputs.password, + db=self.inputs.database_name) c = conn.cursor() c.execute("REPLACE INTO %s (" % self.inputs.table_name + ",".join(self._input_names) + ") VALUES (" + @@ -2204,14 +2288,21 @@ class SSHDataGrabberInputSpec(DataGrabberInputSpec): hostname = Str(mandatory=True, desc='Server hostname.') username = Str(desc='Server username.') password = traits.Password(desc='Server password.') - download_files = traits.Bool(True, usedefault=True, - desc='If false it will return the file names without downloading them') - base_directory = Str(mandatory=True, - desc='Path to the base directory consisting of subject data.') - template_expression = traits.Enum(['fnmatch', 'regexp'], usedefault=True, - desc='Use either fnmatch or regexp to express templates') - ssh_log_to_file = Str('', usedefault=True, - desc='If set SSH commands will be logged to the given file') + download_files = traits.Bool( + True, + usedefault=True, + desc='If false it will return the file names without downloading them') + base_directory = Str( + mandatory=True, + desc='Path to the base directory consisting of subject data.') + template_expression = traits.Enum( + ['fnmatch', 'regexp'], + usedefault=True, + desc='Use either fnmatch or regexp to express templates') + ssh_log_to_file = Str( + '', + usedefault=True, + desc='If set SSH commands will be logged to the given file') class SSHDataGrabber(DataGrabber): @@ -2295,38 +2386,28 @@ def __init__(self, infields=None, outfields=None, **kwargs): try: paramiko except NameError: - warn( - "The library paramiko needs to be installed" - " for this module to run." - ) + warn("The library paramiko needs to be installed" + " for this module to run.") if not outfields: outfields = ['outfiles'] kwargs = kwargs.copy() kwargs['infields'] = infields kwargs['outfields'] = outfields super(SSHDataGrabber, self).__init__(**kwargs) - if ( - None in (self.inputs.username, self.inputs.password) - ): - raise ValueError( - "either both username and password " - "are provided or none of them" - ) - - if ( - self.inputs.template_expression == 'regexp' and - self.inputs.template[-1] != '$' - ): + if (None in (self.inputs.username, self.inputs.password)): + raise ValueError("either both username and password " + "are provided or none of them") + + if (self.inputs.template_expression == 'regexp' + and self.inputs.template[-1] != '$'): self.inputs.template += '$' def _list_outputs(self): try: paramiko except NameError: - raise ImportError( - "The library paramiko needs to be installed" - " for this module to run." - ) + raise ImportError("The library paramiko needs to be installed" + " for this module to run.") if len(self.inputs.ssh_log_to_file) > 0: paramiko.util.log_to_file(self.inputs.ssh_log_to_file) @@ -2377,18 +2458,22 @@ def _list_outputs(self): for argnum, arglist in enumerate(args): maxlen = 1 for arg in arglist: - if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): + if isinstance(arg, + (str, bytes)) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): - raise ValueError('incompatible number of arguments for %s' % key) + raise ValueError( + 'incompatible number of arguments for %s' % + key) if len(arg) > maxlen: maxlen = len(arg) outfiles = [] for i in range(maxlen): argtuple = [] for arg in arglist: - if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): + if isinstance(arg, (str, bytes)) and hasattr( + self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): argtuple.append(arg[i]) @@ -2399,7 +2484,10 @@ def _list_outputs(self): try: filledtemplate = template % tuple(argtuple) except TypeError as e: - raise TypeError(e.message + ": Template %s failed to convert with args %s" % (template, str(tuple(argtuple)))) + raise TypeError( + e.message + + ": Template %s failed to convert with args %s" + % (template, str(tuple(argtuple)))) client = self._get_ssh_client() sftp = client.open_sftp() sftp.chdir(self.inputs.base_directory) @@ -2407,14 +2495,16 @@ def _list_outputs(self): filledtemplate_base = os.path.basename(filledtemplate) filelist = sftp.listdir(filledtemplate_dir) if self.inputs.template_expression == 'fnmatch': - outfiles = fnmatch.filter(filelist, filledtemplate_base) + outfiles = fnmatch.filter(filelist, + filledtemplate_base) elif self.inputs.template_expression == 'regexp': regexp = re.compile(filledtemplate_base) outfiles = list(filter(regexp.match, filelist)) else: raise ValueError('template_expression value invalid') if len(outfiles) == 0: - msg = 'Output key: %s Template: %s returned no files' % (key, filledtemplate) + msg = 'Output key: %s Template: %s returned no files' % ( + key, filledtemplate) if self.inputs.raise_on_empty: raise IOError(msg) else: @@ -2427,9 +2517,11 @@ def _list_outputs(self): if self.inputs.download_files: for f in outfiles: try: - sftp.get(os.path.join(filledtemplate_dir, f), f) + sftp.get( + os.path.join(filledtemplate_dir, f), f) except IOError: - iflogger.info('remote file %s not found', f) + iflogger.info('remote file %s not found', + f) if any([val is None for val in outputs[key]]): outputs[key] = [] if len(outputs[key]) == 0: @@ -2448,10 +2540,10 @@ def _get_ssh_client(self): host = config.lookup(self.inputs.hostname) if 'proxycommand' in host: proxy = paramiko.ProxyCommand( - subprocess.check_output( - [os.environ['SHELL'], '-c', 'echo %s' % host['proxycommand']] - ).strip() - ) + subprocess.check_output([ + os.environ['SHELL'], '-c', + 'echo %s' % host['proxycommand'] + ]).strip()) else: proxy = None client = paramiko.SSHClient() @@ -2463,12 +2555,12 @@ def _get_ssh_client(self): class JSONFileGrabberInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): in_file = File(exists=True, desc='JSON source file') - defaults = traits.Dict(desc=('JSON dictionary that sets default output' - 'values, overridden by values found in in_file')) + defaults = traits.Dict( + desc=('JSON dictionary that sets default output' + 'values, overridden by values found in in_file')) class JSONFileGrabber(IOBase): - """ Datagrabber interface that loads a json file and generates an output for every first-level object @@ -2529,8 +2621,8 @@ def _list_outputs(self): class JSONFileSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): out_file = File(desc='JSON sink file') - in_dict = traits.Dict(value={}, usedefault=True, - desc='input JSON dictionary') + in_dict = traits.Dict( + value={}, usedefault=True, desc='input JSON dictionary') _outputs = traits.Dict(value={}, usedefault=True) def __setattr__(self, key, value): @@ -2549,7 +2641,6 @@ class JSONFileSinkOutputSpec(TraitedSpec): class JSONFileSink(IOBase): - """ Very simple frontend for storing values into a JSON file. Entries already existing in in_dict will be overridden by matching diff --git a/nipype/interfaces/matlab.py b/nipype/interfaces/matlab.py index 0d8aa29e16..fed7bfeb57 100644 --- a/nipype/interfaces/matlab.py +++ b/nipype/interfaces/matlab.py @@ -2,7 +2,8 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ General matlab interface code """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -21,51 +22,67 @@ def get_matlab_command(): matlab_cmd = 'matlab' try: - res = CommandLine(command='which', args=matlab_cmd, - resource_monitor=False, - terminal_output='allatonce').run() + res = CommandLine( + command='which', + args=matlab_cmd, + resource_monitor=False, + terminal_output='allatonce').run() matlab_path = res.runtime.stdout.strip() - except Exception as e: + except Exception: return None return matlab_cmd + no_matlab = get_matlab_command() is None class MatlabInputSpec(CommandLineInputSpec): """ Basic expected inputs to Matlab interface """ - script = traits.Str(argstr='-r \"%s;exit\"', desc='m-code to run', - mandatory=True, position=-1) - uses_mcr = traits.Bool(desc='use MCR interface', - xor=['nodesktop', 'nosplash', - 'single_comp_thread'], - nohash=True) - nodesktop = traits.Bool(True, argstr='-nodesktop', - usedefault=True, - desc='Switch off desktop mode on unix platforms', - nohash=True) - nosplash = traits.Bool(True, argstr='-nosplash', usedefault=True, - desc='Switch of splash screen', - nohash=True) - logfile = File(argstr='-logfile %s', - desc='Save matlab output to log') - single_comp_thread = traits.Bool(argstr="-singleCompThread", - desc="force single threaded operation", - nohash=True) + script = traits.Str( + argstr='-r \"%s;exit\"', + desc='m-code to run', + mandatory=True, + position=-1) + uses_mcr = traits.Bool( + desc='use MCR interface', + xor=['nodesktop', 'nosplash', 'single_comp_thread'], + nohash=True) + nodesktop = traits.Bool( + True, + argstr='-nodesktop', + usedefault=True, + desc='Switch off desktop mode on unix platforms', + nohash=True) + nosplash = traits.Bool( + True, + argstr='-nosplash', + usedefault=True, + desc='Switch of splash screen', + nohash=True) + logfile = File(argstr='-logfile %s', desc='Save matlab output to log') + single_comp_thread = traits.Bool( + argstr="-singleCompThread", + desc="force single threaded operation", + nohash=True) # non-commandline options - mfile = traits.Bool(True, desc='Run m-code using m-file', - usedefault=True) - script_file = File('pyscript.m', usedefault=True, - desc='Name of file to write m-code to') + mfile = traits.Bool(True, desc='Run m-code using m-file', usedefault=True) + script_file = File( + 'pyscript.m', usedefault=True, desc='Name of file to write m-code to') paths = InputMultiPath(Directory(), desc='Paths to add to matlabpath') - prescript = traits.List(["ver,", "try,"], usedefault=True, - desc='prescript to be added before code') - postscript = traits.List(["\n,catch ME,", - "fprintf(2,'MATLAB code threw an exception:\\n');", - "fprintf(2,'%s\\n',ME.message);", - "if length(ME.stack) ~= 0, fprintf(2,'File:%s\\nName:%s\\nLine:%d\\n',ME.stack.file,ME.stack.name,ME.stack.line);, end;", - "end;"], desc='script added after code', usedefault=True) + prescript = traits.List( + ["ver,", "try,"], + usedefault=True, + desc='prescript to be added before code') + postscript = traits.List( + [ + "\n,catch ME,", "fprintf(2,'MATLAB code threw an exception:\\n');", + "fprintf(2,'%s\\n',ME.message);", + "if length(ME.stack) ~= 0, fprintf(2,'File:%s\\nName:%s\\nLine:%d\\n',ME.stack.file,ME.stack.name,ME.stack.line);, end;", + "end;" + ], + desc='script added after code', + usedefault=True) class MatlabCommand(CommandLine): @@ -174,24 +191,34 @@ def _gen_matlab_command(self, argstr, script_lines): # prescript takes different default value depending on the mfile argument if mfile: - prescript.insert(0, "fprintf(1,'Executing %s at %s:\\n',mfilename(),datestr(now));") + prescript.insert( + 0, + "fprintf(1,'Executing %s at %s:\\n',mfilename(),datestr(now));" + ) else: - prescript.insert(0, "fprintf(1,'Executing code at %s:\\n',datestr(now));") + prescript.insert( + 0, "fprintf(1,'Executing code at %s:\\n',datestr(now));") for path in paths: prescript.append("addpath('%s');\n" % path) if not mfile: # clean up the code of comments and replace newlines with commas - script_lines = ','.join([line for line in script_lines.split("\n") if not line.strip().startswith("%")]) + script_lines = ','.join([ + line for line in script_lines.split("\n") + if not line.strip().startswith("%") + ]) - script_lines = '\n'.join(prescript) + script_lines + '\n'.join(postscript) + script_lines = '\n'.join(prescript) + script_lines + '\n'.join( + postscript) if mfile: - with open(os.path.join(cwd, self.inputs.script_file), 'wt') as mfile: + with open(os.path.join(cwd, self.inputs.script_file), + 'wt') as mfile: mfile.write(script_lines) if self.inputs.uses_mcr: script = '%s' % (os.path.join(cwd, self.inputs.script_file)) else: - script = "addpath('%s');%s" % (cwd, self.inputs.script_file.split('.')[0]) + script = "addpath('%s');%s" % ( + cwd, self.inputs.script_file.split('.')[0]) else: script = ''.join(script_lines.split('\n')) return argstr % script diff --git a/nipype/interfaces/meshfix.py b/nipype/interfaces/meshfix.py index 466190468a..52f9e4f0bc 100644 --- a/nipype/interfaces/meshfix.py +++ b/nipype/interfaces/meshfix.py @@ -10,68 +10,143 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op from ..utils.filemanip import split_filename -from .base import (CommandLine, CommandLineInputSpec, - traits, TraitedSpec, isdefined, File) +from .base import (CommandLine, CommandLineInputSpec, traits, TraitedSpec, + isdefined, File) class MeshFixInputSpec(CommandLineInputSpec): - number_of_biggest_shells = traits.Int(argstr='--shells %d', desc="Only the N biggest shells are kept") + number_of_biggest_shells = traits.Int( + argstr='--shells %d', desc="Only the N biggest shells are kept") - epsilon_angle = traits.Range(argstr='-a %f', low=0.0, high=2.0, desc="Epsilon angle in degrees (must be between 0 and 2)") + epsilon_angle = traits.Range( + argstr='-a %f', + low=0.0, + high=2.0, + desc="Epsilon angle in degrees (must be between 0 and 2)") - join_overlapping_largest_components = traits.Bool(argstr='-j', xor=['join_closest_components'], desc='Join 2 biggest components if they overlap, remove the rest.') + join_overlapping_largest_components = traits.Bool( + argstr='-j', + xor=['join_closest_components'], + desc='Join 2 biggest components if they overlap, remove the rest.') - join_closest_components = traits.Bool(argstr='-jc', xor=['join_closest_components'], desc='Join the closest pair of components.') + join_closest_components = traits.Bool( + argstr='-jc', + xor=['join_closest_components'], + desc='Join the closest pair of components.') - quiet_mode = traits.Bool(argstr='-q', desc="Quiet mode, don't write much to stdout.") + quiet_mode = traits.Bool( + argstr='-q', desc="Quiet mode, don't write much to stdout.") dont_clean = traits.Bool(argstr='--no-clean', desc="Don't Clean") - save_as_stl = traits.Bool(xor=['save_as_vmrl', 'save_as_freesurfer_mesh'], argstr='--stl', desc="Result is saved in stereolithographic format (.stl)") - save_as_vmrl = traits.Bool(argstr='--wrl', xor=['save_as_stl', 'save_as_freesurfer_mesh'], desc="Result is saved in VRML1.0 format (.wrl)") - save_as_freesurfer_mesh = traits.Bool(argstr='--fsmesh', xor=['save_as_vrml', 'save_as_stl'], desc="Result is saved in freesurfer mesh format") - - remove_handles = traits.Bool(argstr='--remove-handles', desc="Remove handles") - - uniform_remeshing_steps = traits.Int(argstr='-u %d', requires=['uniform_remeshing_vertices'], desc="Number of steps for uniform remeshing of the whole mesh") - - uniform_remeshing_vertices = traits.Int(argstr='--vertices %d', requires=['uniform_remeshing_steps'], desc="Constrains the number of vertices." - "Must be used with uniform_remeshing_steps") - - laplacian_smoothing_steps = traits.Int(argstr='--smooth %d', desc="The number of laplacian smoothing steps to apply") - - x_shift = traits.Int(argstr='--smooth %d', desc="Shifts the coordinates of the vertices when saving. Output must be in FreeSurfer format") + save_as_stl = traits.Bool( + xor=['save_as_vmrl', 'save_as_freesurfer_mesh'], + argstr='--stl', + desc="Result is saved in stereolithographic format (.stl)") + save_as_vmrl = traits.Bool( + argstr='--wrl', + xor=['save_as_stl', 'save_as_freesurfer_mesh'], + desc="Result is saved in VRML1.0 format (.wrl)") + save_as_freesurfer_mesh = traits.Bool( + argstr='--fsmesh', + xor=['save_as_vrml', 'save_as_stl'], + desc="Result is saved in freesurfer mesh format") + + remove_handles = traits.Bool( + argstr='--remove-handles', desc="Remove handles") + + uniform_remeshing_steps = traits.Int( + argstr='-u %d', + requires=['uniform_remeshing_vertices'], + desc="Number of steps for uniform remeshing of the whole mesh") + + uniform_remeshing_vertices = traits.Int( + argstr='--vertices %d', + requires=['uniform_remeshing_steps'], + desc="Constrains the number of vertices." + "Must be used with uniform_remeshing_steps") + + laplacian_smoothing_steps = traits.Int( + argstr='--smooth %d', + desc="The number of laplacian smoothing steps to apply") + + x_shift = traits.Int( + argstr='--smooth %d', + desc= + "Shifts the coordinates of the vertices when saving. Output must be in FreeSurfer format" + ) # Cutting, decoupling, dilation - cut_outer = traits.Int(argstr='--cut-outer %d', desc="Remove triangles of 1st that are outside of the 2nd shell.") - cut_inner = traits.Int(argstr='--cut-inner %d', desc="Remove triangles of 1st that are inside of the 2nd shell. Dilate 2nd by N; Fill holes and keep only 1st afterwards.") - decouple_inin = traits.Int(argstr='--decouple-inin %d', desc="Treat 1st file as inner, 2nd file as outer component." - "Resolve overlaps by moving inners triangles inwards. Constrain the min distance between the components > d.") - decouple_outin = traits.Int(argstr='--decouple-outin %d', desc="Treat 1st file as outer, 2nd file as inner component." - "Resolve overlaps by moving outers triangles inwards. Constrain the min distance between the components > d.") - decouple_outout = traits.Int(argstr='--decouple-outout %d', desc="Treat 1st file as outer, 2nd file as inner component." - "Resolve overlaps by moving outers triangles outwards. Constrain the min distance between the components > d.") - - finetuning_inwards = traits.Bool(argstr='--fineTuneIn ', requires=['finetuning_distance', 'finetuning_substeps']) - finetuning_outwards = traits.Bool(argstr='--fineTuneIn ', requires=['finetuning_distance', 'finetuning_substeps'], xor=['finetuning_inwards'], - desc='Similar to finetuning_inwards, but ensures minimal distance in the other direction') - finetuning_distance = traits.Float(argstr='%f', requires=['finetuning_substeps'], desc="Used to fine-tune the minimal distance between surfaces." - "A minimal distance d is ensured, and reached in n substeps. When using the surfaces for subsequent volume meshing by gmsh, this step prevent too flat tetrahedra2)") - finetuning_substeps = traits.Int(argstr='%d', requires=['finetuning_distance'], desc="Used to fine-tune the minimal distance between surfaces." - "A minimal distance d is ensured, and reached in n substeps. When using the surfaces for subsequent volume meshing by gmsh, this step prevent too flat tetrahedra2)") - - dilation = traits.Int(argstr='--dilate %d', desc="Dilate the surface by d. d < 0 means shrinking.") - set_intersections_to_one = traits.Bool(argstr='--intersect', desc="If the mesh contains intersections, return value = 1." - "If saved in gmsh format, intersections will be highlighted.") + cut_outer = traits.Int( + argstr='--cut-outer %d', + desc="Remove triangles of 1st that are outside of the 2nd shell.") + cut_inner = traits.Int( + argstr='--cut-inner %d', + desc= + "Remove triangles of 1st that are inside of the 2nd shell. Dilate 2nd by N; Fill holes and keep only 1st afterwards." + ) + decouple_inin = traits.Int( + argstr='--decouple-inin %d', + desc="Treat 1st file as inner, 2nd file as outer component." + "Resolve overlaps by moving inners triangles inwards. Constrain the min distance between the components > d." + ) + decouple_outin = traits.Int( + argstr='--decouple-outin %d', + desc="Treat 1st file as outer, 2nd file as inner component." + "Resolve overlaps by moving outers triangles inwards. Constrain the min distance between the components > d." + ) + decouple_outout = traits.Int( + argstr='--decouple-outout %d', + desc="Treat 1st file as outer, 2nd file as inner component." + "Resolve overlaps by moving outers triangles outwards. Constrain the min distance between the components > d." + ) + + finetuning_inwards = traits.Bool( + argstr='--fineTuneIn ', + requires=['finetuning_distance', 'finetuning_substeps']) + finetuning_outwards = traits.Bool( + argstr='--fineTuneIn ', + requires=['finetuning_distance', 'finetuning_substeps'], + xor=['finetuning_inwards'], + desc= + 'Similar to finetuning_inwards, but ensures minimal distance in the other direction' + ) + finetuning_distance = traits.Float( + argstr='%f', + requires=['finetuning_substeps'], + desc="Used to fine-tune the minimal distance between surfaces." + "A minimal distance d is ensured, and reached in n substeps. When using the surfaces for subsequent volume meshing by gmsh, this step prevent too flat tetrahedra2)" + ) + finetuning_substeps = traits.Int( + argstr='%d', + requires=['finetuning_distance'], + desc="Used to fine-tune the minimal distance between surfaces." + "A minimal distance d is ensured, and reached in n substeps. When using the surfaces for subsequent volume meshing by gmsh, this step prevent too flat tetrahedra2)" + ) + + dilation = traits.Int( + argstr='--dilate %d', + desc="Dilate the surface by d. d < 0 means shrinking.") + set_intersections_to_one = traits.Bool( + argstr='--intersect', + desc="If the mesh contains intersections, return value = 1." + "If saved in gmsh format, intersections will be highlighted.") in_file1 = File(exists=True, argstr="%s", position=1, mandatory=True) in_file2 = File(exists=True, argstr="%s", position=2) - output_type = traits.Enum('off', ['stl', 'msh', 'wrl', 'vrml', 'fs', 'off'], usedefault=True, desc='The output type to save the file as.') - out_filename = File(genfile=True, argstr="-o %s", desc='The output filename for the fixed mesh file') + output_type = traits.Enum( + 'off', ['stl', 'msh', 'wrl', 'vrml', 'fs', 'off'], + usedefault=True, + desc='The output type to save the file as.') + out_filename = File( + genfile=True, + argstr="-o %s", + desc='The output filename for the fixed mesh file') class MeshFixOutputSpec(TraitedSpec): @@ -122,7 +197,8 @@ def _list_outputs(self): if any(ext == out_type.lower() for out_type in out_types): outputs['mesh_file'] = op.abspath(self.inputs.out_filename) else: - outputs['mesh_file'] = op.abspath(name + '.' + self.inputs.output_type) + outputs['mesh_file'] = op.abspath( + name + '.' + self.inputs.output_type) else: outputs['mesh_file'] = op.abspath(self._gen_outfilename()) return outputs diff --git a/nipype/interfaces/minc/__init__.py b/nipype/interfaces/minc/__init__.py index d3235c987d..1ebea58b64 100644 --- a/nipype/interfaces/minc/__init__.py +++ b/nipype/interfaces/minc/__init__.py @@ -2,42 +2,42 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The minc module provides classes for interfacing with the `MINC -`_ command line tools. This +`_ command line tools. This module was written to work with MINC version 2.2.00. Author: Carlo Hamalainen http://carlo-hamalainen.net """ - from .base import (Info) - -from .minc import (Average, - BBox, - Beast, - BestLinReg, - BigAverage, - Blob, - Blur, - Calc, - Convert, - Copy, - Dump, - Extract, - Gennlxfm, - Math, - NlpFit, - Norm, - Pik, - Resample, - Reshape, - ToEcat, - ToRaw, - Volcentre, - Voliso, - Volpad, - VolSymm, - XfmAvg, - XfmConcat, - XfmInvert, ) +from .minc import ( + Average, + BBox, + Beast, + BestLinReg, + BigAverage, + Blob, + Blur, + Calc, + Convert, + Copy, + Dump, + Extract, + Gennlxfm, + Math, + NlpFit, + Norm, + Pik, + Resample, + Reshape, + ToEcat, + ToRaw, + Volcentre, + Voliso, + Volpad, + VolSymm, + XfmAvg, + XfmConcat, + XfmInvert, +) diff --git a/nipype/interfaces/minc/base.py b/nipype/interfaces/minc/base.py index e4b8592adf..67b7938176 100644 --- a/nipype/interfaces/minc/base.py +++ b/nipype/interfaces/minc/base.py @@ -2,13 +2,14 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The minc module provides classes for interfacing with the `MINC -`_ command line tools. This -module was written to work with MINC version 2.2.00. +`_ command line tools. +This module was written to work with MINC version 2.2.00. Author: Carlo Hamalainen http://carlo-hamalainen.net """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object import os import os.path @@ -16,7 +17,6 @@ from ..base import CommandLine - warnings.filterwarnings('always', category=UserWarning) @@ -54,9 +54,10 @@ def version(): """ try: - clout = CommandLine(command='mincinfo', - args='-version', - terminal_output='allatonce').run() + clout = CommandLine( + command='mincinfo', + args='-version', + terminal_output='allatonce').run() except IOError: return None @@ -82,16 +83,20 @@ def read_hdf5_version(s): return s.split(':')[1].strip() return None - versions = {'minc': None, - 'libminc': None, - 'netcdf': None, - 'hdf5': None, } + versions = { + 'minc': None, + 'libminc': None, + 'netcdf': None, + 'hdf5': None, + } for l in out.split('\n'): - for (name, f) in [('minc', read_program_version), - ('libminc', read_libminc_version), - ('netcdf', read_netcdf_version), - ('hdf5', read_hdf5_version), ]: + for (name, f) in [ + ('minc', read_program_version), + ('libminc', read_libminc_version), + ('netcdf', read_netcdf_version), + ('hdf5', read_hdf5_version), + ]: if f(l) is not None: versions[name] = f(l) @@ -125,6 +130,10 @@ def aggregate_filename(files, new_suffix): path = os.getcwd() if common_prefix == '': - return os.path.abspath(os.path.join(path, os.path.splitext(files[0])[0] + '_' + new_suffix + '.mnc')) + return os.path.abspath( + os.path.join( + path, + os.path.splitext(files[0])[0] + '_' + new_suffix + '.mnc')) else: - return os.path.abspath(os.path.join(path, common_prefix + '_' + new_suffix + '.mnc')) + return os.path.abspath( + os.path.join(path, common_prefix + '_' + new_suffix + '.mnc')) diff --git a/nipype/interfaces/minc/minc.py b/nipype/interfaces/minc/minc.py index a6fc9f5902..a520768bde 100644 --- a/nipype/interfaces/minc/minc.py +++ b/nipype/interfaces/minc/minc.py @@ -16,7 +16,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import glob @@ -40,7 +41,8 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -50,10 +52,18 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): name_template='%s.raw', keep_extension=False) - _xor_write = ('write_ascii', 'write_ascii', 'write_byte', - 'write_short', 'write_int', 'write_long', - 'write_float', 'write_double', 'write_signed', - 'write_unsigned',) + _xor_write = ( + 'write_ascii', + 'write_ascii', + 'write_byte', + 'write_short', + 'write_int', + 'write_long', + 'write_float', + 'write_double', + 'write_signed', + 'write_unsigned', + ) write_ascii = traits.Bool( desc='Write out data as ascii strings (default).', @@ -61,9 +71,7 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): xor=_xor_write) write_byte = traits.Bool( - desc='Write out data as bytes.', - argstr='-byte', - xor=_xor_write) + desc='Write out data as bytes.', argstr='-byte', xor=_xor_write) write_short = traits.Bool( desc='Write out data as short integers.', @@ -76,9 +84,7 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): xor=_xor_write) write_long = traits.Bool( - desc='Superseded by write_int.', - argstr='-long', - xor=_xor_write) + desc='Superseded by write_int.', argstr='-long', xor=_xor_write) write_float = traits.Bool( desc='Write out data as single precision floating-point values.', @@ -93,20 +99,23 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): _xor_signed = ('write_signed', 'write_unsigned') write_signed = traits.Bool( - desc='Write out signed data.', - argstr='-signed', - xor=_xor_signed) + desc='Write out signed data.', argstr='-signed', xor=_xor_signed) write_unsigned = traits.Bool( - desc='Write out unsigned data.', - argstr='-unsigned', - xor=_xor_signed) + desc='Write out unsigned data.', argstr='-unsigned', xor=_xor_signed) write_range = traits.Tuple( - traits.Float, traits.Float, argstr='-range %s %s', - desc='Specify the range of output values\nDefault value: 1.79769e+308 1.79769e+308.',) + traits.Float, + traits.Float, + argstr='-range %s %s', + desc= + 'Specify the range of output values\nDefault value: 1.79769e+308 1.79769e+308.', + ) - _xor_normalize = ('normalize', 'nonormalize',) + _xor_normalize = ( + 'normalize', + 'nonormalize', + ) normalize = traits.Bool( desc='Normalize integer pixel values to file max and min.', @@ -119,7 +128,8 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): xor=_xor_normalize) image_range = traits.Tuple( - traits.Float, traits.Float, + traits.Float, + traits.Float, desc='Specify the range of real image values for normalization.', argstr='-image_range %s %s') @@ -137,20 +147,20 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): traits.Int, desc='Specifies corner of hyperslab (C conventions for indices).', sep=',', - argstr='-start %s',) + argstr='-start %s', + ) count = InputMultiPath( traits.Int, desc='Specifies edge lengths of hyperslab to read.', sep=',', - argstr='-count %s',) + argstr='-count %s', + ) # FIXME Can we make sure that len(start) == len(count)? - _xor_flip = ( - 'flip_positive_direction', - 'flip_negative_direction', - 'flip_any_direction') + _xor_flip = ('flip_positive_direction', 'flip_negative_direction', + 'flip_any_direction') flip_positive_direction = traits.Bool( desc='Flip images to always have positive direction.', @@ -242,7 +252,8 @@ class ToRawInputSpec(StdOutCommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -252,13 +263,11 @@ class ToRawInputSpec(StdOutCommandLineInputSpec): name_template='%s.raw', keep_extension=False) - _xor_write = ('write_byte', 'write_short', 'write_int', - 'write_long', 'write_float', 'write_double') + _xor_write = ('write_byte', 'write_short', 'write_int', 'write_long', + 'write_float', 'write_double') write_byte = traits.Bool( - desc='Write out data as bytes.', - argstr='-byte', - xor=_xor_write) + desc='Write out data as bytes.', argstr='-byte', xor=_xor_write) write_short = traits.Bool( desc='Write out data as short integers.', @@ -271,9 +280,7 @@ class ToRawInputSpec(StdOutCommandLineInputSpec): xor=_xor_write) write_long = traits.Bool( - desc='Superseded by write_int.', - argstr='-long', - xor=_xor_write) + desc='Superseded by write_int.', argstr='-long', xor=_xor_write) write_float = traits.Bool( desc='Write out data as single precision floating-point values.', @@ -288,21 +295,23 @@ class ToRawInputSpec(StdOutCommandLineInputSpec): _xor_signed = ('write_signed', 'write_unsigned') write_signed = traits.Bool( - desc='Write out signed data.', - argstr='-signed', - xor=_xor_signed) + desc='Write out signed data.', argstr='-signed', xor=_xor_signed) write_unsigned = traits.Bool( - desc='Write out unsigned data.', - argstr='-unsigned', - xor=_xor_signed) + desc='Write out unsigned data.', argstr='-unsigned', xor=_xor_signed) write_range = traits.Tuple( - traits.Float, traits.Float, argstr='-range %s %s', + traits.Float, + traits.Float, + argstr='-range %s %s', desc=('Specify the range of output values.' - 'Default value: 1.79769e+308 1.79769e+308.'),) + 'Default value: 1.79769e+308 1.79769e+308.'), + ) - _xor_normalize = ('normalize', 'nonormalize',) + _xor_normalize = ( + 'normalize', + 'nonormalize', + ) normalize = traits.Bool( desc='Normalize integer pixel values to file max and min.', @@ -347,7 +356,8 @@ class ConvertInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -366,8 +376,10 @@ class ConvertInputSpec(CommandLineInputSpec): two = traits.Bool(desc='Create a MINC 2 output file.', argstr='-2') template = traits.Bool( - desc=('Create a template file. The dimensions, variables, and' - 'attributes of the input file are preserved but all data it set to zero.'), + desc= + ('Create a template file. The dimensions, variables, and' + 'attributes of the input file are preserved but all data it set to zero.' + ), argstr='-template', ) @@ -388,7 +400,8 @@ class ConvertInputSpec(CommandLineInputSpec): chunk = traits.Range( low=0, - desc='Set the target block size for chunking (0 default, >1 block size).', + desc= + 'Set the target block size for chunking (0 default, >1 block size).', value=0, usedefault=False, argstr='-chunk %d', @@ -422,7 +435,8 @@ class CopyInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -473,7 +487,8 @@ class ToEcatInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -487,36 +502,44 @@ class ToEcatInputSpec(CommandLineInputSpec): ignore_patient_variable = traits.Bool( desc='Ignore informations from the minc patient variable.', - argstr='-ignore_patient_variable',) + argstr='-ignore_patient_variable', + ) ignore_study_variable = traits.Bool( desc='Ignore informations from the minc study variable.', - argstr='-ignore_study_variable',) + argstr='-ignore_study_variable', + ) ignore_acquisition_variable = traits.Bool( desc='Ignore informations from the minc acquisition variable.', - argstr='-ignore_acquisition_variable',) + argstr='-ignore_acquisition_variable', + ) ignore_ecat_acquisition_variable = traits.Bool( desc='Ignore informations from the minc ecat_acquisition variable.', - argstr='-ignore_ecat_acquisition_variable',) + argstr='-ignore_ecat_acquisition_variable', + ) ignore_ecat_main = traits.Bool( desc='Ignore informations from the minc ecat-main variable.', - argstr='-ignore_ecat_main',) + argstr='-ignore_ecat_main', + ) ignore_ecat_subheader_variable = traits.Bool( desc='Ignore informations from the minc ecat-subhdr variable.', - argstr='-ignore_ecat_subheader_variable',) + argstr='-ignore_ecat_subheader_variable', + ) no_decay_corr_fctr = traits.Bool( desc='Do not compute the decay correction factors', - argstr='-no_decay_corr_fctr',) + argstr='-no_decay_corr_fctr', + ) voxels_as_integers = traits.Bool( desc=('Voxel values are treated as integers, scale and' 'calibration factors are set to unity'), - argstr='-label',) + argstr='-label', + ) class ToEcatOutputSpec(TraitedSpec): @@ -552,7 +575,8 @@ class DumpInputSpec(StdOutCommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -562,7 +586,10 @@ class DumpInputSpec(StdOutCommandLineInputSpec): name_template='%s_dump.txt', keep_extension=False) - _xor_coords_or_header = ('coordinate_data', 'header_data',) + _xor_coords_or_header = ( + 'coordinate_data', + 'header_data', + ) coordinate_data = traits.Bool( desc='Coordinate variable data and header information.', @@ -574,7 +601,10 @@ class DumpInputSpec(StdOutCommandLineInputSpec): argstr='-h', xor=_xor_coords_or_header) - _xor_annotations = ('annotations_brief', 'annotations_full',) + _xor_annotations = ( + 'annotations_brief', + 'annotations_full', + ) annotations_brief = traits.Enum( 'c', @@ -611,7 +641,8 @@ class DumpInputSpec(StdOutCommandLineInputSpec): traits.Int(), traits.Tuple(traits.Int, traits.Int), desc='Display floating-point values with less precision', - argstr='%s',) # See _format_arg in Dump for actual formatting. + argstr='%s', + ) # See _format_arg in Dump for actual formatting. class DumpOutputSpec(TraitedSpec): @@ -643,8 +674,12 @@ def _format_arg(self, name, spec, value): if name == 'precision': if isinstance(value, int): return '-p %d' % value - elif isinstance(value, tuple) and isinstance(value[0], int) and isinstance(value[1], int): - return '-p %d,%d' % (value[0], value[1],) + elif isinstance(value, tuple) and isinstance( + value[0], int) and isinstance(value[1], int): + return '-p %d,%d' % ( + value[0], + value[1], + ) else: raise ValueError('Invalid precision argument: ' + str(value)) return super(Dump, self)._format_arg(name, spec, value) @@ -686,7 +721,10 @@ class AverageInputSpec(CommandLineInputSpec): usedefault=True, default_value=True) - _xor_verbose = ('verbose', 'quiet',) + _xor_verbose = ( + 'verbose', + 'quiet', + ) verbose = traits.Bool( desc='Print out log messages (default).', @@ -699,7 +737,10 @@ class AverageInputSpec(CommandLineInputSpec): debug = traits.Bool(desc='Print out debugging messages.', argstr='-debug') - _xor_check_dimensions = ('check_dimensions', 'no_check_dimensions',) + _xor_check_dimensions = ( + 'check_dimensions', + 'no_check_dimensions', + ) check_dimensions = traits.Bool( desc='Check that dimension info matches across files (default).', @@ -727,21 +768,13 @@ class AverageInputSpec(CommandLineInputSpec): argstr='-filetype', xor=_xor_format) format_byte = traits.Bool( - desc='Write out byte data.', - argstr='-byte', - xor=_xor_format) + desc='Write out byte data.', argstr='-byte', xor=_xor_format) format_short = traits.Bool( - desc='Write out short integer data.', - argstr='-short', - xor=_xor_format) + desc='Write out short integer data.', argstr='-short', xor=_xor_format) format_int = traits.Bool( - desc='Write out 32-bit integer data.', - argstr='-int', - xor=_xor_format) + desc='Write out 32-bit integer data.', argstr='-int', xor=_xor_format) format_long = traits.Bool( - desc='Superseded by -int.', - argstr='-long', - xor=_xor_format) + desc='Superseded by -int.', argstr='-long', xor=_xor_format) format_float = traits.Bool( desc='Write out single-precision floating-point data.', argstr='-float', @@ -751,9 +784,7 @@ class AverageInputSpec(CommandLineInputSpec): argstr='-double', xor=_xor_format) format_signed = traits.Bool( - desc='Write signed integer data.', - argstr='-signed', - xor=_xor_format) + desc='Write signed integer data.', argstr='-signed', xor=_xor_format) format_unsigned = traits.Bool( desc='Write unsigned integer data (default).', argstr='-unsigned', @@ -763,9 +794,13 @@ class AverageInputSpec(CommandLineInputSpec): low=0, desc='Specify the maximum size of the internal buffers (in kbytes).', value=4096, - argstr='-max_buffer_size_in_kb %d',) + argstr='-max_buffer_size_in_kb %d', + ) - _xor_normalize = ('normalize', 'nonormalize',) + _xor_normalize = ( + 'normalize', + 'nonormalize', + ) normalize = traits.Bool( desc='Normalize data sets for mean intensity.', @@ -777,21 +812,24 @@ class AverageInputSpec(CommandLineInputSpec): xor=_xor_normalize) voxel_range = traits.Tuple( - traits.Int, traits.Int, argstr='-range %d %d', + traits.Int, + traits.Int, + argstr='-range %d %d', desc='Valid range for output data.') sdfile = traits.File( - desc='Specify an output sd file (default=none).', - argstr='-sdfile %s') + desc='Specify an output sd file (default=none).', argstr='-sdfile %s') _xor_copy_header = ('copy_header', 'no_copy_header') copy_header = traits.Bool( - desc='Copy all of the header from the first file (default for one file).', + desc= + 'Copy all of the header from the first file (default for one file).', argstr='-copy_header', xor=_xor_copy_header) no_copy_header = traits.Bool( - desc='Do not copy all of the header from the first file (default for many files)).', + desc= + 'Do not copy all of the header from the first file (default for many files)).', argstr='-nocopy_header', xor=_xor_copy_header) @@ -804,8 +842,12 @@ class AverageInputSpec(CommandLineInputSpec): argstr='-binarize') binrange = traits.Tuple( - traits.Float, traits.Float, argstr='-binrange %s %s', - desc='Specify a range for binarization. Default value: 1.79769e+308 -1.79769e+308.') + traits.Float, + traits.Float, + argstr='-binrange %s %s', + desc= + 'Specify a range for binarization. Default value: 1.79769e+308 -1.79769e+308.' + ) binvalue = traits.Float( desc=('Specify a target value (+/- 0.5) for' @@ -816,14 +858,13 @@ class AverageInputSpec(CommandLineInputSpec): traits.Str, desc='Specify weights for averaging (",,...").', sep=',', - argstr='-weights %s',) + argstr='-weights %s', + ) width_weighted = traits.Bool( desc='Weight by dimension widths when -avgdim is used.', argstr='-width_weighted', - requires=( - 'avgdim', - )) + requires=('avgdim', )) class AverageOutputSpec(TraitedSpec): @@ -856,7 +897,8 @@ class BlobInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -912,7 +954,8 @@ class CalcInputSpec(CommandLineInputSpec): mandatory=True, sep=' ', argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -931,7 +974,10 @@ class CalcInputSpec(CommandLineInputSpec): usedefault=True, default_value=True) - _xor_verbose = ('verbose', 'quiet',) + _xor_verbose = ( + 'verbose', + 'quiet', + ) verbose = traits.Bool( desc='Print out log messages (default).', @@ -978,21 +1024,13 @@ class CalcInputSpec(CommandLineInputSpec): argstr='-filetype', xor=_xor_format) format_byte = traits.Bool( - desc='Write out byte data.', - argstr='-byte', - xor=_xor_format) + desc='Write out byte data.', argstr='-byte', xor=_xor_format) format_short = traits.Bool( - desc='Write out short integer data.', - argstr='-short', - xor=_xor_format) + desc='Write out short integer data.', argstr='-short', xor=_xor_format) format_int = traits.Bool( - desc='Write out 32-bit integer data.', - argstr='-int', - xor=_xor_format) + desc='Write out 32-bit integer data.', argstr='-int', xor=_xor_format) format_long = traits.Bool( - desc='Superseded by -int.', - argstr='-long', - xor=_xor_format) + desc='Superseded by -int.', argstr='-long', xor=_xor_format) format_float = traits.Bool( desc='Write out single-precision floating-point data.', argstr='-float', @@ -1002,17 +1040,18 @@ class CalcInputSpec(CommandLineInputSpec): argstr='-double', xor=_xor_format) format_signed = traits.Bool( - desc='Write signed integer data.', - argstr='-signed', - xor=_xor_format) + desc='Write signed integer data.', argstr='-signed', xor=_xor_format) format_unsigned = traits.Bool( desc='Write unsigned integer data (default).', argstr='-unsigned', xor=_xor_format) voxel_range = traits.Tuple( - traits.Int, traits.Int, argstr='-range %d %d', - desc='Valid range for output data.',) + traits.Int, + traits.Int, + argstr='-range %d %d', + desc='Valid range for output data.', + ) max_buffer_size_in_kb = traits.Range( low=0, @@ -1021,7 +1060,10 @@ class CalcInputSpec(CommandLineInputSpec): usedefault=False, argstr='-max_buffer_size_in_kb %d') - _xor_check_dimensions = ('check_dimensions', 'no_check_dimensions',) + _xor_check_dimensions = ( + 'check_dimensions', + 'no_check_dimensions', + ) check_dimensions = traits.Bool( desc='Check that files have matching dimensions (default).', @@ -1042,10 +1084,8 @@ class CalcInputSpec(CommandLineInputSpec): argstr='-propagate_nan') # FIXME Double-check that these are mutually exclusive? - _xor_nan_zero_illegal = ( - 'output_nan', - 'output_zero', - 'output_illegal_value') + _xor_nan_zero_illegal = ('output_nan', 'output_zero', + 'output_illegal_value') output_nan = traits.Bool( desc='Output NaN when an illegal operation is done (default).', @@ -1056,7 +1096,8 @@ class CalcInputSpec(CommandLineInputSpec): argstr='-zero', xor=_xor_nan_zero_illegal) output_illegal = traits.Bool( - desc='Value to write out when an illegal operation is done. Default value: 1.79769e+308', + desc= + 'Value to write out when an illegal operation is done. Default value: 1.79769e+308', argstr='-illegal_value', xor=_xor_nan_zero_illegal) @@ -1080,11 +1121,13 @@ class CalcInputSpec(CommandLineInputSpec): traits.Str, traits.File, argstr='-outfile %s %s', - desc=('List of (symbol, file) tuples indicating that output should be written' - 'to the specified file, taking values from the symbol which should be' - 'created in the expression (see the EXAMPLES section). If this option' - 'is given, then all non-option arguments are taken as input files.' - 'This option can be used multiple times for multiple output files.'))) + desc= + ('List of (symbol, file) tuples indicating that output should be written' + 'to the specified file, taking values from the symbol which should be' + 'created in the expression (see the EXAMPLES section). If this option' + 'is given, then all non-option arguments are taken as input files.' + 'This option can be used multiple times for multiple output files.' + ))) eval_width = traits.Int( 200, @@ -1131,7 +1174,8 @@ class BBoxInputSpec(StdOutCommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file containing bounding box corners', @@ -1158,7 +1202,8 @@ class BBoxInputSpec(StdOutCommandLineInputSpec): xor=_xor_one_two) format_mincresample = traits.Bool( - desc='Output format for mincresample: (-step x y z -start x y z -nelements x y z', + desc= + 'Output format for mincresample: (-step x y z -start x y z -nelements x y z', argstr='-mincresample') format_mincreshape = traits.Bool( desc='Output format for mincreshape: (-start x,y,z -count dx,dy,dz', @@ -1177,8 +1222,7 @@ class BBoxInputSpec(StdOutCommandLineInputSpec): class BBoxOutputSpec(TraitedSpec): output_file = File( - desc='output file containing bounding box corners', - exists=True) + desc='output file containing bounding box corners', exists=True) class BBox(StdOutCommandLine): @@ -1250,18 +1294,17 @@ class BeastInputSpec(CommandLineInputSpec): desc='Output the probability map instead of crisp mask.', argstr='-probability') flip_images = traits.Bool( - desc='Flip images around the mid-sagittal plane to increase patch count.', + desc= + 'Flip images around the mid-sagittal plane to increase patch count.', argstr='-flip') load_moments = traits.Bool( desc=('Do not calculate moments instead use precalculated' 'library moments. (for optimization purposes)'), argstr='-load_moments') fill_holes = traits.Bool( - desc='Fill holes in the binary output.', - argstr='-fill') + desc='Fill holes in the binary output.', argstr='-fill') median_filter = traits.Bool( - desc='Apply a median filter on the probability map.', - argstr='-median') + desc='Apply a median filter on the probability map.', argstr='-median') nlm_filter = traits.Bool( desc='Apply an NLM filter on the probability map (experimental).', argstr='-nlm_filter') @@ -1273,8 +1316,7 @@ class BeastInputSpec(CommandLineInputSpec): default_value=True) configuration_file = traits.File( - desc='Specify configuration file.', - argstr='-configuration %s') + desc='Specify configuration file.', argstr='-configuration %s') voxel_size = traits.Int( 4, @@ -1284,7 +1326,8 @@ class BeastInputSpec(CommandLineInputSpec): argstr='-voxel_size %s') abspath = traits.Bool( - desc='File paths in the library are absolute (default is relative to library root).', + desc= + 'File paths in the library are absolute (default is relative to library root).', argstr='-abspath', usedefault=True, default_value=True) @@ -1296,7 +1339,8 @@ class BeastInputSpec(CommandLineInputSpec): search_area = traits.Int( 2, - desc='Specify size of search area for single scale approach. Default value: 2.', + desc= + 'Specify size of search area for single scale approach. Default value: 2.', argstr='-search_area %s') confidence_level_alpha = traits.Float( @@ -1321,15 +1365,9 @@ class BeastInputSpec(CommandLineInputSpec): argstr='-same_resolution') library_dir = traits.Directory( - desc='library directory', - position=-3, - argstr='%s', - mandatory=True) + desc='library directory', position=-3, argstr='%s', mandatory=True) input_file = traits.File( - desc='input file', - position=-2, - argstr='%s', - mandatory=True) + desc='input file', position=-2, argstr='%s', mandatory=True) output_file = traits.File( desc='output file', position=-1, @@ -1369,7 +1407,8 @@ class PikInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) _xor_image_type = ('jpg', 'png') @@ -1403,7 +1442,8 @@ class PikInputSpec(CommandLineInputSpec): argstr='--scale %s') width = traits.Int( - desc='Autoscale the resulting image to have a fixed image width (in pixels).', + desc= + 'Autoscale the resulting image to have a fixed image width (in pixels).', argstr='--width %s') depth = traits.Enum( @@ -1425,25 +1465,29 @@ class PikInputSpec(CommandLineInputSpec): requires=['title']) annotated_bar = traits.Bool( - desc='create an annotated bar to match the image (use height of the output image)', + desc= + 'create an annotated bar to match the image (use height of the output image)', argstr='--anot_bar') # FIXME tuple of floats? Not voxel values? Man page doesn't specify. minc_range = traits.Tuple( - traits.Float, traits.Float, + traits.Float, + traits.Float, desc='Valid range of values for MINC file.', argstr='--range %s %s') _xor_image_range = ('image_range', 'auto_range') image_range = traits.Tuple( - traits.Float, traits.Float, + traits.Float, + traits.Float, desc='Range of image values to use for pixel intensity.', argstr='--image_range %s %s', xor=_xor_image_range) auto_range = traits.Bool( - desc='Automatically determine image range using a 5 and 95% PcT. (histogram)', + desc= + 'Automatically determine image range using a 5 and 95% PcT. (histogram)', argstr='--auto_range', xor=_xor_image_range) @@ -1454,16 +1498,11 @@ class PikInputSpec(CommandLineInputSpec): _xor_slice = ('slice_z', 'slice_y', 'slice_x') slice_z = traits.Bool( - desc='Get an axial/transverse (z) slice.', - argstr='-z', - xor=_xor_slice) + desc='Get an axial/transverse (z) slice.', argstr='-z', xor=_xor_slice) slice_y = traits.Bool( - desc='Get a coronal (y) slice.', - argstr='-y', - xor=_xor_slice) + desc='Get a coronal (y) slice.', argstr='-y', xor=_xor_slice) slice_x = traits.Bool( - desc='Get a sagittal (x) slice.', - argstr='-x', + desc='Get a sagittal (x) slice.', argstr='-x', xor=_xor_slice) # FIXME typo in man page? sagital? triplanar = traits.Bool( @@ -1485,9 +1524,8 @@ class PikInputSpec(CommandLineInputSpec): argstr='--sagittal_offset_perc %d', ) - _xor_vertical_horizontal = ( - 'vertical_triplanar_view', - 'horizontal_triplanar_view') + _xor_vertical_horizontal = ('vertical_triplanar_view', + 'horizontal_triplanar_view') vertical_triplanar_view = traits.Bool( desc='Create a vertical triplanar view (Default).', @@ -1499,8 +1537,7 @@ class PikInputSpec(CommandLineInputSpec): xor=_xor_vertical_horizontal) lookup = traits.Str( - desc='Arguments to pass to minclookup', - argstr='--lookup %s') + desc='Arguments to pass to minclookup', argstr='--lookup %s') class PikOutputSpec(TraitedSpec): @@ -1534,7 +1571,7 @@ def _format_arg(self, name, spec, value): if isinstance(value, bool) and value: return '--title' elif isinstance(value, str): - return '--title --title_text %s' % (value,) + return '--title --title_text %s' % (value, ) else: raise ValueError( 'Unknown value for "title" argument: ' + str(value)) @@ -1547,12 +1584,10 @@ class BlurInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) - output_file_base = File( - desc='output file base', - argstr='%s', - position=-1) + output_file_base = File(desc='output file base', argstr='%s', position=-1) clobber = traits.Bool( desc='Overwrite existing file.', @@ -1575,12 +1610,12 @@ class BlurInputSpec(CommandLineInputSpec): desc='Create the gradient magnitude volume as well.', argstr='-gradient') partial = traits.Bool( - desc='Create the partial derivative and gradient magnitude volumes as well.', + desc= + 'Create the partial derivative and gradient magnitude volumes as well.', argstr='-partial') no_apodize = traits.Bool( - desc='Do not apodize the data before blurring.', - argstr='-no_apodize') + desc='Do not apodize the data before blurring.', argstr='-no_apodize') _xor_main_options = ('fwhm', 'fwhm3d', 'standard_dev') @@ -1612,7 +1647,8 @@ class BlurInputSpec(CommandLineInputSpec): 1, 2, 3, - desc='Number of dimensions to blur (either 1,2 or 3). Default value: 3.', + desc= + 'Number of dimensions to blur (either 1,2 or 3). Default value: 3.', argstr='-dimensions %s', default=3) @@ -1674,13 +1710,12 @@ def _gen_output_base(self): if isdefined(output_file_base): return output_file_base else: - base_file_name = os.path.split(self.inputs.input_file)[ - 1] # e.g. 'foo.mnc' - base_file_name_no_ext = os.path.splitext( - base_file_name)[0] # e.g. 'foo' + base_file_name = os.path.split( + self.inputs.input_file)[1] # e.g. 'foo.mnc' + base_file_name_no_ext = os.path.splitext(base_file_name)[ + 0] # e.g. 'foo' output_base = os.path.join( - os.getcwd(), - base_file_name_no_ext + + os.getcwd(), base_file_name_no_ext + '_bluroutput') # e.g. '/tmp/blah/foo_bluroutput' # return os.path.splitext(self.inputs.input_file)[0] + # '_bluroutput' @@ -1757,11 +1792,13 @@ class MathInputSpec(CommandLineInputSpec): _xor_copy_header = ('copy_header', 'no_copy_header') copy_header = traits.Bool( - desc='Copy all of the header from the first file (default for one file).', + desc= + 'Copy all of the header from the first file (default for one file).', argstr='-copy_header', xor=_xor_copy_header) no_copy_header = traits.Bool( - desc='Do not copy all of the header from the first file (default for many files)).', + desc= + 'Do not copy all of the header from the first file (default for many files)).', argstr='-nocopy_header', xor=_xor_copy_header) @@ -1782,21 +1819,13 @@ class MathInputSpec(CommandLineInputSpec): argstr='-filetype', xor=_xor_format) format_byte = traits.Bool( - desc='Write out byte data.', - argstr='-byte', - xor=_xor_format) + desc='Write out byte data.', argstr='-byte', xor=_xor_format) format_short = traits.Bool( - desc='Write out short integer data.', - argstr='-short', - xor=_xor_format) + desc='Write out short integer data.', argstr='-short', xor=_xor_format) format_int = traits.Bool( - desc='Write out 32-bit integer data.', - argstr='-int', - xor=_xor_format) + desc='Write out 32-bit integer data.', argstr='-int', xor=_xor_format) format_long = traits.Bool( - desc='Superseded by -int.', - argstr='-long', - xor=_xor_format) + desc='Superseded by -int.', argstr='-long', xor=_xor_format) format_float = traits.Bool( desc='Write out single-precision floating-point data.', argstr='-float', @@ -1806,25 +1835,29 @@ class MathInputSpec(CommandLineInputSpec): argstr='-double', xor=_xor_format) format_signed = traits.Bool( - desc='Write signed integer data.', - argstr='-signed', - xor=_xor_format) + desc='Write signed integer data.', argstr='-signed', xor=_xor_format) format_unsigned = traits.Bool( desc='Write unsigned integer data (default).', argstr='-unsigned', xor=_xor_format) voxel_range = traits.Tuple( - traits.Int, traits.Int, argstr='-range %d %d', + traits.Int, + traits.Int, + argstr='-range %d %d', desc='Valid range for output data.') max_buffer_size_in_kb = traits.Range( low=0, desc='Specify the maximum size of the internal buffers (in kbytes).', value=4096, - argstr='-max_buffer_size_in_kb %d',) + argstr='-max_buffer_size_in_kb %d', + ) - _xor_check_dimensions = ('check_dimensions', 'no_check_dimensions',) + _xor_check_dimensions = ( + 'check_dimensions', + 'no_check_dimensions', + ) check_dimensions = traits.Bool( desc='Check that dimension info matches across files (default).', @@ -1836,7 +1869,8 @@ class MathInputSpec(CommandLineInputSpec): xor=_xor_check_dimensions) dimension = traits.Str( - desc='Specify a dimension along which we wish to perform a calculation.', + desc= + 'Specify a dimension along which we wish to perform a calculation.', argstr='-dimension %s') # FIXME Is it sensible to use ignore_nan and propagate_nan at the same @@ -1849,10 +1883,8 @@ class MathInputSpec(CommandLineInputSpec): argstr='-propagate_nan') # FIXME Double-check that these are mutually exclusive? - _xor_nan_zero_illegal = ( - 'output_nan', - 'output_zero', - 'output_illegal_value') + _xor_nan_zero_illegal = ('output_nan', 'output_zero', + 'output_illegal_value') output_nan = traits.Bool( desc='Output NaN when an illegal operation is done (default).', @@ -1876,16 +1908,9 @@ class MathInputSpec(CommandLineInputSpec): ########################################################################## bool_or_const_traits = [ - 'test_gt', - 'test_lt', - 'test_eq', - 'test_ne', - 'test_ge', - 'test_le', - 'calc_add', - 'calc_sub', - 'calc_mul', - 'calc_div'] + 'test_gt', 'test_lt', 'test_eq', 'test_ne', 'test_ge', 'test_le', + 'calc_add', 'calc_sub', 'calc_mul', 'calc_div' + ] test_gt = traits.Either( traits.Bool(), @@ -1944,24 +1969,12 @@ class MathInputSpec(CommandLineInputSpec): ###################################### single_volume_traits = [ - 'invert', - 'calc_not', - 'sqrt', - 'square', - 'abs', - 'exp', - 'log', - 'scale', - 'clamp', - 'segment', - 'nsegment', - 'isnan', - 'isnan'] # FIXME enforce this in _parse_inputs and check for other members + 'invert', 'calc_not', 'sqrt', 'square', 'abs', 'exp', 'log', 'scale', + 'clamp', 'segment', 'nsegment', 'isnan', 'isnan' + ] # FIXME enforce this in _parse_inputs and check for other members invert = traits.Either( - traits.Float(), - desc='Calculate 1/c.', - argstr='-invert -const %s') + traits.Float(), desc='Calculate 1/c.', argstr='-invert -const %s') calc_not = traits.Bool(desc='Calculate !vol1.', argstr='-not') @@ -1970,27 +1983,41 @@ class MathInputSpec(CommandLineInputSpec): abs = traits.Bool(desc='Take absolute value of a volume.', argstr='-abs') exp = traits.Tuple( - traits.Float, traits.Float, argstr='-exp -const2 %s %s', + traits.Float, + traits.Float, + argstr='-exp -const2 %s %s', desc='Calculate c2*exp(c1*x). Both constants must be specified.') log = traits.Tuple( - traits.Float, traits.Float, argstr='-log -const2 %s %s', + traits.Float, + traits.Float, + argstr='-log -const2 %s %s', desc='Calculate log(x/c2)/c1. The constants c1 and c2 default to 1.') scale = traits.Tuple( - traits.Float, traits.Float, argstr='-scale -const2 %s %s', + traits.Float, + traits.Float, + argstr='-scale -const2 %s %s', desc='Scale a volume: volume * c1 + c2.') clamp = traits.Tuple( - traits.Float, traits.Float, argstr='-clamp -const2 %s %s', + traits.Float, + traits.Float, + argstr='-clamp -const2 %s %s', desc='Clamp a volume to lie between two values.') segment = traits.Tuple( - traits.Float, traits.Float, argstr='-segment -const2 %s %s', - desc='Segment a volume using range of -const2: within range = 1, outside range = 0.') + traits.Float, + traits.Float, + argstr='-segment -const2 %s %s', + desc= + 'Segment a volume using range of -const2: within range = 1, outside range = 0.' + ) nsegment = traits.Tuple( - traits.Float, traits.Float, argstr='-nsegment -const2 %s %s', + traits.Float, + traits.Float, + argstr='-nsegment -const2 %s %s', desc='Opposite of -segment: within range = 0, outside range = 1.') isnan = traits.Bool(desc='Test for NaN values in vol1.', argstr='-isnan') @@ -2004,7 +2031,8 @@ class MathInputSpec(CommandLineInputSpec): two_volume_traits = ['percentdiff'] percentdiff = traits.Float( - desc='Percent difference between 2 volumes, thresholded (const def=0.0).', + desc= + 'Percent difference between 2 volumes, thresholded (const def=0.0).', argstr='-percentdiff') ##################################### @@ -2012,11 +2040,8 @@ class MathInputSpec(CommandLineInputSpec): ##################################### n_volume_traits = [ - 'count_valid', - 'maximum', - 'minimum', - 'calc_add', - 'calc_or'] + 'count_valid', 'maximum', 'minimum', 'calc_add', 'calc_or' + ] count_valid = traits.Bool( desc='Count the number of valid values in N volumes.', @@ -2026,11 +2051,9 @@ class MathInputSpec(CommandLineInputSpec): minimum = traits.Bool(desc='Find minimum of N volumes.', argstr='-minimum') calc_and = traits.Bool( - desc='Calculate vol1 && vol2 (&& ...).', - argstr='-and') + desc='Calculate vol1 && vol2 (&& ...).', argstr='-and') calc_or = traits.Bool( - desc='Calculate vol1 || vol2 (|| ...).', - argstr='-or') + desc='Calculate vol1 || vol2 (|| ...).', argstr='-or') class MathOutputSpec(TraitedSpec): @@ -2072,13 +2095,18 @@ def _format_arg(self, name, spec, value): if isinstance(value, bool) and value: return spec.argstr elif isinstance(value, bool) and not value: - raise ValueError( - 'Does not make sense to specify %s=False' % - (name,)) + raise ValueError('Does not make sense to specify %s=False' % + (name, )) elif isinstance(value, float): - return '%s -const %s' % (spec.argstr, value,) + return '%s -const %s' % ( + spec.argstr, + value, + ) else: - raise ValueError('Invalid %s argument: %s' % (name, value,)) + raise ValueError('Invalid %s argument: %s' % ( + name, + value, + )) return super(Math, self)._format_arg(name, spec, value) @@ -2095,17 +2123,22 @@ def _parse_inputs(self): if isinstance(t, bool): if nr_input_files != 2: raise ValueError( - 'Due to the %s option we expected 2 files but input_files is of length %d' % - (n, nr_input_files,)) + 'Due to the %s option we expected 2 files but input_files is of length %d' + % ( + n, + nr_input_files, + )) elif isinstance(t, float): if nr_input_files != 1: raise ValueError( - 'Due to the %s option we expected 1 file but input_files is of length %d' % - (n, nr_input_files,)) + 'Due to the %s option we expected 1 file but input_files is of length %d' + % ( + n, + nr_input_files, + )) else: raise ValueError( - 'Argument should be a bool or const, but got: %s' % - t) + 'Argument should be a bool or const, but got: %s' % t) for n in self.input_spec.single_volume_traits: t = self.inputs.__getattribute__(n) @@ -2113,8 +2146,11 @@ def _parse_inputs(self): if isdefined(t): if nr_input_files != 1: raise ValueError( - 'Due to the %s option we expected 1 file but input_files is of length %d' % - (n, nr_input_files,)) + 'Due to the %s option we expected 1 file but input_files is of length %d' + % ( + n, + nr_input_files, + )) for n in self.input_spec.two_volume_traits: t = self.inputs.__getattribute__(n) @@ -2122,8 +2158,11 @@ def _parse_inputs(self): if isdefined(t): if nr_input_files != 2: raise ValueError( - 'Due to the %s option we expected 2 files but input_files is of length %d' % - (n, nr_input_files,)) + 'Due to the %s option we expected 2 files but input_files is of length %d' + % ( + n, + nr_input_files, + )) for n in self.input_spec.n_volume_traits: t = self.inputs.__getattribute__(n) @@ -2131,8 +2170,11 @@ def _parse_inputs(self): if isdefined(t): if not nr_input_files >= 1: raise ValueError( - 'Due to the %s option we expected at least one file but input_files is of length %d' % - (n, nr_input_files,)) + 'Due to the %s option we expected at least one file but input_files is of length %d' + % ( + n, + nr_input_files, + )) return super(Math, self)._parse_inputs() @@ -2152,7 +2194,8 @@ class ResampleInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -2166,7 +2209,8 @@ class ResampleInputSpec(CommandLineInputSpec): # This is a dummy input. input_grid_files = InputMultiPath( traits.File, - desc='input grid file(s)',) + desc='input grid file(s)', + ) two = traits.Bool(desc='Create a MINC 2 output file.', argstr='-2') @@ -2176,11 +2220,9 @@ class ResampleInputSpec(CommandLineInputSpec): usedefault=True, default_value=True) - _xor_interpolation = ( - 'trilinear_interpolation', - 'tricubic_interpolation', - 'nearest_neighbour_interpolation', - 'sinc_interpolation') + _xor_interpolation = ('trilinear_interpolation', 'tricubic_interpolation', + 'nearest_neighbour_interpolation', + 'sinc_interpolation') trilinear_interpolation = traits.Bool( desc='Do trilinear interpolation.', @@ -2268,21 +2310,13 @@ class ResampleInputSpec(CommandLineInputSpec): ) format_byte = traits.Bool( - desc='Write out byte data.', - argstr='-byte', - xor=_xor_format) + desc='Write out byte data.', argstr='-byte', xor=_xor_format) format_short = traits.Bool( - desc='Write out short integer data.', - argstr='-short', - xor=_xor_format) + desc='Write out short integer data.', argstr='-short', xor=_xor_format) format_int = traits.Bool( - desc='Write out 32-bit integer data.', - argstr='-int', - xor=_xor_format) + desc='Write out 32-bit integer data.', argstr='-int', xor=_xor_format) format_long = traits.Bool( - desc='Superseded by -int.', - argstr='-long', - xor=_xor_format) + desc='Superseded by -int.', argstr='-long', xor=_xor_format) format_float = traits.Bool( desc='Write out single-precision floating-point data.', argstr='-float', @@ -2292,17 +2326,19 @@ class ResampleInputSpec(CommandLineInputSpec): argstr='-double', xor=_xor_format) format_signed = traits.Bool( - desc='Write signed integer data.', - argstr='-signed', - xor=_xor_format) + desc='Write signed integer data.', argstr='-signed', xor=_xor_format) format_unsigned = traits.Bool( desc='Write unsigned integer data (default).', argstr='-unsigned', xor=_xor_format) output_range = traits.Tuple( - traits.Float, traits.Float, argstr='-range %s %s', - desc='Valid range for output data. Default value: -1.79769e+308 -1.79769e+308.') + traits.Float, + traits.Float, + argstr='-range %s %s', + desc= + 'Valid range for output data. Default value: -1.79769e+308 -1.79769e+308.' + ) _xor_slices = ('transverse', 'sagittal', 'coronal') @@ -2312,14 +2348,10 @@ class ResampleInputSpec(CommandLineInputSpec): xor=_xor_slices) sagittal_slices = traits.Bool( - desc='Write out sagittal slices', - argstr='-sagittal', - xor=_xor_slices) + desc='Write out sagittal slices', argstr='-sagittal', xor=_xor_slices) coronal_slices = traits.Bool( - desc='Write out coronal slices', - argstr='-coronal', - xor=_xor_slices) + desc='Write out coronal slices', argstr='-coronal', xor=_xor_slices) _xor_fill = ('nofill', 'fill') @@ -2356,11 +2388,12 @@ class ResampleInputSpec(CommandLineInputSpec): desc='Set the spacetype attribute to a specified string.', argstr='-spacetype %s') talairach = traits.Bool( - desc='Output is in Talairach space.', - argstr='-talairach') + desc='Output is in Talairach space.', argstr='-talairach') origin = traits.Tuple( - traits.Float, traits.Float, traits.Float, + traits.Float, + traits.Float, + traits.Float, desc=('Origin of first pixel in 3D space.' 'Default value: 1.79769e+308 1.79769e+308 1.79769e+308.'), argstr='-origin %s %s %s') @@ -2394,15 +2427,17 @@ class ResampleInputSpec(CommandLineInputSpec): requires=('ynelements', 'znelements'), xor=_xor_nelements) - ynelements = traits.Int(desc='Number of elements along the Y dimension.', - argstr='-ynelements %s', - requires=('xnelements', 'znelements'), - xor=_xor_nelements) + ynelements = traits.Int( + desc='Number of elements along the Y dimension.', + argstr='-ynelements %s', + requires=('xnelements', 'znelements'), + xor=_xor_nelements) - znelements = traits.Int(desc='Number of elements along the Z dimension.', - argstr='-znelements %s', - requires=('xnelements', 'ynelements'), - xor=_xor_nelements) + znelements = traits.Int( + desc='Number of elements along the Z dimension.', + argstr='-znelements %s', + requires=('xnelements', 'ynelements'), + xor=_xor_nelements) # step size along each dimension _xor_step = ('step', 'step_x_y_or_z') @@ -2411,7 +2446,8 @@ class ResampleInputSpec(CommandLineInputSpec): traits.Int, traits.Int, traits.Int, - desc='Step size along each dimension (X, Y, Z). Default value: (0, 0, 0).', + desc= + 'Step size along each dimension (X, Y, Z). Default value: (0, 0, 0).', argstr='-step %s %s %s', xor=_xor_nelements) @@ -2425,17 +2461,13 @@ class ResampleInputSpec(CommandLineInputSpec): ystep = traits.Int( desc='Step size along the Y dimension. Default value: 0.', argstr='-ystep %s', - requires=( - 'xstep', - 'zstep'), + requires=('xstep', 'zstep'), xor=_xor_step) zstep = traits.Int( desc='Step size along the Z dimension. Default value: 0.', argstr='-zstep %s', - requires=( - 'xstep', - 'ystep'), + requires=('xstep', 'ystep'), xor=_xor_step) # start point along each dimension @@ -2460,17 +2492,13 @@ class ResampleInputSpec(CommandLineInputSpec): ystart = traits.Float( desc='Start point along the Y dimension. Default value: 1.79769e+308.', argstr='-ystart %s', - requires=( - 'xstart', - 'zstart'), + requires=('xstart', 'zstart'), xor=_xor_start) zstart = traits.Float( desc='Start point along the Z dimension. Default value: 1.79769e+308.', argstr='-zstart %s', - requires=( - 'xstart', - 'ystart'), + requires=('xstart', 'ystart'), xor=_xor_start) # dircos along each dimension @@ -2480,9 +2508,11 @@ class ResampleInputSpec(CommandLineInputSpec): traits.Float, traits.Float, traits.Float, - desc=('Direction cosines along each dimension (X, Y, Z). Default value:' - '1.79769e+308 1.79769e+308 1.79769e+308 1.79769e+308 ...' - ' 1.79769e+308 1.79769e+308 1.79769e+308 1.79769e+308 1.79769e+308.'), + desc=( + 'Direction cosines along each dimension (X, Y, Z). Default value:' + '1.79769e+308 1.79769e+308 1.79769e+308 1.79769e+308 ...' + ' 1.79769e+308 1.79769e+308 1.79769e+308 1.79769e+308 1.79769e+308.' + ), argstr='-dircos %s %s %s', xor=_xor_nelements) @@ -2491,27 +2521,21 @@ class ResampleInputSpec(CommandLineInputSpec): desc=('Direction cosines along the X dimension.' 'Default value: 1.79769e+308 1.79769e+308 1.79769e+308.'), argstr='-xdircos %s', - requires=( - 'ydircos', - 'zdircos'), + requires=('ydircos', 'zdircos'), xor=_xor_dircos) ydircos = traits.Float( desc=('Direction cosines along the Y dimension.' 'Default value: 1.79769e+308 1.79769e+308 1.79769e+308.'), argstr='-ydircos %s', - requires=( - 'xdircos', - 'zdircos'), + requires=('xdircos', 'zdircos'), xor=_xor_dircos) zdircos = traits.Float( desc=('Direction cosines along the Z dimension.' 'Default value: 1.79769e+308 1.79769e+308 1.79769e+308.'), argstr='-zdircos %s', - requires=( - 'xdircos', - 'ydircos'), + requires=('xdircos', 'ydircos'), xor=_xor_dircos) @@ -2557,7 +2581,8 @@ class NormInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -2595,7 +2620,8 @@ class NormInputSpec(CommandLineInputSpec): cutoff = traits.Range( low=0.0, high=100.0, - desc='Cutoff value to use to calculate thresholds by a histogram PcT in %. [default: 0.01]', + desc= + 'Cutoff value to use to calculate thresholds by a histogram PcT in %. [default: 0.01]', argstr='-cutoff %s', ) @@ -2611,13 +2637,15 @@ class NormInputSpec(CommandLineInputSpec): # Threshold Options threshold = traits.Bool( - desc='Threshold the image (set values below threshold_perc to -out_floor).', + desc= + 'Threshold the image (set values below threshold_perc to -out_floor).', argstr='-threshold') threshold_perc = traits.Range( low=0.0, high=100.0, - desc='Threshold percentage (0.1 == lower 10% of intensity range) [default: 0.1].', + desc= + 'Threshold percentage (0.1 == lower 10% of intensity range) [default: 0.1].', argstr='-threshold_perc %s') threshold_bmt = traits.Bool( @@ -2694,7 +2722,8 @@ class VolcentreInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -2706,8 +2735,7 @@ class VolcentreInputSpec(CommandLineInputSpec): name_template='%s_volcentre.mnc') verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -2715,13 +2743,17 @@ class VolcentreInputSpec(CommandLineInputSpec): default_value=True) com = traits.Bool( - desc='Use the CoM of the volume for the new centre (via mincstats). Default: False', + desc= + 'Use the CoM of the volume for the new centre (via mincstats). Default: False', argstr='-com') centre = traits.Tuple( - traits.Float, traits.Float, traits.Float, + traits.Float, + traits.Float, + traits.Float, argstr='-centre %s %s %s', - desc='Centre to use (x,y,z) [default: 0 0 0].',) + desc='Centre to use (x,y,z) [default: 0 0 0].', + ) zero_dircos = traits.Bool( desc='Set the direction cosines to identity [default].', @@ -2778,7 +2810,8 @@ class VolpadInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -2790,8 +2823,7 @@ class VolpadInputSpec(CommandLineInputSpec): name_template='%s_volpad.mnc') verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -2799,11 +2831,13 @@ class VolpadInputSpec(CommandLineInputSpec): default_value=True) auto = traits.Bool( - desc='Automatically determine padding distances (uses -distance as max). Default: False.', + desc= + 'Automatically determine padding distances (uses -distance as max). Default: False.', argstr='-auto') auto_freq = traits.Float( - desc='Frequency of voxels over bimodalt threshold to stop at [default: 500].', + desc= + 'Frequency of voxels over bimodalt threshold to stop at [default: 500].', argstr='-auto_freq %s') distance = traits.Int( @@ -2847,7 +2881,8 @@ class VolisoInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_file = File( desc='output file', @@ -2859,8 +2894,7 @@ class VolisoInputSpec(CommandLineInputSpec): name_template='%s_voliso.mnc') verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='--verbose') + desc='Print out log messages. Default: False.', argstr='--verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='--clobber', @@ -2876,7 +2910,8 @@ class VolisoInputSpec(CommandLineInputSpec): argstr='--minstep %s') avgstep = traits.Bool( - desc='Calculate the maximum step from the average steps of the input volume.', + desc= + 'Calculate the maximum step from the average steps of the input volume.', argstr='--avgstep') @@ -2913,8 +2948,7 @@ class GennlxfmInputSpec(CommandLineInputSpec): name_template='%s_gennlxfm.xfm') verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -2922,15 +2956,15 @@ class GennlxfmInputSpec(CommandLineInputSpec): default_value=True) ident = traits.Bool( - desc='Generate an identity xfm. Default: False.', - argstr='-ident') + desc='Generate an identity xfm. Default: False.', argstr='-ident') step = traits.Int( - desc='Output ident xfm step [default: 1].', - argstr='-step %s') + desc='Output ident xfm step [default: 1].', argstr='-step %s') - like = File(desc='Generate a nlxfm like this file.', - exists=True, - argstr='-like %s',) + like = File( + desc='Generate a nlxfm like this file.', + exists=True, + argstr='-like %s', + ) class GennlxfmOutputSpec(TraitedSpec): @@ -2962,8 +2996,8 @@ class Gennlxfm(CommandLine): def _list_outputs(self): outputs = super(Gennlxfm, self)._list_outputs() - outputs['output_grid'] = re.sub( - '.(nlxfm|xfm)$', '_grid_0.mnc', outputs['output_file']) + outputs['output_grid'] = re.sub('.(nlxfm|xfm)$', '_grid_0.mnc', + outputs['output_file']) return outputs @@ -2979,7 +3013,8 @@ class XfmConcatInputSpec(CommandLineInputSpec): # This is a dummy input. input_grid_files = InputMultiPath( traits.File, - desc='input grid file(s)',) + desc='input grid file(s)', + ) output_file = File( desc='output file', @@ -2991,8 +3026,7 @@ class XfmConcatInputSpec(CommandLineInputSpec): name_template='%s_xfmconcat.xfm') verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -3029,10 +3063,8 @@ def _list_outputs(self): if os.path.exists(outputs['output_file']): if 'grid' in open(outputs['output_file'], 'r').read(): outputs['output_grids'] = glob.glob( - re.sub( - '.(nlxfm|xfm)$', - '_grid_*.mnc', - outputs['output_file'])) + re.sub('.(nlxfm|xfm)$', '_grid_*.mnc', + outputs['output_file'])) return outputs @@ -3043,14 +3075,16 @@ class BestLinRegInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-4,) + position=-4, + ) target = File( desc='target Minc file', exists=True, mandatory=True, argstr='%s', - position=-3,) + position=-3, + ) output_xfm = File( desc='output xfm file', @@ -3073,8 +3107,7 @@ class BestLinRegInputSpec(CommandLineInputSpec): keep_extension=False) verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -3127,25 +3160,29 @@ class NlpFitInputSpec(CommandLineInputSpec): exists=True, mandatory=True, argstr='%s', - position=-3,) + position=-3, + ) target = File( desc='target Minc file', exists=True, mandatory=True, argstr='%s', - position=-2,) + position=-2, + ) output_xfm = File( desc='output xfm file', genfile=True, argstr='%s', - position=-1,) + position=-1, + ) # This is a dummy input. input_grid_files = InputMultiPath( traits.File, - desc='input grid file(s)',) + desc='input grid file(s)', + ) config_file = File( desc='File containing the fitting configuration use.', @@ -3166,8 +3203,7 @@ class NlpFitInputSpec(CommandLineInputSpec): exists=True) verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -3215,7 +3251,8 @@ def _gen_filename(self, name): return os.path.abspath(output_xfm) else: return aggregate_filename( - [self.inputs.source, self.inputs.target], 'nlpfit_xfm_output') + '.xfm' + [self.inputs.source, self.inputs.target], + 'nlpfit_xfm_output') + '.xfm' else: raise NotImplemented @@ -3226,8 +3263,8 @@ def _list_outputs(self): assert os.path.exists(outputs['output_xfm']) if 'grid' in open(outputs['output_xfm'], 'r').read(): - outputs['output_grid'] = re.sub( - '.(nlxfm|xfm)$', '_grid_0.mnc', outputs['output_xfm']) + outputs['output_grid'] = re.sub('.(nlxfm|xfm)$', '_grid_0.mnc', + outputs['output_xfm']) return outputs @@ -3244,17 +3281,18 @@ class XfmAvgInputSpec(CommandLineInputSpec): # This is a dummy input. input_grid_files = InputMultiPath( traits.File, - desc='input grid file(s)',) + desc='input grid file(s)', + ) output_file = File( desc='output file', genfile=True, argstr='%s', - position=-1,) + position=-1, + ) verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -3264,18 +3302,14 @@ class XfmAvgInputSpec(CommandLineInputSpec): # FIXME xor these: avg_linear = traits.Bool( - desc='average the linear part [default].', - argstr='-avg_linear') + desc='average the linear part [default].', argstr='-avg_linear') avg_nonlinear = traits.Bool( - desc='average the non-linear part [default].', - argstr='-avg_nonlinear') + desc='average the non-linear part [default].', argstr='-avg_nonlinear') ignore_linear = traits.Bool( - desc='opposite of -avg_linear.', - argstr='-ignore_linear') + desc='opposite of -avg_linear.', argstr='-ignore_linear') ignore_nonlinear = traits.Bool( - desc='opposite of -avg_nonlinear.', - argstr='-ignore_nonline') + desc='opposite of -avg_nonlinear.', argstr='-ignore_nonline') class XfmAvgOutputSpec(TraitedSpec): @@ -3315,8 +3349,8 @@ def _gen_filename(self, name): if isdefined(output_file): return os.path.abspath(output_file) else: - return aggregate_filename( - self.inputs.input_files, 'xfmavg_output') + '.xfm' + return aggregate_filename(self.inputs.input_files, + 'xfmavg_output') + '.xfm' else: raise NotImplemented @@ -3329,8 +3363,8 @@ def _list_outputs(self): assert os.path.exists(outputs['output_file']) if 'grid' in open(outputs['output_file'], 'r').read(): - outputs['output_grid'] = re.sub( - '.(nlxfm|xfm)$', '_grid_0.mnc', outputs['output_file']) + outputs['output_grid'] = re.sub('.(nlxfm|xfm)$', '_grid_0.mnc', + outputs['output_file']) return outputs @@ -3347,11 +3381,11 @@ class XfmInvertInputSpec(CommandLineInputSpec): desc='output file', genfile=True, argstr='%s', - position=-1,) + position=-1, + ) verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -3389,8 +3423,8 @@ def _gen_filename(self, name): if isdefined(output_file): return os.path.abspath(output_file) else: - return aggregate_filename( - [self.inputs.input_file], 'xfminvert_output') + '.xfm' + return aggregate_filename([self.inputs.input_file], + 'xfminvert_output') + '.xfm' else: raise NotImplemented @@ -3403,8 +3437,8 @@ def _list_outputs(self): assert os.path.exists(outputs['output_file']) if 'grid' in open(outputs['output_file'], 'r').read(): - outputs['output_grid'] = re.sub( - '.(nlxfm|xfm)$', '_grid_0.mnc', outputs['output_file']) + outputs['output_grid'] = re.sub('.(nlxfm|xfm)$', '_grid_0.mnc', + outputs['output_file']) return outputs @@ -3428,8 +3462,7 @@ class BigAverageInputSpec(CommandLineInputSpec): name_template='%s_bigaverage.mnc') verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='--verbose') + desc='Print out log messages. Default: False.', argstr='--verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='--clobber', @@ -3439,8 +3472,7 @@ class BigAverageInputSpec(CommandLineInputSpec): # FIXME Redumentary implementation, various parameters not implemented. # TODO! output_float = traits.Bool( - desc='Output files with float precision.', - argstr='--float') + desc='Output files with float precision.', argstr='--float') robust = traits.Bool( desc=('Perform robust averaging, features that are outside 1 standard' @@ -3520,8 +3552,7 @@ class ReshapeInputSpec(CommandLineInputSpec): name_template='%s_reshape.mnc') verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -3531,8 +3562,7 @@ class ReshapeInputSpec(CommandLineInputSpec): # FIXME MANY options not implemented! write_short = traits.Bool( - desc='Convert to short integer data.', - argstr='-short') + desc='Convert to short integer data.', argstr='-short') class ReshapeOutputSpec(TraitedSpec): @@ -3592,11 +3622,11 @@ class VolSymmInputSpec(CommandLineInputSpec): # This is a dummy input. input_grid_files = InputMultiPath( traits.File, - desc='input grid file(s)',) + desc='input grid file(s)', + ) verbose = traits.Bool( - desc='Print out log messages. Default: False.', - argstr='-verbose') + desc='Print out log messages. Default: False.', argstr='-verbose') clobber = traits.Bool( desc='Overwrite existing file.', argstr='-clobber', @@ -3607,8 +3637,7 @@ class VolSymmInputSpec(CommandLineInputSpec): fit_linear = traits.Bool(desc='Fit using a linear xfm.', argstr='-linear') fit_nonlinear = traits.Bool( - desc='Fit using a non-linear xfm.', - argstr='-nonlinear') + desc='Fit using a non-linear xfm.', argstr='-nonlinear') # FIXME This changes the input/output behaviour of trans_file! Split into # two separate interfaces? @@ -3617,7 +3646,8 @@ class VolSymmInputSpec(CommandLineInputSpec): argstr='-nofit') config_file = File( - desc='File containing the fitting configuration (nlpfit -help for info).', + desc= + 'File containing the fitting configuration (nlpfit -help for info).', argstr='-config_file %s', exists=True) @@ -3629,8 +3659,8 @@ class VolSymmInputSpec(CommandLineInputSpec): class VolSymmOutputSpec(TraitedSpec): output_file = File(desc='output file', exists=True) trans_file = File(desc='xfm trans file', exists=True) - output_grid = File(desc='output grid file', - exists=True) # FIXME Is exists=True correct? + output_grid = File( + desc='output grid file', exists=True) # FIXME Is exists=True correct? class VolSymm(CommandLine): @@ -3664,7 +3694,7 @@ def _list_outputs(self): # Have to manually check for the grid files. if os.path.exists(outputs['trans_file']): if 'grid' in open(outputs['trans_file'], 'r').read(): - outputs['output_grid'] = re.sub( - '.(nlxfm|xfm)$', '_grid_0.mnc', outputs['trans_file']) + outputs['output_grid'] = re.sub('.(nlxfm|xfm)$', '_grid_0.mnc', + outputs['trans_file']) return outputs diff --git a/nipype/interfaces/minc/testdata.py b/nipype/interfaces/minc/testdata.py index c586bd6f99..0a8d6bfd88 100644 --- a/nipype/interfaces/minc/testdata.py +++ b/nipype/interfaces/minc/testdata.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from ...testing import example_data @@ -9,5 +10,9 @@ nlp_config = example_data('minc_nlp.conf') + def nonempty_minc_data(i, shape='2D'): - return example_data('minc_test_%s_%.2d.mnc' % (shape, i,)) + return example_data('minc_test_%s_%.2d.mnc' % ( + shape, + i, + )) diff --git a/nipype/interfaces/minc/tests/test_auto_Average.py b/nipype/interfaces/minc/tests/test_auto_Average.py index b7adb07145..e93fc3fc88 100644 --- a/nipype/interfaces/minc/tests/test_auto_Average.py +++ b/nipype/interfaces/minc/tests/test_auto_Average.py @@ -4,124 +4,156 @@ def test_Average_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - avgdim=dict(argstr='-avgdim %s', - ), - binarize=dict(argstr='-binarize', - ), - binrange=dict(argstr='-binrange %s %s', - ), - binvalue=dict(argstr='-binvalue %s', - ), - check_dimensions=dict(argstr='-check_dimensions', - xor=('check_dimensions', 'no_check_dimensions'), - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - copy_header=dict(argstr='-copy_header', - xor=('copy_header', 'no_copy_header'), - ), - debug=dict(argstr='-debug', - ), - environ=dict(nohash=True, - usedefault=True, - ), - filelist=dict(argstr='-filelist %s', - mandatory=True, - xor=('input_files', 'filelist'), - ), - format_byte=dict(argstr='-byte', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_double=dict(argstr='-double', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_filetype=dict(argstr='-filetype', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_float=dict(argstr='-float', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_int=dict(argstr='-int', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_long=dict(argstr='-long', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_short=dict(argstr='-short', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_signed=dict(argstr='-signed', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_unsigned=dict(argstr='-unsigned', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_files=dict(argstr='%s', - mandatory=True, - position=-2, - sep=' ', - xor=('input_files', 'filelist'), - ), - max_buffer_size_in_kb=dict(argstr='-max_buffer_size_in_kb %d', - ), - no_check_dimensions=dict(argstr='-nocheck_dimensions', - xor=('check_dimensions', 'no_check_dimensions'), - ), - no_copy_header=dict(argstr='-nocopy_header', - xor=('copy_header', 'no_copy_header'), - ), - nonormalize=dict(argstr='-nonormalize', - xor=('normalize', 'nonormalize'), - ), - normalize=dict(argstr='-normalize', - xor=('normalize', 'nonormalize'), - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_files'], - name_template='%s_averaged.mnc', - position=-1, - ), - quiet=dict(argstr='-quiet', - xor=('verbose', 'quiet'), - ), - sdfile=dict(argstr='-sdfile %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - two=dict(argstr='-2', - ), - verbose=dict(argstr='-verbose', - xor=('verbose', 'quiet'), - ), - voxel_range=dict(argstr='-range %d %d', - ), - weights=dict(argstr='-weights %s', - sep=',', - ), - width_weighted=dict(argstr='-width_weighted', - requires=('avgdim',), - ), + input_map = dict( + args=dict(argstr='%s', ), + avgdim=dict(argstr='-avgdim %s', ), + binarize=dict(argstr='-binarize', ), + binrange=dict(argstr='-binrange %s %s', ), + binvalue=dict(argstr='-binvalue %s', ), + check_dimensions=dict( + argstr='-check_dimensions', + xor=('check_dimensions', 'no_check_dimensions'), + ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + copy_header=dict( + argstr='-copy_header', + xor=('copy_header', 'no_copy_header'), + ), + debug=dict(argstr='-debug', ), + environ=dict( + nohash=True, + usedefault=True, + ), + filelist=dict( + argstr='-filelist %s', + mandatory=True, + xor=('input_files', 'filelist'), + ), + format_byte=dict( + argstr='-byte', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_double=dict( + argstr='-double', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_filetype=dict( + argstr='-filetype', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_float=dict( + argstr='-float', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_int=dict( + argstr='-int', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_long=dict( + argstr='-long', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_short=dict( + argstr='-short', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_signed=dict( + argstr='-signed', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_unsigned=dict( + argstr='-unsigned', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_files=dict( + argstr='%s', + mandatory=True, + position=-2, + sep=' ', + xor=('input_files', 'filelist'), + ), + max_buffer_size_in_kb=dict(argstr='-max_buffer_size_in_kb %d', ), + no_check_dimensions=dict( + argstr='-nocheck_dimensions', + xor=('check_dimensions', 'no_check_dimensions'), + ), + no_copy_header=dict( + argstr='-nocopy_header', + xor=('copy_header', 'no_copy_header'), + ), + nonormalize=dict( + argstr='-nonormalize', + xor=('normalize', 'nonormalize'), + ), + normalize=dict( + argstr='-normalize', + xor=('normalize', 'nonormalize'), + ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_files'], + name_template='%s_averaged.mnc', + position=-1, + ), + quiet=dict( + argstr='-quiet', + xor=('verbose', 'quiet'), + ), + sdfile=dict(argstr='-sdfile %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + two=dict(argstr='-2', ), + verbose=dict( + argstr='-verbose', + xor=('verbose', 'quiet'), + ), + voxel_range=dict(argstr='-range %d %d', ), + weights=dict( + argstr='-weights %s', + sep=',', + ), + width_weighted=dict( + argstr='-width_weighted', + requires=('avgdim', ), + ), ) inputs = Average.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Average_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Average.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_BBox.py b/nipype/interfaces/minc/tests/test_auto_BBox.py index b469e57184..bb6b7bc06e 100644 --- a/nipype/interfaces/minc/tests/test_auto_BBox.py +++ b/nipype/interfaces/minc/tests/test_auto_BBox.py @@ -4,57 +4,58 @@ def test_BBox_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - format_minccrop=dict(argstr='-minccrop', - ), - format_mincresample=dict(argstr='-mincresample', - ), - format_mincreshape=dict(argstr='-mincreshape', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - one_line=dict(argstr='-one_line', - xor=('one_line', 'two_lines'), - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - output_file=dict(hash_files=False, - keep_extension=False, - name_source=['input_file'], - name_template='%s_bbox.txt', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='-threshold', - ), - two_lines=dict(argstr='-two_lines', - xor=('one_line', 'two_lines'), - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + format_minccrop=dict(argstr='-minccrop', ), + format_mincresample=dict(argstr='-mincresample', ), + format_mincreshape=dict(argstr='-mincreshape', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + one_line=dict( + argstr='-one_line', + xor=('one_line', 'two_lines'), + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + output_file=dict( + hash_files=False, + keep_extension=False, + name_source=['input_file'], + name_template='%s_bbox.txt', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='-threshold', ), + two_lines=dict( + argstr='-two_lines', + xor=('one_line', 'two_lines'), + ), ) inputs = BBox.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BBox_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = BBox.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Beast.py b/nipype/interfaces/minc/tests/test_auto_Beast.py index 9b24d9cb0b..92f3e4c2d1 100644 --- a/nipype/interfaces/minc/tests/test_auto_Beast.py +++ b/nipype/interfaces/minc/tests/test_auto_Beast.py @@ -4,79 +4,69 @@ def test_Beast_inputs(): - input_map = dict(abspath=dict(argstr='-abspath', - usedefault=True, - ), - args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - confidence_level_alpha=dict(argstr='-alpha %s', - ), - configuration_file=dict(argstr='-configuration %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fill_holes=dict(argstr='-fill', - ), - flip_images=dict(argstr='-flip', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - library_dir=dict(argstr='%s', - mandatory=True, - position=-3, - ), - load_moments=dict(argstr='-load_moments', - ), - median_filter=dict(argstr='-median', - ), - nlm_filter=dict(argstr='-nlm_filter', - ), - number_selected_images=dict(argstr='-selection_num %s', - ), - output_file=dict(argstr='%s', - hash_files=False, - name_source=['input_file'], - name_template='%s_beast_mask.mnc', - position=-1, - ), - patch_size=dict(argstr='-patch_size %s', - ), - probability_map=dict(argstr='-probability', - ), - same_resolution=dict(argstr='-same_resolution', - ), - search_area=dict(argstr='-search_area %s', - ), - smoothness_factor_beta=dict(argstr='-beta %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold_patch_selection=dict(argstr='-threshold %s', - ), - voxel_size=dict(argstr='-voxel_size %s', - ), + input_map = dict( + abspath=dict( + argstr='-abspath', + usedefault=True, + ), + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + confidence_level_alpha=dict(argstr='-alpha %s', ), + configuration_file=dict(argstr='-configuration %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_holes=dict(argstr='-fill', ), + flip_images=dict(argstr='-flip', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + library_dir=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + load_moments=dict(argstr='-load_moments', ), + median_filter=dict(argstr='-median', ), + nlm_filter=dict(argstr='-nlm_filter', ), + number_selected_images=dict(argstr='-selection_num %s', ), + output_file=dict( + argstr='%s', + hash_files=False, + name_source=['input_file'], + name_template='%s_beast_mask.mnc', + position=-1, + ), + patch_size=dict(argstr='-patch_size %s', ), + probability_map=dict(argstr='-probability', ), + same_resolution=dict(argstr='-same_resolution', ), + search_area=dict(argstr='-search_area %s', ), + smoothness_factor_beta=dict(argstr='-beta %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold_patch_selection=dict(argstr='-threshold %s', ), + voxel_size=dict(argstr='-voxel_size %s', ), ) inputs = Beast.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Beast_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Beast.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_BestLinReg.py b/nipype/interfaces/minc/tests/test_auto_BestLinReg.py index 8d9641db16..19c0cd0cb0 100644 --- a/nipype/interfaces/minc/tests/test_auto_BestLinReg.py +++ b/nipype/interfaces/minc/tests/test_auto_BestLinReg.py @@ -4,58 +4,64 @@ def test_BestLinReg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - output_mnc=dict(argstr='%s', - genfile=True, - hash_files=False, - keep_extension=False, - name_source=['source'], - name_template='%s_bestlinreg.mnc', - position=-1, - ), - output_xfm=dict(argstr='%s', - genfile=True, - hash_files=False, - keep_extension=False, - name_source=['source'], - name_template='%s_bestlinreg.xfm', - position=-2, - ), - source=dict(argstr='%s', - mandatory=True, - position=-4, - ), - target=dict(argstr='%s', - mandatory=True, - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + output_mnc=dict( + argstr='%s', + genfile=True, + hash_files=False, + keep_extension=False, + name_source=['source'], + name_template='%s_bestlinreg.mnc', + position=-1, + ), + output_xfm=dict( + argstr='%s', + genfile=True, + hash_files=False, + keep_extension=False, + name_source=['source'], + name_template='%s_bestlinreg.xfm', + position=-2, + ), + source=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + target=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = BestLinReg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BestLinReg_outputs(): - output_map = dict(output_mnc=dict(), - output_xfm=dict(), + output_map = dict( + output_mnc=dict(), + output_xfm=dict(), ) outputs = BestLinReg.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_BigAverage.py b/nipype/interfaces/minc/tests/test_auto_BigAverage.py index f0f4bd20f8..4ba3cbf72f 100644 --- a/nipype/interfaces/minc/tests/test_auto_BigAverage.py +++ b/nipype/interfaces/minc/tests/test_auto_BigAverage.py @@ -4,57 +4,59 @@ def test_BigAverage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='--clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_files=dict(argstr='%s', - mandatory=True, - position=-2, - sep=' ', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_files'], - name_template='%s_bigaverage.mnc', - position=-1, - ), - output_float=dict(argstr='--float', - ), - robust=dict(argstr='-robust', - ), - sd_file=dict(argstr='--sdfile %s', - hash_files=False, - name_source=['input_files'], - name_template='%s_bigaverage_stdev.mnc', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tmpdir=dict(argstr='-tmpdir %s', - ), - verbose=dict(argstr='--verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='--clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_files=dict( + argstr='%s', + mandatory=True, + position=-2, + sep=' ', + ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_files'], + name_template='%s_bigaverage.mnc', + position=-1, + ), + output_float=dict(argstr='--float', ), + robust=dict(argstr='-robust', ), + sd_file=dict( + argstr='--sdfile %s', + hash_files=False, + name_source=['input_files'], + name_template='%s_bigaverage_stdev.mnc', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tmpdir=dict(argstr='-tmpdir %s', ), + verbose=dict(argstr='--verbose', ), ) inputs = BigAverage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BigAverage_outputs(): - output_map = dict(output_file=dict(), - sd_file=dict(), + output_map = dict( + output_file=dict(), + sd_file=dict(), ) outputs = BigAverage.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Blob.py b/nipype/interfaces/minc/tests/test_auto_Blob.py index a0f2d95d40..3a28435e69 100644 --- a/nipype/interfaces/minc/tests/test_auto_Blob.py +++ b/nipype/interfaces/minc/tests/test_auto_Blob.py @@ -4,48 +4,46 @@ def test_Blob_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - determinant=dict(argstr='-determinant', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - magnitude=dict(argstr='-magnitude', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_blob.mnc', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trace=dict(argstr='-trace', - ), - translation=dict(argstr='-translation', - ), + input_map = dict( + args=dict(argstr='%s', ), + determinant=dict(argstr='-determinant', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + magnitude=dict(argstr='-magnitude', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_blob.mnc', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trace=dict(argstr='-trace', ), + translation=dict(argstr='-translation', ), ) inputs = Blob.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Blob_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Blob.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Blur.py b/nipype/interfaces/minc/tests/test_auto_Blur.py index e50f0f0b47..7d55ce9903 100644 --- a/nipype/interfaces/minc/tests/test_auto_Blur.py +++ b/nipype/interfaces/minc/tests/test_auto_Blur.py @@ -4,69 +4,75 @@ def test_Blur_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - dimensions=dict(argstr='-dimensions %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm=dict(argstr='-fwhm %s', - mandatory=True, - xor=('fwhm', 'fwhm3d', 'standard_dev'), - ), - fwhm3d=dict(argstr='-3dfwhm %s %s %s', - mandatory=True, - xor=('fwhm', 'fwhm3d', 'standard_dev'), - ), - gaussian=dict(argstr='-gaussian', - xor=('gaussian', 'rect'), - ), - gradient=dict(argstr='-gradient', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - no_apodize=dict(argstr='-no_apodize', - ), - output_file_base=dict(argstr='%s', - position=-1, - ), - partial=dict(argstr='-partial', - ), - rect=dict(argstr='-rect', - xor=('gaussian', 'rect'), - ), - standard_dev=dict(argstr='-standarddev %s', - mandatory=True, - xor=('fwhm', 'fwhm3d', 'standard_dev'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + dimensions=dict(argstr='-dimensions %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr='-fwhm %s', + mandatory=True, + xor=('fwhm', 'fwhm3d', 'standard_dev'), + ), + fwhm3d=dict( + argstr='-3dfwhm %s %s %s', + mandatory=True, + xor=('fwhm', 'fwhm3d', 'standard_dev'), + ), + gaussian=dict( + argstr='-gaussian', + xor=('gaussian', 'rect'), + ), + gradient=dict(argstr='-gradient', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + no_apodize=dict(argstr='-no_apodize', ), + output_file_base=dict( + argstr='%s', + position=-1, + ), + partial=dict(argstr='-partial', ), + rect=dict( + argstr='-rect', + xor=('gaussian', 'rect'), + ), + standard_dev=dict( + argstr='-standarddev %s', + mandatory=True, + xor=('fwhm', 'fwhm3d', 'standard_dev'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Blur.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Blur_outputs(): - output_map = dict(gradient_dxyz=dict(), - output_file=dict(), - partial_dx=dict(), - partial_dxyz=dict(), - partial_dy=dict(), - partial_dz=dict(), + output_map = dict( + gradient_dxyz=dict(), + output_file=dict(), + partial_dx=dict(), + partial_dxyz=dict(), + partial_dy=dict(), + partial_dz=dict(), ) outputs = Blur.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Calc.py b/nipype/interfaces/minc/tests/test_auto_Calc.py index 1e690a1468..eee80e97d5 100644 --- a/nipype/interfaces/minc/tests/test_auto_Calc.py +++ b/nipype/interfaces/minc/tests/test_auto_Calc.py @@ -4,127 +4,166 @@ def test_Calc_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - check_dimensions=dict(argstr='-check_dimensions', - xor=('check_dimensions', 'no_check_dimensions'), - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - copy_header=dict(argstr='-copy_header', - xor=('copy_header', 'no_copy_header'), - ), - debug=dict(argstr='-debug', - ), - environ=dict(nohash=True, - usedefault=True, - ), - eval_width=dict(argstr='-eval_width %s', - usedefault=False, - ), - expfile=dict(argstr='-expfile %s', - mandatory=True, - xor=('expression', 'expfile'), - ), - expression=dict(argstr="-expression '%s'", - mandatory=True, - xor=('expression', 'expfile'), - ), - filelist=dict(argstr='-filelist %s', - mandatory=True, - xor=('input_files', 'filelist'), - ), - format_byte=dict(argstr='-byte', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_double=dict(argstr='-double', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_filetype=dict(argstr='-filetype', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_float=dict(argstr='-float', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_int=dict(argstr='-int', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_long=dict(argstr='-long', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_short=dict(argstr='-short', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_signed=dict(argstr='-signed', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_unsigned=dict(argstr='-unsigned', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_nan=dict(argstr='-ignore_nan', - ), - input_files=dict(argstr='%s', - mandatory=True, - position=-2, - sep=' ', - ), - max_buffer_size_in_kb=dict(argstr='-max_buffer_size_in_kb %d', - usedefault=False, - ), - no_check_dimensions=dict(argstr='-nocheck_dimensions', - xor=('check_dimensions', 'no_check_dimensions'), - ), - no_copy_header=dict(argstr='-nocopy_header', - xor=('copy_header', 'no_copy_header'), - ), - outfiles=dict(), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_files'], - name_template='%s_calc.mnc', - position=-1, - ), - output_illegal=dict(argstr='-illegal_value', - xor=('output_nan', 'output_zero', 'output_illegal_value'), - ), - output_nan=dict(argstr='-nan', - xor=('output_nan', 'output_zero', 'output_illegal_value'), - ), - output_zero=dict(argstr='-zero', - xor=('output_nan', 'output_zero', 'output_illegal_value'), - ), - propagate_nan=dict(argstr='-propagate_nan', - ), - quiet=dict(argstr='-quiet', - xor=('verbose', 'quiet'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - two=dict(argstr='-2', - ), - verbose=dict(argstr='-verbose', - xor=('verbose', 'quiet'), - ), - voxel_range=dict(argstr='-range %d %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + check_dimensions=dict( + argstr='-check_dimensions', + xor=('check_dimensions', 'no_check_dimensions'), + ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + copy_header=dict( + argstr='-copy_header', + xor=('copy_header', 'no_copy_header'), + ), + debug=dict(argstr='-debug', ), + environ=dict( + nohash=True, + usedefault=True, + ), + eval_width=dict( + argstr='-eval_width %s', + usedefault=False, + ), + expfile=dict( + argstr='-expfile %s', + mandatory=True, + xor=('expression', 'expfile'), + ), + expression=dict( + argstr="-expression '%s'", + mandatory=True, + xor=('expression', 'expfile'), + ), + filelist=dict( + argstr='-filelist %s', + mandatory=True, + xor=('input_files', 'filelist'), + ), + format_byte=dict( + argstr='-byte', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_double=dict( + argstr='-double', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_filetype=dict( + argstr='-filetype', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_float=dict( + argstr='-float', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_int=dict( + argstr='-int', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_long=dict( + argstr='-long', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_short=dict( + argstr='-short', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_signed=dict( + argstr='-signed', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_unsigned=dict( + argstr='-unsigned', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_nan=dict(argstr='-ignore_nan', ), + input_files=dict( + argstr='%s', + mandatory=True, + position=-2, + sep=' ', + ), + max_buffer_size_in_kb=dict( + argstr='-max_buffer_size_in_kb %d', + usedefault=False, + ), + no_check_dimensions=dict( + argstr='-nocheck_dimensions', + xor=('check_dimensions', 'no_check_dimensions'), + ), + no_copy_header=dict( + argstr='-nocopy_header', + xor=('copy_header', 'no_copy_header'), + ), + outfiles=dict(), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_files'], + name_template='%s_calc.mnc', + position=-1, + ), + output_illegal=dict( + argstr='-illegal_value', + xor=('output_nan', 'output_zero', 'output_illegal_value'), + ), + output_nan=dict( + argstr='-nan', + xor=('output_nan', 'output_zero', 'output_illegal_value'), + ), + output_zero=dict( + argstr='-zero', + xor=('output_nan', 'output_zero', 'output_illegal_value'), + ), + propagate_nan=dict(argstr='-propagate_nan', ), + quiet=dict( + argstr='-quiet', + xor=('verbose', 'quiet'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + two=dict(argstr='-2', ), + verbose=dict( + argstr='-verbose', + xor=('verbose', 'quiet'), + ), + voxel_range=dict(argstr='-range %d %d', ), ) inputs = Calc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Calc_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Calc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Convert.py b/nipype/interfaces/minc/tests/test_auto_Convert.py index 6df129aee4..8d827acb28 100644 --- a/nipype/interfaces/minc/tests/test_auto_Convert.py +++ b/nipype/interfaces/minc/tests/test_auto_Convert.py @@ -4,52 +4,53 @@ def test_Convert_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - chunk=dict(argstr='-chunk %d', - usedefault=False, - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - compression=dict(argstr='-compress %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_convert_output.mnc', - position=-1, - ), - template=dict(argstr='-template', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - two=dict(argstr='-2', - ), + input_map = dict( + args=dict(argstr='%s', ), + chunk=dict( + argstr='-chunk %d', + usedefault=False, + ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + compression=dict(argstr='-compress %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_convert_output.mnc', + position=-1, + ), + template=dict(argstr='-template', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + two=dict(argstr='-2', ), ) inputs = Convert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Convert_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Convert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Copy.py b/nipype/interfaces/minc/tests/test_auto_Copy.py index 73662e9b88..d0079de888 100644 --- a/nipype/interfaces/minc/tests/test_auto_Copy.py +++ b/nipype/interfaces/minc/tests/test_auto_Copy.py @@ -4,46 +4,50 @@ def test_Copy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_copy.mnc', - position=-1, - ), - pixel_values=dict(argstr='-pixel_values', - xor=('pixel_values', 'real_values'), - ), - real_values=dict(argstr='-real_values', - xor=('pixel_values', 'real_values'), - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_copy.mnc', + position=-1, + ), + pixel_values=dict( + argstr='-pixel_values', + xor=('pixel_values', 'real_values'), + ), + real_values=dict( + argstr='-real_values', + xor=('pixel_values', 'real_values'), + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Copy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Copy_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Copy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Dump.py b/nipype/interfaces/minc/tests/test_auto_Dump.py index 2e9ab091b4..ff2237f58a 100644 --- a/nipype/interfaces/minc/tests/test_auto_Dump.py +++ b/nipype/interfaces/minc/tests/test_auto_Dump.py @@ -4,65 +4,72 @@ def test_Dump_inputs(): - input_map = dict(annotations_brief=dict(argstr='-b %s', - xor=('annotations_brief', 'annotations_full'), - ), - annotations_full=dict(argstr='-f %s', - xor=('annotations_brief', 'annotations_full'), - ), - args=dict(argstr='%s', - ), - coordinate_data=dict(argstr='-c', - xor=('coordinate_data', 'header_data'), - ), - environ=dict(nohash=True, - usedefault=True, - ), - header_data=dict(argstr='-h', - xor=('coordinate_data', 'header_data'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - line_length=dict(argstr='-l %d', - usedefault=False, - ), - netcdf_name=dict(argstr='-n %s', - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - output_file=dict(hash_files=False, - keep_extension=False, - name_source=['input_file'], - name_template='%s_dump.txt', - position=-1, - ), - precision=dict(argstr='%s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - variables=dict(argstr='-v %s', - sep=',', - ), + input_map = dict( + annotations_brief=dict( + argstr='-b %s', + xor=('annotations_brief', 'annotations_full'), + ), + annotations_full=dict( + argstr='-f %s', + xor=('annotations_brief', 'annotations_full'), + ), + args=dict(argstr='%s', ), + coordinate_data=dict( + argstr='-c', + xor=('coordinate_data', 'header_data'), + ), + environ=dict( + nohash=True, + usedefault=True, + ), + header_data=dict( + argstr='-h', + xor=('coordinate_data', 'header_data'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + line_length=dict( + argstr='-l %d', + usedefault=False, + ), + netcdf_name=dict(argstr='-n %s', ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + output_file=dict( + hash_files=False, + keep_extension=False, + name_source=['input_file'], + name_template='%s_dump.txt', + position=-1, + ), + precision=dict(argstr='%s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + variables=dict( + argstr='-v %s', + sep=',', + ), ) inputs = Dump.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Dump_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Dump.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Extract.py b/nipype/interfaces/minc/tests/test_auto_Extract.py index 0df7132519..80b81fdb2b 100644 --- a/nipype/interfaces/minc/tests/test_auto_Extract.py +++ b/nipype/interfaces/minc/tests/test_auto_Extract.py @@ -4,126 +4,167 @@ def test_Extract_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - count=dict(argstr='-count %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - flip_any_direction=dict(argstr='-any_direction', - xor=('flip_positive_direction', 'flip_negative_direction', 'flip_any_direction'), - ), - flip_negative_direction=dict(argstr='-negative_direction', - xor=('flip_positive_direction', 'flip_negative_direction', 'flip_any_direction'), - ), - flip_positive_direction=dict(argstr='-positive_direction', - xor=('flip_positive_direction', 'flip_negative_direction', 'flip_any_direction'), - ), - flip_x_any=dict(argstr='-xanydirection', - xor=('flip_x_positive', 'flip_x_negative', 'flip_x_any'), - ), - flip_x_negative=dict(argstr='-xdirection', - xor=('flip_x_positive', 'flip_x_negative', 'flip_x_any'), - ), - flip_x_positive=dict(argstr='+xdirection', - xor=('flip_x_positive', 'flip_x_negative', 'flip_x_any'), - ), - flip_y_any=dict(argstr='-yanydirection', - xor=('flip_y_positive', 'flip_y_negative', 'flip_y_any'), - ), - flip_y_negative=dict(argstr='-ydirection', - xor=('flip_y_positive', 'flip_y_negative', 'flip_y_any'), - ), - flip_y_positive=dict(argstr='+ydirection', - xor=('flip_y_positive', 'flip_y_negative', 'flip_y_any'), - ), - flip_z_any=dict(argstr='-zanydirection', - xor=('flip_z_positive', 'flip_z_negative', 'flip_z_any'), - ), - flip_z_negative=dict(argstr='-zdirection', - xor=('flip_z_positive', 'flip_z_negative', 'flip_z_any'), - ), - flip_z_positive=dict(argstr='+zdirection', - xor=('flip_z_positive', 'flip_z_negative', 'flip_z_any'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_maximum=dict(argstr='-image_maximum %s', - ), - image_minimum=dict(argstr='-image_minimum %s', - ), - image_range=dict(argstr='-image_range %s %s', - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - nonormalize=dict(argstr='-nonormalize', - xor=('normalize', 'nonormalize'), - ), - normalize=dict(argstr='-normalize', - xor=('normalize', 'nonormalize'), - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - output_file=dict(hash_files=False, - keep_extension=False, - name_source=['input_file'], - name_template='%s.raw', - position=-1, - ), - start=dict(argstr='-start %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - write_ascii=dict(argstr='-ascii', - xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double', 'write_signed', 'write_unsigned'), - ), - write_byte=dict(argstr='-byte', - xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double', 'write_signed', 'write_unsigned'), - ), - write_double=dict(argstr='-double', - xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double', 'write_signed', 'write_unsigned'), - ), - write_float=dict(argstr='-float', - xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double', 'write_signed', 'write_unsigned'), - ), - write_int=dict(argstr='-int', - xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double', 'write_signed', 'write_unsigned'), - ), - write_long=dict(argstr='-long', - xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double', 'write_signed', 'write_unsigned'), - ), - write_range=dict(argstr='-range %s %s', - ), - write_short=dict(argstr='-short', - xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double', 'write_signed', 'write_unsigned'), - ), - write_signed=dict(argstr='-signed', - xor=('write_signed', 'write_unsigned'), - ), - write_unsigned=dict(argstr='-unsigned', - xor=('write_signed', 'write_unsigned'), - ), + input_map = dict( + args=dict(argstr='%s', ), + count=dict( + argstr='-count %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip_any_direction=dict( + argstr='-any_direction', + xor=('flip_positive_direction', 'flip_negative_direction', + 'flip_any_direction'), + ), + flip_negative_direction=dict( + argstr='-negative_direction', + xor=('flip_positive_direction', 'flip_negative_direction', + 'flip_any_direction'), + ), + flip_positive_direction=dict( + argstr='-positive_direction', + xor=('flip_positive_direction', 'flip_negative_direction', + 'flip_any_direction'), + ), + flip_x_any=dict( + argstr='-xanydirection', + xor=('flip_x_positive', 'flip_x_negative', 'flip_x_any'), + ), + flip_x_negative=dict( + argstr='-xdirection', + xor=('flip_x_positive', 'flip_x_negative', 'flip_x_any'), + ), + flip_x_positive=dict( + argstr='+xdirection', + xor=('flip_x_positive', 'flip_x_negative', 'flip_x_any'), + ), + flip_y_any=dict( + argstr='-yanydirection', + xor=('flip_y_positive', 'flip_y_negative', 'flip_y_any'), + ), + flip_y_negative=dict( + argstr='-ydirection', + xor=('flip_y_positive', 'flip_y_negative', 'flip_y_any'), + ), + flip_y_positive=dict( + argstr='+ydirection', + xor=('flip_y_positive', 'flip_y_negative', 'flip_y_any'), + ), + flip_z_any=dict( + argstr='-zanydirection', + xor=('flip_z_positive', 'flip_z_negative', 'flip_z_any'), + ), + flip_z_negative=dict( + argstr='-zdirection', + xor=('flip_z_positive', 'flip_z_negative', 'flip_z_any'), + ), + flip_z_positive=dict( + argstr='+zdirection', + xor=('flip_z_positive', 'flip_z_negative', 'flip_z_any'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_maximum=dict(argstr='-image_maximum %s', ), + image_minimum=dict(argstr='-image_minimum %s', ), + image_range=dict(argstr='-image_range %s %s', ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + nonormalize=dict( + argstr='-nonormalize', + xor=('normalize', 'nonormalize'), + ), + normalize=dict( + argstr='-normalize', + xor=('normalize', 'nonormalize'), + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + output_file=dict( + hash_files=False, + keep_extension=False, + name_source=['input_file'], + name_template='%s.raw', + position=-1, + ), + start=dict( + argstr='-start %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + write_ascii=dict( + argstr='-ascii', + xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', + 'write_int', 'write_long', 'write_float', 'write_double', + 'write_signed', 'write_unsigned'), + ), + write_byte=dict( + argstr='-byte', + xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', + 'write_int', 'write_long', 'write_float', 'write_double', + 'write_signed', 'write_unsigned'), + ), + write_double=dict( + argstr='-double', + xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', + 'write_int', 'write_long', 'write_float', 'write_double', + 'write_signed', 'write_unsigned'), + ), + write_float=dict( + argstr='-float', + xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', + 'write_int', 'write_long', 'write_float', 'write_double', + 'write_signed', 'write_unsigned'), + ), + write_int=dict( + argstr='-int', + xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', + 'write_int', 'write_long', 'write_float', 'write_double', + 'write_signed', 'write_unsigned'), + ), + write_long=dict( + argstr='-long', + xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', + 'write_int', 'write_long', 'write_float', 'write_double', + 'write_signed', 'write_unsigned'), + ), + write_range=dict(argstr='-range %s %s', ), + write_short=dict( + argstr='-short', + xor=('write_ascii', 'write_ascii', 'write_byte', 'write_short', + 'write_int', 'write_long', 'write_float', 'write_double', + 'write_signed', 'write_unsigned'), + ), + write_signed=dict( + argstr='-signed', + xor=('write_signed', 'write_unsigned'), + ), + write_unsigned=dict( + argstr='-unsigned', + xor=('write_signed', 'write_unsigned'), + ), ) inputs = Extract.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Extract_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Extract.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py b/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py index e09dc43c73..a1909e2fe0 100644 --- a/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py +++ b/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py @@ -4,47 +4,47 @@ def test_Gennlxfm_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ident=dict(argstr='-ident', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - like=dict(argstr='-like %s', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['like'], - name_template='%s_gennlxfm.xfm', - position=-1, - ), - step=dict(argstr='-step %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ident=dict(argstr='-ident', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + like=dict(argstr='-like %s', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['like'], + name_template='%s_gennlxfm.xfm', + position=-1, + ), + step=dict(argstr='-step %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = Gennlxfm.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Gennlxfm_outputs(): - output_map = dict(output_file=dict(), - output_grid=dict(), + output_map = dict( + output_file=dict(), + output_grid=dict(), ) outputs = Gennlxfm.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Math.py b/nipype/interfaces/minc/tests/test_auto_Math.py index 33946b7e44..c5215e80b7 100644 --- a/nipype/interfaces/minc/tests/test_auto_Math.py +++ b/nipype/interfaces/minc/tests/test_auto_Math.py @@ -4,167 +4,170 @@ def test_Math_inputs(): - input_map = dict(abs=dict(argstr='-abs', - ), - args=dict(argstr='%s', - ), - calc_add=dict(argstr='-add', - ), - calc_and=dict(argstr='-and', - ), - calc_div=dict(argstr='-div', - ), - calc_mul=dict(argstr='-mult', - ), - calc_not=dict(argstr='-not', - ), - calc_or=dict(argstr='-or', - ), - calc_sub=dict(argstr='-sub', - ), - check_dimensions=dict(argstr='-check_dimensions', - xor=('check_dimensions', 'no_check_dimensions'), - ), - clamp=dict(argstr='-clamp -const2 %s %s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - copy_header=dict(argstr='-copy_header', - xor=('copy_header', 'no_copy_header'), - ), - count_valid=dict(argstr='-count_valid', - ), - dimension=dict(argstr='-dimension %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - exp=dict(argstr='-exp -const2 %s %s', - ), - filelist=dict(argstr='-filelist %s', - mandatory=True, - xor=('input_files', 'filelist'), - ), - format_byte=dict(argstr='-byte', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_double=dict(argstr='-double', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_filetype=dict(argstr='-filetype', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_float=dict(argstr='-float', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_int=dict(argstr='-int', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_long=dict(argstr='-long', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_short=dict(argstr='-short', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_signed=dict(argstr='-signed', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_unsigned=dict(argstr='-unsigned', - xor=('format_filetype', 'format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_nan=dict(argstr='-ignore_nan', - ), - input_files=dict(argstr='%s', - mandatory=True, - position=-2, - sep=' ', - xor=('input_files', 'filelist'), - ), - invert=dict(argstr='-invert -const %s', - ), - isnan=dict(argstr='-isnan', - ), - log=dict(argstr='-log -const2 %s %s', - ), - max_buffer_size_in_kb=dict(argstr='-max_buffer_size_in_kb %d', - ), - maximum=dict(argstr='-maximum', - ), - minimum=dict(argstr='-minimum', - ), - nisnan=dict(argstr='-nisnan', - ), - no_check_dimensions=dict(argstr='-nocheck_dimensions', - xor=('check_dimensions', 'no_check_dimensions'), - ), - no_copy_header=dict(argstr='-nocopy_header', - xor=('copy_header', 'no_copy_header'), - ), - nsegment=dict(argstr='-nsegment -const2 %s %s', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_files'], - name_template='%s_mincmath.mnc', - position=-1, - ), - output_illegal=dict(argstr='-illegal_value', - xor=('output_nan', 'output_zero', 'output_illegal_value'), - ), - output_nan=dict(argstr='-nan', - xor=('output_nan', 'output_zero', 'output_illegal_value'), - ), - output_zero=dict(argstr='-zero', - xor=('output_nan', 'output_zero', 'output_illegal_value'), - ), - percentdiff=dict(argstr='-percentdiff', - ), - propagate_nan=dict(argstr='-propagate_nan', - ), - scale=dict(argstr='-scale -const2 %s %s', - ), - segment=dict(argstr='-segment -const2 %s %s', - ), - sqrt=dict(argstr='-sqrt', - ), - square=dict(argstr='-square', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - test_eq=dict(argstr='-eq', - ), - test_ge=dict(argstr='-ge', - ), - test_gt=dict(argstr='-gt', - ), - test_le=dict(argstr='-le', - ), - test_lt=dict(argstr='-lt', - ), - test_ne=dict(argstr='-ne', - ), - two=dict(argstr='-2', - ), - voxel_range=dict(argstr='-range %d %d', - ), + input_map = dict( + abs=dict(argstr='-abs', ), + args=dict(argstr='%s', ), + calc_add=dict(argstr='-add', ), + calc_and=dict(argstr='-and', ), + calc_div=dict(argstr='-div', ), + calc_mul=dict(argstr='-mult', ), + calc_not=dict(argstr='-not', ), + calc_or=dict(argstr='-or', ), + calc_sub=dict(argstr='-sub', ), + check_dimensions=dict( + argstr='-check_dimensions', + xor=('check_dimensions', 'no_check_dimensions'), + ), + clamp=dict(argstr='-clamp -const2 %s %s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + copy_header=dict( + argstr='-copy_header', + xor=('copy_header', 'no_copy_header'), + ), + count_valid=dict(argstr='-count_valid', ), + dimension=dict(argstr='-dimension %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + exp=dict(argstr='-exp -const2 %s %s', ), + filelist=dict( + argstr='-filelist %s', + mandatory=True, + xor=('input_files', 'filelist'), + ), + format_byte=dict( + argstr='-byte', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_double=dict( + argstr='-double', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_filetype=dict( + argstr='-filetype', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_float=dict( + argstr='-float', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_int=dict( + argstr='-int', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_long=dict( + argstr='-long', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_short=dict( + argstr='-short', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_signed=dict( + argstr='-signed', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + format_unsigned=dict( + argstr='-unsigned', + xor=('format_filetype', 'format_byte', 'format_short', + 'format_int', 'format_long', 'format_float', 'format_double', + 'format_signed', 'format_unsigned'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_nan=dict(argstr='-ignore_nan', ), + input_files=dict( + argstr='%s', + mandatory=True, + position=-2, + sep=' ', + xor=('input_files', 'filelist'), + ), + invert=dict(argstr='-invert -const %s', ), + isnan=dict(argstr='-isnan', ), + log=dict(argstr='-log -const2 %s %s', ), + max_buffer_size_in_kb=dict(argstr='-max_buffer_size_in_kb %d', ), + maximum=dict(argstr='-maximum', ), + minimum=dict(argstr='-minimum', ), + nisnan=dict(argstr='-nisnan', ), + no_check_dimensions=dict( + argstr='-nocheck_dimensions', + xor=('check_dimensions', 'no_check_dimensions'), + ), + no_copy_header=dict( + argstr='-nocopy_header', + xor=('copy_header', 'no_copy_header'), + ), + nsegment=dict(argstr='-nsegment -const2 %s %s', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_files'], + name_template='%s_mincmath.mnc', + position=-1, + ), + output_illegal=dict( + argstr='-illegal_value', + xor=('output_nan', 'output_zero', 'output_illegal_value'), + ), + output_nan=dict( + argstr='-nan', + xor=('output_nan', 'output_zero', 'output_illegal_value'), + ), + output_zero=dict( + argstr='-zero', + xor=('output_nan', 'output_zero', 'output_illegal_value'), + ), + percentdiff=dict(argstr='-percentdiff', ), + propagate_nan=dict(argstr='-propagate_nan', ), + scale=dict(argstr='-scale -const2 %s %s', ), + segment=dict(argstr='-segment -const2 %s %s', ), + sqrt=dict(argstr='-sqrt', ), + square=dict(argstr='-square', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + test_eq=dict(argstr='-eq', ), + test_ge=dict(argstr='-ge', ), + test_gt=dict(argstr='-gt', ), + test_le=dict(argstr='-le', ), + test_lt=dict(argstr='-lt', ), + test_ne=dict(argstr='-ne', ), + two=dict(argstr='-2', ), + voxel_range=dict(argstr='-range %d %d', ), ) inputs = Math.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Math_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Math.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_NlpFit.py b/nipype/interfaces/minc/tests/test_auto_NlpFit.py index 905c4b9080..990b9dfe82 100644 --- a/nipype/interfaces/minc/tests/test_auto_NlpFit.py +++ b/nipype/interfaces/minc/tests/test_auto_NlpFit.py @@ -4,56 +4,64 @@ def test_NlpFit_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - config_file=dict(argstr='-config_file %s', - mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - init_xfm=dict(argstr='-init_xfm %s', - mandatory=True, - ), - input_grid_files=dict(), - output_xfm=dict(argstr='%s', - genfile=True, - position=-1, - ), - source=dict(argstr='%s', - mandatory=True, - position=-3, - ), - source_mask=dict(argstr='-source_mask %s', - mandatory=True, - ), - target=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + config_file=dict( + argstr='-config_file %s', + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + init_xfm=dict( + argstr='-init_xfm %s', + mandatory=True, + ), + input_grid_files=dict(), + output_xfm=dict( + argstr='%s', + genfile=True, + position=-1, + ), + source=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + source_mask=dict( + argstr='-source_mask %s', + mandatory=True, + ), + target=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = NlpFit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NlpFit_outputs(): - output_map = dict(output_grid=dict(), - output_xfm=dict(), + output_map = dict( + output_grid=dict(), + output_xfm=dict(), ) outputs = NlpFit.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Norm.py b/nipype/interfaces/minc/tests/test_auto_Norm.py index ca19629e3a..15f47b16ad 100644 --- a/nipype/interfaces/minc/tests/test_auto_Norm.py +++ b/nipype/interfaces/minc/tests/test_auto_Norm.py @@ -4,71 +4,68 @@ def test_Norm_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clamp=dict(argstr='-clamp', - usedefault=True, - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - cutoff=dict(argstr='-cutoff %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - lower=dict(argstr='-lower %s', - ), - mask=dict(argstr='-mask %s', - ), - out_ceil=dict(argstr='-out_ceil %s', - ), - out_floor=dict(argstr='-out_floor %s', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_norm.mnc', - position=-1, - ), - output_threshold_mask=dict(argstr='-threshold_mask %s', - hash_files=False, - name_source=['input_file'], - name_template='%s_norm_threshold_mask.mnc', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='-threshold', - ), - threshold_blur=dict(argstr='-threshold_blur %s', - ), - threshold_bmt=dict(argstr='-threshold_bmt', - ), - threshold_perc=dict(argstr='-threshold_perc %s', - ), - upper=dict(argstr='-upper %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + clamp=dict( + argstr='-clamp', + usedefault=True, + ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + cutoff=dict(argstr='-cutoff %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + lower=dict(argstr='-lower %s', ), + mask=dict(argstr='-mask %s', ), + out_ceil=dict(argstr='-out_ceil %s', ), + out_floor=dict(argstr='-out_floor %s', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_norm.mnc', + position=-1, + ), + output_threshold_mask=dict( + argstr='-threshold_mask %s', + hash_files=False, + name_source=['input_file'], + name_template='%s_norm_threshold_mask.mnc', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='-threshold', ), + threshold_blur=dict(argstr='-threshold_blur %s', ), + threshold_bmt=dict(argstr='-threshold_bmt', ), + threshold_perc=dict(argstr='-threshold_perc %s', ), + upper=dict(argstr='-upper %s', ), ) inputs = Norm.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Norm_outputs(): - output_map = dict(output_file=dict(), - output_threshold_mask=dict(), + output_map = dict( + output_file=dict(), + output_threshold_mask=dict(), ) outputs = Norm.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Pik.py b/nipype/interfaces/minc/tests/test_auto_Pik.py index 1e0b92fb35..a822fb0574 100644 --- a/nipype/interfaces/minc/tests/test_auto_Pik.py +++ b/nipype/interfaces/minc/tests/test_auto_Pik.py @@ -4,96 +4,93 @@ def test_Pik_inputs(): - input_map = dict(annotated_bar=dict(argstr='--anot_bar', - ), - args=dict(argstr='%s', - ), - auto_range=dict(argstr='--auto_range', - xor=('image_range', 'auto_range'), - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - depth=dict(argstr='--depth %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - horizontal_triplanar_view=dict(argstr='--horizontal', - xor=('vertical_triplanar_view', 'horizontal_triplanar_view'), - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_range=dict(argstr='--image_range %s %s', - xor=('image_range', 'auto_range'), - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - jpg=dict(xor=('jpg', 'png'), - ), - lookup=dict(argstr='--lookup %s', - ), - minc_range=dict(argstr='--range %s %s', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - keep_extension=False, - name_source=['input_file'], - name_template='%s.png', - position=-1, - ), - png=dict(xor=('jpg', 'png'), - ), - sagittal_offset=dict(argstr='--sagittal_offset %s', - ), - sagittal_offset_perc=dict(argstr='--sagittal_offset_perc %d', - ), - scale=dict(argstr='--scale %s', - ), - slice_x=dict(argstr='-x', - xor=('slice_z', 'slice_y', 'slice_x'), - ), - slice_y=dict(argstr='-y', - xor=('slice_z', 'slice_y', 'slice_x'), - ), - slice_z=dict(argstr='-z', - xor=('slice_z', 'slice_y', 'slice_x'), - ), - start=dict(argstr='--slice %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tile_size=dict(argstr='--tilesize %s', - ), - title=dict(argstr='%s', - ), - title_size=dict(argstr='--title_size %s', - requires=['title'], - ), - triplanar=dict(argstr='--triplanar', - ), - vertical_triplanar_view=dict(argstr='--vertical', - xor=('vertical_triplanar_view', 'horizontal_triplanar_view'), - ), - width=dict(argstr='--width %s', - ), + input_map = dict( + annotated_bar=dict(argstr='--anot_bar', ), + args=dict(argstr='%s', ), + auto_range=dict( + argstr='--auto_range', + xor=('image_range', 'auto_range'), + ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + depth=dict(argstr='--depth %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + horizontal_triplanar_view=dict( + argstr='--horizontal', + xor=('vertical_triplanar_view', 'horizontal_triplanar_view'), + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_range=dict( + argstr='--image_range %s %s', + xor=('image_range', 'auto_range'), + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + jpg=dict(xor=('jpg', 'png'), ), + lookup=dict(argstr='--lookup %s', ), + minc_range=dict(argstr='--range %s %s', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + keep_extension=False, + name_source=['input_file'], + name_template='%s.png', + position=-1, + ), + png=dict(xor=('jpg', 'png'), ), + sagittal_offset=dict(argstr='--sagittal_offset %s', ), + sagittal_offset_perc=dict(argstr='--sagittal_offset_perc %d', ), + scale=dict(argstr='--scale %s', ), + slice_x=dict( + argstr='-x', + xor=('slice_z', 'slice_y', 'slice_x'), + ), + slice_y=dict( + argstr='-y', + xor=('slice_z', 'slice_y', 'slice_x'), + ), + slice_z=dict( + argstr='-z', + xor=('slice_z', 'slice_y', 'slice_x'), + ), + start=dict(argstr='--slice %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tile_size=dict(argstr='--tilesize %s', ), + title=dict(argstr='%s', ), + title_size=dict( + argstr='--title_size %s', + requires=['title'], + ), + triplanar=dict(argstr='--triplanar', ), + vertical_triplanar_view=dict( + argstr='--vertical', + xor=('vertical_triplanar_view', 'horizontal_triplanar_view'), + ), + width=dict(argstr='--width %s', ), ) inputs = Pik.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Pik_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Pik.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Resample.py b/nipype/interfaces/minc/tests/test_auto_Resample.py index f11c11daf0..abce0a6c79 100644 --- a/nipype/interfaces/minc/tests/test_auto_Resample.py +++ b/nipype/interfaces/minc/tests/test_auto_Resample.py @@ -4,201 +4,255 @@ def test_Resample_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - coronal_slices=dict(argstr='-coronal', - xor=('transverse', 'sagittal', 'coronal'), - ), - dircos=dict(argstr='-dircos %s %s %s', - xor=('nelements', 'nelements_x_y_or_z'), - ), - environ=dict(nohash=True, - usedefault=True, - ), - fill=dict(argstr='-fill', - xor=('nofill', 'fill'), - ), - fill_value=dict(argstr='-fillvalue %s', - requires=['fill'], - ), - format_byte=dict(argstr='-byte', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_double=dict(argstr='-double', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_float=dict(argstr='-float', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_int=dict(argstr='-int', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_long=dict(argstr='-long', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_short=dict(argstr='-short', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_signed=dict(argstr='-signed', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - format_unsigned=dict(argstr='-unsigned', - xor=('format_byte', 'format_short', 'format_int', 'format_long', 'format_float', 'format_double', 'format_signed', 'format_unsigned'), - ), - half_width_sinc_window=dict(argstr='-width %s', - requires=['sinc_interpolation'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - input_grid_files=dict(), - invert_transformation=dict(argstr='-invert_transformation', - ), - keep_real_range=dict(argstr='-keep_real_range', - xor=('keep_real_range', 'nokeep_real_range'), - ), - like=dict(argstr='-like %s', - ), - nearest_neighbour_interpolation=dict(argstr='-nearest_neighbour', - xor=('trilinear_interpolation', 'tricubic_interpolation', 'nearest_neighbour_interpolation', 'sinc_interpolation'), - ), - nelements=dict(argstr='-nelements %s %s %s', - xor=('nelements', 'nelements_x_y_or_z'), - ), - no_fill=dict(argstr='-nofill', - xor=('nofill', 'fill'), - ), - no_input_sampling=dict(argstr='-use_input_sampling', - xor=('vio_transform', 'no_input_sampling'), - ), - nokeep_real_range=dict(argstr='-nokeep_real_range', - xor=('keep_real_range', 'nokeep_real_range'), - ), - origin=dict(argstr='-origin %s %s %s', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_resample.mnc', - position=-1, - ), - output_range=dict(argstr='-range %s %s', - ), - sagittal_slices=dict(argstr='-sagittal', - xor=('transverse', 'sagittal', 'coronal'), - ), - sinc_interpolation=dict(argstr='-sinc', - xor=('trilinear_interpolation', 'tricubic_interpolation', 'nearest_neighbour_interpolation', 'sinc_interpolation'), - ), - sinc_window_hamming=dict(argstr='-hamming', - requires=['sinc_interpolation'], - xor=('sinc_window_hanning', 'sinc_window_hamming'), - ), - sinc_window_hanning=dict(argstr='-hanning', - requires=['sinc_interpolation'], - xor=('sinc_window_hanning', 'sinc_window_hamming'), - ), - spacetype=dict(argstr='-spacetype %s', - ), - standard_sampling=dict(argstr='-standard_sampling', - ), - start=dict(argstr='-start %s %s %s', - xor=('nelements', 'nelements_x_y_or_z'), - ), - step=dict(argstr='-step %s %s %s', - xor=('nelements', 'nelements_x_y_or_z'), - ), - talairach=dict(argstr='-talairach', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformation=dict(argstr='-transformation %s', - ), - transverse_slices=dict(argstr='-transverse', - xor=('transverse', 'sagittal', 'coronal'), - ), - tricubic_interpolation=dict(argstr='-tricubic', - xor=('trilinear_interpolation', 'tricubic_interpolation', 'nearest_neighbour_interpolation', 'sinc_interpolation'), - ), - trilinear_interpolation=dict(argstr='-trilinear', - xor=('trilinear_interpolation', 'tricubic_interpolation', 'nearest_neighbour_interpolation', 'sinc_interpolation'), - ), - two=dict(argstr='-2', - ), - units=dict(argstr='-units %s', - ), - vio_transform=dict(argstr='-tfm_input_sampling', - xor=('vio_transform', 'no_input_sampling'), - ), - xdircos=dict(argstr='-xdircos %s', - requires=('ydircos', 'zdircos'), - xor=('dircos', 'dircos_x_y_or_z'), - ), - xnelements=dict(argstr='-xnelements %s', - requires=('ynelements', 'znelements'), - xor=('nelements', 'nelements_x_y_or_z'), - ), - xstart=dict(argstr='-xstart %s', - requires=('ystart', 'zstart'), - xor=('start', 'start_x_y_or_z'), - ), - xstep=dict(argstr='-xstep %s', - requires=('ystep', 'zstep'), - xor=('step', 'step_x_y_or_z'), - ), - ydircos=dict(argstr='-ydircos %s', - requires=('xdircos', 'zdircos'), - xor=('dircos', 'dircos_x_y_or_z'), - ), - ynelements=dict(argstr='-ynelements %s', - requires=('xnelements', 'znelements'), - xor=('nelements', 'nelements_x_y_or_z'), - ), - ystart=dict(argstr='-ystart %s', - requires=('xstart', 'zstart'), - xor=('start', 'start_x_y_or_z'), - ), - ystep=dict(argstr='-ystep %s', - requires=('xstep', 'zstep'), - xor=('step', 'step_x_y_or_z'), - ), - zdircos=dict(argstr='-zdircos %s', - requires=('xdircos', 'ydircos'), - xor=('dircos', 'dircos_x_y_or_z'), - ), - znelements=dict(argstr='-znelements %s', - requires=('xnelements', 'ynelements'), - xor=('nelements', 'nelements_x_y_or_z'), - ), - zstart=dict(argstr='-zstart %s', - requires=('xstart', 'ystart'), - xor=('start', 'start_x_y_or_z'), - ), - zstep=dict(argstr='-zstep %s', - requires=('xstep', 'ystep'), - xor=('step', 'step_x_y_or_z'), - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + coronal_slices=dict( + argstr='-coronal', + xor=('transverse', 'sagittal', 'coronal'), + ), + dircos=dict( + argstr='-dircos %s %s %s', + xor=('nelements', 'nelements_x_y_or_z'), + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill=dict( + argstr='-fill', + xor=('nofill', 'fill'), + ), + fill_value=dict( + argstr='-fillvalue %s', + requires=['fill'], + ), + format_byte=dict( + argstr='-byte', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + format_double=dict( + argstr='-double', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + format_float=dict( + argstr='-float', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + format_int=dict( + argstr='-int', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + format_long=dict( + argstr='-long', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + format_short=dict( + argstr='-short', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + format_signed=dict( + argstr='-signed', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + format_unsigned=dict( + argstr='-unsigned', + xor=('format_byte', 'format_short', 'format_int', 'format_long', + 'format_float', 'format_double', 'format_signed', + 'format_unsigned'), + ), + half_width_sinc_window=dict( + argstr='-width %s', + requires=['sinc_interpolation'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + input_grid_files=dict(), + invert_transformation=dict(argstr='-invert_transformation', ), + keep_real_range=dict( + argstr='-keep_real_range', + xor=('keep_real_range', 'nokeep_real_range'), + ), + like=dict(argstr='-like %s', ), + nearest_neighbour_interpolation=dict( + argstr='-nearest_neighbour', + xor=('trilinear_interpolation', 'tricubic_interpolation', + 'nearest_neighbour_interpolation', 'sinc_interpolation'), + ), + nelements=dict( + argstr='-nelements %s %s %s', + xor=('nelements', 'nelements_x_y_or_z'), + ), + no_fill=dict( + argstr='-nofill', + xor=('nofill', 'fill'), + ), + no_input_sampling=dict( + argstr='-use_input_sampling', + xor=('vio_transform', 'no_input_sampling'), + ), + nokeep_real_range=dict( + argstr='-nokeep_real_range', + xor=('keep_real_range', 'nokeep_real_range'), + ), + origin=dict(argstr='-origin %s %s %s', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_resample.mnc', + position=-1, + ), + output_range=dict(argstr='-range %s %s', ), + sagittal_slices=dict( + argstr='-sagittal', + xor=('transverse', 'sagittal', 'coronal'), + ), + sinc_interpolation=dict( + argstr='-sinc', + xor=('trilinear_interpolation', 'tricubic_interpolation', + 'nearest_neighbour_interpolation', 'sinc_interpolation'), + ), + sinc_window_hamming=dict( + argstr='-hamming', + requires=['sinc_interpolation'], + xor=('sinc_window_hanning', 'sinc_window_hamming'), + ), + sinc_window_hanning=dict( + argstr='-hanning', + requires=['sinc_interpolation'], + xor=('sinc_window_hanning', 'sinc_window_hamming'), + ), + spacetype=dict(argstr='-spacetype %s', ), + standard_sampling=dict(argstr='-standard_sampling', ), + start=dict( + argstr='-start %s %s %s', + xor=('nelements', 'nelements_x_y_or_z'), + ), + step=dict( + argstr='-step %s %s %s', + xor=('nelements', 'nelements_x_y_or_z'), + ), + talairach=dict(argstr='-talairach', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformation=dict(argstr='-transformation %s', ), + transverse_slices=dict( + argstr='-transverse', + xor=('transverse', 'sagittal', 'coronal'), + ), + tricubic_interpolation=dict( + argstr='-tricubic', + xor=('trilinear_interpolation', 'tricubic_interpolation', + 'nearest_neighbour_interpolation', 'sinc_interpolation'), + ), + trilinear_interpolation=dict( + argstr='-trilinear', + xor=('trilinear_interpolation', 'tricubic_interpolation', + 'nearest_neighbour_interpolation', 'sinc_interpolation'), + ), + two=dict(argstr='-2', ), + units=dict(argstr='-units %s', ), + vio_transform=dict( + argstr='-tfm_input_sampling', + xor=('vio_transform', 'no_input_sampling'), + ), + xdircos=dict( + argstr='-xdircos %s', + requires=('ydircos', 'zdircos'), + xor=('dircos', 'dircos_x_y_or_z'), + ), + xnelements=dict( + argstr='-xnelements %s', + requires=('ynelements', 'znelements'), + xor=('nelements', 'nelements_x_y_or_z'), + ), + xstart=dict( + argstr='-xstart %s', + requires=('ystart', 'zstart'), + xor=('start', 'start_x_y_or_z'), + ), + xstep=dict( + argstr='-xstep %s', + requires=('ystep', 'zstep'), + xor=('step', 'step_x_y_or_z'), + ), + ydircos=dict( + argstr='-ydircos %s', + requires=('xdircos', 'zdircos'), + xor=('dircos', 'dircos_x_y_or_z'), + ), + ynelements=dict( + argstr='-ynelements %s', + requires=('xnelements', 'znelements'), + xor=('nelements', 'nelements_x_y_or_z'), + ), + ystart=dict( + argstr='-ystart %s', + requires=('xstart', 'zstart'), + xor=('start', 'start_x_y_or_z'), + ), + ystep=dict( + argstr='-ystep %s', + requires=('xstep', 'zstep'), + xor=('step', 'step_x_y_or_z'), + ), + zdircos=dict( + argstr='-zdircos %s', + requires=('xdircos', 'ydircos'), + xor=('dircos', 'dircos_x_y_or_z'), + ), + znelements=dict( + argstr='-znelements %s', + requires=('xnelements', 'ynelements'), + xor=('nelements', 'nelements_x_y_or_z'), + ), + zstart=dict( + argstr='-zstart %s', + requires=('xstart', 'ystart'), + xor=('start', 'start_x_y_or_z'), + ), + zstep=dict( + argstr='-zstep %s', + requires=('xstep', 'ystep'), + xor=('step', 'step_x_y_or_z'), + ), ) inputs = Resample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Resample_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Reshape.py b/nipype/interfaces/minc/tests/test_auto_Reshape.py index 64f28362c9..773a51563d 100644 --- a/nipype/interfaces/minc/tests/test_auto_Reshape.py +++ b/nipype/interfaces/minc/tests/test_auto_Reshape.py @@ -4,47 +4,48 @@ def test_Reshape_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_reshape.mnc', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), - write_short=dict(argstr='-short', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_reshape.mnc', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), + write_short=dict(argstr='-short', ), ) inputs = Reshape.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Reshape_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Reshape.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_ToEcat.py b/nipype/interfaces/minc/tests/test_auto_ToEcat.py index 3b48a27654..97d1b4c2db 100644 --- a/nipype/interfaces/minc/tests/test_auto_ToEcat.py +++ b/nipype/interfaces/minc/tests/test_auto_ToEcat.py @@ -4,57 +4,54 @@ def test_ToEcat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_acquisition_variable=dict(argstr='-ignore_acquisition_variable', - ), - ignore_ecat_acquisition_variable=dict(argstr='-ignore_ecat_acquisition_variable', - ), - ignore_ecat_main=dict(argstr='-ignore_ecat_main', - ), - ignore_ecat_subheader_variable=dict(argstr='-ignore_ecat_subheader_variable', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_patient_variable=dict(argstr='-ignore_patient_variable', - ), - ignore_study_variable=dict(argstr='-ignore_study_variable', - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - no_decay_corr_fctr=dict(argstr='-no_decay_corr_fctr', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - keep_extension=False, - name_source=['input_file'], - name_template='%s_to_ecat.v', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxels_as_integers=dict(argstr='-label', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_acquisition_variable=dict( + argstr='-ignore_acquisition_variable', ), + ignore_ecat_acquisition_variable=dict( + argstr='-ignore_ecat_acquisition_variable', ), + ignore_ecat_main=dict(argstr='-ignore_ecat_main', ), + ignore_ecat_subheader_variable=dict( + argstr='-ignore_ecat_subheader_variable', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_patient_variable=dict(argstr='-ignore_patient_variable', ), + ignore_study_variable=dict(argstr='-ignore_study_variable', ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + no_decay_corr_fctr=dict(argstr='-no_decay_corr_fctr', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + keep_extension=False, + name_source=['input_file'], + name_template='%s_to_ecat.v', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxels_as_integers=dict(argstr='-label', ), ) inputs = ToEcat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ToEcat_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = ToEcat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_ToRaw.py b/nipype/interfaces/minc/tests/test_auto_ToRaw.py index 02af1da373..66463e38ef 100644 --- a/nipype/interfaces/minc/tests/test_auto_ToRaw.py +++ b/nipype/interfaces/minc/tests/test_auto_ToRaw.py @@ -4,75 +4,93 @@ def test_ToRaw_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - nonormalize=dict(argstr='-nonormalize', - xor=('normalize', 'nonormalize'), - ), - normalize=dict(argstr='-normalize', - xor=('normalize', 'nonormalize'), - ), - out_file=dict(argstr='> %s', - genfile=True, - position=-1, - ), - output_file=dict(hash_files=False, - keep_extension=False, - name_source=['input_file'], - name_template='%s.raw', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - write_byte=dict(argstr='-byte', - xor=('write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double'), - ), - write_double=dict(argstr='-double', - xor=('write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double'), - ), - write_float=dict(argstr='-float', - xor=('write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double'), - ), - write_int=dict(argstr='-int', - xor=('write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double'), - ), - write_long=dict(argstr='-long', - xor=('write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double'), - ), - write_range=dict(argstr='-range %s %s', - ), - write_short=dict(argstr='-short', - xor=('write_byte', 'write_short', 'write_int', 'write_long', 'write_float', 'write_double'), - ), - write_signed=dict(argstr='-signed', - xor=('write_signed', 'write_unsigned'), - ), - write_unsigned=dict(argstr='-unsigned', - xor=('write_signed', 'write_unsigned'), - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + nonormalize=dict( + argstr='-nonormalize', + xor=('normalize', 'nonormalize'), + ), + normalize=dict( + argstr='-normalize', + xor=('normalize', 'nonormalize'), + ), + out_file=dict( + argstr='> %s', + genfile=True, + position=-1, + ), + output_file=dict( + hash_files=False, + keep_extension=False, + name_source=['input_file'], + name_template='%s.raw', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + write_byte=dict( + argstr='-byte', + xor=('write_byte', 'write_short', 'write_int', 'write_long', + 'write_float', 'write_double'), + ), + write_double=dict( + argstr='-double', + xor=('write_byte', 'write_short', 'write_int', 'write_long', + 'write_float', 'write_double'), + ), + write_float=dict( + argstr='-float', + xor=('write_byte', 'write_short', 'write_int', 'write_long', + 'write_float', 'write_double'), + ), + write_int=dict( + argstr='-int', + xor=('write_byte', 'write_short', 'write_int', 'write_long', + 'write_float', 'write_double'), + ), + write_long=dict( + argstr='-long', + xor=('write_byte', 'write_short', 'write_int', 'write_long', + 'write_float', 'write_double'), + ), + write_range=dict(argstr='-range %s %s', ), + write_short=dict( + argstr='-short', + xor=('write_byte', 'write_short', 'write_int', 'write_long', + 'write_float', 'write_double'), + ), + write_signed=dict( + argstr='-signed', + xor=('write_signed', 'write_unsigned'), + ), + write_unsigned=dict( + argstr='-unsigned', + xor=('write_signed', 'write_unsigned'), + ), ) inputs = ToRaw.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ToRaw_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = ToRaw.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_VolSymm.py b/nipype/interfaces/minc/tests/test_auto_VolSymm.py index 88145f639d..96687e56fd 100644 --- a/nipype/interfaces/minc/tests/test_auto_VolSymm.py +++ b/nipype/interfaces/minc/tests/test_auto_VolSymm.py @@ -4,69 +4,67 @@ def test_VolSymm_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - config_file=dict(argstr='-config_file %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fit_linear=dict(argstr='-linear', - ), - fit_nonlinear=dict(argstr='-nonlinear', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - input_grid_files=dict(), - nofit=dict(argstr='-nofit', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_vol_symm.mnc', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trans_file=dict(argstr='%s', - genfile=True, - hash_files=False, - keep_extension=False, - name_source=['input_file'], - name_template='%s_vol_symm.xfm', - position=-2, - ), - verbose=dict(argstr='-verbose', - ), - x=dict(argstr='-x', - ), - y=dict(argstr='-y', - ), - z=dict(argstr='-z', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + config_file=dict(argstr='-config_file %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fit_linear=dict(argstr='-linear', ), + fit_nonlinear=dict(argstr='-nonlinear', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + input_grid_files=dict(), + nofit=dict(argstr='-nofit', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_vol_symm.mnc', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trans_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + keep_extension=False, + name_source=['input_file'], + name_template='%s_vol_symm.xfm', + position=-2, + ), + verbose=dict(argstr='-verbose', ), + x=dict(argstr='-x', ), + y=dict(argstr='-y', ), + z=dict(argstr='-z', ), ) inputs = VolSymm.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VolSymm_outputs(): - output_map = dict(output_file=dict(), - output_grid=dict(), - trans_file=dict(), + output_map = dict( + output_file=dict(), + output_grid=dict(), + trans_file=dict(), ) outputs = VolSymm.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Volcentre.py b/nipype/interfaces/minc/tests/test_auto_Volcentre.py index 7bf95a9c3d..f6acddb1b2 100644 --- a/nipype/interfaces/minc/tests/test_auto_Volcentre.py +++ b/nipype/interfaces/minc/tests/test_auto_Volcentre.py @@ -4,51 +4,50 @@ def test_Volcentre_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - centre=dict(argstr='-centre %s %s %s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - com=dict(argstr='-com', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_volcentre.mnc', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), - zero_dircos=dict(argstr='-zero_dircos', - ), + input_map = dict( + args=dict(argstr='%s', ), + centre=dict(argstr='-centre %s %s %s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + com=dict(argstr='-com', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_volcentre.mnc', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), + zero_dircos=dict(argstr='-zero_dircos', ), ) inputs = Volcentre.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Volcentre_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Volcentre.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Voliso.py b/nipype/interfaces/minc/tests/test_auto_Voliso.py index 76ad3283c8..6d8309616c 100644 --- a/nipype/interfaces/minc/tests/test_auto_Voliso.py +++ b/nipype/interfaces/minc/tests/test_auto_Voliso.py @@ -4,51 +4,50 @@ def test_Voliso_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - avgstep=dict(argstr='--avgstep', - ), - clobber=dict(argstr='--clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - maxstep=dict(argstr='--maxstep %s', - ), - minstep=dict(argstr='--minstep %s', - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_voliso.mnc', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + avgstep=dict(argstr='--avgstep', ), + clobber=dict( + argstr='--clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + maxstep=dict(argstr='--maxstep %s', ), + minstep=dict(argstr='--minstep %s', ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_voliso.mnc', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose', ), ) inputs = Voliso.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Voliso_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Voliso.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Volpad.py b/nipype/interfaces/minc/tests/test_auto_Volpad.py index 6ac867639e..12fb32b1d7 100644 --- a/nipype/interfaces/minc/tests/test_auto_Volpad.py +++ b/nipype/interfaces/minc/tests/test_auto_Volpad.py @@ -4,55 +4,52 @@ def test_Volpad_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - auto=dict(argstr='-auto', - ), - auto_freq=dict(argstr='-auto_freq %s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - distance=dict(argstr='-distance %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_file'], - name_template='%s_volpad.mnc', - position=-1, - ), - smooth=dict(argstr='-smooth', - ), - smooth_distance=dict(argstr='-smooth_distance %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + auto=dict(argstr='-auto', ), + auto_freq=dict(argstr='-auto_freq %s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + distance=dict(argstr='-distance %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_file'], + name_template='%s_volpad.mnc', + position=-1, + ), + smooth=dict(argstr='-smooth', ), + smooth_distance=dict(argstr='-smooth_distance %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = Volpad.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Volpad_outputs(): - output_map = dict(output_file=dict(), - ) + output_map = dict(output_file=dict(), ) outputs = Volpad.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_XfmAvg.py b/nipype/interfaces/minc/tests/test_auto_XfmAvg.py index 3d288aa1cd..e23df966ca 100644 --- a/nipype/interfaces/minc/tests/test_auto_XfmAvg.py +++ b/nipype/interfaces/minc/tests/test_auto_XfmAvg.py @@ -4,52 +4,52 @@ def test_XfmAvg_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - avg_linear=dict(argstr='-avg_linear', - ), - avg_nonlinear=dict(argstr='-avg_nonlinear', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_linear=dict(argstr='-ignore_linear', - ), - ignore_nonlinear=dict(argstr='-ignore_nonline', - ), - input_files=dict(argstr='%s', - mandatory=True, - position=-2, - sep=' ', - ), - input_grid_files=dict(), - output_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + avg_linear=dict(argstr='-avg_linear', ), + avg_nonlinear=dict(argstr='-avg_nonlinear', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_linear=dict(argstr='-ignore_linear', ), + ignore_nonlinear=dict(argstr='-ignore_nonline', ), + input_files=dict( + argstr='%s', + mandatory=True, + position=-2, + sep=' ', + ), + input_grid_files=dict(), + output_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = XfmAvg.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_XfmAvg_outputs(): - output_map = dict(output_file=dict(), - output_grid=dict(), + output_map = dict( + output_file=dict(), + output_grid=dict(), ) outputs = XfmAvg.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_XfmConcat.py b/nipype/interfaces/minc/tests/test_auto_XfmConcat.py index 4d3cdadb24..50f791f4c6 100644 --- a/nipype/interfaces/minc/tests/test_auto_XfmConcat.py +++ b/nipype/interfaces/minc/tests/test_auto_XfmConcat.py @@ -4,47 +4,51 @@ def test_XfmConcat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_files=dict(argstr='%s', - mandatory=True, - position=-2, - sep=' ', - ), - input_grid_files=dict(), - output_file=dict(argstr='%s', - genfile=True, - hash_files=False, - name_source=['input_files'], - name_template='%s_xfmconcat.xfm', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_files=dict( + argstr='%s', + mandatory=True, + position=-2, + sep=' ', + ), + input_grid_files=dict(), + output_file=dict( + argstr='%s', + genfile=True, + hash_files=False, + name_source=['input_files'], + name_template='%s_xfmconcat.xfm', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = XfmConcat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_XfmConcat_outputs(): - output_map = dict(output_file=dict(), - output_grids=dict(), + output_map = dict( + output_file=dict(), + output_grids=dict(), ) outputs = XfmConcat.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_XfmInvert.py b/nipype/interfaces/minc/tests/test_auto_XfmInvert.py index 10f5e9ec6a..bf19920888 100644 --- a/nipype/interfaces/minc/tests/test_auto_XfmInvert.py +++ b/nipype/interfaces/minc/tests/test_auto_XfmInvert.py @@ -4,42 +4,46 @@ def test_XfmInvert_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clobber=dict(argstr='-clobber', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - output_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-verbose', - ), + input_map = dict( + args=dict(argstr='%s', ), + clobber=dict( + argstr='-clobber', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + output_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='-verbose', ), ) inputs = XfmInvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_XfmInvert_outputs(): - output_map = dict(output_file=dict(), - output_grid=dict(), + output_map = dict( + output_file=dict(), + output_grid=dict(), ) outputs = XfmInvert.output_spec() diff --git a/nipype/interfaces/mipav/__init__.py b/nipype/interfaces/mipav/__init__.py index d3a6b785fa..8a9e08fd9b 100644 --- a/nipype/interfaces/mipav/__init__.py +++ b/nipype/interfaces/mipav/__init__.py @@ -1,3 +1,12 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import -from .developer import JistLaminarVolumetricLayering, JistBrainMgdmSegmentation, JistLaminarProfileGeometry, JistLaminarProfileCalculator, MedicAlgorithmN3, JistLaminarROIAveraging, MedicAlgorithmLesionToads, JistBrainMp2rageSkullStripping, JistCortexSurfaceMeshInflation, RandomVol, MedicAlgorithmImageCalculator, JistBrainMp2rageDuraEstimation, JistLaminarProfileSampling, MedicAlgorithmMipavReorient, MedicAlgorithmSPECTRE2010, JistBrainPartialVolumeFilter, JistIntensityMp2rageMasking, MedicAlgorithmThresholdToBinaryMask +from __future__ import (print_function, division, unicode_literals, + absolute_import) +from .developer import ( + JistLaminarVolumetricLayering, JistBrainMgdmSegmentation, + JistLaminarProfileGeometry, JistLaminarProfileCalculator, MedicAlgorithmN3, + JistLaminarROIAveraging, MedicAlgorithmLesionToads, + JistBrainMp2rageSkullStripping, JistCortexSurfaceMeshInflation, RandomVol, + MedicAlgorithmImageCalculator, JistBrainMp2rageDuraEstimation, + JistLaminarProfileSampling, MedicAlgorithmMipavReorient, + MedicAlgorithmSPECTRE2010, JistBrainPartialVolumeFilter, + JistIntensityMp2rageMasking, MedicAlgorithmThresholdToBinaryMask) diff --git a/nipype/interfaces/mipav/developer.py b/nipype/interfaces/mipav/developer.py index 141a7de1cf..ffb9e10cc3 100644 --- a/nipype/interfaces/mipav/developer.py +++ b/nipype/interfaces/mipav/developer.py @@ -11,24 +11,78 @@ class JistLaminarVolumetricLayeringInputSpec(CommandLineInputSpec): - inInner = File(desc="Inner Distance Image (GM/WM boundary)", exists=True, argstr="--inInner %s") - inOuter = File(desc="Outer Distance Image (CSF/GM boundary)", exists=True, argstr="--inOuter %s") + inInner = File( + desc="Inner Distance Image (GM/WM boundary)", + exists=True, + argstr="--inInner %s") + inOuter = File( + desc="Outer Distance Image (CSF/GM boundary)", + exists=True, + argstr="--inOuter %s") inNumber = traits.Int(desc="Number of layers", argstr="--inNumber %d") - inMax = traits.Int(desc="Max iterations for narrow band evolution", argstr="--inMax %d") - inMin = traits.Float(desc="Min change ratio for narrow band evolution", argstr="--inMin %f") - inLayering = traits.Enum("distance-preserving", "volume-preserving", desc="Layering method", argstr="--inLayering %s") - inLayering2 = traits.Enum("outward", "inward", desc="Layering direction", argstr="--inLayering2 %s") - incurvature = traits.Int(desc="curvature approximation scale (voxels)", argstr="--incurvature %d") - inratio = traits.Float(desc="ratio smoothing kernel size (voxels)", argstr="--inratio %f") - inpresmooth = traits.Enum("true", "false", desc="pre-smooth cortical surfaces", argstr="--inpresmooth %s") - inTopology = traits.Enum("26/6", "6/26", "18/6", "6/18", "6/6", "wcs", "wco", "no", desc="Topology", argstr="--inTopology %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outContinuous = traits.Either(traits.Bool, File(), hash_files=False, desc="Continuous depth measurement", argstr="--outContinuous %s") - outDiscrete = traits.Either(traits.Bool, File(), hash_files=False, desc="Discrete sampled layers", argstr="--outDiscrete %s") - outLayer = traits.Either(traits.Bool, File(), hash_files=False, desc="Layer boundary surfaces", argstr="--outLayer %s") + inMax = traits.Int( + desc="Max iterations for narrow band evolution", argstr="--inMax %d") + inMin = traits.Float( + desc="Min change ratio for narrow band evolution", argstr="--inMin %f") + inLayering = traits.Enum( + "distance-preserving", + "volume-preserving", + desc="Layering method", + argstr="--inLayering %s") + inLayering2 = traits.Enum( + "outward", + "inward", + desc="Layering direction", + argstr="--inLayering2 %s") + incurvature = traits.Int( + desc="curvature approximation scale (voxels)", + argstr="--incurvature %d") + inratio = traits.Float( + desc="ratio smoothing kernel size (voxels)", argstr="--inratio %f") + inpresmooth = traits.Enum( + "true", + "false", + desc="pre-smooth cortical surfaces", + argstr="--inpresmooth %s") + inTopology = traits.Enum( + "26/6", + "6/26", + "18/6", + "6/18", + "6/6", + "wcs", + "wco", + "no", + desc="Topology", + argstr="--inTopology %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outContinuous = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Continuous depth measurement", + argstr="--outContinuous %s") + outDiscrete = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Discrete sampled layers", + argstr="--outDiscrete %s") + outLayer = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Layer boundary surfaces", + argstr="--outLayer %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistLaminarVolumetricLayeringOutputSpec(TraitedSpec): @@ -54,41 +108,98 @@ class JistLaminarVolumetricLayering(SEMLikeCommandLine): input_spec = JistLaminarVolumetricLayeringInputSpec output_spec = JistLaminarVolumetricLayeringOutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run de.mpg.cbs.jist.laminar.JistLaminarVolumetricLayering " - _outputs_filenames = {'outContinuous': 'outContinuous.nii', 'outLayer': 'outLayer.nii', 'outDiscrete': 'outDiscrete.nii'} + _outputs_filenames = { + 'outContinuous': 'outContinuous.nii', + 'outLayer': 'outLayer.nii', + 'outDiscrete': 'outDiscrete.nii' + } _redirect_x = True class JistBrainMgdmSegmentationInputSpec(CommandLineInputSpec): - inMP2RAGE = File(desc="MP2RAGE T1 Map Image", exists=True, argstr="--inMP2RAGE %s") - inMP2RAGE2 = File(desc="MP2RAGE T1-weighted Image", exists=True, argstr="--inMP2RAGE2 %s") + inMP2RAGE = File( + desc="MP2RAGE T1 Map Image", exists=True, argstr="--inMP2RAGE %s") + inMP2RAGE2 = File( + desc="MP2RAGE T1-weighted Image", + exists=True, + argstr="--inMP2RAGE2 %s") inPV = File(desc="PV / Dura Image", exists=True, argstr="--inPV %s") - inMPRAGE = File(desc="MPRAGE T1-weighted Image", exists=True, argstr="--inMPRAGE %s") + inMPRAGE = File( + desc="MPRAGE T1-weighted Image", exists=True, argstr="--inMPRAGE %s") inFLAIR = File(desc="FLAIR Image", exists=True, argstr="--inFLAIR %s") inAtlas = File(desc="Atlas file", exists=True, argstr="--inAtlas %s") inData = traits.Float(desc="Data weight", argstr="--inData %f") - inCurvature = traits.Float(desc="Curvature weight", argstr="--inCurvature %f") - inPosterior = traits.Float(desc="Posterior scale (mm)", argstr="--inPosterior %f") + inCurvature = traits.Float( + desc="Curvature weight", argstr="--inCurvature %f") + inPosterior = traits.Float( + desc="Posterior scale (mm)", argstr="--inPosterior %f") inMax = traits.Int(desc="Max iterations", argstr="--inMax %d") inMin = traits.Float(desc="Min change", argstr="--inMin %f") inSteps = traits.Int(desc="Steps", argstr="--inSteps %d") - inTopology = traits.Enum("26/6", "6/26", "18/6", "6/18", "6/6", "wcs", "wco", "no", desc="Topology", argstr="--inTopology %s") - inCompute = traits.Enum("true", "false", desc="Compute posteriors", argstr="--inCompute %s") - inAdjust = traits.Enum("true", "false", desc="Adjust intensity priors", argstr="--inAdjust %s") - inOutput = traits.Enum("segmentation", "memberships", desc="Output images", argstr="--inOutput %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outSegmented = traits.Either(traits.Bool, File(), hash_files=False, desc="Segmented Brain Image", argstr="--outSegmented %s") - outLevelset = traits.Either(traits.Bool, File(), hash_files=False, desc="Levelset Boundary Image", argstr="--outLevelset %s") - outPosterior2 = traits.Either(traits.Bool, File(), hash_files=False, desc="Posterior Maximum Memberships (4D)", argstr="--outPosterior2 %s") - outPosterior3 = traits.Either(traits.Bool, File(), hash_files=False, desc="Posterior Maximum Labels (4D)", argstr="--outPosterior3 %s") + inTopology = traits.Enum( + "26/6", + "6/26", + "18/6", + "6/18", + "6/6", + "wcs", + "wco", + "no", + desc="Topology", + argstr="--inTopology %s") + inCompute = traits.Enum( + "true", "false", desc="Compute posteriors", argstr="--inCompute %s") + inAdjust = traits.Enum( + "true", + "false", + desc="Adjust intensity priors", + argstr="--inAdjust %s") + inOutput = traits.Enum( + "segmentation", + "memberships", + desc="Output images", + argstr="--inOutput %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outSegmented = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Segmented Brain Image", + argstr="--outSegmented %s") + outLevelset = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Levelset Boundary Image", + argstr="--outLevelset %s") + outPosterior2 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Posterior Maximum Memberships (4D)", + argstr="--outPosterior2 %s") + outPosterior3 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Posterior Maximum Labels (4D)", + argstr="--outPosterior3 %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistBrainMgdmSegmentationOutputSpec(TraitedSpec): outSegmented = File(desc="Segmented Brain Image", exists=True) outLevelset = File(desc="Levelset Boundary Image", exists=True) - outPosterior2 = File(desc="Posterior Maximum Memberships (4D)", exists=True) + outPosterior2 = File( + desc="Posterior Maximum Memberships (4D)", exists=True) outPosterior3 = File(desc="Posterior Maximum Labels (4D)", exists=True) @@ -106,21 +217,54 @@ class JistBrainMgdmSegmentation(SEMLikeCommandLine): input_spec = JistBrainMgdmSegmentationInputSpec output_spec = JistBrainMgdmSegmentationOutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run de.mpg.cbs.jist.brain.JistBrainMgdmSegmentation " - _outputs_filenames = {'outSegmented': 'outSegmented.nii', 'outPosterior2': 'outPosterior2.nii', 'outPosterior3': 'outPosterior3.nii', 'outLevelset': 'outLevelset.nii'} + _outputs_filenames = { + 'outSegmented': 'outSegmented.nii', + 'outPosterior2': 'outPosterior2.nii', + 'outPosterior3': 'outPosterior3.nii', + 'outLevelset': 'outLevelset.nii' + } _redirect_x = True class JistLaminarProfileGeometryInputSpec(CommandLineInputSpec): - inProfile = File(desc="Profile Surface Image", exists=True, argstr="--inProfile %s") - incomputed = traits.Enum("thickness", "curvedness", "shape_index", "mean_curvature", "gauss_curvature", "profile_length", "profile_curvature", "profile_torsion", desc="computed measure", argstr="--incomputed %s") - inregularization = traits.Enum("none", "Gaussian", desc="regularization", argstr="--inregularization %s") - insmoothing = traits.Float(desc="smoothing parameter", argstr="--insmoothing %f") - inoutside = traits.Float(desc="outside extension (mm)", argstr="--inoutside %f") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outResult = traits.Either(traits.Bool, File(), hash_files=False, desc="Result", argstr="--outResult %s") + inProfile = File( + desc="Profile Surface Image", exists=True, argstr="--inProfile %s") + incomputed = traits.Enum( + "thickness", + "curvedness", + "shape_index", + "mean_curvature", + "gauss_curvature", + "profile_length", + "profile_curvature", + "profile_torsion", + desc="computed measure", + argstr="--incomputed %s") + inregularization = traits.Enum( + "none", + "Gaussian", + desc="regularization", + argstr="--inregularization %s") + insmoothing = traits.Float( + desc="smoothing parameter", argstr="--insmoothing %f") + inoutside = traits.Float( + desc="outside extension (mm)", argstr="--inoutside %f") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outResult = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Result", + argstr="--outResult %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistLaminarProfileGeometryOutputSpec(TraitedSpec): @@ -146,14 +290,33 @@ class JistLaminarProfileGeometry(SEMLikeCommandLine): class JistLaminarProfileCalculatorInputSpec(CommandLineInputSpec): - inIntensity = File(desc="Intensity Profile Image", exists=True, argstr="--inIntensity %s") - inMask = File(desc="Mask Image (opt, 3D or 4D)", exists=True, argstr="--inMask %s") - incomputed = traits.Enum("mean", "stdev", "skewness", "kurtosis", desc="computed statistic", argstr="--incomputed %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outResult = traits.Either(traits.Bool, File(), hash_files=False, desc="Result", argstr="--outResult %s") + inIntensity = File( + desc="Intensity Profile Image", exists=True, argstr="--inIntensity %s") + inMask = File( + desc="Mask Image (opt, 3D or 4D)", exists=True, argstr="--inMask %s") + incomputed = traits.Enum( + "mean", + "stdev", + "skewness", + "kurtosis", + desc="computed statistic", + argstr="--incomputed %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outResult = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Result", + argstr="--outResult %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistLaminarProfileCalculatorOutputSpec(TraitedSpec): @@ -180,20 +343,58 @@ class JistLaminarProfileCalculator(SEMLikeCommandLine): class MedicAlgorithmN3InputSpec(CommandLineInputSpec): inInput = File(desc="Input Volume", exists=True, argstr="--inInput %s") - inSignal = traits.Float(desc="Default = min + 1, Values at less than threshold are treated as part of the background", argstr="--inSignal %f") - inMaximum = traits.Int(desc="Maximum number of Iterations", argstr="--inMaximum %d") - inEnd = traits.Float(desc="Usually 0.01-0.00001, The measure used to terminate the iterations is the coefficient of variation of change in field estimates between successive iterations.", argstr="--inEnd %f") - inField = traits.Float(desc="Characteristic distance over which the field varies. The distance between adjacent knots in bspline fitting with at least 4 knots going in every dimension. The default in the dialog is one third the distance (resolution * extents) of the smallest dimension.", argstr="--inField %f") - inSubsample = traits.Float(desc="Usually between 1-32, The factor by which the data is subsampled to a lower resolution in estimating the slowly varying non-uniformity field. Reduce sampling in the finest sampling direction by the shrink factor.", argstr="--inSubsample %f") - inKernel = traits.Float(desc="Usually between 0.05-0.50, Width of deconvolution kernel used to sharpen the histogram. Larger values give faster convergence while smaller values give greater accuracy.", argstr="--inKernel %f") - inWeiner = traits.Float(desc="Usually between 0.0-1.0", argstr="--inWeiner %f") - inAutomatic = traits.Enum("true", "false", desc="If true determines the threshold by histogram analysis. If true a VOI cannot be used and the input threshold is ignored.", argstr="--inAutomatic %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outInhomogeneity = traits.Either(traits.Bool, File(), hash_files=False, desc="Inhomogeneity Corrected Volume", argstr="--outInhomogeneity %s") - outInhomogeneity2 = traits.Either(traits.Bool, File(), hash_files=False, desc="Inhomogeneity Field", argstr="--outInhomogeneity2 %s") + inSignal = traits.Float( + desc= + "Default = min + 1, Values at less than threshold are treated as part of the background", + argstr="--inSignal %f") + inMaximum = traits.Int( + desc="Maximum number of Iterations", argstr="--inMaximum %d") + inEnd = traits.Float( + desc= + "Usually 0.01-0.00001, The measure used to terminate the iterations is the coefficient of variation of change in field estimates between successive iterations.", + argstr="--inEnd %f") + inField = traits.Float( + desc= + "Characteristic distance over which the field varies. The distance between adjacent knots in bspline fitting with at least 4 knots going in every dimension. The default in the dialog is one third the distance (resolution * extents) of the smallest dimension.", + argstr="--inField %f") + inSubsample = traits.Float( + desc= + "Usually between 1-32, The factor by which the data is subsampled to a lower resolution in estimating the slowly varying non-uniformity field. Reduce sampling in the finest sampling direction by the shrink factor.", + argstr="--inSubsample %f") + inKernel = traits.Float( + desc= + "Usually between 0.05-0.50, Width of deconvolution kernel used to sharpen the histogram. Larger values give faster convergence while smaller values give greater accuracy.", + argstr="--inKernel %f") + inWeiner = traits.Float( + desc="Usually between 0.0-1.0", argstr="--inWeiner %f") + inAutomatic = traits.Enum( + "true", + "false", + desc= + "If true determines the threshold by histogram analysis. If true a VOI cannot be used and the input threshold is ignored.", + argstr="--inAutomatic %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outInhomogeneity = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Inhomogeneity Corrected Volume", + argstr="--outInhomogeneity %s") + outInhomogeneity2 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Inhomogeneity Field", + argstr="--outInhomogeneity2 %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class MedicAlgorithmN3OutputSpec(TraitedSpec): @@ -215,20 +416,36 @@ class MedicAlgorithmN3(SEMLikeCommandLine): input_spec = MedicAlgorithmN3InputSpec output_spec = MedicAlgorithmN3OutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run edu.jhu.ece.iacl.plugins.classification.MedicAlgorithmN3 " - _outputs_filenames = {'outInhomogeneity2': 'outInhomogeneity2.nii', 'outInhomogeneity': 'outInhomogeneity.nii'} + _outputs_filenames = { + 'outInhomogeneity2': 'outInhomogeneity2.nii', + 'outInhomogeneity': 'outInhomogeneity.nii' + } _redirect_x = True class JistLaminarROIAveragingInputSpec(CommandLineInputSpec): - inIntensity = File(desc="Intensity Profile Image", exists=True, argstr="--inIntensity %s") + inIntensity = File( + desc="Intensity Profile Image", exists=True, argstr="--inIntensity %s") inROI = File(desc="ROI Mask", exists=True, argstr="--inROI %s") inROI2 = traits.Str(desc="ROI Name", argstr="--inROI2 %s") - inMask = File(desc="Mask Image (opt, 3D or 4D)", exists=True, argstr="--inMask %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outROI3 = traits.Either(traits.Bool, File(), hash_files=False, desc="ROI Average", argstr="--outROI3 %s") + inMask = File( + desc="Mask Image (opt, 3D or 4D)", exists=True, argstr="--inMask %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outROI3 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="ROI Average", + argstr="--outROI3 %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistLaminarROIAveragingOutputSpec(TraitedSpec): @@ -254,40 +471,147 @@ class JistLaminarROIAveraging(SEMLikeCommandLine): class MedicAlgorithmLesionToadsInputSpec(CommandLineInputSpec): - inT1_MPRAGE = File(desc="T1_MPRAGE Image", exists=True, argstr="--inT1_MPRAGE %s") - inT1_SPGR = File(desc="T1_SPGR Image", exists=True, argstr="--inT1_SPGR %s") + inT1_MPRAGE = File( + desc="T1_MPRAGE Image", exists=True, argstr="--inT1_MPRAGE %s") + inT1_SPGR = File( + desc="T1_SPGR Image", exists=True, argstr="--inT1_SPGR %s") inFLAIR = File(desc="FLAIR Image", exists=True, argstr="--inFLAIR %s") - inAtlas = traits.Enum("With Lesion", "No Lesion", desc="Atlas to Use", argstr="--inAtlas %s") - inOutput = traits.Enum("hard segmentation", "hard segmentation+memberships", "cruise inputs", "dura removal inputs", desc="Output images", argstr="--inOutput %s") - inOutput2 = traits.Enum("true", "false", desc="Output the hard classification using maximum membership (not neceesarily topologically correct)", argstr="--inOutput2 %s") - inCorrect = traits.Enum("true", "false", desc="Correct MR field inhomogeneity.", argstr="--inCorrect %s") - inOutput3 = traits.Enum("true", "false", desc="Output the estimated inhomogeneity field", argstr="--inOutput3 %s") - inAtlas2 = File(desc="Atlas File - With Lesions", exists=True, argstr="--inAtlas2 %s") - inAtlas3 = File(desc="Atlas File - No Lesion - T1 and FLAIR", exists=True, argstr="--inAtlas3 %s") - inAtlas4 = File(desc="Atlas File - No Lesion - T1 Only", exists=True, argstr="--inAtlas4 %s") - inMaximum = traits.Int(desc="Maximum distance from the interventricular WM boundary to downweight the lesion membership to avoid false postives", argstr="--inMaximum %d") - inMaximum2 = traits.Int(desc="Maximum Ventircle Distance", argstr="--inMaximum2 %d") - inMaximum3 = traits.Int(desc="Maximum InterVentricular Distance", argstr="--inMaximum3 %d") - inInclude = traits.Enum("true", "false", desc="Include lesion in WM class in hard classification", argstr="--inInclude %s") - inAtlas5 = traits.Float(desc="Controls the effect of the statistical atlas on the segmentation", argstr="--inAtlas5 %f") - inSmooting = traits.Float(desc="Controls the effect of neighberhood voxels on the membership", argstr="--inSmooting %f") - inMaximum4 = traits.Float(desc="Maximum amount of relative change in the energy function considered as the convergence criteria", argstr="--inMaximum4 %f") - inMaximum5 = traits.Int(desc="Maximum iterations", argstr="--inMaximum5 %d") - inAtlas6 = traits.Enum("rigid", "multi_fully_affine", desc="Atlas alignment", argstr="--inAtlas6 %s") - inConnectivity = traits.Enum("(26,6)", "(6,26)", "(6,18)", "(18,6)", desc="Connectivity (foreground,background)", argstr="--inConnectivity %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outHard = traits.Either(traits.Bool, File(), hash_files=False, desc="Hard segmentation", argstr="--outHard %s") - outHard2 = traits.Either(traits.Bool, File(), hash_files=False, desc="Hard segmentationfrom memberships", argstr="--outHard2 %s") - outInhomogeneity = traits.Either(traits.Bool, File(), hash_files=False, desc="Inhomogeneity Field", argstr="--outInhomogeneity %s") - outMembership = traits.Either(traits.Bool, File(), hash_files=False, desc="Membership Functions", argstr="--outMembership %s") - outLesion = traits.Either(traits.Bool, File(), hash_files=False, desc="Lesion Segmentation", argstr="--outLesion %s") - outSulcal = traits.Either(traits.Bool, File(), hash_files=False, desc="Sulcal CSF Membership", argstr="--outSulcal %s") - outCortical = traits.Either(traits.Bool, File(), hash_files=False, desc="Cortical GM Membership", argstr="--outCortical %s") - outFilled = traits.Either(traits.Bool, File(), hash_files=False, desc="Filled WM Membership", argstr="--outFilled %s") - outWM = traits.Either(traits.Bool, File(), hash_files=False, desc="WM Mask", argstr="--outWM %s") + inAtlas = traits.Enum( + "With Lesion", "No Lesion", desc="Atlas to Use", argstr="--inAtlas %s") + inOutput = traits.Enum( + "hard segmentation", + "hard segmentation+memberships", + "cruise inputs", + "dura removal inputs", + desc="Output images", + argstr="--inOutput %s") + inOutput2 = traits.Enum( + "true", + "false", + desc= + "Output the hard classification using maximum membership (not neceesarily topologically correct)", + argstr="--inOutput2 %s") + inCorrect = traits.Enum( + "true", + "false", + desc="Correct MR field inhomogeneity.", + argstr="--inCorrect %s") + inOutput3 = traits.Enum( + "true", + "false", + desc="Output the estimated inhomogeneity field", + argstr="--inOutput3 %s") + inAtlas2 = File( + desc="Atlas File - With Lesions", exists=True, argstr="--inAtlas2 %s") + inAtlas3 = File( + desc="Atlas File - No Lesion - T1 and FLAIR", + exists=True, + argstr="--inAtlas3 %s") + inAtlas4 = File( + desc="Atlas File - No Lesion - T1 Only", + exists=True, + argstr="--inAtlas4 %s") + inMaximum = traits.Int( + desc= + "Maximum distance from the interventricular WM boundary to downweight the lesion membership to avoid false postives", + argstr="--inMaximum %d") + inMaximum2 = traits.Int( + desc="Maximum Ventircle Distance", argstr="--inMaximum2 %d") + inMaximum3 = traits.Int( + desc="Maximum InterVentricular Distance", argstr="--inMaximum3 %d") + inInclude = traits.Enum( + "true", + "false", + desc="Include lesion in WM class in hard classification", + argstr="--inInclude %s") + inAtlas5 = traits.Float( + desc="Controls the effect of the statistical atlas on the segmentation", + argstr="--inAtlas5 %f") + inSmooting = traits.Float( + desc="Controls the effect of neighberhood voxels on the membership", + argstr="--inSmooting %f") + inMaximum4 = traits.Float( + desc= + "Maximum amount of relative change in the energy function considered as the convergence criteria", + argstr="--inMaximum4 %f") + inMaximum5 = traits.Int( + desc="Maximum iterations", argstr="--inMaximum5 %d") + inAtlas6 = traits.Enum( + "rigid", + "multi_fully_affine", + desc="Atlas alignment", + argstr="--inAtlas6 %s") + inConnectivity = traits.Enum( + "(26,6)", + "(6,26)", + "(6,18)", + "(18,6)", + desc="Connectivity (foreground,background)", + argstr="--inConnectivity %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outHard = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Hard segmentation", + argstr="--outHard %s") + outHard2 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Hard segmentationfrom memberships", + argstr="--outHard2 %s") + outInhomogeneity = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Inhomogeneity Field", + argstr="--outInhomogeneity %s") + outMembership = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Membership Functions", + argstr="--outMembership %s") + outLesion = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Lesion Segmentation", + argstr="--outLesion %s") + outSulcal = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Sulcal CSF Membership", + argstr="--outSulcal %s") + outCortical = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Cortical GM Membership", + argstr="--outCortical %s") + outFilled = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Filled WM Membership", + argstr="--outFilled %s") + outWM = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="WM Mask", + argstr="--outWM %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class MedicAlgorithmLesionToadsOutputSpec(TraitedSpec): @@ -319,24 +643,69 @@ class MedicAlgorithmLesionToads(SEMLikeCommandLine): input_spec = MedicAlgorithmLesionToadsInputSpec output_spec = MedicAlgorithmLesionToadsOutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run edu.jhu.ece.iacl.plugins.classification.MedicAlgorithmLesionToads " - _outputs_filenames = {'outWM': 'outWM.nii', 'outHard': 'outHard.nii', 'outFilled': 'outFilled.nii', 'outMembership': 'outMembership.nii', 'outInhomogeneity': 'outInhomogeneity.nii', 'outCortical': 'outCortical.nii', 'outHard2': 'outHard2.nii', 'outLesion': 'outLesion.nii', 'outSulcal': 'outSulcal.nii'} + _outputs_filenames = { + 'outWM': 'outWM.nii', + 'outHard': 'outHard.nii', + 'outFilled': 'outFilled.nii', + 'outMembership': 'outMembership.nii', + 'outInhomogeneity': 'outInhomogeneity.nii', + 'outCortical': 'outCortical.nii', + 'outHard2': 'outHard2.nii', + 'outLesion': 'outLesion.nii', + 'outSulcal': 'outSulcal.nii' + } _redirect_x = True class JistBrainMp2rageSkullStrippingInputSpec(CommandLineInputSpec): - inSecond = File(desc="Second inversion (Inv2) Image", exists=True, argstr="--inSecond %s") - inT1 = File(desc="T1 Map (T1_Images) Image (opt)", exists=True, argstr="--inT1 %s") - inT1weighted = File(desc="T1-weighted (UNI) Image (opt)", exists=True, argstr="--inT1weighted %s") - inFilter = File(desc="Filter Image (opt)", exists=True, argstr="--inFilter %s") - inSkip = traits.Enum("true", "false", desc="Skip zero values", argstr="--inSkip %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outBrain = traits.Either(traits.Bool, File(), hash_files=False, desc="Brain Mask Image", argstr="--outBrain %s") - outMasked = traits.Either(traits.Bool, File(), hash_files=False, desc="Masked T1 Map Image", argstr="--outMasked %s") - outMasked2 = traits.Either(traits.Bool, File(), hash_files=False, desc="Masked T1-weighted Image", argstr="--outMasked2 %s") - outMasked3 = traits.Either(traits.Bool, File(), hash_files=False, desc="Masked Filter Image", argstr="--outMasked3 %s") + inSecond = File( + desc="Second inversion (Inv2) Image", + exists=True, + argstr="--inSecond %s") + inT1 = File( + desc="T1 Map (T1_Images) Image (opt)", exists=True, argstr="--inT1 %s") + inT1weighted = File( + desc="T1-weighted (UNI) Image (opt)", + exists=True, + argstr="--inT1weighted %s") + inFilter = File( + desc="Filter Image (opt)", exists=True, argstr="--inFilter %s") + inSkip = traits.Enum( + "true", "false", desc="Skip zero values", argstr="--inSkip %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outBrain = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Brain Mask Image", + argstr="--outBrain %s") + outMasked = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Masked T1 Map Image", + argstr="--outMasked %s") + outMasked2 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Masked T1-weighted Image", + argstr="--outMasked2 %s") + outMasked3 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Masked Filter Image", + argstr="--outMasked3 %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistBrainMp2rageSkullStrippingOutputSpec(TraitedSpec): @@ -360,24 +729,58 @@ class JistBrainMp2rageSkullStripping(SEMLikeCommandLine): input_spec = JistBrainMp2rageSkullStrippingInputSpec output_spec = JistBrainMp2rageSkullStrippingOutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run de.mpg.cbs.jist.brain.JistBrainMp2rageSkullStripping " - _outputs_filenames = {'outBrain': 'outBrain.nii', 'outMasked3': 'outMasked3.nii', 'outMasked2': 'outMasked2.nii', 'outMasked': 'outMasked.nii'} + _outputs_filenames = { + 'outBrain': 'outBrain.nii', + 'outMasked3': 'outMasked3.nii', + 'outMasked2': 'outMasked2.nii', + 'outMasked': 'outMasked.nii' + } _redirect_x = True class JistCortexSurfaceMeshInflationInputSpec(CommandLineInputSpec): - inLevelset = File(desc="Levelset Image", exists=True, argstr="--inLevelset %s") + inLevelset = File( + desc="Levelset Image", exists=True, argstr="--inLevelset %s") inSOR = traits.Float(desc="SOR Parameter", argstr="--inSOR %f") - inMean = traits.Float(desc="Mean Curvature Threshold", argstr="--inMean %f") + inMean = traits.Float( + desc="Mean Curvature Threshold", argstr="--inMean %f") inStep = traits.Int(desc="Step Size", argstr="--inStep %d") inMax = traits.Int(desc="Max Iterations", argstr="--inMax %d") - inLorentzian = traits.Enum("true", "false", desc="Lorentzian Norm", argstr="--inLorentzian %s") - inTopology = traits.Enum("26/6", "6/26", "18/6", "6/18", "6/6", "wcs", "wco", "no", desc="Topology", argstr="--inTopology %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outOriginal = traits.Either(traits.Bool, File(), hash_files=False, desc="Original Surface", argstr="--outOriginal %s") - outInflated = traits.Either(traits.Bool, File(), hash_files=False, desc="Inflated Surface", argstr="--outInflated %s") + inLorentzian = traits.Enum( + "true", "false", desc="Lorentzian Norm", argstr="--inLorentzian %s") + inTopology = traits.Enum( + "26/6", + "6/26", + "18/6", + "6/18", + "6/6", + "wcs", + "wco", + "no", + desc="Topology", + argstr="--inTopology %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outOriginal = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Original Surface", + argstr="--outOriginal %s") + outInflated = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Inflated Surface", + argstr="--outInflated %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistCortexSurfaceMeshInflationOutputSpec(TraitedSpec): @@ -402,25 +805,52 @@ class JistCortexSurfaceMeshInflation(SEMLikeCommandLine): input_spec = JistCortexSurfaceMeshInflationInputSpec output_spec = JistCortexSurfaceMeshInflationOutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run de.mpg.cbs.jist.cortex.JistCortexSurfaceMeshInflation " - _outputs_filenames = {'outOriginal': 'outOriginal', 'outInflated': 'outInflated'} + _outputs_filenames = { + 'outOriginal': 'outOriginal', + 'outInflated': 'outInflated' + } _redirect_x = True class RandomVolInputSpec(CommandLineInputSpec): - inSize = traits.Int(desc="Size of Volume in X direction", argstr="--inSize %d") - inSize2 = traits.Int(desc="Size of Volume in Y direction", argstr="--inSize2 %d") - inSize3 = traits.Int(desc="Size of Volume in Z direction", argstr="--inSize3 %d") - inSize4 = traits.Int(desc="Size of Volume in t direction", argstr="--inSize4 %d") - inStandard = traits.Int(desc="Standard Deviation for Normal Distribution", argstr="--inStandard %d") - inLambda = traits.Float(desc="Lambda Value for Exponential Distribution", argstr="--inLambda %f") + inSize = traits.Int( + desc="Size of Volume in X direction", argstr="--inSize %d") + inSize2 = traits.Int( + desc="Size of Volume in Y direction", argstr="--inSize2 %d") + inSize3 = traits.Int( + desc="Size of Volume in Z direction", argstr="--inSize3 %d") + inSize4 = traits.Int( + desc="Size of Volume in t direction", argstr="--inSize4 %d") + inStandard = traits.Int( + desc="Standard Deviation for Normal Distribution", + argstr="--inStandard %d") + inLambda = traits.Float( + desc="Lambda Value for Exponential Distribution", + argstr="--inLambda %f") inMaximum = traits.Int(desc="Maximum Value", argstr="--inMaximum %d") inMinimum = traits.Int(desc="Minimum Value", argstr="--inMinimum %d") - inField = traits.Enum("Uniform", "Normal", "Exponential", desc="Field", argstr="--inField %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outRand1 = traits.Either(traits.Bool, File(), hash_files=False, desc="Rand1", argstr="--outRand1 %s") + inField = traits.Enum( + "Uniform", + "Normal", + "Exponential", + desc="Field", + argstr="--inField %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outRand1 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Rand1", + argstr="--outRand1 %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class RandomVolOutputSpec(TraitedSpec): @@ -450,12 +880,31 @@ class RandomVol(SEMLikeCommandLine): class MedicAlgorithmImageCalculatorInputSpec(CommandLineInputSpec): inVolume = File(desc="Volume 1", exists=True, argstr="--inVolume %s") inVolume2 = File(desc="Volume 2", exists=True, argstr="--inVolume2 %s") - inOperation = traits.Enum("Add", "Subtract", "Multiply", "Divide", "Min", "Max", desc="Operation", argstr="--inOperation %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outResult = traits.Either(traits.Bool, File(), hash_files=False, desc="Result Volume", argstr="--outResult %s") + inOperation = traits.Enum( + "Add", + "Subtract", + "Multiply", + "Divide", + "Min", + "Max", + desc="Operation", + argstr="--inOperation %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outResult = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Result Volume", + argstr="--outResult %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class MedicAlgorithmImageCalculatorOutputSpec(TraitedSpec): @@ -483,15 +932,39 @@ class MedicAlgorithmImageCalculator(SEMLikeCommandLine): class JistBrainMp2rageDuraEstimationInputSpec(CommandLineInputSpec): - inSecond = File(desc="Second inversion (Inv2) Image", exists=True, argstr="--inSecond %s") - inSkull = File(desc="Skull Stripping Mask", exists=True, argstr="--inSkull %s") - inDistance = traits.Float(desc="Distance to background (mm)", argstr="--inDistance %f") - inoutput = traits.Enum("dura_region", "boundary", "dura_prior", "bg_prior", "intens_prior", desc="Outputs an estimate of the dura / CSF boundary or an estimate of the entire dura region.", argstr="--inoutput %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outDura = traits.Either(traits.Bool, File(), hash_files=False, desc="Dura Image", argstr="--outDura %s") + inSecond = File( + desc="Second inversion (Inv2) Image", + exists=True, + argstr="--inSecond %s") + inSkull = File( + desc="Skull Stripping Mask", exists=True, argstr="--inSkull %s") + inDistance = traits.Float( + desc="Distance to background (mm)", argstr="--inDistance %f") + inoutput = traits.Enum( + "dura_region", + "boundary", + "dura_prior", + "bg_prior", + "intens_prior", + desc= + "Outputs an estimate of the dura / CSF boundary or an estimate of the entire dura region.", + argstr="--inoutput %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outDura = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Dura Image", + argstr="--outDura %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistBrainMp2rageDuraEstimationOutputSpec(TraitedSpec): @@ -517,15 +990,34 @@ class JistBrainMp2rageDuraEstimation(SEMLikeCommandLine): class JistLaminarProfileSamplingInputSpec(CommandLineInputSpec): - inProfile = File(desc="Profile Surface Image", exists=True, argstr="--inProfile %s") - inIntensity = File(desc="Intensity Image", exists=True, argstr="--inIntensity %s") - inCortex = File(desc="Cortex Mask (opt)", exists=True, argstr="--inCortex %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outProfilemapped = traits.Either(traits.Bool, File(), hash_files=False, desc="Profile-mapped Intensity Image", argstr="--outProfilemapped %s") - outProfile2 = traits.Either(traits.Bool, File(), hash_files=False, desc="Profile 4D Mask", argstr="--outProfile2 %s") + inProfile = File( + desc="Profile Surface Image", exists=True, argstr="--inProfile %s") + inIntensity = File( + desc="Intensity Image", exists=True, argstr="--inIntensity %s") + inCortex = File( + desc="Cortex Mask (opt)", exists=True, argstr="--inCortex %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outProfilemapped = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Profile-mapped Intensity Image", + argstr="--outProfilemapped %s") + outProfile2 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Profile 4D Mask", + argstr="--outProfile2 %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistLaminarProfileSamplingOutputSpec(TraitedSpec): @@ -547,25 +1039,91 @@ class JistLaminarProfileSampling(SEMLikeCommandLine): input_spec = JistLaminarProfileSamplingInputSpec output_spec = JistLaminarProfileSamplingOutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run de.mpg.cbs.jist.laminar.JistLaminarProfileSampling " - _outputs_filenames = {'outProfile2': 'outProfile2.nii', 'outProfilemapped': 'outProfilemapped.nii'} + _outputs_filenames = { + 'outProfile2': 'outProfile2.nii', + 'outProfilemapped': 'outProfilemapped.nii' + } _redirect_x = True class MedicAlgorithmMipavReorientInputSpec(CommandLineInputSpec): - inSource = InputMultiPath(File, desc="Source", sep=";", argstr="--inSource %s") + inSource = InputMultiPath( + File, desc="Source", sep=";", argstr="--inSource %s") inTemplate = File(desc="Template", exists=True, argstr="--inTemplate %s") - inNew = traits.Enum("Dicom axial", "Dicom coronal", "Dicom sagittal", "User defined", desc="New image orientation", argstr="--inNew %s") - inUser = traits.Enum("Unknown", "Patient Right to Left", "Patient Left to Right", "Patient Posterior to Anterior", "Patient Anterior to Posterior", "Patient Inferior to Superior", "Patient Superior to Inferior", desc="User defined X-axis orientation (image left to right)", argstr="--inUser %s") - inUser2 = traits.Enum("Unknown", "Patient Right to Left", "Patient Left to Right", "Patient Posterior to Anterior", "Patient Anterior to Posterior", "Patient Inferior to Superior", "Patient Superior to Inferior", desc="User defined Y-axis orientation (image top to bottom)", argstr="--inUser2 %s") - inUser3 = traits.Enum("Unknown", "Patient Right to Left", "Patient Left to Right", "Patient Posterior to Anterior", "Patient Anterior to Posterior", "Patient Inferior to Superior", "Patient Superior to Inferior", desc="User defined Z-axis orientation (into the screen)", argstr="--inUser3 %s") - inUser4 = traits.Enum("Axial", "Coronal", "Sagittal", "Unknown", desc="User defined Image Orientation", argstr="--inUser4 %s") - inInterpolation = traits.Enum("Nearest Neighbor", "Trilinear", "Bspline 3rd order", "Bspline 4th order", "Cubic Lagrangian", "Quintic Lagrangian", "Heptic Lagrangian", "Windowed Sinc", desc="Interpolation", argstr="--inInterpolation %s") - inResolution = traits.Enum("Unchanged", "Finest cubic", "Coarsest cubic", "Same as template", desc="Resolution", argstr="--inResolution %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outReoriented = InputMultiPath(File, desc="Reoriented Volume", sep=";", argstr="--outReoriented %s") + inNew = traits.Enum( + "Dicom axial", + "Dicom coronal", + "Dicom sagittal", + "User defined", + desc="New image orientation", + argstr="--inNew %s") + inUser = traits.Enum( + "Unknown", + "Patient Right to Left", + "Patient Left to Right", + "Patient Posterior to Anterior", + "Patient Anterior to Posterior", + "Patient Inferior to Superior", + "Patient Superior to Inferior", + desc="User defined X-axis orientation (image left to right)", + argstr="--inUser %s") + inUser2 = traits.Enum( + "Unknown", + "Patient Right to Left", + "Patient Left to Right", + "Patient Posterior to Anterior", + "Patient Anterior to Posterior", + "Patient Inferior to Superior", + "Patient Superior to Inferior", + desc="User defined Y-axis orientation (image top to bottom)", + argstr="--inUser2 %s") + inUser3 = traits.Enum( + "Unknown", + "Patient Right to Left", + "Patient Left to Right", + "Patient Posterior to Anterior", + "Patient Anterior to Posterior", + "Patient Inferior to Superior", + "Patient Superior to Inferior", + desc="User defined Z-axis orientation (into the screen)", + argstr="--inUser3 %s") + inUser4 = traits.Enum( + "Axial", + "Coronal", + "Sagittal", + "Unknown", + desc="User defined Image Orientation", + argstr="--inUser4 %s") + inInterpolation = traits.Enum( + "Nearest Neighbor", + "Trilinear", + "Bspline 3rd order", + "Bspline 4th order", + "Cubic Lagrangian", + "Quintic Lagrangian", + "Heptic Lagrangian", + "Windowed Sinc", + desc="Interpolation", + argstr="--inInterpolation %s") + inResolution = traits.Enum( + "Unchanged", + "Finest cubic", + "Coarsest cubic", + "Same as template", + desc="Resolution", + argstr="--inResolution %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outReoriented = InputMultiPath( + File, desc="Reoriented Volume", sep=";", argstr="--outReoriented %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class MedicAlgorithmMipavReorientOutputSpec(TraitedSpec): @@ -591,65 +1149,238 @@ class MedicAlgorithmMipavReorient(SEMLikeCommandLine): class MedicAlgorithmSPECTRE2010InputSpec(CommandLineInputSpec): - inInput = File(desc="Input volume to be skullstripped.", exists=True, argstr="--inInput %s") - inAtlas = File(desc="SPECTRE atlas description file. A text file enumerating atlas files and landmarks.", exists=True, argstr="--inAtlas %s") - inInitial = traits.Int(desc="Erosion of the inital mask, which is based on the probability mask and the classification., The initial mask is ouput as the d0 volume at the conclusion of SPECTRE.", argstr="--inInitial %d") - inImage = traits.Enum("T1_SPGR", "T1_ALT", "T1_MPRAGE", "T2", "FLAIR", desc="Set the image modality. MP-RAGE is recommended for most T1 sequence images.", argstr="--inImage %s") - inOutput = traits.Enum("true", "false", desc="Determines if the output results are transformed back into the space of the original input image.", argstr="--inOutput %s") - inFind = traits.Enum("true", "false", desc="Find Midsaggital Plane", argstr="--inFind %s") - inRun = traits.Enum("true", "false", desc="Run Smooth Brain Mask", argstr="--inRun %s") - inResample = traits.Enum("true", "false", desc="Determines if the data is resampled to be isotropic during the processing.", argstr="--inResample %s") - inInitial2 = traits.Float(desc="Initial probability threshold", argstr="--inInitial2 %f") - inMinimum = traits.Float(desc="Minimum probability threshold", argstr="--inMinimum %f") - inMMC = traits.Int(desc="The size of the dilation step within the Modified Morphological Closing.", argstr="--inMMC %d") - inMMC2 = traits.Int(desc="The size of the erosion step within the Modified Morphological Closing.", argstr="--inMMC2 %d") - inInhomogeneity = traits.Enum("true", "false", desc="Set to false by default, this parameter will make FANTASM try to do inhomogeneity correction during it's iterative cycle.", argstr="--inInhomogeneity %s") + inInput = File( + desc="Input volume to be skullstripped.", + exists=True, + argstr="--inInput %s") + inAtlas = File( + desc= + "SPECTRE atlas description file. A text file enumerating atlas files and landmarks.", + exists=True, + argstr="--inAtlas %s") + inInitial = traits.Int( + desc= + "Erosion of the inital mask, which is based on the probability mask and the classification., The initial mask is ouput as the d0 volume at the conclusion of SPECTRE.", + argstr="--inInitial %d") + inImage = traits.Enum( + "T1_SPGR", + "T1_ALT", + "T1_MPRAGE", + "T2", + "FLAIR", + desc= + "Set the image modality. MP-RAGE is recommended for most T1 sequence images.", + argstr="--inImage %s") + inOutput = traits.Enum( + "true", + "false", + desc= + "Determines if the output results are transformed back into the space of the original input image.", + argstr="--inOutput %s") + inFind = traits.Enum( + "true", "false", desc="Find Midsaggital Plane", argstr="--inFind %s") + inRun = traits.Enum( + "true", "false", desc="Run Smooth Brain Mask", argstr="--inRun %s") + inResample = traits.Enum( + "true", + "false", + desc= + "Determines if the data is resampled to be isotropic during the processing.", + argstr="--inResample %s") + inInitial2 = traits.Float( + desc="Initial probability threshold", argstr="--inInitial2 %f") + inMinimum = traits.Float( + desc="Minimum probability threshold", argstr="--inMinimum %f") + inMMC = traits.Int( + desc= + "The size of the dilation step within the Modified Morphological Closing.", + argstr="--inMMC %d") + inMMC2 = traits.Int( + desc= + "The size of the erosion step within the Modified Morphological Closing.", + argstr="--inMMC2 %d") + inInhomogeneity = traits.Enum( + "true", + "false", + desc= + "Set to false by default, this parameter will make FANTASM try to do inhomogeneity correction during it's iterative cycle.", + argstr="--inInhomogeneity %s") inSmoothing = traits.Float(argstr="--inSmoothing %f") inBackground = traits.Float(argstr="--inBackground %f") - inOutput2 = traits.Enum("true", "false", desc="Output Plane?", argstr="--inOutput2 %s") - inOutput3 = traits.Enum("true", "false", desc="Output Split-Halves?", argstr="--inOutput3 %s") - inOutput4 = traits.Enum("true", "false", desc="Output Segmentation on Plane?", argstr="--inOutput4 %s") - inDegrees = traits.Enum("Rigid - 6", "Global rescale - 7", "Specific rescale - 9", "Affine - 12", desc="Degrees of freedom", argstr="--inDegrees %s") - inCost = traits.Enum("Correlation ratio", "Least squares", "Normalized cross correlation", "Normalized mutual information", desc="Cost function", argstr="--inCost %s") - inRegistration = traits.Enum("Trilinear", "Bspline 3rd order", "Bspline 4th order", "Cubic Lagrangian", "Quintic Lagrangian", "Heptic Lagrangian", "Windowed sinc", desc="Registration interpolation", argstr="--inRegistration %s") - inOutput5 = traits.Enum("Trilinear", "Bspline 3rd order", "Bspline 4th order", "Cubic Lagrangian", "Quintic Lagrangian", "Heptic Lagrangian", "Windowed sinc", "Nearest Neighbor", desc="Output interpolation", argstr="--inOutput5 %s") - inApply = traits.Enum("All", "X", "Y", "Z", desc="Apply rotation", argstr="--inApply %s") + inOutput2 = traits.Enum( + "true", "false", desc="Output Plane?", argstr="--inOutput2 %s") + inOutput3 = traits.Enum( + "true", "false", desc="Output Split-Halves?", argstr="--inOutput3 %s") + inOutput4 = traits.Enum( + "true", + "false", + desc="Output Segmentation on Plane?", + argstr="--inOutput4 %s") + inDegrees = traits.Enum( + "Rigid - 6", + "Global rescale - 7", + "Specific rescale - 9", + "Affine - 12", + desc="Degrees of freedom", + argstr="--inDegrees %s") + inCost = traits.Enum( + "Correlation ratio", + "Least squares", + "Normalized cross correlation", + "Normalized mutual information", + desc="Cost function", + argstr="--inCost %s") + inRegistration = traits.Enum( + "Trilinear", + "Bspline 3rd order", + "Bspline 4th order", + "Cubic Lagrangian", + "Quintic Lagrangian", + "Heptic Lagrangian", + "Windowed sinc", + desc="Registration interpolation", + argstr="--inRegistration %s") + inOutput5 = traits.Enum( + "Trilinear", + "Bspline 3rd order", + "Bspline 4th order", + "Cubic Lagrangian", + "Quintic Lagrangian", + "Heptic Lagrangian", + "Windowed sinc", + "Nearest Neighbor", + desc="Output interpolation", + argstr="--inOutput5 %s") + inApply = traits.Enum( + "All", "X", "Y", "Z", desc="Apply rotation", argstr="--inApply %s") inMinimum2 = traits.Float(desc="Minimum angle", argstr="--inMinimum2 %f") inMaximum = traits.Float(desc="Maximum angle", argstr="--inMaximum %f") - inCoarse = traits.Float(desc="Coarse angle increment", argstr="--inCoarse %f") + inCoarse = traits.Float( + desc="Coarse angle increment", argstr="--inCoarse %f") inFine = traits.Float(desc="Fine angle increment", argstr="--inFine %f") - inMultiple = traits.Int(desc="Multiple of tolerance to bracket the minimum", argstr="--inMultiple %d") + inMultiple = traits.Int( + desc="Multiple of tolerance to bracket the minimum", + argstr="--inMultiple %d") inNumber = traits.Int(desc="Number of iterations", argstr="--inNumber %d") - inNumber2 = traits.Int(desc="Number of minima from Level 8 to test at Level 4", argstr="--inNumber2 %d") - inUse = traits.Enum("true", "false", desc="Use the max of the min resolutions of the two datasets when resampling", argstr="--inUse %s") - inSubsample = traits.Enum("true", "false", desc="Subsample image for speed", argstr="--inSubsample %s") - inSkip = traits.Enum("true", "false", desc="Skip multilevel search (Assume images are close to alignment)", argstr="--inSkip %s") - inMultithreading = traits.Enum("true", "false", desc="Set to false by default, this parameter controls the multithreaded behavior of the linear registration.", argstr="--inMultithreading %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outOriginal = traits.Either(traits.Bool, File(), hash_files=False, desc="If Output in Original Space Flag is true then outputs the original input volume. Otherwise outputs the axialy reoriented input volume.", argstr="--outOriginal %s") - outStripped = traits.Either(traits.Bool, File(), hash_files=False, desc="Skullstripped result of the input volume with just the brain.", argstr="--outStripped %s") - outMask = traits.Either(traits.Bool, File(), hash_files=False, desc="Binary Mask of the skullstripped result with just the brain", argstr="--outMask %s") - outPrior = traits.Either(traits.Bool, File(), hash_files=False, desc="Probability prior from the atlas registrations", argstr="--outPrior %s") - outFANTASM = traits.Either(traits.Bool, File(), hash_files=False, desc="Tissue classification of of the whole input volume.", argstr="--outFANTASM %s") - outd0 = traits.Either(traits.Bool, File(), hash_files=False, desc="Initial Brainmask", argstr="--outd0 %s") - outMidsagittal = traits.Either(traits.Bool, File(), hash_files=False, desc="Plane dividing the brain hemispheres", argstr="--outMidsagittal %s") - outSplitHalves = traits.Either(traits.Bool, File(), hash_files=False, desc="Skullstripped mask of the brain with the hemispheres divided.", argstr="--outSplitHalves %s") - outSegmentation = traits.Either(traits.Bool, File(), hash_files=False, desc="2D image showing the tissue classification on the midsagittal plane", argstr="--outSegmentation %s") + inNumber2 = traits.Int( + desc="Number of minima from Level 8 to test at Level 4", + argstr="--inNumber2 %d") + inUse = traits.Enum( + "true", + "false", + desc= + "Use the max of the min resolutions of the two datasets when resampling", + argstr="--inUse %s") + inSubsample = traits.Enum( + "true", + "false", + desc="Subsample image for speed", + argstr="--inSubsample %s") + inSkip = traits.Enum( + "true", + "false", + desc="Skip multilevel search (Assume images are close to alignment)", + argstr="--inSkip %s") + inMultithreading = traits.Enum( + "true", + "false", + desc= + "Set to false by default, this parameter controls the multithreaded behavior of the linear registration.", + argstr="--inMultithreading %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outOriginal = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "If Output in Original Space Flag is true then outputs the original input volume. Otherwise outputs the axialy reoriented input volume.", + argstr="--outOriginal %s") + outStripped = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Skullstripped result of the input volume with just the brain.", + argstr="--outStripped %s") + outMask = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Binary Mask of the skullstripped result with just the brain", + argstr="--outMask %s") + outPrior = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Probability prior from the atlas registrations", + argstr="--outPrior %s") + outFANTASM = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Tissue classification of of the whole input volume.", + argstr="--outFANTASM %s") + outd0 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Initial Brainmask", + argstr="--outd0 %s") + outMidsagittal = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Plane dividing the brain hemispheres", + argstr="--outMidsagittal %s") + outSplitHalves = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Skullstripped mask of the brain with the hemispheres divided.", + argstr="--outSplitHalves %s") + outSegmentation = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "2D image showing the tissue classification on the midsagittal plane", + argstr="--outSegmentation %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class MedicAlgorithmSPECTRE2010OutputSpec(TraitedSpec): - outOriginal = File(desc="If Output in Original Space Flag is true then outputs the original input volume. Otherwise outputs the axialy reoriented input volume.", exists=True) - outStripped = File(desc="Skullstripped result of the input volume with just the brain.", exists=True) - outMask = File(desc="Binary Mask of the skullstripped result with just the brain", exists=True) - outPrior = File(desc="Probability prior from the atlas registrations", exists=True) - outFANTASM = File(desc="Tissue classification of of the whole input volume.", exists=True) + outOriginal = File( + desc= + "If Output in Original Space Flag is true then outputs the original input volume. Otherwise outputs the axialy reoriented input volume.", + exists=True) + outStripped = File( + desc="Skullstripped result of the input volume with just the brain.", + exists=True) + outMask = File( + desc="Binary Mask of the skullstripped result with just the brain", + exists=True) + outPrior = File( + desc="Probability prior from the atlas registrations", exists=True) + outFANTASM = File( + desc="Tissue classification of of the whole input volume.", + exists=True) outd0 = File(desc="Initial Brainmask", exists=True) - outMidsagittal = File(desc="Plane dividing the brain hemispheres", exists=True) - outSplitHalves = File(desc="Skullstripped mask of the brain with the hemispheres divided.", exists=True) - outSegmentation = File(desc="2D image showing the tissue classification on the midsagittal plane", exists=True) + outMidsagittal = File( + desc="Plane dividing the brain hemispheres", exists=True) + outSplitHalves = File( + desc="Skullstripped mask of the brain with the hemispheres divided.", + exists=True) + outSegmentation = File( + desc= + "2D image showing the tissue classification on the midsagittal plane", + exists=True) class MedicAlgorithmSPECTRE2010(SEMLikeCommandLine): @@ -677,19 +1408,47 @@ class MedicAlgorithmSPECTRE2010(SEMLikeCommandLine): input_spec = MedicAlgorithmSPECTRE2010InputSpec output_spec = MedicAlgorithmSPECTRE2010OutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run edu.jhu.ece.iacl.plugins.segmentation.skull_strip.MedicAlgorithmSPECTRE2010 " - _outputs_filenames = {'outd0': 'outd0.nii', 'outOriginal': 'outOriginal.nii', 'outMask': 'outMask.nii', 'outSplitHalves': 'outSplitHalves.nii', 'outMidsagittal': 'outMidsagittal.nii', 'outPrior': 'outPrior.nii', 'outFANTASM': 'outFANTASM.nii', 'outSegmentation': 'outSegmentation.nii', 'outStripped': 'outStripped.nii'} + _outputs_filenames = { + 'outd0': 'outd0.nii', + 'outOriginal': 'outOriginal.nii', + 'outMask': 'outMask.nii', + 'outSplitHalves': 'outSplitHalves.nii', + 'outMidsagittal': 'outMidsagittal.nii', + 'outPrior': 'outPrior.nii', + 'outFANTASM': 'outFANTASM.nii', + 'outSegmentation': 'outSegmentation.nii', + 'outStripped': 'outStripped.nii' + } _redirect_x = True class JistBrainPartialVolumeFilterInputSpec(CommandLineInputSpec): inInput = File(desc="Input Image", exists=True, argstr="--inInput %s") - inPV = traits.Enum("bright", "dark", "both", desc="Outputs the raw intensity values or a probability score for the partial volume regions.", argstr="--inPV %s") - inoutput = traits.Enum("probability", "intensity", desc="output", argstr="--inoutput %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outPartial = traits.Either(traits.Bool, File(), hash_files=False, desc="Partial Volume Image", argstr="--outPartial %s") + inPV = traits.Enum( + "bright", + "dark", + "both", + desc= + "Outputs the raw intensity values or a probability score for the partial volume regions.", + argstr="--inPV %s") + inoutput = traits.Enum( + "probability", "intensity", desc="output", argstr="--inoutput %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outPartial = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Partial Volume Image", + argstr="--outPartial %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistBrainPartialVolumeFilterOutputSpec(TraitedSpec): @@ -715,20 +1474,66 @@ class JistBrainPartialVolumeFilter(SEMLikeCommandLine): class JistIntensityMp2rageMaskingInputSpec(CommandLineInputSpec): - inSecond = File(desc="Second inversion (Inv2) Image", exists=True, argstr="--inSecond %s") - inQuantitative = File(desc="Quantitative T1 Map (T1_Images) Image", exists=True, argstr="--inQuantitative %s") - inT1weighted = File(desc="T1-weighted (UNI) Image", exists=True, argstr="--inT1weighted %s") - inBackground = traits.Enum("exponential", "half-normal", desc="Model distribution for background noise (default is half-normal, exponential is more stringent).", argstr="--inBackground %s") - inSkip = traits.Enum("true", "false", desc="Skip zero values", argstr="--inSkip %s") - inMasking = traits.Enum("binary", "proba", desc="Whether to use a binary threshold or a weighted average based on the probability.", argstr="--inMasking %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outSignal = traits.Either(traits.Bool, File(), hash_files=False, desc="Signal Proba Image", argstr="--outSignal_Proba %s") - outSignal2 = traits.Either(traits.Bool, File(), hash_files=False, desc="Signal Mask Image", argstr="--outSignal_Mask %s") - outMasked = traits.Either(traits.Bool, File(), hash_files=False, desc="Masked T1 Map Image", argstr="--outMasked_T1_Map %s") - outMasked2 = traits.Either(traits.Bool, File(), hash_files=False, desc="Masked Iso Image", argstr="--outMasked_T1weighted %s") + inSecond = File( + desc="Second inversion (Inv2) Image", + exists=True, + argstr="--inSecond %s") + inQuantitative = File( + desc="Quantitative T1 Map (T1_Images) Image", + exists=True, + argstr="--inQuantitative %s") + inT1weighted = File( + desc="T1-weighted (UNI) Image", + exists=True, + argstr="--inT1weighted %s") + inBackground = traits.Enum( + "exponential", + "half-normal", + desc= + "Model distribution for background noise (default is half-normal, exponential is more stringent).", + argstr="--inBackground %s") + inSkip = traits.Enum( + "true", "false", desc="Skip zero values", argstr="--inSkip %s") + inMasking = traits.Enum( + "binary", + "proba", + desc= + "Whether to use a binary threshold or a weighted average based on the probability.", + argstr="--inMasking %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outSignal = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Signal Proba Image", + argstr="--outSignal_Proba %s") + outSignal2 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Signal Mask Image", + argstr="--outSignal_Mask %s") + outMasked = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Masked T1 Map Image", + argstr="--outMasked_T1_Map %s") + outMasked2 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Masked Iso Image", + argstr="--outMasked_T1weighted %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class JistIntensityMp2rageMaskingOutputSpec(TraitedSpec): @@ -752,20 +1557,39 @@ class JistIntensityMp2rageMasking(SEMLikeCommandLine): input_spec = JistIntensityMp2rageMaskingInputSpec output_spec = JistIntensityMp2rageMaskingOutputSpec _cmd = "java edu.jhu.ece.iacl.jist.cli.run de.mpg.cbs.jist.intensity.JistIntensityMp2rageMasking " - _outputs_filenames = {'outSignal2': 'outSignal2.nii', 'outSignal': 'outSignal.nii', 'outMasked2': 'outMasked2.nii', 'outMasked': 'outMasked.nii'} + _outputs_filenames = { + 'outSignal2': 'outSignal2.nii', + 'outSignal': 'outSignal.nii', + 'outMasked2': 'outMasked2.nii', + 'outMasked': 'outMasked.nii' + } _redirect_x = True class MedicAlgorithmThresholdToBinaryMaskInputSpec(CommandLineInputSpec): - inLabel = InputMultiPath(File, desc="Input volumes", sep=";", argstr="--inLabel %s") - inMinimum = traits.Float(desc="Minimum threshold value.", argstr="--inMinimum %f") - inMaximum = traits.Float(desc="Maximum threshold value.", argstr="--inMaximum %f") - inUse = traits.Enum("true", "false", desc="Use the images max intensity as the max value of the range.", argstr="--inUse %s") - xPrefExt = traits.Enum("nrrd", desc="Output File Type", argstr="--xPrefExt %s") - outBinary = InputMultiPath(File, desc="Binary Mask", sep=";", argstr="--outBinary %s") + inLabel = InputMultiPath( + File, desc="Input volumes", sep=";", argstr="--inLabel %s") + inMinimum = traits.Float( + desc="Minimum threshold value.", argstr="--inMinimum %f") + inMaximum = traits.Float( + desc="Maximum threshold value.", argstr="--inMaximum %f") + inUse = traits.Enum( + "true", + "false", + desc="Use the images max intensity as the max value of the range.", + argstr="--inUse %s") + xPrefExt = traits.Enum( + "nrrd", desc="Output File Type", argstr="--xPrefExt %s") + outBinary = InputMultiPath( + File, desc="Binary Mask", sep=";", argstr="--outBinary %s") null = traits.Str(desc="Execution Time", argstr="--null %s") - xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d") - xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True) + xDefaultMem = traits.Int( + desc="Set default maximum heap size", argstr="-xDefaultMem %d") + xMaxProcess = traits.Int( + 1, + desc="Set default maximum number of processes.", + argstr="-xMaxProcess %d", + usedefault=True) class MedicAlgorithmThresholdToBinaryMaskOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/mipav/generate_classes.py b/nipype/interfaces/mipav/generate_classes.py index d348ef2546..df48a2d2da 100644 --- a/nipype/interfaces/mipav/generate_classes.py +++ b/nipype/interfaces/mipav/generate_classes.py @@ -6,33 +6,50 @@ # NOTE: For now either the launcher needs to be found on the default path, or # every tool in the modules list must be found on the default path # AND calling the module with --xml must be supported and compliant. - modules_list = ['edu.jhu.bme.smile.demo.RandomVol', - 'de.mpg.cbs.jist.laminar.JistLaminarProfileCalculator', - 'de.mpg.cbs.jist.laminar.JistLaminarProfileSampling', - 'de.mpg.cbs.jist.laminar.JistLaminarROIAveraging', - 'de.mpg.cbs.jist.laminar.JistLaminarVolumetricLayering', - 'de.mpg.cbs.jist.laminar.JistLaminarProfileGeometry', - 'de.mpg.cbs.jist.brain.JistBrainMgdmSegmentation', - 'de.mpg.cbs.jist.brain.JistBrainMp2rageSkullStripping', - 'de.mpg.cbs.jist.brain.JistBrainPartialVolumeFilter', - 'de.mpg.cbs.jist.brain.JistBrainMp2rageDuraEstimation'] - - modules_from_chris = ['edu.jhu.ece.iacl.plugins.segmentation.skull_strip.MedicAlgorithmSPECTRE2010', - 'edu.jhu.ece.iacl.plugins.utilities.volume.MedicAlgorithmMipavReorient', - 'edu.jhu.ece.iacl.plugins.utilities.math.MedicAlgorithmImageCalculator', - 'de.mpg.cbs.jist.brain.JistBrainMp2rageDuraEstimation', - 'de.mpg.cbs.jist.brain.JistBrainPartialVolumeFilter', - 'edu.jhu.ece.iacl.plugins.utilities.volume.MedicAlgorithmThresholdToBinaryMask', - # 'de.mpg.cbs.jist.cortex.JistCortexFullCRUISE', # waiting for http://www.nitrc.org/tracker/index.php?func=detail&aid=7236&group_id=228&atid=942 to be fixed - 'de.mpg.cbs.jist.cortex.JistCortexSurfaceMeshInflation'] - - modules_from_julia = ['de.mpg.cbs.jist.intensity.JistIntensityMp2rageMasking', - 'edu.jhu.ece.iacl.plugins.segmentation.skull_strip.MedicAlgorithmSPECTRE2010'] - - modules_from_leonie = ['edu.jhu.ece.iacl.plugins.classification.MedicAlgorithmLesionToads'] - - modules_from_yasinyazici = ['edu.jhu.ece.iacl.plugins.classification.MedicAlgorithmN3'] - - modules_list = list(set(modules_list).union(modules_from_chris).union(modules_from_leonie).union(modules_from_julia).union(modules_from_yasinyazici).union(modules_list)) - - generate_all_classes(modules_list=modules_list, launcher=["java edu.jhu.ece.iacl.jist.cli.run"], redirect_x=True, mipav_hacks=True) + modules_list = [ + 'edu.jhu.bme.smile.demo.RandomVol', + 'de.mpg.cbs.jist.laminar.JistLaminarProfileCalculator', + 'de.mpg.cbs.jist.laminar.JistLaminarProfileSampling', + 'de.mpg.cbs.jist.laminar.JistLaminarROIAveraging', + 'de.mpg.cbs.jist.laminar.JistLaminarVolumetricLayering', + 'de.mpg.cbs.jist.laminar.JistLaminarProfileGeometry', + 'de.mpg.cbs.jist.brain.JistBrainMgdmSegmentation', + 'de.mpg.cbs.jist.brain.JistBrainMp2rageSkullStripping', + 'de.mpg.cbs.jist.brain.JistBrainPartialVolumeFilter', + 'de.mpg.cbs.jist.brain.JistBrainMp2rageDuraEstimation' + ] + + modules_from_chris = [ + 'edu.jhu.ece.iacl.plugins.segmentation.skull_strip.MedicAlgorithmSPECTRE2010', + 'edu.jhu.ece.iacl.plugins.utilities.volume.MedicAlgorithmMipavReorient', + 'edu.jhu.ece.iacl.plugins.utilities.math.MedicAlgorithmImageCalculator', + 'de.mpg.cbs.jist.brain.JistBrainMp2rageDuraEstimation', + 'de.mpg.cbs.jist.brain.JistBrainPartialVolumeFilter', + 'edu.jhu.ece.iacl.plugins.utilities.volume.MedicAlgorithmThresholdToBinaryMask', + # 'de.mpg.cbs.jist.cortex.JistCortexFullCRUISE', # waiting for http://www.nitrc.org/tracker/index.php?func=detail&aid=7236&group_id=228&atid=942 to be fixed + 'de.mpg.cbs.jist.cortex.JistCortexSurfaceMeshInflation' + ] + + modules_from_julia = [ + 'de.mpg.cbs.jist.intensity.JistIntensityMp2rageMasking', + 'edu.jhu.ece.iacl.plugins.segmentation.skull_strip.MedicAlgorithmSPECTRE2010' + ] + + modules_from_leonie = [ + 'edu.jhu.ece.iacl.plugins.classification.MedicAlgorithmLesionToads' + ] + + modules_from_yasinyazici = [ + 'edu.jhu.ece.iacl.plugins.classification.MedicAlgorithmN3' + ] + + modules_list = list( + set(modules_list).union(modules_from_chris).union(modules_from_leonie) + .union(modules_from_julia).union(modules_from_yasinyazici).union( + modules_list)) + + generate_all_classes( + modules_list=modules_list, + launcher=["java edu.jhu.ece.iacl.jist.cli.run"], + redirect_x=True, + mipav_hacks=True) diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py index 64349fa299..c062113c4a 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py @@ -4,84 +4,72 @@ def test_JistBrainMgdmSegmentation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inAdjust=dict(argstr='--inAdjust %s', - ), - inAtlas=dict(argstr='--inAtlas %s', - ), - inCompute=dict(argstr='--inCompute %s', - ), - inCurvature=dict(argstr='--inCurvature %f', - ), - inData=dict(argstr='--inData %f', - ), - inFLAIR=dict(argstr='--inFLAIR %s', - ), - inMP2RAGE=dict(argstr='--inMP2RAGE %s', - ), - inMP2RAGE2=dict(argstr='--inMP2RAGE2 %s', - ), - inMPRAGE=dict(argstr='--inMPRAGE %s', - ), - inMax=dict(argstr='--inMax %d', - ), - inMin=dict(argstr='--inMin %f', - ), - inOutput=dict(argstr='--inOutput %s', - ), - inPV=dict(argstr='--inPV %s', - ), - inPosterior=dict(argstr='--inPosterior %f', - ), - inSteps=dict(argstr='--inSteps %d', - ), - inTopology=dict(argstr='--inTopology %s', - ), - null=dict(argstr='--null %s', - ), - outLevelset=dict(argstr='--outLevelset %s', - hash_files=False, - ), - outPosterior2=dict(argstr='--outPosterior2 %s', - hash_files=False, - ), - outPosterior3=dict(argstr='--outPosterior3 %s', - hash_files=False, - ), - outSegmented=dict(argstr='--outSegmented %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inAdjust=dict(argstr='--inAdjust %s', ), + inAtlas=dict(argstr='--inAtlas %s', ), + inCompute=dict(argstr='--inCompute %s', ), + inCurvature=dict(argstr='--inCurvature %f', ), + inData=dict(argstr='--inData %f', ), + inFLAIR=dict(argstr='--inFLAIR %s', ), + inMP2RAGE=dict(argstr='--inMP2RAGE %s', ), + inMP2RAGE2=dict(argstr='--inMP2RAGE2 %s', ), + inMPRAGE=dict(argstr='--inMPRAGE %s', ), + inMax=dict(argstr='--inMax %d', ), + inMin=dict(argstr='--inMin %f', ), + inOutput=dict(argstr='--inOutput %s', ), + inPV=dict(argstr='--inPV %s', ), + inPosterior=dict(argstr='--inPosterior %f', ), + inSteps=dict(argstr='--inSteps %d', ), + inTopology=dict(argstr='--inTopology %s', ), + null=dict(argstr='--null %s', ), + outLevelset=dict( + argstr='--outLevelset %s', + hash_files=False, + ), + outPosterior2=dict( + argstr='--outPosterior2 %s', + hash_files=False, + ), + outPosterior3=dict( + argstr='--outPosterior3 %s', + hash_files=False, + ), + outSegmented=dict( + argstr='--outSegmented %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistBrainMgdmSegmentation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistBrainMgdmSegmentation_outputs(): - output_map = dict(outLevelset=dict(), - outPosterior2=dict(), - outPosterior3=dict(), - outSegmented=dict(), + output_map = dict( + outLevelset=dict(), + outPosterior2=dict(), + outPosterior3=dict(), + outSegmented=dict(), ) outputs = JistBrainMgdmSegmentation.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py index 113bc27c4d..e03ca11118 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py @@ -4,49 +4,44 @@ def test_JistBrainMp2rageDuraEstimation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inDistance=dict(argstr='--inDistance %f', - ), - inSecond=dict(argstr='--inSecond %s', - ), - inSkull=dict(argstr='--inSkull %s', - ), - inoutput=dict(argstr='--inoutput %s', - ), - null=dict(argstr='--null %s', - ), - outDura=dict(argstr='--outDura %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inDistance=dict(argstr='--inDistance %f', ), + inSecond=dict(argstr='--inSecond %s', ), + inSkull=dict(argstr='--inSkull %s', ), + inoutput=dict(argstr='--inoutput %s', ), + null=dict(argstr='--null %s', ), + outDura=dict( + argstr='--outDura %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistBrainMp2rageDuraEstimation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistBrainMp2rageDuraEstimation_outputs(): - output_map = dict(outDura=dict(), - ) + output_map = dict(outDura=dict(), ) outputs = JistBrainMp2rageDuraEstimation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py index 624326b534..ffa970da75 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py @@ -4,62 +4,61 @@ def test_JistBrainMp2rageSkullStripping_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inFilter=dict(argstr='--inFilter %s', - ), - inSecond=dict(argstr='--inSecond %s', - ), - inSkip=dict(argstr='--inSkip %s', - ), - inT1=dict(argstr='--inT1 %s', - ), - inT1weighted=dict(argstr='--inT1weighted %s', - ), - null=dict(argstr='--null %s', - ), - outBrain=dict(argstr='--outBrain %s', - hash_files=False, - ), - outMasked=dict(argstr='--outMasked %s', - hash_files=False, - ), - outMasked2=dict(argstr='--outMasked2 %s', - hash_files=False, - ), - outMasked3=dict(argstr='--outMasked3 %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inFilter=dict(argstr='--inFilter %s', ), + inSecond=dict(argstr='--inSecond %s', ), + inSkip=dict(argstr='--inSkip %s', ), + inT1=dict(argstr='--inT1 %s', ), + inT1weighted=dict(argstr='--inT1weighted %s', ), + null=dict(argstr='--null %s', ), + outBrain=dict( + argstr='--outBrain %s', + hash_files=False, + ), + outMasked=dict( + argstr='--outMasked %s', + hash_files=False, + ), + outMasked2=dict( + argstr='--outMasked2 %s', + hash_files=False, + ), + outMasked3=dict( + argstr='--outMasked3 %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistBrainMp2rageSkullStripping.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistBrainMp2rageSkullStripping_outputs(): - output_map = dict(outBrain=dict(), - outMasked=dict(), - outMasked2=dict(), - outMasked3=dict(), + output_map = dict( + outBrain=dict(), + outMasked=dict(), + outMasked2=dict(), + outMasked3=dict(), ) outputs = JistBrainMp2rageSkullStripping.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py index 8fe4e3df73..a159256305 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py @@ -4,47 +4,43 @@ def test_JistBrainPartialVolumeFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inInput=dict(argstr='--inInput %s', - ), - inPV=dict(argstr='--inPV %s', - ), - inoutput=dict(argstr='--inoutput %s', - ), - null=dict(argstr='--null %s', - ), - outPartial=dict(argstr='--outPartial %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inInput=dict(argstr='--inInput %s', ), + inPV=dict(argstr='--inPV %s', ), + inoutput=dict(argstr='--inoutput %s', ), + null=dict(argstr='--null %s', ), + outPartial=dict( + argstr='--outPartial %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistBrainPartialVolumeFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistBrainPartialVolumeFilter_outputs(): - output_map = dict(outPartial=dict(), - ) + output_map = dict(outPartial=dict(), ) outputs = JistBrainPartialVolumeFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py b/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py index 238e2fd02e..5ff5b02822 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py @@ -4,58 +4,53 @@ def test_JistCortexSurfaceMeshInflation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inLevelset=dict(argstr='--inLevelset %s', - ), - inLorentzian=dict(argstr='--inLorentzian %s', - ), - inMax=dict(argstr='--inMax %d', - ), - inMean=dict(argstr='--inMean %f', - ), - inSOR=dict(argstr='--inSOR %f', - ), - inStep=dict(argstr='--inStep %d', - ), - inTopology=dict(argstr='--inTopology %s', - ), - null=dict(argstr='--null %s', - ), - outInflated=dict(argstr='--outInflated %s', - hash_files=False, - ), - outOriginal=dict(argstr='--outOriginal %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inLevelset=dict(argstr='--inLevelset %s', ), + inLorentzian=dict(argstr='--inLorentzian %s', ), + inMax=dict(argstr='--inMax %d', ), + inMean=dict(argstr='--inMean %f', ), + inSOR=dict(argstr='--inSOR %f', ), + inStep=dict(argstr='--inStep %d', ), + inTopology=dict(argstr='--inTopology %s', ), + null=dict(argstr='--null %s', ), + outInflated=dict( + argstr='--outInflated %s', + hash_files=False, + ), + outOriginal=dict( + argstr='--outOriginal %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistCortexSurfaceMeshInflation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistCortexSurfaceMeshInflation_outputs(): - output_map = dict(outInflated=dict(), - outOriginal=dict(), + output_map = dict( + outInflated=dict(), + outOriginal=dict(), ) outputs = JistCortexSurfaceMeshInflation.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py b/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py index 769202018d..93cb74c334 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py @@ -4,64 +4,62 @@ def test_JistIntensityMp2rageMasking_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inBackground=dict(argstr='--inBackground %s', - ), - inMasking=dict(argstr='--inMasking %s', - ), - inQuantitative=dict(argstr='--inQuantitative %s', - ), - inSecond=dict(argstr='--inSecond %s', - ), - inSkip=dict(argstr='--inSkip %s', - ), - inT1weighted=dict(argstr='--inT1weighted %s', - ), - null=dict(argstr='--null %s', - ), - outMasked=dict(argstr='--outMasked_T1_Map %s', - hash_files=False, - ), - outMasked2=dict(argstr='--outMasked_T1weighted %s', - hash_files=False, - ), - outSignal=dict(argstr='--outSignal_Proba %s', - hash_files=False, - ), - outSignal2=dict(argstr='--outSignal_Mask %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inBackground=dict(argstr='--inBackground %s', ), + inMasking=dict(argstr='--inMasking %s', ), + inQuantitative=dict(argstr='--inQuantitative %s', ), + inSecond=dict(argstr='--inSecond %s', ), + inSkip=dict(argstr='--inSkip %s', ), + inT1weighted=dict(argstr='--inT1weighted %s', ), + null=dict(argstr='--null %s', ), + outMasked=dict( + argstr='--outMasked_T1_Map %s', + hash_files=False, + ), + outMasked2=dict( + argstr='--outMasked_T1weighted %s', + hash_files=False, + ), + outSignal=dict( + argstr='--outSignal_Proba %s', + hash_files=False, + ), + outSignal2=dict( + argstr='--outSignal_Mask %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistIntensityMp2rageMasking.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistIntensityMp2rageMasking_outputs(): - output_map = dict(outMasked=dict(), - outMasked2=dict(), - outSignal=dict(), - outSignal2=dict(), + output_map = dict( + outMasked=dict(), + outMasked2=dict(), + outSignal=dict(), + outSignal2=dict(), ) outputs = JistIntensityMp2rageMasking.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py index 0485ed2ad2..a07f6bce20 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py @@ -4,47 +4,43 @@ def test_JistLaminarProfileCalculator_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inIntensity=dict(argstr='--inIntensity %s', - ), - inMask=dict(argstr='--inMask %s', - ), - incomputed=dict(argstr='--incomputed %s', - ), - null=dict(argstr='--null %s', - ), - outResult=dict(argstr='--outResult %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inIntensity=dict(argstr='--inIntensity %s', ), + inMask=dict(argstr='--inMask %s', ), + incomputed=dict(argstr='--incomputed %s', ), + null=dict(argstr='--null %s', ), + outResult=dict( + argstr='--outResult %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistLaminarProfileCalculator.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistLaminarProfileCalculator_outputs(): - output_map = dict(outResult=dict(), - ) + output_map = dict(outResult=dict(), ) outputs = JistLaminarProfileCalculator.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py index 21f94d42e9..f89925af06 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py @@ -4,51 +4,45 @@ def test_JistLaminarProfileGeometry_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inProfile=dict(argstr='--inProfile %s', - ), - incomputed=dict(argstr='--incomputed %s', - ), - inoutside=dict(argstr='--inoutside %f', - ), - inregularization=dict(argstr='--inregularization %s', - ), - insmoothing=dict(argstr='--insmoothing %f', - ), - null=dict(argstr='--null %s', - ), - outResult=dict(argstr='--outResult %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inProfile=dict(argstr='--inProfile %s', ), + incomputed=dict(argstr='--incomputed %s', ), + inoutside=dict(argstr='--inoutside %f', ), + inregularization=dict(argstr='--inregularization %s', ), + insmoothing=dict(argstr='--insmoothing %f', ), + null=dict(argstr='--null %s', ), + outResult=dict( + argstr='--outResult %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistLaminarProfileGeometry.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistLaminarProfileGeometry_outputs(): - output_map = dict(outResult=dict(), - ) + output_map = dict(outResult=dict(), ) outputs = JistLaminarProfileGeometry.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py index 6d9ad3493a..170ed4b517 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py @@ -4,50 +4,49 @@ def test_JistLaminarProfileSampling_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inCortex=dict(argstr='--inCortex %s', - ), - inIntensity=dict(argstr='--inIntensity %s', - ), - inProfile=dict(argstr='--inProfile %s', - ), - null=dict(argstr='--null %s', - ), - outProfile2=dict(argstr='--outProfile2 %s', - hash_files=False, - ), - outProfilemapped=dict(argstr='--outProfilemapped %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inCortex=dict(argstr='--inCortex %s', ), + inIntensity=dict(argstr='--inIntensity %s', ), + inProfile=dict(argstr='--inProfile %s', ), + null=dict(argstr='--null %s', ), + outProfile2=dict( + argstr='--outProfile2 %s', + hash_files=False, + ), + outProfilemapped=dict( + argstr='--outProfilemapped %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistLaminarProfileSampling.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistLaminarProfileSampling_outputs(): - output_map = dict(outProfile2=dict(), - outProfilemapped=dict(), + output_map = dict( + outProfile2=dict(), + outProfilemapped=dict(), ) outputs = JistLaminarProfileSampling.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py index 012fa2872b..9b5c00e23b 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py @@ -4,49 +4,44 @@ def test_JistLaminarROIAveraging_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inIntensity=dict(argstr='--inIntensity %s', - ), - inMask=dict(argstr='--inMask %s', - ), - inROI=dict(argstr='--inROI %s', - ), - inROI2=dict(argstr='--inROI2 %s', - ), - null=dict(argstr='--null %s', - ), - outROI3=dict(argstr='--outROI3 %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inIntensity=dict(argstr='--inIntensity %s', ), + inMask=dict(argstr='--inMask %s', ), + inROI=dict(argstr='--inROI %s', ), + inROI2=dict(argstr='--inROI2 %s', ), + null=dict(argstr='--null %s', ), + outROI3=dict( + argstr='--outROI3 %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistLaminarROIAveraging.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistLaminarROIAveraging_outputs(): - output_map = dict(outROI3=dict(), - ) + output_map = dict(outROI3=dict(), ) outputs = JistLaminarROIAveraging.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py index e80496ec47..268e7a3c9e 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py @@ -4,70 +4,62 @@ def test_JistLaminarVolumetricLayering_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inInner=dict(argstr='--inInner %s', - ), - inLayering=dict(argstr='--inLayering %s', - ), - inLayering2=dict(argstr='--inLayering2 %s', - ), - inMax=dict(argstr='--inMax %d', - ), - inMin=dict(argstr='--inMin %f', - ), - inNumber=dict(argstr='--inNumber %d', - ), - inOuter=dict(argstr='--inOuter %s', - ), - inTopology=dict(argstr='--inTopology %s', - ), - incurvature=dict(argstr='--incurvature %d', - ), - inpresmooth=dict(argstr='--inpresmooth %s', - ), - inratio=dict(argstr='--inratio %f', - ), - null=dict(argstr='--null %s', - ), - outContinuous=dict(argstr='--outContinuous %s', - hash_files=False, - ), - outDiscrete=dict(argstr='--outDiscrete %s', - hash_files=False, - ), - outLayer=dict(argstr='--outLayer %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inInner=dict(argstr='--inInner %s', ), + inLayering=dict(argstr='--inLayering %s', ), + inLayering2=dict(argstr='--inLayering2 %s', ), + inMax=dict(argstr='--inMax %d', ), + inMin=dict(argstr='--inMin %f', ), + inNumber=dict(argstr='--inNumber %d', ), + inOuter=dict(argstr='--inOuter %s', ), + inTopology=dict(argstr='--inTopology %s', ), + incurvature=dict(argstr='--incurvature %d', ), + inpresmooth=dict(argstr='--inpresmooth %s', ), + inratio=dict(argstr='--inratio %f', ), + null=dict(argstr='--null %s', ), + outContinuous=dict( + argstr='--outContinuous %s', + hash_files=False, + ), + outDiscrete=dict( + argstr='--outDiscrete %s', + hash_files=False, + ), + outLayer=dict( + argstr='--outLayer %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistLaminarVolumetricLayering.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JistLaminarVolumetricLayering_outputs(): - output_map = dict(outContinuous=dict(), - outDiscrete=dict(), - outLayer=dict(), + output_map = dict( + outContinuous=dict(), + outDiscrete=dict(), + outLayer=dict(), ) outputs = JistLaminarVolumetricLayering.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py index c273cbf378..814decb823 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py @@ -4,47 +4,43 @@ def test_MedicAlgorithmImageCalculator_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inOperation=dict(argstr='--inOperation %s', - ), - inVolume=dict(argstr='--inVolume %s', - ), - inVolume2=dict(argstr='--inVolume2 %s', - ), - null=dict(argstr='--null %s', - ), - outResult=dict(argstr='--outResult %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inOperation=dict(argstr='--inOperation %s', ), + inVolume=dict(argstr='--inVolume %s', ), + inVolume2=dict(argstr='--inVolume2 %s', ), + null=dict(argstr='--null %s', ), + outResult=dict( + argstr='--outResult %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = MedicAlgorithmImageCalculator.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedicAlgorithmImageCalculator_outputs(): - output_map = dict(outResult=dict(), - ) + output_map = dict(outResult=dict(), ) outputs = MedicAlgorithmImageCalculator.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py index dd97b91a1f..a5b79b4a2e 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py @@ -4,114 +4,102 @@ def test_MedicAlgorithmLesionToads_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inAtlas=dict(argstr='--inAtlas %s', - ), - inAtlas2=dict(argstr='--inAtlas2 %s', - ), - inAtlas3=dict(argstr='--inAtlas3 %s', - ), - inAtlas4=dict(argstr='--inAtlas4 %s', - ), - inAtlas5=dict(argstr='--inAtlas5 %f', - ), - inAtlas6=dict(argstr='--inAtlas6 %s', - ), - inConnectivity=dict(argstr='--inConnectivity %s', - ), - inCorrect=dict(argstr='--inCorrect %s', - ), - inFLAIR=dict(argstr='--inFLAIR %s', - ), - inInclude=dict(argstr='--inInclude %s', - ), - inMaximum=dict(argstr='--inMaximum %d', - ), - inMaximum2=dict(argstr='--inMaximum2 %d', - ), - inMaximum3=dict(argstr='--inMaximum3 %d', - ), - inMaximum4=dict(argstr='--inMaximum4 %f', - ), - inMaximum5=dict(argstr='--inMaximum5 %d', - ), - inOutput=dict(argstr='--inOutput %s', - ), - inOutput2=dict(argstr='--inOutput2 %s', - ), - inOutput3=dict(argstr='--inOutput3 %s', - ), - inSmooting=dict(argstr='--inSmooting %f', - ), - inT1_MPRAGE=dict(argstr='--inT1_MPRAGE %s', - ), - inT1_SPGR=dict(argstr='--inT1_SPGR %s', - ), - null=dict(argstr='--null %s', - ), - outCortical=dict(argstr='--outCortical %s', - hash_files=False, - ), - outFilled=dict(argstr='--outFilled %s', - hash_files=False, - ), - outHard=dict(argstr='--outHard %s', - hash_files=False, - ), - outHard2=dict(argstr='--outHard2 %s', - hash_files=False, - ), - outInhomogeneity=dict(argstr='--outInhomogeneity %s', - hash_files=False, - ), - outLesion=dict(argstr='--outLesion %s', - hash_files=False, - ), - outMembership=dict(argstr='--outMembership %s', - hash_files=False, - ), - outSulcal=dict(argstr='--outSulcal %s', - hash_files=False, - ), - outWM=dict(argstr='--outWM %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inAtlas=dict(argstr='--inAtlas %s', ), + inAtlas2=dict(argstr='--inAtlas2 %s', ), + inAtlas3=dict(argstr='--inAtlas3 %s', ), + inAtlas4=dict(argstr='--inAtlas4 %s', ), + inAtlas5=dict(argstr='--inAtlas5 %f', ), + inAtlas6=dict(argstr='--inAtlas6 %s', ), + inConnectivity=dict(argstr='--inConnectivity %s', ), + inCorrect=dict(argstr='--inCorrect %s', ), + inFLAIR=dict(argstr='--inFLAIR %s', ), + inInclude=dict(argstr='--inInclude %s', ), + inMaximum=dict(argstr='--inMaximum %d', ), + inMaximum2=dict(argstr='--inMaximum2 %d', ), + inMaximum3=dict(argstr='--inMaximum3 %d', ), + inMaximum4=dict(argstr='--inMaximum4 %f', ), + inMaximum5=dict(argstr='--inMaximum5 %d', ), + inOutput=dict(argstr='--inOutput %s', ), + inOutput2=dict(argstr='--inOutput2 %s', ), + inOutput3=dict(argstr='--inOutput3 %s', ), + inSmooting=dict(argstr='--inSmooting %f', ), + inT1_MPRAGE=dict(argstr='--inT1_MPRAGE %s', ), + inT1_SPGR=dict(argstr='--inT1_SPGR %s', ), + null=dict(argstr='--null %s', ), + outCortical=dict( + argstr='--outCortical %s', + hash_files=False, + ), + outFilled=dict( + argstr='--outFilled %s', + hash_files=False, + ), + outHard=dict( + argstr='--outHard %s', + hash_files=False, + ), + outHard2=dict( + argstr='--outHard2 %s', + hash_files=False, + ), + outInhomogeneity=dict( + argstr='--outInhomogeneity %s', + hash_files=False, + ), + outLesion=dict( + argstr='--outLesion %s', + hash_files=False, + ), + outMembership=dict( + argstr='--outMembership %s', + hash_files=False, + ), + outSulcal=dict( + argstr='--outSulcal %s', + hash_files=False, + ), + outWM=dict( + argstr='--outWM %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = MedicAlgorithmLesionToads.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedicAlgorithmLesionToads_outputs(): - output_map = dict(outCortical=dict(), - outFilled=dict(), - outHard=dict(), - outHard2=dict(), - outInhomogeneity=dict(), - outLesion=dict(), - outMembership=dict(), - outSulcal=dict(), - outWM=dict(), + output_map = dict( + outCortical=dict(), + outFilled=dict(), + outHard=dict(), + outHard2=dict(), + outInhomogeneity=dict(), + outLesion=dict(), + outMembership=dict(), + outSulcal=dict(), + outWM=dict(), ) outputs = MedicAlgorithmLesionToads.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py index e089749b4c..e64f3a5faa 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py @@ -4,57 +4,50 @@ def test_MedicAlgorithmMipavReorient_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inInterpolation=dict(argstr='--inInterpolation %s', - ), - inNew=dict(argstr='--inNew %s', - ), - inResolution=dict(argstr='--inResolution %s', - ), - inSource=dict(argstr='--inSource %s', - sep=';', - ), - inTemplate=dict(argstr='--inTemplate %s', - ), - inUser=dict(argstr='--inUser %s', - ), - inUser2=dict(argstr='--inUser2 %s', - ), - inUser3=dict(argstr='--inUser3 %s', - ), - inUser4=dict(argstr='--inUser4 %s', - ), - null=dict(argstr='--null %s', - ), - outReoriented=dict(argstr='--outReoriented %s', - sep=';', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inInterpolation=dict(argstr='--inInterpolation %s', ), + inNew=dict(argstr='--inNew %s', ), + inResolution=dict(argstr='--inResolution %s', ), + inSource=dict( + argstr='--inSource %s', + sep=';', + ), + inTemplate=dict(argstr='--inTemplate %s', ), + inUser=dict(argstr='--inUser %s', ), + inUser2=dict(argstr='--inUser2 %s', ), + inUser3=dict(argstr='--inUser3 %s', ), + inUser4=dict(argstr='--inUser4 %s', ), + null=dict(argstr='--null %s', ), + outReoriented=dict( + argstr='--outReoriented %s', + sep=';', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = MedicAlgorithmMipavReorient.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedicAlgorithmMipavReorient_outputs(): output_map = dict() outputs = MedicAlgorithmMipavReorient.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py index 42a161c44e..16e6b26144 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py @@ -4,62 +4,55 @@ def test_MedicAlgorithmN3_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inAutomatic=dict(argstr='--inAutomatic %s', - ), - inEnd=dict(argstr='--inEnd %f', - ), - inField=dict(argstr='--inField %f', - ), - inInput=dict(argstr='--inInput %s', - ), - inKernel=dict(argstr='--inKernel %f', - ), - inMaximum=dict(argstr='--inMaximum %d', - ), - inSignal=dict(argstr='--inSignal %f', - ), - inSubsample=dict(argstr='--inSubsample %f', - ), - inWeiner=dict(argstr='--inWeiner %f', - ), - null=dict(argstr='--null %s', - ), - outInhomogeneity=dict(argstr='--outInhomogeneity %s', - hash_files=False, - ), - outInhomogeneity2=dict(argstr='--outInhomogeneity2 %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inAutomatic=dict(argstr='--inAutomatic %s', ), + inEnd=dict(argstr='--inEnd %f', ), + inField=dict(argstr='--inField %f', ), + inInput=dict(argstr='--inInput %s', ), + inKernel=dict(argstr='--inKernel %f', ), + inMaximum=dict(argstr='--inMaximum %d', ), + inSignal=dict(argstr='--inSignal %f', ), + inSubsample=dict(argstr='--inSubsample %f', ), + inWeiner=dict(argstr='--inWeiner %f', ), + null=dict(argstr='--null %s', ), + outInhomogeneity=dict( + argstr='--outInhomogeneity %s', + hash_files=False, + ), + outInhomogeneity2=dict( + argstr='--outInhomogeneity2 %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = MedicAlgorithmN3.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedicAlgorithmN3_outputs(): - output_map = dict(outInhomogeneity=dict(), - outInhomogeneity2=dict(), + output_map = dict( + outInhomogeneity=dict(), + outInhomogeneity2=dict(), ) outputs = MedicAlgorithmN3.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py index 6d2c379fcf..d8b873350f 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py @@ -4,140 +4,115 @@ def test_MedicAlgorithmSPECTRE2010_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inApply=dict(argstr='--inApply %s', - ), - inAtlas=dict(argstr='--inAtlas %s', - ), - inBackground=dict(argstr='--inBackground %f', - ), - inCoarse=dict(argstr='--inCoarse %f', - ), - inCost=dict(argstr='--inCost %s', - ), - inDegrees=dict(argstr='--inDegrees %s', - ), - inFind=dict(argstr='--inFind %s', - ), - inFine=dict(argstr='--inFine %f', - ), - inImage=dict(argstr='--inImage %s', - ), - inInhomogeneity=dict(argstr='--inInhomogeneity %s', - ), - inInitial=dict(argstr='--inInitial %d', - ), - inInitial2=dict(argstr='--inInitial2 %f', - ), - inInput=dict(argstr='--inInput %s', - ), - inMMC=dict(argstr='--inMMC %d', - ), - inMMC2=dict(argstr='--inMMC2 %d', - ), - inMaximum=dict(argstr='--inMaximum %f', - ), - inMinimum=dict(argstr='--inMinimum %f', - ), - inMinimum2=dict(argstr='--inMinimum2 %f', - ), - inMultiple=dict(argstr='--inMultiple %d', - ), - inMultithreading=dict(argstr='--inMultithreading %s', - ), - inNumber=dict(argstr='--inNumber %d', - ), - inNumber2=dict(argstr='--inNumber2 %d', - ), - inOutput=dict(argstr='--inOutput %s', - ), - inOutput2=dict(argstr='--inOutput2 %s', - ), - inOutput3=dict(argstr='--inOutput3 %s', - ), - inOutput4=dict(argstr='--inOutput4 %s', - ), - inOutput5=dict(argstr='--inOutput5 %s', - ), - inRegistration=dict(argstr='--inRegistration %s', - ), - inResample=dict(argstr='--inResample %s', - ), - inRun=dict(argstr='--inRun %s', - ), - inSkip=dict(argstr='--inSkip %s', - ), - inSmoothing=dict(argstr='--inSmoothing %f', - ), - inSubsample=dict(argstr='--inSubsample %s', - ), - inUse=dict(argstr='--inUse %s', - ), - null=dict(argstr='--null %s', - ), - outFANTASM=dict(argstr='--outFANTASM %s', - hash_files=False, - ), - outMask=dict(argstr='--outMask %s', - hash_files=False, - ), - outMidsagittal=dict(argstr='--outMidsagittal %s', - hash_files=False, - ), - outOriginal=dict(argstr='--outOriginal %s', - hash_files=False, - ), - outPrior=dict(argstr='--outPrior %s', - hash_files=False, - ), - outSegmentation=dict(argstr='--outSegmentation %s', - hash_files=False, - ), - outSplitHalves=dict(argstr='--outSplitHalves %s', - hash_files=False, - ), - outStripped=dict(argstr='--outStripped %s', - hash_files=False, - ), - outd0=dict(argstr='--outd0 %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inApply=dict(argstr='--inApply %s', ), + inAtlas=dict(argstr='--inAtlas %s', ), + inBackground=dict(argstr='--inBackground %f', ), + inCoarse=dict(argstr='--inCoarse %f', ), + inCost=dict(argstr='--inCost %s', ), + inDegrees=dict(argstr='--inDegrees %s', ), + inFind=dict(argstr='--inFind %s', ), + inFine=dict(argstr='--inFine %f', ), + inImage=dict(argstr='--inImage %s', ), + inInhomogeneity=dict(argstr='--inInhomogeneity %s', ), + inInitial=dict(argstr='--inInitial %d', ), + inInitial2=dict(argstr='--inInitial2 %f', ), + inInput=dict(argstr='--inInput %s', ), + inMMC=dict(argstr='--inMMC %d', ), + inMMC2=dict(argstr='--inMMC2 %d', ), + inMaximum=dict(argstr='--inMaximum %f', ), + inMinimum=dict(argstr='--inMinimum %f', ), + inMinimum2=dict(argstr='--inMinimum2 %f', ), + inMultiple=dict(argstr='--inMultiple %d', ), + inMultithreading=dict(argstr='--inMultithreading %s', ), + inNumber=dict(argstr='--inNumber %d', ), + inNumber2=dict(argstr='--inNumber2 %d', ), + inOutput=dict(argstr='--inOutput %s', ), + inOutput2=dict(argstr='--inOutput2 %s', ), + inOutput3=dict(argstr='--inOutput3 %s', ), + inOutput4=dict(argstr='--inOutput4 %s', ), + inOutput5=dict(argstr='--inOutput5 %s', ), + inRegistration=dict(argstr='--inRegistration %s', ), + inResample=dict(argstr='--inResample %s', ), + inRun=dict(argstr='--inRun %s', ), + inSkip=dict(argstr='--inSkip %s', ), + inSmoothing=dict(argstr='--inSmoothing %f', ), + inSubsample=dict(argstr='--inSubsample %s', ), + inUse=dict(argstr='--inUse %s', ), + null=dict(argstr='--null %s', ), + outFANTASM=dict( + argstr='--outFANTASM %s', + hash_files=False, + ), + outMask=dict( + argstr='--outMask %s', + hash_files=False, + ), + outMidsagittal=dict( + argstr='--outMidsagittal %s', + hash_files=False, + ), + outOriginal=dict( + argstr='--outOriginal %s', + hash_files=False, + ), + outPrior=dict( + argstr='--outPrior %s', + hash_files=False, + ), + outSegmentation=dict( + argstr='--outSegmentation %s', + hash_files=False, + ), + outSplitHalves=dict( + argstr='--outSplitHalves %s', + hash_files=False, + ), + outStripped=dict( + argstr='--outStripped %s', + hash_files=False, + ), + outd0=dict( + argstr='--outd0 %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = MedicAlgorithmSPECTRE2010.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedicAlgorithmSPECTRE2010_outputs(): - output_map = dict(outFANTASM=dict(), - outMask=dict(), - outMidsagittal=dict(), - outOriginal=dict(), - outPrior=dict(), - outSegmentation=dict(), - outSplitHalves=dict(), - outStripped=dict(), - outd0=dict(), + output_map = dict( + outFANTASM=dict(), + outMask=dict(), + outMidsagittal=dict(), + outOriginal=dict(), + outPrior=dict(), + outSegmentation=dict(), + outSplitHalves=dict(), + outStripped=dict(), + outd0=dict(), ) outputs = MedicAlgorithmSPECTRE2010.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py index c895cd75d5..3e551c2478 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py @@ -4,47 +4,45 @@ def test_MedicAlgorithmThresholdToBinaryMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inLabel=dict(argstr='--inLabel %s', - sep=';', - ), - inMaximum=dict(argstr='--inMaximum %f', - ), - inMinimum=dict(argstr='--inMinimum %f', - ), - inUse=dict(argstr='--inUse %s', - ), - null=dict(argstr='--null %s', - ), - outBinary=dict(argstr='--outBinary %s', - sep=';', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inLabel=dict( + argstr='--inLabel %s', + sep=';', + ), + inMaximum=dict(argstr='--inMaximum %f', ), + inMinimum=dict(argstr='--inMinimum %f', ), + inUse=dict(argstr='--inUse %s', ), + null=dict(argstr='--null %s', ), + outBinary=dict( + argstr='--outBinary %s', + sep=';', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = MedicAlgorithmThresholdToBinaryMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedicAlgorithmThresholdToBinaryMask_outputs(): output_map = dict() outputs = MedicAlgorithmThresholdToBinaryMask.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_RandomVol.py b/nipype/interfaces/mipav/tests/test_auto_RandomVol.py index b7e3c098f7..1349e7cd90 100644 --- a/nipype/interfaces/mipav/tests/test_auto_RandomVol.py +++ b/nipype/interfaces/mipav/tests/test_auto_RandomVol.py @@ -4,59 +4,49 @@ def test_RandomVol_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inField=dict(argstr='--inField %s', - ), - inLambda=dict(argstr='--inLambda %f', - ), - inMaximum=dict(argstr='--inMaximum %d', - ), - inMinimum=dict(argstr='--inMinimum %d', - ), - inSize=dict(argstr='--inSize %d', - ), - inSize2=dict(argstr='--inSize2 %d', - ), - inSize3=dict(argstr='--inSize3 %d', - ), - inSize4=dict(argstr='--inSize4 %d', - ), - inStandard=dict(argstr='--inStandard %d', - ), - null=dict(argstr='--null %s', - ), - outRand1=dict(argstr='--outRand1 %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - xDefaultMem=dict(argstr='-xDefaultMem %d', - ), - xMaxProcess=dict(argstr='-xMaxProcess %d', - usedefault=True, - ), - xPrefExt=dict(argstr='--xPrefExt %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inField=dict(argstr='--inField %s', ), + inLambda=dict(argstr='--inLambda %f', ), + inMaximum=dict(argstr='--inMaximum %d', ), + inMinimum=dict(argstr='--inMinimum %d', ), + inSize=dict(argstr='--inSize %d', ), + inSize2=dict(argstr='--inSize2 %d', ), + inSize3=dict(argstr='--inSize3 %d', ), + inSize4=dict(argstr='--inSize4 %d', ), + inStandard=dict(argstr='--inStandard %d', ), + null=dict(argstr='--null %s', ), + outRand1=dict( + argstr='--outRand1 %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + xDefaultMem=dict(argstr='-xDefaultMem %d', ), + xMaxProcess=dict( + argstr='-xMaxProcess %d', + usedefault=True, + ), + xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = RandomVol.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RandomVol_outputs(): - output_map = dict(outRand1=dict(), - ) + output_map = dict(outRand1=dict(), ) outputs = RandomVol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mne/base.py b/nipype/interfaces/mne/base.py index 5196ddf5be..14cfcd53e5 100644 --- a/nipype/interfaces/mne/base.py +++ b/nipype/interfaces/mne/base.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, bytes import os.path as op @@ -14,35 +15,67 @@ class WatershedBEMInputSpec(FSTraitedSpec): - subject_id = traits.Str(argstr='--subject %s', mandatory=True, - desc='Subject ID (must have a complete Freesurfer directory)') - subjects_dir = Directory(exists=True, mandatory=True, usedefault=True, - desc='Path to Freesurfer subjects directory') - volume = traits.Enum('T1', 'aparc+aseg', 'aseg', 'brain', 'orig', 'brainmask', 'ribbon', - argstr='--volume %s', usedefault=True, - desc='The volume from the "mri" directory to use (defaults to T1)') - overwrite = traits.Bool(True, usedefault=True, argstr='--overwrite', - desc='Overwrites the existing files') - atlas_mode = traits.Bool(argstr='--atlas', - desc='Use atlas mode for registration (default: no rigid alignment)') + subject_id = traits.Str( + argstr='--subject %s', + mandatory=True, + desc='Subject ID (must have a complete Freesurfer directory)') + subjects_dir = Directory( + exists=True, + mandatory=True, + usedefault=True, + desc='Path to Freesurfer subjects directory') + volume = traits.Enum( + 'T1', + 'aparc+aseg', + 'aseg', + 'brain', + 'orig', + 'brainmask', + 'ribbon', + argstr='--volume %s', + usedefault=True, + desc='The volume from the "mri" directory to use (defaults to T1)') + overwrite = traits.Bool( + True, + usedefault=True, + argstr='--overwrite', + desc='Overwrites the existing files') + atlas_mode = traits.Bool( + argstr='--atlas', + desc='Use atlas mode for registration (default: no rigid alignment)') class WatershedBEMOutputSpec(TraitedSpec): - mesh_files = OutputMultiPath(File(exists=True), - desc=('Paths to the output meshes (brain, inner ' - 'skull, outer skull, outer skin)')) - brain_surface = File(exists=True, loc='bem/watershed', - desc='Brain surface (in Freesurfer format)') - inner_skull_surface = File(exists=True, loc='bem/watershed', - desc='Inner skull surface (in Freesurfer format)') - outer_skull_surface = File(exists=True, loc='bem/watershed', - desc='Outer skull surface (in Freesurfer format)') - outer_skin_surface = File(exists=True, loc='bem/watershed', - desc='Outer skin surface (in Freesurfer format)') - fif_file = File(exists=True, loc='bem', altkey='fif', - desc='"fif" format file for EEG processing in MNE') - cor_files = OutputMultiPath(File(exists=True), loc='bem/watershed/ws', - altkey='COR', desc='"COR" format files') + mesh_files = OutputMultiPath( + File(exists=True), + desc=('Paths to the output meshes (brain, inner ' + 'skull, outer skull, outer skin)')) + brain_surface = File( + exists=True, + loc='bem/watershed', + desc='Brain surface (in Freesurfer format)') + inner_skull_surface = File( + exists=True, + loc='bem/watershed', + desc='Inner skull surface (in Freesurfer format)') + outer_skull_surface = File( + exists=True, + loc='bem/watershed', + desc='Outer skull surface (in Freesurfer format)') + outer_skin_surface = File( + exists=True, + loc='bem/watershed', + desc='Outer skin surface (in Freesurfer format)') + fif_file = File( + exists=True, + loc='bem', + altkey='fif', + desc='"fif" format file for EEG processing in MNE') + cor_files = OutputMultiPath( + File(exists=True), + loc='bem/watershed/ws', + altkey='COR', + desc='"COR" format files') class WatershedBEM(FSCommand): diff --git a/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py b/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py index 4fb5dcee55..58e94d0850 100644 --- a/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py +++ b/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py @@ -4,56 +4,59 @@ def test_WatershedBEM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - atlas_mode=dict(argstr='--atlas', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - overwrite=dict(argstr='--overwrite', - usedefault=True, - ), - subject_id=dict(argstr='--subject %s', - mandatory=True, - ), - subjects_dir=dict(mandatory=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - volume=dict(argstr='--volume %s', - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + atlas_mode=dict(argstr='--atlas', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + overwrite=dict( + argstr='--overwrite', + usedefault=True, + ), + subject_id=dict( + argstr='--subject %s', + mandatory=True, + ), + subjects_dir=dict( + mandatory=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + volume=dict( + argstr='--volume %s', + usedefault=True, + ), ) inputs = WatershedBEM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_WatershedBEM_outputs(): - output_map = dict(brain_surface=dict(loc='bem/watershed', - ), - cor_files=dict(altkey='COR', - loc='bem/watershed/ws', - ), - fif_file=dict(altkey='fif', - loc='bem', - ), - inner_skull_surface=dict(loc='bem/watershed', - ), - mesh_files=dict(), - outer_skin_surface=dict(loc='bem/watershed', - ), - outer_skull_surface=dict(loc='bem/watershed', - ), + output_map = dict( + brain_surface=dict(loc='bem/watershed', ), + cor_files=dict( + altkey='COR', + loc='bem/watershed/ws', + ), + fif_file=dict( + altkey='fif', + loc='bem', + ), + inner_skull_surface=dict(loc='bem/watershed', ), + mesh_files=dict(), + outer_skin_surface=dict(loc='bem/watershed', ), + outer_skull_surface=dict(loc='bem/watershed', ), ) outputs = WatershedBEM.output_spec() diff --git a/nipype/interfaces/mrtrix/convert.py b/nipype/interfaces/mrtrix/convert.py index eb34de974e..0f9e0f29ff 100644 --- a/nipype/interfaces/mrtrix/convert.py +++ b/nipype/interfaces/mrtrix/convert.py @@ -8,7 +8,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from io import open import os.path as op @@ -34,14 +35,14 @@ else: from dipy.tracking.utils import move_streamlines, affine_from_fsl_mat_file - iflogger = logging.getLogger('interface') def transform_to_affine(streams, header, affine): rotation, scale = np.linalg.qr(affine) streams = move_streamlines(streams, rotation) - scale[0:3, 0:3] = np.dot(scale[0:3, 0:3], np.diag(1. / header['voxel_size'])) + scale[0:3, 0:3] = np.dot(scale[0:3, 0:3], + np.diag(1. / header['voxel_size'])) scale[0:3, 3] = abs(scale[0:3, 3]) streams = move_streamlines(streams, scale) return streams @@ -86,21 +87,21 @@ def read_mrtrix_streamlines(in_file, header, as_generator=True): bytesize = pt_cols * 4 def points_per_track(offset): - n_streams = 0 - n_points = 0 track_points = [] iflogger.info('Identifying the number of points per tract...') all_str = fileobj.read() num_triplets = int(len(all_str) / bytesize) - pts = np.ndarray(shape=(num_triplets, pt_cols), dtype='f4', buffer=all_str) - nonfinite_list = np.where(np.isfinite(pts[:, 2]) == False) - nonfinite_list = list(nonfinite_list[0])[0:-1] # Converts numpy array to list, removes the last value - nonfinite_list_bytes = [offset + x * bytesize for x in nonfinite_list] + pts = np.ndarray( + shape=(num_triplets, pt_cols), dtype='f4', buffer=all_str) + nonfinite_list = np.where(np.invert(np.isfinite(pts[:, 2]))) + nonfinite_list = list(nonfinite_list[0])[ + 0:-1] # Converts numpy array to list, removes the last value for idx, value in enumerate(nonfinite_list): if idx == 0: track_points.append(nonfinite_list[idx]) else: - track_points.append(nonfinite_list[idx] - nonfinite_list[idx - 1] - 1) + track_points.append( + nonfinite_list[idx] - nonfinite_list[idx - 1] - 1) return track_points, nonfinite_list def track_gen(track_points): @@ -115,20 +116,14 @@ def track_gen(track_points): nan_str = fileobj.read(bytesize) if len(pts_str) < (n_pts * bytesize): if not n_streams == stream_count: - raise HeaderError( - 'Expecting %s points, found only %s' % ( - stream_count, n_streams)) + raise HeaderError('Expecting %s points, found only %s' % + (stream_count, n_streams)) iflogger.error('Expecting %s points, found only %s', stream_count, n_streams) break pts = np.ndarray( - shape=(n_pts, pt_cols), - dtype=f4dt, - buffer=pts_str) - nan_pt = np.ndarray( - shape=(1, pt_cols), - dtype=f4dt, - buffer=nan_str) + shape=(n_pts, pt_cols), dtype=f4dt, buffer=pts_str) + nan_pt = np.ndarray(shape=(1, pt_cols), dtype=f4dt, buffer=nan_str) if np.isfinite(nan_pt[0][0]): raise ValueError break @@ -145,6 +140,7 @@ def track_gen(track_points): except ZeroDivisionError: iflogger.info('%i stream read out of %i', n_streams, stream_count) + track_points, nonfinite_list = points_per_track(offset) fileobj.seek(offset) streamlines = track_gen(track_points) @@ -154,12 +150,25 @@ def track_gen(track_points): class MRTrix2TrackVisInputSpec(TraitedSpec): - in_file = File(exists=True, mandatory=True, - desc='The input file for the tracks in MRTrix (.tck) format') - image_file = File(exists=True, desc='The image the tracks were generated from') - matrix_file = File(exists=True, desc='A transformation matrix to apply to the tracts after they have been generated (from FLIRT - affine transformation from image_file to registration_image_file)') - registration_image_file = File(exists=True, desc='The final image the tracks should be registered to.') - out_filename = File('converted.trk', genfile=True, usedefault=True, desc='The output filename for the tracks in TrackVis (.trk) format') + in_file = File( + exists=True, + mandatory=True, + desc='The input file for the tracks in MRTrix (.tck) format') + image_file = File( + exists=True, desc='The image the tracks were generated from') + matrix_file = File( + exists=True, + desc= + 'A transformation matrix to apply to the tracts after they have been generated (from FLIRT - affine transformation from image_file to registration_image_file)' + ) + registration_image_file = File( + exists=True, + desc='The final image the tracks should be registered to.') + out_filename = File( + 'converted.trk', + genfile=True, + usedefault=True, + desc='The output filename for the tracks in TrackVis (.trk) format') class MRTrix2TrackVisOutputSpec(TraitedSpec): @@ -189,7 +198,8 @@ def _run_interface(self, runtime): out_filename = op.abspath(self.inputs.out_filename) # Reads MRTrix tracks - header, streamlines = read_mrtrix_tracks(self.inputs.in_file, as_generator=True) + header, streamlines = read_mrtrix_tracks( + self.inputs.in_file, as_generator=True) iflogger.info('MRTrix Header:') iflogger.info(header) # Writes to Trackvis @@ -198,15 +208,19 @@ def _run_interface(self, runtime): trk_header['voxel_size'] = [vx, vy, vz] trk_header['n_count'] = header['count'] - if isdefined(self.inputs.matrix_file) and isdefined(self.inputs.registration_image_file): + if isdefined(self.inputs.matrix_file) and isdefined( + self.inputs.registration_image_file): iflogger.info('Applying transformation from matrix file %s', self.inputs.matrix_file) xfm = np.genfromtxt(self.inputs.matrix_file) iflogger.info(xfm) - registration_image_file = nb.load(self.inputs.registration_image_file) + registration_image_file = nb.load( + self.inputs.registration_image_file) reg_affine = registration_image_file.affine - r_dx, r_dy, r_dz = get_data_dims(self.inputs.registration_image_file) - r_vx, r_vy, r_vz = get_vox_dims(self.inputs.registration_image_file) + r_dx, r_dy, r_dz = get_data_dims( + self.inputs.registration_image_file) + r_vx, r_vy, r_vz = get_vox_dims( + self.inputs.registration_image_file) iflogger.info('Using affine from registration image file %s', self.inputs.registration_image_file) iflogger.info(reg_affine) @@ -215,9 +229,11 @@ def _run_interface(self, runtime): trk_header['voxel_size'] = [r_vx, r_vy, r_vz] affine = np.dot(affine, np.diag(1. / np.array([vx, vy, vz, 1]))) - transformed_streamlines = transform_to_affine(streamlines, trk_header, affine) + transformed_streamlines = transform_to_affine( + streamlines, trk_header, affine) - aff = affine_from_fsl_mat_file(xfm, [vx, vy, vz], [r_vx, r_vy, r_vz]) + aff = affine_from_fsl_mat_file(xfm, [vx, vy, vz], + [r_vx, r_vy, r_vz]) iflogger.info(aff) axcode = aff2axcodes(reg_affine) @@ -226,16 +242,19 @@ def _run_interface(self, runtime): final_streamlines = move_streamlines(transformed_streamlines, aff) trk_tracks = ((ii, None, None) for ii in final_streamlines) trk.write(out_filename, trk_tracks, trk_header) - iflogger.info('Saving transformed Trackvis file as %s', out_filename) + iflogger.info('Saving transformed Trackvis file as %s', + out_filename) iflogger.info('New TrackVis Header:') iflogger.info(trk_header) else: - iflogger.info('Applying transformation from scanner coordinates to %s', - self.inputs.image_file) + iflogger.info( + 'Applying transformation from scanner coordinates to %s', + self.inputs.image_file) axcode = aff2axcodes(affine) trk_header['voxel_order'] = axcode[0] + axcode[1] + axcode[2] trk_header['vox_to_ras'] = affine - transformed_streamlines = transform_to_affine(streamlines, trk_header, affine) + transformed_streamlines = transform_to_affine( + streamlines, trk_header, affine) trk_tracks = ((ii, None, None) for ii in transformed_streamlines) trk.write(out_filename, trk_tracks, trk_header) iflogger.info('Saving Trackvis file as %s', out_filename) diff --git a/nipype/interfaces/mrtrix/preprocess.py b/nipype/interfaces/mrtrix/preprocess.py index becee5088f..4de430bb58 100644 --- a/nipype/interfaces/mrtrix/preprocess.py +++ b/nipype/interfaces/mrtrix/preprocess.py @@ -9,7 +9,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op @@ -19,28 +20,99 @@ class MRConvertInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='voxel-order data filename') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output filename') - extract_at_axis = traits.Enum(1, 2, 3, argstr='-coord %s', position=1, - desc='"Extract data only at the coordinates specified. This option specifies the Axis. Must be used in conjunction with extract_at_coordinate.') - extract_at_coordinate = traits.List(traits.Float, argstr='%s', sep=',', position=2, minlen=1, maxlen=3, - desc='"Extract data only at the coordinates specified. This option specifies the coordinates. Must be used in conjunction with extract_at_axis. Three comma-separated numbers giving the size of each voxel in mm.') - voxel_dims = traits.List(traits.Float, argstr='-vox %s', sep=',', - position=3, minlen=3, maxlen=3, - desc='Three comma-separated numbers giving the size of each voxel in mm.') - output_datatype = traits.Enum("nii", "float", "char", "short", "int", "long", "double", argstr='-output %s', position=2, - desc='"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"') # , usedefault=True) - extension = traits.Enum("mif", "nii", "float", "char", "short", "int", "long", "double", position=2, - desc='"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"', usedefault=True) - layout = traits.Enum("nii", "float", "char", "short", "int", "long", "double", argstr='-output %s', position=2, - desc='specify the layout of the data in memory. The actual layout produced will depend on whether the output image format can support it.') - resample = traits.Float(argstr='-scale %d', position=3, - units='mm', desc='Apply scaling to the intensity values.') - offset_bias = traits.Float(argstr='-scale %d', position=3, - units='mm', desc='Apply offset to the intensity values.') - replace_NaN_with_zero = traits.Bool(argstr='-zero', position=3, desc="Replace all NaN values with zero.") - prs = traits.Bool(argstr='-prs', position=3, desc="Assume that the DW gradients are specified in the PRS frame (Siemens DICOM only).") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='voxel-order data filename') + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output filename') + extract_at_axis = traits.Enum( + 1, + 2, + 3, + argstr='-coord %s', + position=1, + desc= + '"Extract data only at the coordinates specified. This option specifies the Axis. Must be used in conjunction with extract_at_coordinate.' + ) + extract_at_coordinate = traits.List( + traits.Float, + argstr='%s', + sep=',', + position=2, + minlen=1, + maxlen=3, + desc= + '"Extract data only at the coordinates specified. This option specifies the coordinates. Must be used in conjunction with extract_at_axis. Three comma-separated numbers giving the size of each voxel in mm.' + ) + voxel_dims = traits.List( + traits.Float, + argstr='-vox %s', + sep=',', + position=3, + minlen=3, + maxlen=3, + desc= + 'Three comma-separated numbers giving the size of each voxel in mm.') + output_datatype = traits.Enum( + "nii", + "float", + "char", + "short", + "int", + "long", + "double", + argstr='-output %s', + position=2, + desc= + '"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"' + ) # , usedefault=True) + extension = traits.Enum( + "mif", + "nii", + "float", + "char", + "short", + "int", + "long", + "double", + position=2, + desc= + '"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"', + usedefault=True) + layout = traits.Enum( + "nii", + "float", + "char", + "short", + "int", + "long", + "double", + argstr='-output %s', + position=2, + desc= + 'specify the layout of the data in memory. The actual layout produced will depend on whether the output image format can support it.' + ) + resample = traits.Float( + argstr='-scale %d', + position=3, + units='mm', + desc='Apply scaling to the intensity values.') + offset_bias = traits.Float( + argstr='-scale %d', + position=3, + units='mm', + desc='Apply offset to the intensity values.') + replace_NaN_with_zero = traits.Bool( + argstr='-zero', position=3, desc="Replace all NaN values with zero.") + prs = traits.Bool( + argstr='-prs', + position=3, + desc= + "Assume that the DW gradients are specified in the PRS frame (Siemens DICOM only)." + ) class MRConvertOutputSpec(TraitedSpec): @@ -95,42 +167,62 @@ def _gen_outfilename(self): class DWI2TensorInputSpec(CommandLineInputSpec): - in_file = InputMultiPath(File(exists=True), argstr='%s', mandatory=True, - position=-2, desc='Diffusion-weighted images') - out_filename = File(name_template="%s_tensor.mif", name_source="in_file", - output_name="tensor", argstr='%s', - desc='Output tensor filename', position=-1) - encoding_file = File(argstr='-grad %s', position=2, - desc=('Encoding file supplied as a 4xN text file with ' - 'each line is in the format [ X Y Z b ], where ' - '[ X Y Z ] describe the direction of the applied ' - 'gradient, and b gives the b-value in units ' - '(1000 s/mm^2). See FSL2MRTrix()')) - ignore_slice_by_volume = traits.List(traits.Int, argstr='-ignoreslices %s', - sep=' ', position=2, minlen=2, - maxlen=2, - desc=('Requires two values (i.e. [34 ' - '1] for [Slice Volume] Ignores ' - 'the image slices specified ' - 'when computing the tensor. ' - 'Slice here means the z ' - 'coordinate of the slice to be ' - 'ignored.')) - ignore_volumes = traits.List(traits.Int, argstr='-ignorevolumes %s', - sep=' ', position=2, minlen=1, - desc=('Requires two values (i.e. [2 5 6] for ' - '[Volumes] Ignores the image volumes ' - 'specified when computing the tensor.')) - quiet = traits.Bool(argstr='-quiet', position=1, - desc=("Do not display information messages or progress " - "status.")) - debug = traits.Bool(argstr='-debug', position=1, - desc="Display debugging messages.") + in_file = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + position=-2, + desc='Diffusion-weighted images') + out_filename = File( + name_template="%s_tensor.mif", + name_source="in_file", + output_name="tensor", + argstr='%s', + desc='Output tensor filename', + position=-1) + encoding_file = File( + argstr='-grad %s', + position=2, + desc=('Encoding file supplied as a 4xN text file with ' + 'each line is in the format [ X Y Z b ], where ' + '[ X Y Z ] describe the direction of the applied ' + 'gradient, and b gives the b-value in units ' + '(1000 s/mm^2). See FSL2MRTrix()')) + ignore_slice_by_volume = traits.List( + traits.Int, + argstr='-ignoreslices %s', + sep=' ', + position=2, + minlen=2, + maxlen=2, + desc=('Requires two values (i.e. [34 ' + '1] for [Slice Volume] Ignores ' + 'the image slices specified ' + 'when computing the tensor. ' + 'Slice here means the z ' + 'coordinate of the slice to be ' + 'ignored.')) + ignore_volumes = traits.List( + traits.Int, + argstr='-ignorevolumes %s', + sep=' ', + position=2, + minlen=1, + desc=('Requires two values (i.e. [2 5 6] for ' + '[Volumes] Ignores the image volumes ' + 'specified when computing the tensor.')) + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc=("Do not display information messages or progress " + "status.")) + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class DWI2TensorOutputSpec(TraitedSpec): - tensor = File(exists=True, - desc='path/name of output diffusion tensor image') + tensor = File( + exists=True, desc='path/name of output diffusion tensor image') class DWI2Tensor(CommandLine): @@ -155,15 +247,28 @@ class DWI2Tensor(CommandLine): class Tensor2VectorInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='Diffusion tensor image') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output vector filename') - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Diffusion tensor image') + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output vector filename') + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class Tensor2VectorOutputSpec(TraitedSpec): - vector = File(exists=True, desc='the output image of the major eigenvectors of the diffusion tensor image.') + vector = File( + exists=True, + desc= + 'the output image of the major eigenvectors of the diffusion tensor image.' + ) class Tensor2Vector(CommandLine): @@ -204,15 +309,31 @@ def _gen_outfilename(self): class Tensor2FractionalAnisotropyInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='Diffusion tensor image') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output Fractional Anisotropy filename') - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Diffusion tensor image') + out_filename = File( + genfile=True, + argstr='%s', + position=-1, + desc='Output Fractional Anisotropy filename') + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class Tensor2FractionalAnisotropyOutputSpec(TraitedSpec): - FA = File(exists=True, desc='the output image of the major eigenvectors of the diffusion tensor image.') + FA = File( + exists=True, + desc= + 'the output image of the major eigenvectors of the diffusion tensor image.' + ) class Tensor2FractionalAnisotropy(CommandLine): @@ -253,15 +374,31 @@ def _gen_outfilename(self): class Tensor2ApparentDiffusionInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='Diffusion tensor image') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output Fractional Anisotropy filename') - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Diffusion tensor image') + out_filename = File( + genfile=True, + argstr='%s', + position=-1, + desc='Output Fractional Anisotropy filename') + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class Tensor2ApparentDiffusionOutputSpec(TraitedSpec): - ADC = File(exists=True, desc='the output image of the major eigenvectors of the diffusion tensor image.') + ADC = File( + exists=True, + desc= + 'the output image of the major eigenvectors of the diffusion tensor image.' + ) class Tensor2ApparentDiffusion(CommandLine): @@ -302,12 +439,20 @@ def _gen_outfilename(self): class MRMultiplyInputSpec(CommandLineInputSpec): - in_files = InputMultiPath(File(exists=True), - argstr='%s', mandatory=True, position=-2, - desc='Input images to be multiplied') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output image filename') - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_files = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + position=-2, + desc='Input images to be multiplied') + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output image filename') + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class MRMultiplyOutputSpec(TraitedSpec): @@ -352,11 +497,18 @@ def _gen_outfilename(self): class MRTrixViewerInputSpec(CommandLineInputSpec): - in_files = InputMultiPath(File(exists=True), argstr='%s', mandatory=True, - position=-2, - desc='Input images to be viewed') - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_files = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + position=-2, + desc='Input images to be viewed') + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class MRTrixViewerOutputSpec(TraitedSpec): @@ -385,8 +537,12 @@ def _list_outputs(self): class MRTrixInfoInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='Input images to be read') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Input images to be read') class MRTrixInfoOutputSpec(TraitedSpec): @@ -415,12 +571,36 @@ def _list_outputs(self): class GenerateWhiteMatterMaskInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, desc='Diffusion-weighted images') - binary_mask = File(exists=True, argstr='%s', mandatory=True, position=-2, desc='Binary brain mask') - out_WMProb_filename = File(genfile=True, argstr='%s', position=-1, desc='Output WM probability image filename') - encoding_file = File(exists=True, argstr='-grad %s', mandatory=True, position=1, - desc='Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix') - noise_level_margin = traits.Float(argstr='-margin %s', desc='Specify the width of the margin on either side of the image to be used to estimate the noise level (default = 10)') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='Diffusion-weighted images') + binary_mask = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Binary brain mask') + out_WMProb_filename = File( + genfile=True, + argstr='%s', + position=-1, + desc='Output WM probability image filename') + encoding_file = File( + exists=True, + argstr='-grad %s', + mandatory=True, + position=1, + desc= + 'Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix' + ) + noise_level_margin = traits.Float( + argstr='-margin %s', + desc= + 'Specify the width of the margin on either side of the image to be used to estimate the noise level (default = 10)' + ) class GenerateWhiteMatterMaskOutputSpec(TraitedSpec): @@ -462,13 +642,26 @@ def _gen_outfilename(self): class ErodeInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='Input mask image to be eroded') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output image filename') - number_of_passes = traits.Int(argstr='-npass %s', desc='the number of passes (default: 1)') - dilate = traits.Bool(argstr='-dilate', position=1, desc="Perform dilation rather than erosion") - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Input mask image to be eroded') + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output image filename') + number_of_passes = traits.Int( + argstr='-npass %s', desc='the number of passes (default: 1)') + dilate = traits.Bool( + argstr='-dilate', + position=1, + desc="Perform dilation rather than erosion") + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class ErodeOutputSpec(TraitedSpec): @@ -512,15 +705,35 @@ def _gen_outfilename(self): class ThresholdInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='The input image to be thresholded') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='The output binary image mask.') - absolute_threshold_value = traits.Float(argstr='-abs %s', desc='Specify threshold value as absolute intensity.') - percentage_threshold_value = traits.Float(argstr='-percent %s', desc='Specify threshold value as a percentage of the peak intensity in the input image.') - invert = traits.Bool(argstr='-invert', position=1, desc="Invert output binary mask") - replace_zeros_with_NaN = traits.Bool(argstr='-nan', position=1, desc="Replace all zero values with NaN") - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='The input image to be thresholded') + out_filename = File( + genfile=True, + argstr='%s', + position=-1, + desc='The output binary image mask.') + absolute_threshold_value = traits.Float( + argstr='-abs %s', + desc='Specify threshold value as absolute intensity.') + percentage_threshold_value = traits.Float( + argstr='-percent %s', + desc= + 'Specify threshold value as a percentage of the peak intensity in the input image.' + ) + invert = traits.Bool( + argstr='-invert', position=1, desc="Invert output binary mask") + replace_zeros_with_NaN = traits.Bool( + argstr='-nan', position=1, desc="Replace all zero values with NaN") + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class ThresholdOutputSpec(TraitedSpec): @@ -570,11 +783,20 @@ def _gen_outfilename(self): class MedianFilter3DInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='Input images to be smoothed') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output image filename') - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Input images to be smoothed') + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output image filename') + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class MedianFilter3DOutputSpec(TraitedSpec): @@ -619,21 +841,53 @@ def _gen_outfilename(self): class MRTransformInputSpec(CommandLineInputSpec): - in_files = InputMultiPath(File(exists=True), argstr='%s', mandatory=True, - position=-2, - desc='Input images to be transformed') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output image') - invert = traits.Bool(argstr='-inverse', position=1, desc="Invert the specified transform before using it") - replace_transform = traits.Bool(argstr='-replace', position=1, desc="replace the current transform by that specified, rather than applying it to the current transform") - transformation_file = File(exists=True, argstr='-transform %s', position=1, - desc='The transform to apply, in the form of a 4x4 ascii file.') - template_image = File(exists=True, argstr='-template %s', position=1, - desc='Reslice the input image to match the specified template image.') - reference_image = File(exists=True, argstr='-reference %s', position=1, - desc='in case the transform supplied maps from the input image onto a reference image, use this option to specify the reference. Note that this implicitly sets the -replace option.') - flip_x = traits.Bool(argstr='-flipx', position=1, desc="assume the transform is supplied assuming a coordinate system with the x-axis reversed relative to the MRtrix convention (i.e. x increases from right to left). This is required to handle transform matrices produced by FSL's FLIRT command. This is only used in conjunction with the -reference option.") - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + in_files = InputMultiPath( + File(exists=True), + argstr='%s', + mandatory=True, + position=-2, + desc='Input images to be transformed') + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output image') + invert = traits.Bool( + argstr='-inverse', + position=1, + desc="Invert the specified transform before using it") + replace_transform = traits.Bool( + argstr='-replace', + position=1, + desc= + "replace the current transform by that specified, rather than applying it to the current transform" + ) + transformation_file = File( + exists=True, + argstr='-transform %s', + position=1, + desc='The transform to apply, in the form of a 4x4 ascii file.') + template_image = File( + exists=True, + argstr='-template %s', + position=1, + desc='Reslice the input image to match the specified template image.') + reference_image = File( + exists=True, + argstr='-reference %s', + position=1, + desc= + 'in case the transform supplied maps from the input image onto a reference image, use this option to specify the reference. Note that this implicitly sets the -replace option.' + ) + flip_x = traits.Bool( + argstr='-flipx', + position=1, + desc= + "assume the transform is supplied assuming a coordinate system with the x-axis reversed relative to the MRtrix convention (i.e. x increases from right to left). This is required to handle transform matrices produced by FSL's FLIRT command. This is only used in conjunction with the -reference option." + ) + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class MRTransformOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/mrtrix/tensors.py b/nipype/interfaces/mrtrix/tensors.py index 025d45b2e5..436dd75a6c 100644 --- a/nipype/interfaces/mrtrix/tensors.py +++ b/nipype/interfaces/mrtrix/tensors.py @@ -9,29 +9,50 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op import numpy as np from ... import logging from ...utils.filemanip import split_filename -from ..base import (CommandLineInputSpec, CommandLine, BaseInterface, - traits, File, TraitedSpec, isdefined) +from ..base import (CommandLineInputSpec, CommandLine, BaseInterface, traits, + File, TraitedSpec, isdefined) iflogger = logging.getLogger('interface') class DWI2SphericalHarmonicsImageInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, desc='Diffusion-weighted images') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output filename') - encoding_file = File(exists=True, argstr='-grad %s', mandatory=True, position=1, - desc='Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix') - maximum_harmonic_order = traits.Float(argstr='-lmax %s', desc='set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.') - normalise = traits.Bool(argstr='-normalise', position=3, desc="normalise the DW signal to the b=0 image") + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='Diffusion-weighted images') + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output filename') + encoding_file = File( + exists=True, + argstr='-grad %s', + mandatory=True, + position=1, + desc= + 'Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix' + ) + maximum_harmonic_order = traits.Float( + argstr='-lmax %s', + desc= + 'set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.' + ) + normalise = traits.Bool( + argstr='-normalise', + position=3, + desc="normalise the DW signal to the b=0 image") class DWI2SphericalHarmonicsImageOutputSpec(TraitedSpec): - spherical_harmonics_image = File(exists=True, desc='Spherical harmonics image') + spherical_harmonics_image = File( + exists=True, desc='Spherical harmonics image') class DWI2SphericalHarmonicsImage(CommandLine): @@ -80,9 +101,11 @@ def _list_outputs(self): outputs = self.output_spec().get() outputs['spherical_harmonics_image'] = self.inputs.out_filename if not isdefined(outputs['spherical_harmonics_image']): - outputs['spherical_harmonics_image'] = op.abspath(self._gen_outfilename()) + outputs['spherical_harmonics_image'] = op.abspath( + self._gen_outfilename()) else: - outputs['spherical_harmonics_image'] = op.abspath(outputs['spherical_harmonics_image']) + outputs['spherical_harmonics_image'] = op.abspath( + outputs['spherical_harmonics_image']) return outputs def _gen_filename(self, name): @@ -97,30 +120,83 @@ def _gen_outfilename(self): class ConstrainedSphericalDeconvolutionInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, desc='diffusion-weighted image') - response_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='the diffusion-weighted signal response function for a single fibre population (see EstimateResponse)') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output filename') - mask_image = File(exists=True, argstr='-mask %s', position=2, desc='only perform computation within the specified binary brain mask image') - encoding_file = File(exists=True, argstr='-grad %s', position=1, - desc='Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix') - filter_file = File(exists=True, argstr='-filter %s', position=-2, - desc='a text file containing the filtering coefficients for each even harmonic order.' - 'the linear frequency filtering parameters used for the initial linear spherical deconvolution step (default = [ 1 1 1 0 0 ]).') - - lambda_value = traits.Float(argstr='-lambda %s', desc='the regularisation parameter lambda that controls the strength of the constraint (default = 1.0).') - maximum_harmonic_order = traits.Int(argstr='-lmax %s', desc='set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.') - threshold_value = traits.Float(argstr='-threshold %s', desc='the threshold below which the amplitude of the FOD is assumed to be zero, expressed as a fraction of the mean value of the initial FOD (default = 0.1)') - iterations = traits.Int(argstr='-niter %s', desc='the maximum number of iterations to perform for each voxel (default = 50)') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='diffusion-weighted image') + response_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc= + 'the diffusion-weighted signal response function for a single fibre population (see EstimateResponse)' + ) + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output filename') + mask_image = File( + exists=True, + argstr='-mask %s', + position=2, + desc= + 'only perform computation within the specified binary brain mask image' + ) + encoding_file = File( + exists=True, + argstr='-grad %s', + position=1, + desc= + 'Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix' + ) + filter_file = File( + exists=True, + argstr='-filter %s', + position=-2, + desc= + 'a text file containing the filtering coefficients for each even harmonic order.' + 'the linear frequency filtering parameters used for the initial linear spherical deconvolution step (default = [ 1 1 1 0 0 ]).' + ) + + lambda_value = traits.Float( + argstr='-lambda %s', + desc= + 'the regularisation parameter lambda that controls the strength of the constraint (default = 1.0).' + ) + maximum_harmonic_order = traits.Int( + argstr='-lmax %s', + desc= + 'set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.' + ) + threshold_value = traits.Float( + argstr='-threshold %s', + desc= + 'the threshold below which the amplitude of the FOD is assumed to be zero, expressed as a fraction of the mean value of the initial FOD (default = 0.1)' + ) + iterations = traits.Int( + argstr='-niter %s', + desc= + 'the maximum number of iterations to perform for each voxel (default = 50)' + ) debug = traits.Bool(argstr='-debug', desc='Display debugging messages.') - directions_file = File(exists=True, argstr='-directions %s', position=-2, - desc='a text file containing the [ el az ] pairs for the directions: Specify the directions over which to apply the non-negativity constraint (by default, the built-in 300 direction set is used)') + directions_file = File( + exists=True, + argstr='-directions %s', + position=-2, + desc= + 'a text file containing the [ el az ] pairs for the directions: Specify the directions over which to apply the non-negativity constraint (by default, the built-in 300 direction set is used)' + ) - normalise = traits.Bool(argstr='-normalise', position=3, desc="normalise the DW signal to the b=0 image") + normalise = traits.Bool( + argstr='-normalise', + position=3, + desc="normalise the DW signal to the b=0 image") class ConstrainedSphericalDeconvolutionOutputSpec(TraitedSpec): - spherical_harmonics_image = File(exists=True, desc='Spherical harmonics image') + spherical_harmonics_image = File( + exists=True, desc='Spherical harmonics image') class ConstrainedSphericalDeconvolution(CommandLine): @@ -163,9 +239,11 @@ def _list_outputs(self): outputs = self.output_spec().get() outputs['spherical_harmonics_image'] = self.inputs.out_filename if not isdefined(outputs['spherical_harmonics_image']): - outputs['spherical_harmonics_image'] = op.abspath(self._gen_outfilename()) + outputs['spherical_harmonics_image'] = op.abspath( + self._gen_outfilename()) else: - outputs['spherical_harmonics_image'] = op.abspath(outputs['spherical_harmonics_image']) + outputs['spherical_harmonics_image'] = op.abspath( + outputs['spherical_harmonics_image']) return outputs def _gen_filename(self, name): @@ -180,14 +258,40 @@ def _gen_outfilename(self): class EstimateResponseForSHInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, desc='Diffusion-weighted images') - mask_image = File(exists=True, mandatory=True, argstr='%s', position=-2, desc='only perform computation within the specified binary brain mask image') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='Output filename') - encoding_file = File(exists=True, argstr='-grad %s', mandatory=True, position=1, - desc='Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix') - maximum_harmonic_order = traits.Int(argstr='-lmax %s', desc='set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.') - normalise = traits.Bool(argstr='-normalise', desc='normalise the DW signal to the b=0 image') - quiet = traits.Bool(argstr='-quiet', desc='Do not display information messages or progress status.') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='Diffusion-weighted images') + mask_image = File( + exists=True, + mandatory=True, + argstr='%s', + position=-2, + desc= + 'only perform computation within the specified binary brain mask image' + ) + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='Output filename') + encoding_file = File( + exists=True, + argstr='-grad %s', + mandatory=True, + position=1, + desc= + 'Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix' + ) + maximum_harmonic_order = traits.Int( + argstr='-lmax %s', + desc= + 'set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.' + ) + normalise = traits.Bool( + argstr='-normalise', desc='normalise the DW signal to the b=0 image') + quiet = traits.Bool( + argstr='-quiet', + desc='Do not display information messages or progress status.') debug = traits.Bool(argstr='-debug', desc='Display debugging messages.') @@ -236,9 +340,7 @@ def _gen_outfilename(self): def concat_files(bvec_file, bval_file, invert_x, invert_y, invert_z): bvecs = np.loadtxt(bvec_file) bvals = np.loadtxt(bval_file) - flip = False if np.shape(bvecs)[0] > np.shape(bvecs)[1]: - flip = True bvecs = np.transpose(bvecs) if invert_x: bvecs[0, :] = -bvecs[0, :] @@ -260,17 +362,24 @@ def concat_files(bvec_file, bval_file, invert_x, invert_y, invert_z): class FSL2MRTrixInputSpec(TraitedSpec): - bvec_file = File(exists=True, mandatory=True, desc='FSL b-vectors file (3xN text file)') - bval_file = File(exists=True, mandatory=True, desc='FSL b-values file (1xN text file)') - invert_x = traits.Bool(False, usedefault=True, desc='Inverts the b-vectors along the x-axis') - invert_y = traits.Bool(False, usedefault=True, desc='Inverts the b-vectors along the y-axis') - invert_z = traits.Bool(False, usedefault=True, desc='Inverts the b-vectors along the z-axis') + bvec_file = File( + exists=True, mandatory=True, desc='FSL b-vectors file (3xN text file)') + bval_file = File( + exists=True, mandatory=True, desc='FSL b-values file (1xN text file)') + invert_x = traits.Bool( + False, usedefault=True, desc='Inverts the b-vectors along the x-axis') + invert_y = traits.Bool( + False, usedefault=True, desc='Inverts the b-vectors along the y-axis') + invert_z = traits.Bool( + False, usedefault=True, desc='Inverts the b-vectors along the z-axis') out_encoding_file = File(genfile=True, desc='Output encoding filename') class FSL2MRTrixOutputSpec(TraitedSpec): - encoding_file = File(desc='The gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient' - 'and b gives the b-value in units (1000 s/mm^2).') + encoding_file = File( + desc= + 'The gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient' + 'and b gives the b-value in units (1000 s/mm^2).') class FSL2MRTrix(BaseInterface): @@ -294,12 +403,15 @@ class FSL2MRTrix(BaseInterface): output_spec = FSL2MRTrixOutputSpec def _run_interface(self, runtime): - encoding = concat_files(self.inputs.bvec_file, self.inputs.bval_file, self.inputs.invert_x, self.inputs.invert_y, self.inputs.invert_z) + encoding = concat_files(self.inputs.bvec_file, self.inputs.bval_file, + self.inputs.invert_x, self.inputs.invert_y, + self.inputs.invert_z) return runtime def _list_outputs(self): outputs = self.output_spec().get() - outputs['encoding_file'] = op.abspath(self._gen_filename('out_encoding_file')) + outputs['encoding_file'] = op.abspath( + self._gen_filename('out_encoding_file')) return outputs def _gen_filename(self, name): @@ -315,15 +427,32 @@ def _gen_outfilename(self): class GenerateDirectionsInputSpec(CommandLineInputSpec): - num_dirs = traits.Int(mandatory=True, argstr='%s', position=-2, desc='the number of directions to generate.') - - power = traits.Float(argstr='-power %s', desc='specify exponent to use for repulsion power law.') - niter = traits.Int(argstr='-niter %s', desc='specify the maximum number of iterations to perform.') - display_info = traits.Bool(argstr='-info', desc='Display information messages.') - quiet_display = traits.Bool(argstr='-quiet', desc='do not display information messages or progress status.') - display_debug = traits.Bool(argstr='-debug', desc='Display debugging messages.') - out_file = File(name_source=['num_dirs'], name_template='directions_%d.txt', argstr='%s', hash_files=False, - position=-1, desc='the text file to write the directions to, as [ az el ] pairs.') + num_dirs = traits.Int( + mandatory=True, + argstr='%s', + position=-2, + desc='the number of directions to generate.') + + power = traits.Float( + argstr='-power %s', + desc='specify exponent to use for repulsion power law.') + niter = traits.Int( + argstr='-niter %s', + desc='specify the maximum number of iterations to perform.') + display_info = traits.Bool( + argstr='-info', desc='Display information messages.') + quiet_display = traits.Bool( + argstr='-quiet', + desc='do not display information messages or progress status.') + display_debug = traits.Bool( + argstr='-debug', desc='Display debugging messages.') + out_file = File( + name_source=['num_dirs'], + name_template='directions_%d.txt', + argstr='%s', + hash_files=False, + position=-1, + desc='the text file to write the directions to, as [ az el ] pairs.') class GenerateDirectionsOutputSpec(TraitedSpec): @@ -349,19 +478,56 @@ class GenerateDirections(CommandLine): class FindShPeaksInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, desc='the input image of SH coefficients.') - directions_file = File(exists=True, argstr='%s', mandatory=True, position=-2, desc='the set of directions to use as seeds for the peak finding') - peaks_image = File(exists=True, argstr='-peaks %s', desc='the program will try to find the peaks that most closely match those in the image provided') - num_peaks = traits.Int(argstr='-num %s', desc='the number of peaks to extract (default is 3)') - peak_directions = traits.List(traits.Float, argstr='-direction %s', sep=' ', minlen=2, maxlen=2, - desc='phi theta. the direction of a peak to estimate. The algorithm will attempt to find the same number of peaks as have been specified using this option ' - ' phi: the azimuthal angle of the direction (in degrees). theta: the elevation angle of the direction (in degrees, from the vertical z-axis)') - peak_threshold = traits.Float(argstr='-threshold %s', desc='only peak amplitudes greater than the threshold will be considered') - display_info = traits.Bool(argstr='-info', desc='Display information messages.') - quiet_display = traits.Bool(argstr='-quiet', desc='do not display information messages or progress status.') - display_debug = traits.Bool(argstr='-debug', desc='Display debugging messages.') - out_file = File(name_template="%s_peak_dirs.mif", keep_extension=False, argstr='%s', hash_files=False, position=-1, - desc='the output image. Each volume corresponds to the x, y & z component of each peak direction vector in turn', name_source=["in_file"]) + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='the input image of SH coefficients.') + directions_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='the set of directions to use as seeds for the peak finding') + peaks_image = File( + exists=True, + argstr='-peaks %s', + desc= + 'the program will try to find the peaks that most closely match those in the image provided' + ) + num_peaks = traits.Int( + argstr='-num %s', desc='the number of peaks to extract (default is 3)') + peak_directions = traits.List( + traits.Float, + argstr='-direction %s', + sep=' ', + minlen=2, + maxlen=2, + desc= + 'phi theta. the direction of a peak to estimate. The algorithm will attempt to find the same number of peaks as have been specified using this option ' + ' phi: the azimuthal angle of the direction (in degrees). theta: the elevation angle of the direction (in degrees, from the vertical z-axis)' + ) + peak_threshold = traits.Float( + argstr='-threshold %s', + desc= + 'only peak amplitudes greater than the threshold will be considered') + display_info = traits.Bool( + argstr='-info', desc='Display information messages.') + quiet_display = traits.Bool( + argstr='-quiet', + desc='do not display information messages or progress status.') + display_debug = traits.Bool( + argstr='-debug', desc='Display debugging messages.') + out_file = File( + name_template="%s_peak_dirs.mif", + keep_extension=False, + argstr='%s', + hash_files=False, + position=-1, + desc= + 'the output image. Each volume corresponds to the x, y & z component of each peak direction vector in turn', + name_source=["in_file"]) class FindShPeaksOutputSpec(TraitedSpec): @@ -389,17 +555,47 @@ class FindShPeaks(CommandLine): class Directions2AmplitudeInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, desc='the input directions image. Each volume corresponds to the x, y & z component of each direction vector in turn.') - peaks_image = File(exists=True, argstr='-peaks %s', desc='the program will try to find the peaks that most closely match those in the image provided') - num_peaks = traits.Int(argstr='-num %s', desc='the number of peaks to extract (default is 3)') - peak_directions = traits.List(traits.Float, argstr='-direction %s', sep=' ', minlen=2, maxlen=2, - desc='phi theta. the direction of a peak to estimate. The algorithm will attempt to find the same number of peaks as have been specified using this option ' - ' phi: the azimuthal angle of the direction (in degrees). theta: the elevation angle of the direction (in degrees, from the vertical z-axis)') - display_info = traits.Bool(argstr='-info', desc='Display information messages.') - quiet_display = traits.Bool(argstr='-quiet', desc='do not display information messages or progress status.') - display_debug = traits.Bool(argstr='-debug', desc='Display debugging messages.') - out_file = File(name_template="%s_amplitudes.mif", keep_extension=False, argstr='%s', hash_files=False, position=-1, - desc='the output amplitudes image', name_source=["in_file"]) + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc= + 'the input directions image. Each volume corresponds to the x, y & z component of each direction vector in turn.' + ) + peaks_image = File( + exists=True, + argstr='-peaks %s', + desc= + 'the program will try to find the peaks that most closely match those in the image provided' + ) + num_peaks = traits.Int( + argstr='-num %s', desc='the number of peaks to extract (default is 3)') + peak_directions = traits.List( + traits.Float, + argstr='-direction %s', + sep=' ', + minlen=2, + maxlen=2, + desc= + 'phi theta. the direction of a peak to estimate. The algorithm will attempt to find the same number of peaks as have been specified using this option ' + ' phi: the azimuthal angle of the direction (in degrees). theta: the elevation angle of the direction (in degrees, from the vertical z-axis)' + ) + display_info = traits.Bool( + argstr='-info', desc='Display information messages.') + quiet_display = traits.Bool( + argstr='-quiet', + desc='do not display information messages or progress status.') + display_debug = traits.Bool( + argstr='-debug', desc='Display debugging messages.') + out_file = File( + name_template="%s_amplitudes.mif", + keep_extension=False, + argstr='%s', + hash_files=False, + position=-1, + desc='the output amplitudes image', + name_source=["in_file"]) class Directions2AmplitudeOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py b/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py index ef66cfc691..af1a566aad 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py @@ -4,66 +4,69 @@ def test_ConstrainedSphericalDeconvolution_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - ), - directions_file=dict(argstr='-directions %s', - position=-2, - ), - encoding_file=dict(argstr='-grad %s', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - filter_file=dict(argstr='-filter %s', - position=-2, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - iterations=dict(argstr='-niter %s', - ), - lambda_value=dict(argstr='-lambda %s', - ), - mask_image=dict(argstr='-mask %s', - position=2, - ), - maximum_harmonic_order=dict(argstr='-lmax %s', - ), - normalise=dict(argstr='-normalise', - position=3, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - response_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold_value=dict(argstr='-threshold %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict(argstr='-debug', ), + directions_file=dict( + argstr='-directions %s', + position=-2, + ), + encoding_file=dict( + argstr='-grad %s', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filter_file=dict( + argstr='-filter %s', + position=-2, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + iterations=dict(argstr='-niter %s', ), + lambda_value=dict(argstr='-lambda %s', ), + mask_image=dict( + argstr='-mask %s', + position=2, + ), + maximum_harmonic_order=dict(argstr='-lmax %s', ), + normalise=dict( + argstr='-normalise', + position=3, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + response_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold_value=dict(argstr='-threshold %s', ), ) inputs = ConstrainedSphericalDeconvolution.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ConstrainedSphericalDeconvolution_outputs(): - output_map = dict(spherical_harmonics_image=dict(), - ) + output_map = dict(spherical_harmonics_image=dict(), ) outputs = ConstrainedSphericalDeconvolution.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py b/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py index 54a028727e..8a500023e9 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py @@ -4,46 +4,49 @@ def test_DWI2SphericalHarmonicsImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - encoding_file=dict(argstr='-grad %s', - mandatory=True, - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - maximum_harmonic_order=dict(argstr='-lmax %s', - ), - normalise=dict(argstr='-normalise', - position=3, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + encoding_file=dict( + argstr='-grad %s', + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + maximum_harmonic_order=dict(argstr='-lmax %s', ), + normalise=dict( + argstr='-normalise', + position=3, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWI2SphericalHarmonicsImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWI2SphericalHarmonicsImage_outputs(): - output_map = dict(spherical_harmonics_image=dict(), - ) + output_map = dict(spherical_harmonics_image=dict(), ) outputs = DWI2SphericalHarmonicsImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py b/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py index 051172702f..e0309f549c 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py @@ -4,56 +4,63 @@ def test_DWI2Tensor_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - encoding_file=dict(argstr='-grad %s', - position=2, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_slice_by_volume=dict(argstr='-ignoreslices %s', - position=2, - sep=' ', - ), - ignore_volumes=dict(argstr='-ignorevolumes %s', - position=2, - sep=' ', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_filename=dict(argstr='%s', - name_source='in_file', - name_template='%s_tensor.mif', - output_name='tensor', - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + encoding_file=dict( + argstr='-grad %s', + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_slice_by_volume=dict( + argstr='-ignoreslices %s', + position=2, + sep=' ', + ), + ignore_volumes=dict( + argstr='-ignorevolumes %s', + position=2, + sep=' ', + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr='%s', + name_source='in_file', + name_template='%s_tensor.mif', + output_name='tensor', + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWI2Tensor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWI2Tensor_outputs(): - output_map = dict(tensor=dict(), - ) + output_map = dict(tensor=dict(), ) outputs = DWI2Tensor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py index 46f45243ee..7408e3f3dc 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py @@ -4,116 +4,129 @@ def test_DiffusionTensorStreamlineTrack_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cutoff_value=dict(argstr='-cutoff %s', - units='NA', - ), - desired_number_of_tracks=dict(argstr='-number %d', - ), - do_not_precompute=dict(argstr='-noprecomputed', - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclude_file=dict(argstr='-exclude %s', - xor=['exclude_file', 'exclude_spec'], - ), - exclude_spec=dict(argstr='-exclude %s', - position=2, - sep=',', - units='mm', - xor=['exclude_file', 'exclude_spec'], - ), - gradient_encoding_file=dict(argstr='-grad %s', - mandatory=True, - position=-2, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - include_file=dict(argstr='-include %s', - xor=['include_file', 'include_spec'], - ), - include_spec=dict(argstr='-include %s', - position=2, - sep=',', - units='mm', - xor=['include_file', 'include_spec'], - ), - initial_cutoff_value=dict(argstr='-initcutoff %s', - units='NA', - ), - initial_direction=dict(argstr='-initdirection %s', - units='voxels', - ), - inputmodel=dict(argstr='%s', - position=-3, - usedefault=True, - ), - mask_file=dict(argstr='-mask %s', - xor=['mask_file', 'mask_spec'], - ), - mask_spec=dict(argstr='-mask %s', - position=2, - sep=',', - units='mm', - xor=['mask_file', 'mask_spec'], - ), - maximum_number_of_tracks=dict(argstr='-maxnum %d', - ), - maximum_tract_length=dict(argstr='-length %s', - units='mm', - ), - minimum_radius_of_curvature=dict(argstr='-curvature %s', - units='mm', - ), - minimum_tract_length=dict(argstr='-minlength %s', - units='mm', - ), - no_mask_interpolation=dict(argstr='-nomaskinterp', - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s_tracked.tck', - output_name='tracked', - position=-1, - ), - seed_file=dict(argstr='-seed %s', - xor=['seed_file', 'seed_spec'], - ), - seed_spec=dict(argstr='-seed %s', - position=2, - sep=',', - units='mm', - xor=['seed_file', 'seed_spec'], - ), - step_size=dict(argstr='-step %s', - units='mm', - ), - stop=dict(argstr='-stop', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unidirectional=dict(argstr='-unidirectional', - ), + input_map = dict( + args=dict(argstr='%s', ), + cutoff_value=dict( + argstr='-cutoff %s', + units='NA', + ), + desired_number_of_tracks=dict(argstr='-number %d', ), + do_not_precompute=dict(argstr='-noprecomputed', ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclude_file=dict( + argstr='-exclude %s', + xor=['exclude_file', 'exclude_spec'], + ), + exclude_spec=dict( + argstr='-exclude %s', + position=2, + sep=',', + units='mm', + xor=['exclude_file', 'exclude_spec'], + ), + gradient_encoding_file=dict( + argstr='-grad %s', + mandatory=True, + position=-2, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + include_file=dict( + argstr='-include %s', + xor=['include_file', 'include_spec'], + ), + include_spec=dict( + argstr='-include %s', + position=2, + sep=',', + units='mm', + xor=['include_file', 'include_spec'], + ), + initial_cutoff_value=dict( + argstr='-initcutoff %s', + units='NA', + ), + initial_direction=dict( + argstr='-initdirection %s', + units='voxels', + ), + inputmodel=dict( + argstr='%s', + position=-3, + usedefault=True, + ), + mask_file=dict( + argstr='-mask %s', + xor=['mask_file', 'mask_spec'], + ), + mask_spec=dict( + argstr='-mask %s', + position=2, + sep=',', + units='mm', + xor=['mask_file', 'mask_spec'], + ), + maximum_number_of_tracks=dict(argstr='-maxnum %d', ), + maximum_tract_length=dict( + argstr='-length %s', + units='mm', + ), + minimum_radius_of_curvature=dict( + argstr='-curvature %s', + units='mm', + ), + minimum_tract_length=dict( + argstr='-minlength %s', + units='mm', + ), + no_mask_interpolation=dict(argstr='-nomaskinterp', ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s_tracked.tck', + output_name='tracked', + position=-1, + ), + seed_file=dict( + argstr='-seed %s', + xor=['seed_file', 'seed_spec'], + ), + seed_spec=dict( + argstr='-seed %s', + position=2, + sep=',', + units='mm', + xor=['seed_file', 'seed_spec'], + ), + step_size=dict( + argstr='-step %s', + units='mm', + ), + stop=dict(argstr='-stop', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unidirectional=dict(argstr='-unidirectional', ), ) inputs = DiffusionTensorStreamlineTrack.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DiffusionTensorStreamlineTrack_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = DiffusionTensorStreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py b/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py index dfe29bbb7c..a0377a3c5e 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py @@ -4,53 +4,51 @@ def test_Directions2Amplitude_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - display_debug=dict(argstr='-debug', - ), - display_info=dict(argstr='-info', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - num_peaks=dict(argstr='-num %s', - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=False, - name_source=['in_file'], - name_template='%s_amplitudes.mif', - position=-1, - ), - peak_directions=dict(argstr='-direction %s', - sep=' ', - ), - peaks_image=dict(argstr='-peaks %s', - ), - quiet_display=dict(argstr='-quiet', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + display_debug=dict(argstr='-debug', ), + display_info=dict(argstr='-info', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + num_peaks=dict(argstr='-num %s', ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=False, + name_source=['in_file'], + name_template='%s_amplitudes.mif', + position=-1, + ), + peak_directions=dict( + argstr='-direction %s', + sep=' ', + ), + peaks_image=dict(argstr='-peaks %s', ), + quiet_display=dict(argstr='-quiet', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Directions2Amplitude.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Directions2Amplitude_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Directions2Amplitude.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Erode.py b/nipype/interfaces/mrtrix/tests/test_auto_Erode.py index 874ad1ba0e..10f05eca1e 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Erode.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Erode.py @@ -4,48 +4,52 @@ def test_Erode_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - dilate=dict(argstr='-dilate', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - number_of_passes=dict(argstr='-npass %s', - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + dilate=dict( + argstr='-dilate', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + number_of_passes=dict(argstr='-npass %s', ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Erode.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Erode_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Erode.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py b/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py index 5d81dbecd6..f3d31ec1f8 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py @@ -4,53 +4,53 @@ def test_EstimateResponseForSH_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - ), - encoding_file=dict(argstr='-grad %s', - mandatory=True, - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - mask_image=dict(argstr='%s', - mandatory=True, - position=-2, - ), - maximum_harmonic_order=dict(argstr='-lmax %s', - ), - normalise=dict(argstr='-normalise', - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict(argstr='-debug', ), + encoding_file=dict( + argstr='-grad %s', + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + mask_image=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + maximum_harmonic_order=dict(argstr='-lmax %s', ), + normalise=dict(argstr='-normalise', ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict(argstr='-quiet', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = EstimateResponseForSH.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EstimateResponseForSH_outputs(): - output_map = dict(response=dict(), - ) + output_map = dict(response=dict(), ) outputs = EstimateResponseForSH.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py b/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py index a194813485..6261b6b0a5 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py @@ -4,29 +4,21 @@ def test_FSL2MRTrix_inputs(): - input_map = dict(bval_file=dict(mandatory=True, - ), - bvec_file=dict(mandatory=True, - ), - invert_x=dict(usedefault=True, - ), - invert_y=dict(usedefault=True, - ), - invert_z=dict(usedefault=True, - ), - out_encoding_file=dict(genfile=True, - ), + input_map = dict( + bval_file=dict(mandatory=True, ), + bvec_file=dict(mandatory=True, ), + invert_x=dict(usedefault=True, ), + invert_y=dict(usedefault=True, ), + invert_z=dict(usedefault=True, ), + out_encoding_file=dict(genfile=True, ), ) inputs = FSL2MRTrix.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FSL2MRTrix_outputs(): - output_map = dict(encoding_file=dict(), - ) + output_map = dict(encoding_file=dict(), ) outputs = FSL2MRTrix.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py b/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py index 5c53341e8f..b34d8372ba 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py @@ -4,70 +4,77 @@ def test_FilterTracks_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclude_file=dict(argstr='-exclude %s', - xor=['exclude_file', 'exclude_spec'], - ), - exclude_spec=dict(argstr='-exclude %s', - position=2, - sep=',', - units='mm', - xor=['exclude_file', 'exclude_spec'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - include_file=dict(argstr='-include %s', - xor=['include_file', 'include_spec'], - ), - include_spec=dict(argstr='-include %s', - position=2, - sep=',', - units='mm', - xor=['include_file', 'include_spec'], - ), - invert=dict(argstr='-invert', - ), - minimum_tract_length=dict(argstr='-minlength %s', - units='mm', - ), - no_mask_interpolation=dict(argstr='-nomaskinterp', - ), - out_file=dict(argstr='%s', - hash_files=False, - name_source=['in_file'], - name_template='%s_filt', - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclude_file=dict( + argstr='-exclude %s', + xor=['exclude_file', 'exclude_spec'], + ), + exclude_spec=dict( + argstr='-exclude %s', + position=2, + sep=',', + units='mm', + xor=['exclude_file', 'exclude_spec'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + include_file=dict( + argstr='-include %s', + xor=['include_file', 'include_spec'], + ), + include_spec=dict( + argstr='-include %s', + position=2, + sep=',', + units='mm', + xor=['include_file', 'include_spec'], + ), + invert=dict(argstr='-invert', ), + minimum_tract_length=dict( + argstr='-minlength %s', + units='mm', + ), + no_mask_interpolation=dict(argstr='-nomaskinterp', ), + out_file=dict( + argstr='%s', + hash_files=False, + name_source=['in_file'], + name_template='%s_filt', + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FilterTracks.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FilterTracks_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = FilterTracks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py b/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py index f0571ad997..a6c570c39c 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py @@ -4,59 +4,57 @@ def test_FindShPeaks_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - directions_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - display_debug=dict(argstr='-debug', - ), - display_info=dict(argstr='-info', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - num_peaks=dict(argstr='-num %s', - ), - out_file=dict(argstr='%s', - hash_files=False, - keep_extension=False, - name_source=['in_file'], - name_template='%s_peak_dirs.mif', - position=-1, - ), - peak_directions=dict(argstr='-direction %s', - sep=' ', - ), - peak_threshold=dict(argstr='-threshold %s', - ), - peaks_image=dict(argstr='-peaks %s', - ), - quiet_display=dict(argstr='-quiet', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + directions_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + display_debug=dict(argstr='-debug', ), + display_info=dict(argstr='-info', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + num_peaks=dict(argstr='-num %s', ), + out_file=dict( + argstr='%s', + hash_files=False, + keep_extension=False, + name_source=['in_file'], + name_template='%s_peak_dirs.mif', + position=-1, + ), + peak_directions=dict( + argstr='-direction %s', + sep=' ', + ), + peak_threshold=dict(argstr='-threshold %s', ), + peaks_image=dict(argstr='-peaks %s', ), + quiet_display=dict(argstr='-quiet', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FindShPeaks.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FindShPeaks_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = FindShPeaks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py b/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py index 8e4167167f..a2c2e2ee7c 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py @@ -4,49 +4,46 @@ def test_GenerateDirections_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - display_debug=dict(argstr='-debug', - ), - display_info=dict(argstr='-info', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - niter=dict(argstr='-niter %s', - ), - num_dirs=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - hash_files=False, - name_source=['num_dirs'], - name_template='directions_%d.txt', - position=-1, - ), - power=dict(argstr='-power %s', - ), - quiet_display=dict(argstr='-quiet', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + display_debug=dict(argstr='-debug', ), + display_info=dict(argstr='-info', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + niter=dict(argstr='-niter %s', ), + num_dirs=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + hash_files=False, + name_source=['num_dirs'], + name_template='directions_%d.txt', + position=-1, + ), + power=dict(argstr='-power %s', ), + quiet_display=dict(argstr='-quiet', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GenerateDirections.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateDirections_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = GenerateDirections.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py b/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py index bda204c9ad..88ba72dcae 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py @@ -4,47 +4,50 @@ def test_GenerateWhiteMatterMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - binary_mask=dict(argstr='%s', - mandatory=True, - position=-2, - ), - encoding_file=dict(argstr='-grad %s', - mandatory=True, - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - noise_level_margin=dict(argstr='-margin %s', - ), - out_WMProb_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + binary_mask=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + encoding_file=dict( + argstr='-grad %s', + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + noise_level_margin=dict(argstr='-margin %s', ), + out_WMProb_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GenerateWhiteMatterMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateWhiteMatterMask_outputs(): - output_map = dict(WMprobabilitymap=dict(), - ) + output_map = dict(WMprobabilitymap=dict(), ) outputs = GenerateWhiteMatterMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py b/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py index ed9071256e..df681c17eb 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py @@ -4,71 +4,83 @@ def test_MRConvert_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - extension=dict(position=2, - usedefault=True, - ), - extract_at_axis=dict(argstr='-coord %s', - position=1, - ), - extract_at_coordinate=dict(argstr='%s', - position=2, - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - layout=dict(argstr='-output %s', - position=2, - ), - offset_bias=dict(argstr='-scale %d', - position=3, - units='mm', - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - output_datatype=dict(argstr='-output %s', - position=2, - ), - prs=dict(argstr='-prs', - position=3, - ), - replace_NaN_with_zero=dict(argstr='-zero', - position=3, - ), - resample=dict(argstr='-scale %d', - position=3, - units='mm', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel_dims=dict(argstr='-vox %s', - position=3, - sep=',', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + extension=dict( + position=2, + usedefault=True, + ), + extract_at_axis=dict( + argstr='-coord %s', + position=1, + ), + extract_at_coordinate=dict( + argstr='%s', + position=2, + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + layout=dict( + argstr='-output %s', + position=2, + ), + offset_bias=dict( + argstr='-scale %d', + position=3, + units='mm', + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + output_datatype=dict( + argstr='-output %s', + position=2, + ), + prs=dict( + argstr='-prs', + position=3, + ), + replace_NaN_with_zero=dict( + argstr='-zero', + position=3, + ), + resample=dict( + argstr='-scale %d', + position=3, + units='mm', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel_dims=dict( + argstr='-vox %s', + position=3, + sep=',', + ), ) inputs = MRConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRConvert_outputs(): - output_map = dict(converted=dict(), - ) + output_map = dict(converted=dict(), ) outputs = MRConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py b/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py index efb8b92249..ddb7a30f8d 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py @@ -4,43 +4,47 @@ def test_MRMultiply_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRMultiply.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRMultiply_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRMultiply.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py index a685293371..a82dfaa858 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py @@ -4,61 +4,71 @@ def test_MRTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - flip_x=dict(argstr='-flipx', - position=1, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=-2, - ), - invert=dict(argstr='-inverse', - position=1, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - reference_image=dict(argstr='-reference %s', - position=1, - ), - replace_transform=dict(argstr='-replace', - position=1, - ), - template_image=dict(argstr='-template %s', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformation_file=dict(argstr='-transform %s', - position=1, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip_x=dict( + argstr='-flipx', + position=1, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + invert=dict( + argstr='-inverse', + position=1, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + reference_image=dict( + argstr='-reference %s', + position=1, + ), + replace_transform=dict( + argstr='-replace', + position=1, + ), + template_image=dict( + argstr='-template %s', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformation_file=dict( + argstr='-transform %s', + position=1, + ), ) inputs = MRTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRTransform_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py index c237386940..b6fefac9a0 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py @@ -4,25 +4,23 @@ def test_MRTrix2TrackVis_inputs(): - input_map = dict(image_file=dict(), - in_file=dict(mandatory=True, - ), - matrix_file=dict(), - out_filename=dict(genfile=True, - usedefault=True, - ), - registration_image_file=dict(), + input_map = dict( + image_file=dict(), + in_file=dict(mandatory=True, ), + matrix_file=dict(), + out_filename=dict( + genfile=True, + usedefault=True, + ), + registration_image_file=dict(), ) inputs = MRTrix2TrackVis.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRTrix2TrackVis_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRTrix2TrackVis.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py index 4fe4d2952b..18bc2c66c4 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py @@ -4,30 +4,32 @@ def test_MRTrixInfo_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRTrixInfo.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRTrixInfo_outputs(): output_map = dict() outputs = MRTrixInfo.output_spec() diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py index 19a0e6f710..5b814209ac 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py @@ -4,36 +4,40 @@ def test_MRTrixViewer_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(argstr='%s', - mandatory=True, - position=-2, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRTrixViewer.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRTrixViewer_outputs(): output_map = dict() outputs = MRTrixViewer.output_spec() diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py b/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py index 0b13574b78..147be28bc8 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py @@ -4,43 +4,47 @@ def test_MedianFilter3D_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MedianFilter3D.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedianFilter3D_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MedianFilter3D.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py index f3fcda4884..ed30b6abb7 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py @@ -4,114 +4,125 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cutoff_value=dict(argstr='-cutoff %s', - units='NA', - ), - desired_number_of_tracks=dict(argstr='-number %d', - ), - do_not_precompute=dict(argstr='-noprecomputed', - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclude_file=dict(argstr='-exclude %s', - xor=['exclude_file', 'exclude_spec'], - ), - exclude_spec=dict(argstr='-exclude %s', - position=2, - sep=',', - units='mm', - xor=['exclude_file', 'exclude_spec'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - include_file=dict(argstr='-include %s', - xor=['include_file', 'include_spec'], - ), - include_spec=dict(argstr='-include %s', - position=2, - sep=',', - units='mm', - xor=['include_file', 'include_spec'], - ), - initial_cutoff_value=dict(argstr='-initcutoff %s', - units='NA', - ), - initial_direction=dict(argstr='-initdirection %s', - units='voxels', - ), - inputmodel=dict(argstr='%s', - position=-3, - usedefault=True, - ), - mask_file=dict(argstr='-mask %s', - xor=['mask_file', 'mask_spec'], - ), - mask_spec=dict(argstr='-mask %s', - position=2, - sep=',', - units='mm', - xor=['mask_file', 'mask_spec'], - ), - maximum_number_of_tracks=dict(argstr='-maxnum %d', - ), - maximum_number_of_trials=dict(argstr='-trials %s', - ), - maximum_tract_length=dict(argstr='-length %s', - units='mm', - ), - minimum_radius_of_curvature=dict(argstr='-curvature %s', - units='mm', - ), - minimum_tract_length=dict(argstr='-minlength %s', - units='mm', - ), - no_mask_interpolation=dict(argstr='-nomaskinterp', - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s_tracked.tck', - output_name='tracked', - position=-1, - ), - seed_file=dict(argstr='-seed %s', - xor=['seed_file', 'seed_spec'], - ), - seed_spec=dict(argstr='-seed %s', - position=2, - sep=',', - units='mm', - xor=['seed_file', 'seed_spec'], - ), - step_size=dict(argstr='-step %s', - units='mm', - ), - stop=dict(argstr='-stop', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unidirectional=dict(argstr='-unidirectional', - ), + input_map = dict( + args=dict(argstr='%s', ), + cutoff_value=dict( + argstr='-cutoff %s', + units='NA', + ), + desired_number_of_tracks=dict(argstr='-number %d', ), + do_not_precompute=dict(argstr='-noprecomputed', ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclude_file=dict( + argstr='-exclude %s', + xor=['exclude_file', 'exclude_spec'], + ), + exclude_spec=dict( + argstr='-exclude %s', + position=2, + sep=',', + units='mm', + xor=['exclude_file', 'exclude_spec'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + include_file=dict( + argstr='-include %s', + xor=['include_file', 'include_spec'], + ), + include_spec=dict( + argstr='-include %s', + position=2, + sep=',', + units='mm', + xor=['include_file', 'include_spec'], + ), + initial_cutoff_value=dict( + argstr='-initcutoff %s', + units='NA', + ), + initial_direction=dict( + argstr='-initdirection %s', + units='voxels', + ), + inputmodel=dict( + argstr='%s', + position=-3, + usedefault=True, + ), + mask_file=dict( + argstr='-mask %s', + xor=['mask_file', 'mask_spec'], + ), + mask_spec=dict( + argstr='-mask %s', + position=2, + sep=',', + units='mm', + xor=['mask_file', 'mask_spec'], + ), + maximum_number_of_tracks=dict(argstr='-maxnum %d', ), + maximum_number_of_trials=dict(argstr='-trials %s', ), + maximum_tract_length=dict( + argstr='-length %s', + units='mm', + ), + minimum_radius_of_curvature=dict( + argstr='-curvature %s', + units='mm', + ), + minimum_tract_length=dict( + argstr='-minlength %s', + units='mm', + ), + no_mask_interpolation=dict(argstr='-nomaskinterp', ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s_tracked.tck', + output_name='tracked', + position=-1, + ), + seed_file=dict( + argstr='-seed %s', + xor=['seed_file', 'seed_spec'], + ), + seed_spec=dict( + argstr='-seed %s', + position=2, + sep=',', + units='mm', + xor=['seed_file', 'seed_spec'], + ), + step_size=dict( + argstr='-step %s', + units='mm', + ), + stop=dict(argstr='-stop', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unidirectional=dict(argstr='-unidirectional', ), ) inputs = ProbabilisticSphericallyDeconvolutedStreamlineTrack.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = ProbabilisticSphericallyDeconvolutedStreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py index a8ef768850..e96f4ec20c 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py @@ -4,112 +4,124 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cutoff_value=dict(argstr='-cutoff %s', - units='NA', - ), - desired_number_of_tracks=dict(argstr='-number %d', - ), - do_not_precompute=dict(argstr='-noprecomputed', - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclude_file=dict(argstr='-exclude %s', - xor=['exclude_file', 'exclude_spec'], - ), - exclude_spec=dict(argstr='-exclude %s', - position=2, - sep=',', - units='mm', - xor=['exclude_file', 'exclude_spec'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - include_file=dict(argstr='-include %s', - xor=['include_file', 'include_spec'], - ), - include_spec=dict(argstr='-include %s', - position=2, - sep=',', - units='mm', - xor=['include_file', 'include_spec'], - ), - initial_cutoff_value=dict(argstr='-initcutoff %s', - units='NA', - ), - initial_direction=dict(argstr='-initdirection %s', - units='voxels', - ), - inputmodel=dict(argstr='%s', - position=-3, - usedefault=True, - ), - mask_file=dict(argstr='-mask %s', - xor=['mask_file', 'mask_spec'], - ), - mask_spec=dict(argstr='-mask %s', - position=2, - sep=',', - units='mm', - xor=['mask_file', 'mask_spec'], - ), - maximum_number_of_tracks=dict(argstr='-maxnum %d', - ), - maximum_tract_length=dict(argstr='-length %s', - units='mm', - ), - minimum_radius_of_curvature=dict(argstr='-curvature %s', - units='mm', - ), - minimum_tract_length=dict(argstr='-minlength %s', - units='mm', - ), - no_mask_interpolation=dict(argstr='-nomaskinterp', - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s_tracked.tck', - output_name='tracked', - position=-1, - ), - seed_file=dict(argstr='-seed %s', - xor=['seed_file', 'seed_spec'], - ), - seed_spec=dict(argstr='-seed %s', - position=2, - sep=',', - units='mm', - xor=['seed_file', 'seed_spec'], - ), - step_size=dict(argstr='-step %s', - units='mm', - ), - stop=dict(argstr='-stop', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unidirectional=dict(argstr='-unidirectional', - ), + input_map = dict( + args=dict(argstr='%s', ), + cutoff_value=dict( + argstr='-cutoff %s', + units='NA', + ), + desired_number_of_tracks=dict(argstr='-number %d', ), + do_not_precompute=dict(argstr='-noprecomputed', ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclude_file=dict( + argstr='-exclude %s', + xor=['exclude_file', 'exclude_spec'], + ), + exclude_spec=dict( + argstr='-exclude %s', + position=2, + sep=',', + units='mm', + xor=['exclude_file', 'exclude_spec'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + include_file=dict( + argstr='-include %s', + xor=['include_file', 'include_spec'], + ), + include_spec=dict( + argstr='-include %s', + position=2, + sep=',', + units='mm', + xor=['include_file', 'include_spec'], + ), + initial_cutoff_value=dict( + argstr='-initcutoff %s', + units='NA', + ), + initial_direction=dict( + argstr='-initdirection %s', + units='voxels', + ), + inputmodel=dict( + argstr='%s', + position=-3, + usedefault=True, + ), + mask_file=dict( + argstr='-mask %s', + xor=['mask_file', 'mask_spec'], + ), + mask_spec=dict( + argstr='-mask %s', + position=2, + sep=',', + units='mm', + xor=['mask_file', 'mask_spec'], + ), + maximum_number_of_tracks=dict(argstr='-maxnum %d', ), + maximum_tract_length=dict( + argstr='-length %s', + units='mm', + ), + minimum_radius_of_curvature=dict( + argstr='-curvature %s', + units='mm', + ), + minimum_tract_length=dict( + argstr='-minlength %s', + units='mm', + ), + no_mask_interpolation=dict(argstr='-nomaskinterp', ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s_tracked.tck', + output_name='tracked', + position=-1, + ), + seed_file=dict( + argstr='-seed %s', + xor=['seed_file', 'seed_spec'], + ), + seed_spec=dict( + argstr='-seed %s', + position=2, + sep=',', + units='mm', + xor=['seed_file', 'seed_spec'], + ), + step_size=dict( + argstr='-step %s', + units='mm', + ), + stop=dict(argstr='-stop', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unidirectional=dict(argstr='-unidirectional', ), ) inputs = SphericallyDeconvolutedStreamlineTrack.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SphericallyDeconvolutedStreamlineTrack_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = SphericallyDeconvolutedStreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py index 5e028c40ac..6626bec4c0 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py @@ -4,112 +4,124 @@ def test_StreamlineTrack_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cutoff_value=dict(argstr='-cutoff %s', - units='NA', - ), - desired_number_of_tracks=dict(argstr='-number %d', - ), - do_not_precompute=dict(argstr='-noprecomputed', - ), - environ=dict(nohash=True, - usedefault=True, - ), - exclude_file=dict(argstr='-exclude %s', - xor=['exclude_file', 'exclude_spec'], - ), - exclude_spec=dict(argstr='-exclude %s', - position=2, - sep=',', - units='mm', - xor=['exclude_file', 'exclude_spec'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - include_file=dict(argstr='-include %s', - xor=['include_file', 'include_spec'], - ), - include_spec=dict(argstr='-include %s', - position=2, - sep=',', - units='mm', - xor=['include_file', 'include_spec'], - ), - initial_cutoff_value=dict(argstr='-initcutoff %s', - units='NA', - ), - initial_direction=dict(argstr='-initdirection %s', - units='voxels', - ), - inputmodel=dict(argstr='%s', - position=-3, - usedefault=True, - ), - mask_file=dict(argstr='-mask %s', - xor=['mask_file', 'mask_spec'], - ), - mask_spec=dict(argstr='-mask %s', - position=2, - sep=',', - units='mm', - xor=['mask_file', 'mask_spec'], - ), - maximum_number_of_tracks=dict(argstr='-maxnum %d', - ), - maximum_tract_length=dict(argstr='-length %s', - units='mm', - ), - minimum_radius_of_curvature=dict(argstr='-curvature %s', - units='mm', - ), - minimum_tract_length=dict(argstr='-minlength %s', - units='mm', - ), - no_mask_interpolation=dict(argstr='-nomaskinterp', - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s_tracked.tck', - output_name='tracked', - position=-1, - ), - seed_file=dict(argstr='-seed %s', - xor=['seed_file', 'seed_spec'], - ), - seed_spec=dict(argstr='-seed %s', - position=2, - sep=',', - units='mm', - xor=['seed_file', 'seed_spec'], - ), - step_size=dict(argstr='-step %s', - units='mm', - ), - stop=dict(argstr='-stop', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unidirectional=dict(argstr='-unidirectional', - ), + input_map = dict( + args=dict(argstr='%s', ), + cutoff_value=dict( + argstr='-cutoff %s', + units='NA', + ), + desired_number_of_tracks=dict(argstr='-number %d', ), + do_not_precompute=dict(argstr='-noprecomputed', ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclude_file=dict( + argstr='-exclude %s', + xor=['exclude_file', 'exclude_spec'], + ), + exclude_spec=dict( + argstr='-exclude %s', + position=2, + sep=',', + units='mm', + xor=['exclude_file', 'exclude_spec'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + include_file=dict( + argstr='-include %s', + xor=['include_file', 'include_spec'], + ), + include_spec=dict( + argstr='-include %s', + position=2, + sep=',', + units='mm', + xor=['include_file', 'include_spec'], + ), + initial_cutoff_value=dict( + argstr='-initcutoff %s', + units='NA', + ), + initial_direction=dict( + argstr='-initdirection %s', + units='voxels', + ), + inputmodel=dict( + argstr='%s', + position=-3, + usedefault=True, + ), + mask_file=dict( + argstr='-mask %s', + xor=['mask_file', 'mask_spec'], + ), + mask_spec=dict( + argstr='-mask %s', + position=2, + sep=',', + units='mm', + xor=['mask_file', 'mask_spec'], + ), + maximum_number_of_tracks=dict(argstr='-maxnum %d', ), + maximum_tract_length=dict( + argstr='-length %s', + units='mm', + ), + minimum_radius_of_curvature=dict( + argstr='-curvature %s', + units='mm', + ), + minimum_tract_length=dict( + argstr='-minlength %s', + units='mm', + ), + no_mask_interpolation=dict(argstr='-nomaskinterp', ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s_tracked.tck', + output_name='tracked', + position=-1, + ), + seed_file=dict( + argstr='-seed %s', + xor=['seed_file', 'seed_spec'], + ), + seed_spec=dict( + argstr='-seed %s', + position=2, + sep=',', + units='mm', + xor=['seed_file', 'seed_spec'], + ), + step_size=dict( + argstr='-step %s', + units='mm', + ), + stop=dict(argstr='-stop', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unidirectional=dict(argstr='-unidirectional', ), ) inputs = StreamlineTrack.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_StreamlineTrack_outputs(): - output_map = dict(tracked=dict(), - ) + output_map = dict(tracked=dict(), ) outputs = StreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py index e4f32e21d2..95836bb573 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py @@ -4,43 +4,47 @@ def test_Tensor2ApparentDiffusion_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Tensor2ApparentDiffusion.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Tensor2ApparentDiffusion_outputs(): - output_map = dict(ADC=dict(), - ) + output_map = dict(ADC=dict(), ) outputs = Tensor2ApparentDiffusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py index 07535aa125..7388988db4 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py @@ -4,43 +4,47 @@ def test_Tensor2FractionalAnisotropy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Tensor2FractionalAnisotropy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Tensor2FractionalAnisotropy_outputs(): - output_map = dict(FA=dict(), - ) + output_map = dict(FA=dict(), ) outputs = Tensor2FractionalAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py index 724c9cb534..e41ca71472 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py @@ -4,43 +4,47 @@ def test_Tensor2Vector_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - quiet=dict(argstr='-quiet', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + quiet=dict( + argstr='-quiet', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Tensor2Vector.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Tensor2Vector_outputs(): - output_map = dict(vector=dict(), - ) + output_map = dict(vector=dict(), ) outputs = Tensor2Vector.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py b/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py index 124e87a0b2..fa7841e968 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py @@ -4,53 +4,57 @@ def test_Threshold_inputs(): - input_map = dict(absolute_threshold_value=dict(argstr='-abs %s', - ), - args=dict(argstr='%s', - ), - debug=dict(argstr='-debug', - position=1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - invert=dict(argstr='-invert', - position=1, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - percentage_threshold_value=dict(argstr='-percent %s', - ), - quiet=dict(argstr='-quiet', - position=1, - ), - replace_zeros_with_NaN=dict(argstr='-nan', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + absolute_threshold_value=dict(argstr='-abs %s', ), + args=dict(argstr='%s', ), + debug=dict( + argstr='-debug', + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + invert=dict( + argstr='-invert', + position=1, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + percentage_threshold_value=dict(argstr='-percent %s', ), + quiet=dict( + argstr='-quiet', + position=1, + ), + replace_zeros_with_NaN=dict( + argstr='-nan', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Threshold.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Threshold_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Threshold.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py b/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py index f1a2a08355..910c76cfad 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py @@ -4,57 +4,65 @@ def test_Tracks2Prob_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - colour=dict(argstr='-colour', - position=3, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fraction=dict(argstr='-fraction', - position=3, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_filename=dict(argstr='%s', - genfile=True, - position=-1, - ), - output_datatype=dict(argstr='-datatype %s', - position=2, - ), - resample=dict(argstr='-resample %d', - position=3, - units='mm', - ), - template_file=dict(argstr='-template %s', - position=1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel_dims=dict(argstr='-vox %s', - position=2, - sep=',', - ), + input_map = dict( + args=dict(argstr='%s', ), + colour=dict( + argstr='-colour', + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fraction=dict( + argstr='-fraction', + position=3, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr='%s', + genfile=True, + position=-1, + ), + output_datatype=dict( + argstr='-datatype %s', + position=2, + ), + resample=dict( + argstr='-resample %d', + position=3, + units='mm', + ), + template_file=dict( + argstr='-template %s', + position=1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel_dims=dict( + argstr='-vox %s', + position=2, + sep=',', + ), ) inputs = Tracks2Prob.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Tracks2Prob_outputs(): - output_map = dict(tract_image=dict(), - ) + output_map = dict(tract_image=dict(), ) outputs = Tracks2Prob.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tracking.py b/nipype/interfaces/mrtrix/tracking.py index c013d7b04a..f159c1c29e 100644 --- a/nipype/interfaces/mrtrix/tracking.py +++ b/nipype/interfaces/mrtrix/tracking.py @@ -9,43 +9,87 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import os.path as op from ...utils.filemanip import split_filename -from ..base import ( - CommandLineInputSpec, CommandLine, traits, TraitedSpec, File, - isdefined -) +from ..base import (CommandLineInputSpec, CommandLine, traits, TraitedSpec, + File, isdefined) class FilterTracksInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input tracks to be filtered') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input tracks to be filtered') include_xor = ['include_file', 'include_spec'] - include_file = File(exists=True, argstr='-include %s', desc='inclusion file', xor=include_xor) - include_spec = traits.List(traits.Float, desc='inclusion specification in mm and radius (x y z r)', position=2, - argstr='-include %s', minlen=4, maxlen=4, sep=',', units='mm', xor=include_xor) + include_file = File( + exists=True, + argstr='-include %s', + desc='inclusion file', + xor=include_xor) + include_spec = traits.List( + traits.Float, + desc='inclusion specification in mm and radius (x y z r)', + position=2, + argstr='-include %s', + minlen=4, + maxlen=4, + sep=',', + units='mm', + xor=include_xor) exclude_xor = ['exclude_file', 'exclude_spec'] - exclude_file = File(exists=True, argstr='-exclude %s', desc='exclusion file', xor=exclude_xor) - exclude_spec = traits.List(traits.Float, desc='exclusion specification in mm and radius (x y z r)', position=2, - argstr='-exclude %s', minlen=4, maxlen=4, sep=',', units='mm', xor=exclude_xor) - - minimum_tract_length = traits.Float(argstr='-minlength %s', units='mm', - desc="Sets the minimum length of any track in millimeters (default is 10 mm).") - - out_file = File(argstr='%s', position=-1, desc='Output filtered track filename', - name_source=['in_file'], hash_files=False, name_template='%s_filt') - - no_mask_interpolation = traits.Bool(argstr='-nomaskinterp', desc="Turns off trilinear interpolation of mask images.") - invert = traits.Bool(argstr='-invert', desc="invert the matching process, so that tracks that would" - "otherwise have been included are now excluded and vice-versa.") - - quiet = traits.Bool(argstr='-quiet', position=1, desc="Do not display information messages or progress status.") - debug = traits.Bool(argstr='-debug', position=1, desc="Display debugging messages.") + exclude_file = File( + exists=True, + argstr='-exclude %s', + desc='exclusion file', + xor=exclude_xor) + exclude_spec = traits.List( + traits.Float, + desc='exclusion specification in mm and radius (x y z r)', + position=2, + argstr='-exclude %s', + minlen=4, + maxlen=4, + sep=',', + units='mm', + xor=exclude_xor) + + minimum_tract_length = traits.Float( + argstr='-minlength %s', + units='mm', + desc= + "Sets the minimum length of any track in millimeters (default is 10 mm)." + ) + + out_file = File( + argstr='%s', + position=-1, + desc='Output filtered track filename', + name_source=['in_file'], + hash_files=False, + name_template='%s_filt') + + no_mask_interpolation = traits.Bool( + argstr='-nomaskinterp', + desc="Turns off trilinear interpolation of mask images.") + invert = traits.Bool( + argstr='-invert', + desc="invert the matching process, so that tracks that would" + "otherwise have been included are now excluded and vice-versa.") + + quiet = traits.Bool( + argstr='-quiet', + position=1, + desc="Do not display information messages or progress status.") + debug = traits.Bool( + argstr='-debug', position=1, desc="Display debugging messages.") class FilterTracksOutputSpec(TraitedSpec): @@ -72,23 +116,69 @@ class FilterTracks(CommandLine): class Tracks2ProbInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='tract file') - template_file = File(exists=True, argstr='-template %s', position=1, - desc='an image file to be used as a template for the output (the output image wil have the same transform and field of view)') - voxel_dims = traits.List(traits.Float, argstr='-vox %s', sep=',', position=2, minlen=3, maxlen=3, - desc='Three comma-separated numbers giving the size of each voxel in mm.') - colour = traits.Bool(argstr='-colour', position=3, desc="add colour to the output image according to the direction of the tracks.") - fraction = traits.Bool(argstr='-fraction', position=3, desc="produce an image of the fraction of fibres through each voxel (as a proportion of the total number in the file), rather than the count.") - output_datatype = traits.Enum("Bit", "Int8", "UInt8", "Int16", "UInt16", "Int32", "UInt32", "float32", "float64", argstr='-datatype %s', position=2, - desc='"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"') # , usedefault=True) - resample = traits.Float(argstr='-resample %d', position=3, - units='mm', desc='resample the tracks at regular intervals using Hermite interpolation. If omitted, the program will select an appropriate interpolation factor automatically.') - out_filename = File(genfile=True, argstr='%s', position=-1, desc='output data file') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='tract file') + template_file = File( + exists=True, + argstr='-template %s', + position=1, + desc= + 'an image file to be used as a template for the output (the output image wil have the same transform and field of view)' + ) + voxel_dims = traits.List( + traits.Float, + argstr='-vox %s', + sep=',', + position=2, + minlen=3, + maxlen=3, + desc= + 'Three comma-separated numbers giving the size of each voxel in mm.') + colour = traits.Bool( + argstr='-colour', + position=3, + desc= + "add colour to the output image according to the direction of the tracks." + ) + fraction = traits.Bool( + argstr='-fraction', + position=3, + desc= + "produce an image of the fraction of fibres through each voxel (as a proportion of the total number in the file), rather than the count." + ) + output_datatype = traits.Enum( + "Bit", + "Int8", + "UInt8", + "Int16", + "UInt16", + "Int32", + "UInt32", + "float32", + "float64", + argstr='-datatype %s', + position=2, + desc= + '"i.e. Bfloat". Can be "char", "short", "int", "long", "float" or "double"' + ) # , usedefault=True) + resample = traits.Float( + argstr='-resample %d', + position=3, + units='mm', + desc= + 'resample the tracks at regular intervals using Hermite interpolation. If omitted, the program will select an appropriate interpolation factor automatically.' + ) + out_filename = File( + genfile=True, argstr='%s', position=-1, desc='output data file') class Tracks2ProbOutputSpec(TraitedSpec): - tract_image = File(exists=True, desc='Output tract count or track density image') + tract_image = File( + exists=True, desc='Output tract count or track density image') class Tracks2Prob(CommandLine): @@ -133,67 +223,174 @@ def _gen_outfilename(self): class StreamlineTrackInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, desc='the image containing the source data.' - 'The type of data required depends on the type of tracking as set in the preceeding argument. For DT methods, ' - 'the base DWI are needed. For SD methods, the SH harmonic coefficients of the FOD are needed.') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='the image containing the source data.' + 'The type of data required depends on the type of tracking as set in the preceeding argument. For DT methods, ' + 'the base DWI are needed. For SD methods, the SH harmonic coefficients of the FOD are needed.' + ) seed_xor = ['seed_file', 'seed_spec'] - seed_file = File(exists=True, argstr='-seed %s', desc='seed file', xor=seed_xor) - seed_spec = traits.List(traits.Float, desc='seed specification in mm and radius (x y z r)', position=2, - argstr='-seed %s', minlen=4, maxlen=4, sep=',', units='mm', xor=seed_xor) + seed_file = File( + exists=True, argstr='-seed %s', desc='seed file', xor=seed_xor) + seed_spec = traits.List( + traits.Float, + desc='seed specification in mm and radius (x y z r)', + position=2, + argstr='-seed %s', + minlen=4, + maxlen=4, + sep=',', + units='mm', + xor=seed_xor) include_xor = ['include_file', 'include_spec'] - include_file = File(exists=True, argstr='-include %s', desc='inclusion file', xor=include_xor) - include_spec = traits.List(traits.Float, desc='inclusion specification in mm and radius (x y z r)', position=2, - argstr='-include %s', minlen=4, maxlen=4, sep=',', units='mm', xor=include_xor) + include_file = File( + exists=True, + argstr='-include %s', + desc='inclusion file', + xor=include_xor) + include_spec = traits.List( + traits.Float, + desc='inclusion specification in mm and radius (x y z r)', + position=2, + argstr='-include %s', + minlen=4, + maxlen=4, + sep=',', + units='mm', + xor=include_xor) exclude_xor = ['exclude_file', 'exclude_spec'] - exclude_file = File(exists=True, argstr='-exclude %s', desc='exclusion file', xor=exclude_xor) - exclude_spec = traits.List(traits.Float, desc='exclusion specification in mm and radius (x y z r)', position=2, - argstr='-exclude %s', minlen=4, maxlen=4, sep=',', units='mm', xor=exclude_xor) + exclude_file = File( + exists=True, + argstr='-exclude %s', + desc='exclusion file', + xor=exclude_xor) + exclude_spec = traits.List( + traits.Float, + desc='exclusion specification in mm and radius (x y z r)', + position=2, + argstr='-exclude %s', + minlen=4, + maxlen=4, + sep=',', + units='mm', + xor=exclude_xor) mask_xor = ['mask_file', 'mask_spec'] - mask_file = File(exists=True, argstr='-mask %s', desc='mask file. Only tracks within mask.', xor=mask_xor) - mask_spec = traits.List(traits.Float, desc='Mask specification in mm and radius (x y z r). Tracks will be terminated when they leave the ROI.', position=2, - argstr='-mask %s', minlen=4, maxlen=4, sep=',', units='mm', xor=mask_xor) - - inputmodel = traits.Enum('DT_STREAM', 'SD_PROB', 'SD_STREAM', - argstr='%s', desc='input model type', usedefault=True, position=-3) - - stop = traits.Bool(argstr='-stop', desc="stop track as soon as it enters any of the include regions.") - do_not_precompute = traits.Bool(argstr='-noprecomputed', desc="Turns off precomputation of the legendre polynomial values. Warning: this will slow down the algorithm by a factor of approximately 4.") - unidirectional = traits.Bool(argstr='-unidirectional', desc="Track from the seed point in one direction only (default is to track in both directions).") - no_mask_interpolation = traits.Bool(argstr='-nomaskinterp', desc="Turns off trilinear interpolation of mask images.") - - step_size = traits.Float(argstr='-step %s', units='mm', - desc="Set the step size of the algorithm in mm (default is 0.2).") - minimum_radius_of_curvature = traits.Float(argstr='-curvature %s', units='mm', - desc="Set the minimum radius of curvature (default is 2 mm for DT_STREAM, 0 for SD_STREAM, 1 mm for SD_PROB and DT_PROB)") - desired_number_of_tracks = traits.Int(argstr='-number %d', desc='Sets the desired number of tracks.' - 'The program will continue to generate tracks until this number of tracks have been selected and written to the output file' - '(default is 100 for *_STREAM methods, 1000 for *_PROB methods).') - maximum_number_of_tracks = traits.Int(argstr='-maxnum %d', desc='Sets the maximum number of tracks to generate.' - "The program will not generate more tracks than this number, even if the desired number of tracks hasn't yet been reached" - '(default is 100 x number).') - - minimum_tract_length = traits.Float(argstr='-minlength %s', units='mm', - desc="Sets the minimum length of any track in millimeters (default is 10 mm).") - maximum_tract_length = traits.Float(argstr='-length %s', units='mm', - desc="Sets the maximum length of any track in millimeters (default is 200 mm).") - - cutoff_value = traits.Float(argstr='-cutoff %s', units='NA', - desc="Set the FA or FOD amplitude cutoff for terminating tracks (default is 0.1).") - initial_cutoff_value = traits.Float(argstr='-initcutoff %s', units='NA', - desc="Sets the minimum FA or FOD amplitude for initiating tracks (default is twice the normal cutoff).") - - initial_direction = traits.List(traits.Int, desc='Specify the initial tracking direction as a vector', - argstr='-initdirection %s', minlen=2, maxlen=2, units='voxels') - out_file = File(argstr='%s', position=-1, name_source=['in_file'], name_template='%s_tracked.tck', - output_name='tracked', desc='output data file') + mask_file = File( + exists=True, + argstr='-mask %s', + desc='mask file. Only tracks within mask.', + xor=mask_xor) + mask_spec = traits.List( + traits.Float, + desc= + 'Mask specification in mm and radius (x y z r). Tracks will be terminated when they leave the ROI.', + position=2, + argstr='-mask %s', + minlen=4, + maxlen=4, + sep=',', + units='mm', + xor=mask_xor) + + inputmodel = traits.Enum( + 'DT_STREAM', + 'SD_PROB', + 'SD_STREAM', + argstr='%s', + desc='input model type', + usedefault=True, + position=-3) + + stop = traits.Bool( + argstr='-stop', + desc="stop track as soon as it enters any of the include regions.") + do_not_precompute = traits.Bool( + argstr='-noprecomputed', + desc= + "Turns off precomputation of the legendre polynomial values. Warning: this will slow down the algorithm by a factor of approximately 4." + ) + unidirectional = traits.Bool( + argstr='-unidirectional', + desc= + "Track from the seed point in one direction only (default is to track in both directions)." + ) + no_mask_interpolation = traits.Bool( + argstr='-nomaskinterp', + desc="Turns off trilinear interpolation of mask images.") + + step_size = traits.Float( + argstr='-step %s', + units='mm', + desc="Set the step size of the algorithm in mm (default is 0.2).") + minimum_radius_of_curvature = traits.Float( + argstr='-curvature %s', + units='mm', + desc= + "Set the minimum radius of curvature (default is 2 mm for DT_STREAM, 0 for SD_STREAM, 1 mm for SD_PROB and DT_PROB)" + ) + desired_number_of_tracks = traits.Int( + argstr='-number %d', + desc='Sets the desired number of tracks.' + 'The program will continue to generate tracks until this number of tracks have been selected and written to the output file' + '(default is 100 for *_STREAM methods, 1000 for *_PROB methods).') + maximum_number_of_tracks = traits.Int( + argstr='-maxnum %d', + desc='Sets the maximum number of tracks to generate.' + "The program will not generate more tracks than this number, even if the desired number of tracks hasn't yet been reached" + '(default is 100 x number).') + + minimum_tract_length = traits.Float( + argstr='-minlength %s', + units='mm', + desc= + "Sets the minimum length of any track in millimeters (default is 10 mm)." + ) + maximum_tract_length = traits.Float( + argstr='-length %s', + units='mm', + desc= + "Sets the maximum length of any track in millimeters (default is 200 mm)." + ) + + cutoff_value = traits.Float( + argstr='-cutoff %s', + units='NA', + desc= + "Set the FA or FOD amplitude cutoff for terminating tracks (default is 0.1)." + ) + initial_cutoff_value = traits.Float( + argstr='-initcutoff %s', + units='NA', + desc= + "Sets the minimum FA or FOD amplitude for initiating tracks (default is twice the normal cutoff)." + ) + + initial_direction = traits.List( + traits.Int, + desc='Specify the initial tracking direction as a vector', + argstr='-initdirection %s', + minlen=2, + maxlen=2, + units='voxels') + out_file = File( + argstr='%s', + position=-1, + name_source=['in_file'], + name_template='%s_tracked.tck', + output_name='tracked', + desc='output data file') class StreamlineTrackOutputSpec(TraitedSpec): - tracked = File(exists=True, desc='output file containing reconstructed tracts') + tracked = File( + exists=True, desc='output file containing reconstructed tracts') class StreamlineTrack(CommandLine): @@ -222,8 +419,14 @@ class StreamlineTrack(CommandLine): class DiffusionTensorStreamlineTrackInputSpec(StreamlineTrackInputSpec): - gradient_encoding_file = File(exists=True, argstr='-grad %s', mandatory=True, position=-2, - desc='Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix') + gradient_encoding_file = File( + exists=True, + argstr='-grad %s', + mandatory=True, + position=-2, + desc= + 'Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix' + ) class DiffusionTensorStreamlineTrack(StreamlineTrack): @@ -246,12 +449,17 @@ class DiffusionTensorStreamlineTrack(StreamlineTrack): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "DT_STREAM" - return super(DiffusionTensorStreamlineTrack, self).__init__(command, **inputs) + return super(DiffusionTensorStreamlineTrack, self).__init__( + command, **inputs) -class ProbabilisticSphericallyDeconvolutedStreamlineTrackInputSpec(StreamlineTrackInputSpec): - maximum_number_of_trials = traits.Int(argstr='-trials %s', - desc="Set the maximum number of sampling trials at each point (only used for probabilistic tracking).") +class ProbabilisticSphericallyDeconvolutedStreamlineTrackInputSpec( + StreamlineTrackInputSpec): + maximum_number_of_trials = traits.Int( + argstr='-trials %s', + desc= + "Set the maximum number of sampling trials at each point (only used for probabilistic tracking)." + ) class ProbabilisticSphericallyDeconvolutedStreamlineTrack(StreamlineTrack): @@ -275,7 +483,8 @@ class ProbabilisticSphericallyDeconvolutedStreamlineTrack(StreamlineTrack): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "SD_PROB" - return super(ProbabilisticSphericallyDeconvolutedStreamlineTrack, self).__init__(command, **inputs) + return super(ProbabilisticSphericallyDeconvolutedStreamlineTrack, + self).__init__(command, **inputs) class SphericallyDeconvolutedStreamlineTrack(StreamlineTrack): @@ -299,4 +508,5 @@ class SphericallyDeconvolutedStreamlineTrack(StreamlineTrack): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "SD_STREAM" - return super(SphericallyDeconvolutedStreamlineTrack, self).__init__(command, **inputs) + return super(SphericallyDeconvolutedStreamlineTrack, self).__init__( + command, **inputs) diff --git a/nipype/interfaces/mrtrix3/base.py b/nipype/interfaces/mrtrix3/base.py index 0d91c3d56d..eb4e834e70 100644 --- a/nipype/interfaces/mrtrix3/base.py +++ b/nipype/interfaces/mrtrix3/base.py @@ -1,7 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- - """ Change directory to provide relative paths for doctests >>> import os @@ -11,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from ... import logging from ..base import (CommandLineInputSpec, CommandLine, traits, File, isdefined) @@ -20,16 +20,24 @@ class MRTrix3BaseInputSpec(CommandLineInputSpec): nthreads = traits.Int( - argstr='-nthreads %d', desc='number of threads. if zero, the number' - ' of available cpus will be used', nohash=True) + argstr='-nthreads %d', + desc='number of threads. if zero, the number' + ' of available cpus will be used', + nohash=True) # DW gradient table import options - grad_file = File(exists=True, argstr='-grad %s', - desc='dw gradient scheme (MRTrix format') + grad_file = File( + exists=True, + argstr='-grad %s', + desc='dw gradient scheme (MRTrix format') grad_fsl = traits.Tuple( - File(exists=True), File(exists=True), argstr='-fslgrad %s %s', + File(exists=True), + File(exists=True), + argstr='-fslgrad %s %s', desc='(bvecs, bvals) dw gradient scheme (FSL format') bval_scale = traits.Enum( - 'yes', 'no', argstr='-bvalue_scaling %s', + 'yes', + 'no', + argstr='-bvalue_scaling %s', desc='specifies whether the b - values should be scaled by the square' ' of the corresponding DW gradient norm, as often required for ' 'multishell or DSI DW acquisition schemes. The default action ' @@ -37,13 +45,12 @@ class MRTrix3BaseInputSpec(CommandLineInputSpec): 'BValueScaling entry. Valid choices are yes / no, true / ' 'false, 0 / 1 (default: true).') - in_bvec = File(exists=True, argstr='-fslgrad %s %s', - desc='bvecs file in FSL format') + in_bvec = File( + exists=True, argstr='-fslgrad %s %s', desc='bvecs file in FSL format') in_bval = File(exists=True, desc='bvals file in FSL format') class MRTrix3Base(CommandLine): - def _format_arg(self, name, trait_spec, value): if name == 'nthreads' and value == 0: value = 1 @@ -65,8 +72,8 @@ def _parse_inputs(self, skip=None): skip = [] try: - if (isdefined(self.inputs.grad_file) or - isdefined(self.inputs.grad_fsl)): + if (isdefined(self.inputs.grad_file) + or isdefined(self.inputs.grad_fsl)): skip += ['in_bvec', 'in_bval'] is_bvec = isdefined(self.inputs.in_bvec) diff --git a/nipype/interfaces/mrtrix3/connectivity.py b/nipype/interfaces/mrtrix3/connectivity.py index 3b79b16442..d6106ed9df 100644 --- a/nipype/interfaces/mrtrix3/connectivity.py +++ b/nipype/interfaces/mrtrix3/connectivity.py @@ -1,7 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- - """ Change directory to provide relative paths for doctests >>> import os @@ -11,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import os.path as op @@ -21,17 +21,27 @@ class BuildConnectomeInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, - desc='input tractography') - in_parc = File(exists=True, argstr='%s', position=-2, - desc='parcellation file') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='input tractography') + in_parc = File( + exists=True, argstr='%s', position=-2, desc='parcellation file') out_file = File( - 'connectome.csv', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output file after processing') + 'connectome.csv', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output file after processing') nthreads = traits.Int( - argstr='-nthreads %d', desc='number of threads. if zero, the number' - ' of available cpus will be used', nohash=True) + argstr='-nthreads %d', + desc='number of threads. if zero, the number' + ' of available cpus will be used', + nohash=True) vox_lookup = traits.Bool( argstr='-assignment_voxel_lookup', @@ -55,25 +65,37 @@ class BuildConnectomeInputSpec(CommandLineInputSpec): 'mm.') metric = traits.Enum( - 'count', 'meanlength', 'invlength', 'invnodevolume', 'mean_scalar', - 'invlength_invnodevolume', argstr='-metric %s', desc='specify the edge' + 'count', + 'meanlength', + 'invlength', + 'invnodevolume', + 'mean_scalar', + 'invlength_invnodevolume', + argstr='-metric %s', + desc='specify the edge' ' weight metric') in_scalar = File( - exists=True, argstr='-image %s', desc='provide the associated image ' + exists=True, + argstr='-image %s', + desc='provide the associated image ' 'for the mean_scalar metric') in_weights = File( - exists=True, argstr='-tck_weights_in %s', desc='specify a text scalar ' + exists=True, + argstr='-tck_weights_in %s', + desc='specify a text scalar ' 'file containing the streamline weights') keep_unassigned = traits.Bool( - argstr='-keep_unassigned', desc='By default, the program discards the' + argstr='-keep_unassigned', + desc='By default, the program discards the' ' information regarding those streamlines that are not successfully ' 'assigned to a node pair. Set this option to keep these values (will ' 'be the first row/column in the output matrix)') zero_diagonal = traits.Bool( - argstr='-zero_diagonal', desc='set all diagonal entries in the matrix ' + argstr='-zero_diagonal', + desc='set all diagonal entries in the matrix ' 'to zero (these represent streamlines that connect to the same node at' ' both ends)') @@ -83,7 +105,6 @@ class BuildConnectomeOutputSpec(TraitedSpec): class BuildConnectome(MRTrix3Base): - """ Generate a connectome matrix from a streamlines file and a node parcellation image @@ -111,31 +132,54 @@ def _list_outputs(self): class LabelConfigInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, - desc='input anatomical image') - in_config = File(exists=True, argstr='%s', position=-2, - desc='connectome configuration file') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='input anatomical image') + in_config = File( + exists=True, + argstr='%s', + position=-2, + desc='connectome configuration file') out_file = File( - 'parcellation.mif', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output file after processing') - - lut_basic = File(argstr='-lut_basic %s', desc='get information from ' - 'a basic lookup table consisting of index / name pairs') - lut_fs = File(argstr='-lut_freesurfer %s', desc='get information from ' - 'a FreeSurfer lookup table(typically "FreeSurferColorLUT' - '.txt")') - lut_aal = File(argstr='-lut_aal %s', desc='get information from the AAL ' - 'lookup table (typically "ROI_MNI_V4.txt")') - lut_itksnap = File(argstr='-lut_itksnap %s', desc='get information from an' - ' ITK - SNAP lookup table(this includes the IIT atlas ' - 'file "LUT_GM.txt")') - spine = File(argstr='-spine %s', desc='provide a manually-defined ' - 'segmentation of the base of the spine where the streamlines' - ' terminate, so that this can become a node in the connection' - ' matrix.') + 'parcellation.mif', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output file after processing') + + lut_basic = File( + argstr='-lut_basic %s', + desc='get information from ' + 'a basic lookup table consisting of index / name pairs') + lut_fs = File( + argstr='-lut_freesurfer %s', + desc='get information from ' + 'a FreeSurfer lookup table(typically "FreeSurferColorLUT' + '.txt")') + lut_aal = File( + argstr='-lut_aal %s', + desc='get information from the AAL ' + 'lookup table (typically "ROI_MNI_V4.txt")') + lut_itksnap = File( + argstr='-lut_itksnap %s', + desc='get information from an' + ' ITK - SNAP lookup table(this includes the IIT atlas ' + 'file "LUT_GM.txt")') + spine = File( + argstr='-spine %s', + desc='provide a manually-defined ' + 'segmentation of the base of the spine where the streamlines' + ' terminate, so that this can become a node in the connection' + ' matrix.') nthreads = traits.Int( - argstr='-nthreads %d', desc='number of threads. if zero, the number' - ' of available cpus will be used', nohash=True) + argstr='-nthreads %d', + desc='number of threads. if zero, the number' + ' of available cpus will be used', + nohash=True) class LabelConfigOutputSpec(TraitedSpec): @@ -143,7 +187,6 @@ class LabelConfigOutputSpec(TraitedSpec): class LabelConfig(MRTrix3Base): - """ Re-configure parcellation to be incrementally defined. @@ -177,7 +220,7 @@ def _parse_inputs(self, skip=None): self.inputs.in_config = op.join( path, 'src/dwi/tractography/connectomics/' - 'example_configs/fs_default.txt') + 'example_configs/fs_default.txt') return super(LabelConfig, self)._parse_inputs(skip=skip) diff --git a/nipype/interfaces/mrtrix3/preprocess.py b/nipype/interfaces/mrtrix3/preprocess.py index 0eedc3f449..ca5996bea8 100644 --- a/nipype/interfaces/mrtrix3/preprocess.py +++ b/nipype/interfaces/mrtrix3/preprocess.py @@ -1,7 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- - """ Change directory to provide relative paths for doctests >>> import os @@ -11,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op @@ -21,18 +21,37 @@ class ResponseSDInputSpec(MRTrix3BaseInputSpec): - algorithm = traits.Enum('msmt_5tt','dhollander','tournier','tax', argstr='%s', position=-6, - mandatory=True, desc='response estimation algorithm (multi-tissue)') - in_file = File(exists=True, argstr='%s', position=-5, - mandatory=True, desc='input DWI image') + algorithm = traits.Enum( + 'msmt_5tt', + 'dhollander', + 'tournier', + 'tax', + argstr='%s', + position=-6, + mandatory=True, + desc='response estimation algorithm (multi-tissue)') + in_file = File( + exists=True, + argstr='%s', + position=-5, + mandatory=True, + desc='input DWI image') mtt_file = File(argstr='%s', position=-4, desc='input 5tt image') - wm_file = File('wm.txt', argstr='%s', position=-3, usedefault=True, + wm_file = File( + 'wm.txt', + argstr='%s', + position=-3, + usedefault=True, desc='output WM response text file') - gm_file = File(argstr='%s', position=-2, desc='output GM response text file') - csf_file = File(argstr='%s', position=-1, desc='output CSF response text file') - in_mask = File(exists=True, argstr='-mask %s', - desc='provide initial mask image') - max_sh = traits.Int(8, argstr='-lmax %d', + gm_file = File( + argstr='%s', position=-2, desc='output GM response text file') + csf_file = File( + argstr='%s', position=-1, desc='output CSF response text file') + in_mask = File( + exists=True, argstr='-mask %s', desc='provide initial mask image') + max_sh = traits.Int( + 8, + argstr='-lmax %d', desc='maximum harmonic degree of response function') @@ -43,7 +62,6 @@ class ResponseSDOutputSpec(TraitedSpec): class ResponseSD(MRTrix3Base): - """ Estimate response function(s) for spherical deconvolution using the specified algorithm. @@ -75,12 +93,20 @@ def _list_outputs(self): class ACTPrepareFSLInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input anatomical image') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input anatomical image') out_file = File( - 'act_5tt.mif', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output file after processing') + 'act_5tt.mif', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output file after processing') class ACTPrepareFSLOutputSpec(TraitedSpec): @@ -88,7 +114,6 @@ class ACTPrepareFSLOutputSpec(TraitedSpec): class ACTPrepareFSL(CommandLine): - """ Generate anatomical information necessary for Anatomically Constrained Tractography (ACT). @@ -115,16 +140,31 @@ def _list_outputs(self): class ReplaceFSwithFIRSTInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-4, - desc='input anatomical image') - in_t1w = File(exists=True, argstr='%s', mandatory=True, position=-3, - desc='input T1 image') - in_config = File(exists=True, argstr='%s', position=-2, - desc='connectome configuration file') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-4, + desc='input anatomical image') + in_t1w = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='input T1 image') + in_config = File( + exists=True, + argstr='%s', + position=-2, + desc='connectome configuration file') out_file = File( - 'aparc+first.mif', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output file after processing') + 'aparc+first.mif', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output file after processing') class ReplaceFSwithFIRSTOutputSpec(TraitedSpec): @@ -132,7 +172,6 @@ class ReplaceFSwithFIRSTOutputSpec(TraitedSpec): class ReplaceFSwithFIRST(CommandLine): - """ Replace deep gray matter structures segmented with FSL FIRST in a FreeSurfer parcellation. diff --git a/nipype/interfaces/mrtrix3/reconst.py b/nipype/interfaces/mrtrix3/reconst.py index f7ea4f01e4..833db6d01f 100644 --- a/nipype/interfaces/mrtrix3/reconst.py +++ b/nipype/interfaces/mrtrix3/reconst.py @@ -1,7 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- - """ Change directory to provide relative paths for doctests >>> import os @@ -11,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op @@ -20,21 +20,36 @@ class FitTensorInputSpec(MRTrix3BaseInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input diffusion weighted images') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input diffusion weighted images') out_file = File( - 'dti.mif', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='the output diffusion tensor image') + 'dti.mif', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='the output diffusion tensor image') # General options - in_mask = File(exists=True, argstr='-mask %s', - desc=('only perform computation within the specified ' - 'binary brain mask image')) + in_mask = File( + exists=True, + argstr='-mask %s', + desc=('only perform computation within the specified ' + 'binary brain mask image')) method = traits.Enum( - 'nonlinear', 'loglinear', 'sech', 'rician', argstr='-method %s', + 'nonlinear', + 'loglinear', + 'sech', + 'rician', + argstr='-method %s', desc=('select method used to perform the fitting')) reg_term = traits.Float( - 5.e3, argstr='-regularisation %f', + 5.e3, + argstr='-regularisation %f', desc=('specify the strength of the regularisation term on the ' 'magnitude of the tensor elements (default = 5000). This ' 'only applies to the non-linear methods')) @@ -45,7 +60,6 @@ class FitTensorOutputSpec(TraitedSpec): class FitTensor(MRTrix3Base): - """ Convert diffusion-weighted images to tensor images @@ -74,14 +88,28 @@ def _list_outputs(self): class EstimateFODInputSpec(MRTrix3BaseInputSpec): - algorithm = traits.Enum('csd','msmt_csd', argstr='%s', position=-8, - mandatory=True, desc='FOD algorithm') - in_file = File(exists=True, argstr='%s', position=-7, - mandatory=True, desc='input DWI image') - wm_txt = File(argstr='%s', position=-6, - mandatory=True, desc='WM response text file') - wm_odf = File('wm.mif', argstr='%s', position=-5, usedefault=True, - mandatory=True, desc='output WM ODF') + algorithm = traits.Enum( + 'csd', + 'msmt_csd', + argstr='%s', + position=-8, + mandatory=True, + desc='FOD algorithm') + in_file = File( + exists=True, + argstr='%s', + position=-7, + mandatory=True, + desc='input DWI image') + wm_txt = File( + argstr='%s', position=-6, mandatory=True, desc='WM response text file') + wm_odf = File( + 'wm.mif', + argstr='%s', + position=-5, + usedefault=True, + mandatory=True, + desc='output WM ODF') gm_txt = File(argstr='%s', position=-4, desc='GM response text file') gm_odf = File('gm.mif', argstr='%s', position=-3, desc='output GM ODF') csf_txt = File(argstr='%s', position=-2, desc='CSF response text file') @@ -89,12 +117,18 @@ class EstimateFODInputSpec(MRTrix3BaseInputSpec): mask_file = File(exists=True, argstr='-mask %s', desc='mask image') # DW Shell selection options - shell = traits.List(traits.Float, sep=',', argstr='-shell %s', - desc='specify one or more dw gradient shells') - max_sh = traits.Int(8, argstr='-lmax %d', - desc='maximum harmonic degree of response function') + shell = traits.List( + traits.Float, + sep=',', + argstr='-shell %s', + desc='specify one or more dw gradient shells') + max_sh = traits.Int( + 8, + argstr='-lmax %d', + desc='maximum harmonic degree of response function') in_dirs = File( - exists=True, argstr='-directions %s', + exists=True, + argstr='-directions %s', desc=('specify the directions over which to apply the non-negativity ' 'constraint (by default, the built-in 300 direction set is ' 'used). These should be supplied as a text file containing the ' @@ -108,7 +142,6 @@ class EstimateFODOutputSpec(TraitedSpec): class EstimateFOD(MRTrix3Base): - """ Estimate fibre orientation distributions from diffusion data using spherical deconvolution @@ -138,6 +171,3 @@ def _list_outputs(self): if self.inputs.csf_odf != Undefined: outputs['csf_odf'] = op.abspath(self.inputs.csf_odf) return outputs - - - diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py b/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py index 9918c9ae32..12b8bd9c53 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py @@ -4,38 +4,40 @@ def test_ACTPrepareFSL_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ACTPrepareFSL.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ACTPrepareFSL_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ACTPrepareFSL.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py b/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py index 25b9716f80..58c1990ec5 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py @@ -4,50 +4,49 @@ def test_BrainMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BrainMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BrainMask_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = BrainMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py b/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py index fdac1f65fb..b47ec4d3b4 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py @@ -4,62 +4,57 @@ def test_BuildConnectome_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - in_parc=dict(argstr='%s', - position=-2, - ), - in_scalar=dict(argstr='-image %s', - ), - in_weights=dict(argstr='-tck_weights_in %s', - ), - keep_unassigned=dict(argstr='-keep_unassigned', - ), - metric=dict(argstr='-metric %s', - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - search_forward=dict(argstr='-assignment_forward_search %f', - ), - search_radius=dict(argstr='-assignment_radial_search %f', - ), - search_reverse=dict(argstr='-assignment_reverse_search %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vox_lookup=dict(argstr='-assignment_voxel_lookup', - ), - zero_diagonal=dict(argstr='-zero_diagonal', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + in_parc=dict( + argstr='%s', + position=-2, + ), + in_scalar=dict(argstr='-image %s', ), + in_weights=dict(argstr='-tck_weights_in %s', ), + keep_unassigned=dict(argstr='-keep_unassigned', ), + metric=dict(argstr='-metric %s', ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + search_forward=dict(argstr='-assignment_forward_search %f', ), + search_radius=dict(argstr='-assignment_radial_search %f', ), + search_reverse=dict(argstr='-assignment_reverse_search %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vox_lookup=dict(argstr='-assignment_voxel_lookup', ), + zero_diagonal=dict(argstr='-zero_diagonal', ), ) inputs = BuildConnectome.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BuildConnectome_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = BuildConnectome.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py b/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py index 0183045c56..eec8bcc926 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py @@ -4,73 +4,62 @@ def test_ComputeTDI_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - contrast=dict(argstr='-constrast %s', - ), - data_type=dict(argstr='-datatype %s', - ), - dixel=dict(argstr='-dixel %s', - ), - ends_only=dict(argstr='-ends_only', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm_tck=dict(argstr='-fwhm_tck %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - in_map=dict(argstr='-image %s', - ), - map_zero=dict(argstr='-map_zero', - ), - max_tod=dict(argstr='-tod %d', - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - position=-1, - usedefault=True, - ), - precise=dict(argstr='-precise', - ), - reference=dict(argstr='-template %s', - ), - stat_tck=dict(argstr='-stat_tck %s', - ), - stat_vox=dict(argstr='-stat_vox %s', - ), - tck_weights=dict(argstr='-tck_weights_in %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upsample=dict(argstr='-upsample %d', - ), - use_dec=dict(argstr='-dec', - ), - vox_size=dict(argstr='-vox %s', - sep=',', - ), + input_map = dict( + args=dict(argstr='%s', ), + contrast=dict(argstr='-constrast %s', ), + data_type=dict(argstr='-datatype %s', ), + dixel=dict(argstr='-dixel %s', ), + ends_only=dict(argstr='-ends_only', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm_tck=dict(argstr='-fwhm_tck %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + in_map=dict(argstr='-image %s', ), + map_zero=dict(argstr='-map_zero', ), + max_tod=dict(argstr='-tod %d', ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + position=-1, + usedefault=True, + ), + precise=dict(argstr='-precise', ), + reference=dict(argstr='-template %s', ), + stat_tck=dict(argstr='-stat_tck %s', ), + stat_vox=dict(argstr='-stat_vox %s', ), + tck_weights=dict(argstr='-tck_weights_in %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upsample=dict(argstr='-upsample %d', ), + use_dec=dict(argstr='-dec', ), + vox_size=dict( + argstr='-vox %s', + sep=',', + ), ) inputs = ComputeTDI.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeTDI_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ComputeTDI.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py b/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py index 805b5b86b0..31849f9bc5 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py @@ -4,58 +4,55 @@ def test_DWIExtract_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - bzero=dict(argstr='-bzero', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - nobzero=dict(argstr='-nobzero', - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - shell=dict(argstr='-shell %s', - sep=',', - ), - singleshell=dict(argstr='-singleshell', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + bzero=dict(argstr='-bzero', ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + nobzero=dict(argstr='-nobzero', ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + shell=dict( + argstr='-shell %s', + sep=',', + ), + singleshell=dict(argstr='-singleshell', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWIExtract.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWIExtract_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = DWIExtract.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py b/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py index a62c21d989..d59948dd74 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py @@ -4,83 +4,85 @@ def test_EstimateFOD_inputs(): - input_map = dict(algorithm=dict(argstr='%s', - mandatory=True, - position=-8, - ), - args=dict(argstr='%s', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - csf_odf=dict(argstr='%s', - position=-1, - ), - csf_txt=dict(argstr='%s', - position=-2, - ), - environ=dict(nohash=True, - usedefault=True, - ), - gm_odf=dict(argstr='%s', - position=-3, - ), - gm_txt=dict(argstr='%s', - position=-4, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_dirs=dict(argstr='-directions %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-7, - ), - mask_file=dict(argstr='-mask %s', - ), - max_sh=dict(argstr='-lmax %d', - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - shell=dict(argstr='-shell %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - wm_odf=dict(argstr='%s', - mandatory=True, - position=-5, - usedefault=True, - ), - wm_txt=dict(argstr='%s', - mandatory=True, - position=-6, - ), + input_map = dict( + algorithm=dict( + argstr='%s', + mandatory=True, + position=-8, + ), + args=dict(argstr='%s', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + csf_odf=dict( + argstr='%s', + position=-1, + ), + csf_txt=dict( + argstr='%s', + position=-2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gm_odf=dict( + argstr='%s', + position=-3, + ), + gm_txt=dict( + argstr='%s', + position=-4, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_dirs=dict(argstr='-directions %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-7, + ), + mask_file=dict(argstr='-mask %s', ), + max_sh=dict(argstr='-lmax %d', ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + shell=dict( + argstr='-shell %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + wm_odf=dict( + argstr='%s', + mandatory=True, + position=-5, + usedefault=True, + ), + wm_txt=dict( + argstr='%s', + mandatory=True, + position=-6, + ), ) inputs = EstimateFOD.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EstimateFOD_outputs(): - output_map = dict(csf_odf=dict(argstr='%s', - ), - gm_odf=dict(argstr='%s', - ), - wm_odf=dict(argstr='%s', - ), + output_map = dict( + csf_odf=dict(argstr='%s', ), + gm_odf=dict(argstr='%s', ), + wm_odf=dict(argstr='%s', ), ) outputs = EstimateFOD.output_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py b/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py index f61669d5c9..dc2ab8261f 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py @@ -4,56 +4,52 @@ def test_FitTensor_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - in_mask=dict(argstr='-mask %s', - ), - method=dict(argstr='-method %s', - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - reg_term=dict(argstr='-regularisation %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + in_mask=dict(argstr='-mask %s', ), + method=dict(argstr='-method %s', ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + reg_term=dict(argstr='-regularisation %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FitTensor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FitTensor_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = FitTensor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py b/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py index cc98ff316e..8c483ca120 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py @@ -4,53 +4,53 @@ def test_Generate5tt_inputs(): - input_map = dict(algorithm=dict(argstr='%s', - mandatory=True, - position=-3, - ), - args=dict(argstr='%s', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + algorithm=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + args=dict(argstr='%s', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Generate5tt.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Generate5tt_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Generate5tt.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py b/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py index 4594894ef1..6c37a1f9d8 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py @@ -4,54 +4,53 @@ def test_LabelConfig_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_config=dict(argstr='%s', - position=-2, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - lut_aal=dict(argstr='-lut_aal %s', - ), - lut_basic=dict(argstr='-lut_basic %s', - ), - lut_fs=dict(argstr='-lut_freesurfer %s', - ), - lut_itksnap=dict(argstr='-lut_itksnap %s', - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - spine=dict(argstr='-spine %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_config=dict( + argstr='%s', + position=-2, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + lut_aal=dict(argstr='-lut_aal %s', ), + lut_basic=dict(argstr='-lut_basic %s', ), + lut_fs=dict(argstr='-lut_freesurfer %s', ), + lut_itksnap=dict(argstr='-lut_itksnap %s', ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + spine=dict(argstr='-spine %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = LabelConfig.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LabelConfig_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = LabelConfig.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py index c1778a9ef6..e05a958c0d 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py @@ -4,62 +4,65 @@ def test_MRConvert_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - axes=dict(argstr='-axes %s', - sep=',', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - coord=dict(argstr='-coord %s', - sep=' ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - scaling=dict(argstr='-scaling %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vox=dict(argstr='-vox %s', - sep=',', - ), + input_map = dict( + args=dict(argstr='%s', ), + axes=dict( + argstr='-axes %s', + sep=',', + ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + coord=dict( + argstr='-coord %s', + sep=' ', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + scaling=dict( + argstr='-scaling %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vox=dict( + argstr='-vox %s', + sep=',', + ), ) inputs = MRConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRConvert_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py index 6b13903f0f..1cc11608f9 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py @@ -4,55 +4,54 @@ def test_MRMath_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - axis=dict(argstr='-axis %d', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - operation=dict(argstr='%s', - mandatory=True, - position=-2, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + axis=dict(argstr='-axis %d', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + operation=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRMath.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MRMath_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MRMath.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py index 1d306b6a86..8e6021d82e 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py @@ -4,22 +4,24 @@ def test_MRTrix3Base_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MRTrix3Base.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py b/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py index 30dac94dda..2ca5bfe208 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py @@ -4,44 +4,46 @@ def test_Mesh2PVE_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-3, - ), - in_first=dict(argstr='-first %s', - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - reference=dict(argstr='%s', - mandatory=True, - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + in_first=dict(argstr='-first %s', ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + reference=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Mesh2PVE.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Mesh2PVE_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Mesh2PVE.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py b/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py index b881dc7d1b..fc38059bed 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py @@ -4,45 +4,49 @@ def test_ReplaceFSwithFIRST_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_config=dict(argstr='%s', - position=-2, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-4, - ), - in_t1w=dict(argstr='%s', - mandatory=True, - position=-3, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_config=dict( + argstr='%s', + position=-2, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-4, + ), + in_t1w=dict( + argstr='%s', + mandatory=True, + position=-3, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ReplaceFSwithFIRST.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ReplaceFSwithFIRST_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ReplaceFSwithFIRST.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py b/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py index ff93d1a8a9..29a89f097a 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py @@ -4,70 +4,70 @@ def test_ResponseSD_inputs(): - input_map = dict(algorithm=dict(argstr='%s', - mandatory=True, - position=-6, - ), - args=dict(argstr='%s', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - csf_file=dict(argstr='%s', - position=-1, - ), - environ=dict(nohash=True, - usedefault=True, - ), - gm_file=dict(argstr='%s', - position=-2, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-5, - ), - in_mask=dict(argstr='-mask %s', - ), - max_sh=dict(argstr='-lmax %d', - ), - mtt_file=dict(argstr='%s', - position=-4, - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - wm_file=dict(argstr='%s', - position=-3, - usedefault=True, - ), + input_map = dict( + algorithm=dict( + argstr='%s', + mandatory=True, + position=-6, + ), + args=dict(argstr='%s', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + csf_file=dict( + argstr='%s', + position=-1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gm_file=dict( + argstr='%s', + position=-2, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-5, + ), + in_mask=dict(argstr='-mask %s', ), + max_sh=dict(argstr='-lmax %d', ), + mtt_file=dict( + argstr='%s', + position=-4, + ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + wm_file=dict( + argstr='%s', + position=-3, + usedefault=True, + ), ) inputs = ResponseSD.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ResponseSD_outputs(): - output_map = dict(csf_file=dict(argstr='%s', - ), - gm_file=dict(argstr='%s', - ), - wm_file=dict(argstr='%s', - ), + output_map = dict( + csf_file=dict(argstr='%s', ), + gm_file=dict(argstr='%s', ), + wm_file=dict(argstr='%s', ), ) outputs = ResponseSD.output_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py b/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py index d5f88bc470..606d311185 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py @@ -4,44 +4,45 @@ def test_TCK2VTK_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - position=-1, - usedefault=True, - ), - reference=dict(argstr='-image %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - voxel=dict(argstr='-image %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + position=-1, + usedefault=True, + ), + reference=dict(argstr='-image %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + voxel=dict(argstr='-image %s', ), ) inputs = TCK2VTK.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TCK2VTK_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TCK2VTK.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py b/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py index d51f5fe53e..20cba01dd2 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py @@ -4,50 +4,48 @@ def test_TensorMetrics_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - component=dict(argstr='-num %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-1, - ), - in_mask=dict(argstr='-mask %s', - ), - modulate=dict(argstr='-modulate %s', - ), - out_adc=dict(argstr='-adc %s', - ), - out_eval=dict(argstr='-value %s', - ), - out_evec=dict(argstr='-vector %s', - ), - out_fa=dict(argstr='-fa %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + component=dict( + argstr='-num %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + in_mask=dict(argstr='-mask %s', ), + modulate=dict(argstr='-modulate %s', ), + out_adc=dict(argstr='-adc %s', ), + out_eval=dict(argstr='-value %s', ), + out_evec=dict(argstr='-vector %s', ), + out_fa=dict(argstr='-fa %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TensorMetrics.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TensorMetrics_outputs(): - output_map = dict(out_adc=dict(), - out_eval=dict(), - out_evec=dict(), - out_fa=dict(), + output_map = dict( + out_adc=dict(), + out_eval=dict(), + out_evec=dict(), + out_fa=dict(), ) outputs = TensorMetrics.output_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py b/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py index 6c715202b5..a540fc99ec 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py @@ -4,122 +4,97 @@ def test_Tractography_inputs(): - input_map = dict(act_file=dict(argstr='-act %s', - ), - algorithm=dict(argstr='-algorithm %s', - usedefault=True, - ), - angle=dict(argstr='-angle %f', - ), - args=dict(argstr='%s', - ), - backtrack=dict(argstr='-backtrack', - ), - bval_scale=dict(argstr='-bvalue_scaling %s', - ), - crop_at_gmwmi=dict(argstr='-crop_at_gmwmi', - ), - cutoff=dict(argstr='-cutoff %f', - ), - cutoff_init=dict(argstr='-initcutoff %f', - ), - downsample=dict(argstr='-downsample %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - grad_file=dict(argstr='-grad %s', - ), - grad_fsl=dict(argstr='-fslgrad %s %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_bval=dict(), - in_bvec=dict(argstr='-fslgrad %s %s', - ), - in_file=dict(argstr='%s', - mandatory=True, - position=-2, - ), - init_dir=dict(argstr='-initdirection %f,%f,%f', - ), - max_length=dict(argstr='-maxlength %f', - ), - max_seed_attempts=dict(argstr='-max_seed_attempts %d', - ), - max_tracks=dict(argstr='-maxnum %d', - ), - min_length=dict(argstr='-minlength %f', - ), - n_samples=dict(argstr='-samples %d', - ), - n_tracks=dict(argstr='-number %d', - ), - n_trials=dict(argstr='-trials %d', - ), - noprecompt=dict(argstr='-noprecomputed', - ), - nthreads=dict(argstr='-nthreads %d', - nohash=True, - ), - out_file=dict(argstr='%s', - mandatory=True, - position=-1, - usedefault=True, - ), - out_seeds=dict(argstr='-output_seeds %s', - ), - power=dict(argstr='-power %d', - ), - roi_excl=dict(argstr='-exclude %s', - ), - roi_incl=dict(argstr='-include %s', - ), - roi_mask=dict(argstr='-mask %s', - ), - seed_dynamic=dict(argstr='-seed_dynamic %s', - ), - seed_gmwmi=dict(argstr='-seed_gmwmi %s', - requires=['act_file'], - ), - seed_grid_voxel=dict(argstr='-seed_grid_per_voxel %s %d', - xor=['seed_image', 'seed_rnd_voxel'], - ), - seed_image=dict(argstr='-seed_image %s', - ), - seed_rejection=dict(argstr='-seed_rejection %s', - ), - seed_rnd_voxel=dict(argstr='-seed_random_per_voxel %s %d', - xor=['seed_image', 'seed_grid_voxel'], - ), - seed_sphere=dict(argstr='-seed_sphere %f,%f,%f,%f', - ), - sph_trait=dict(argstr='%f,%f,%f,%f', - ), - step_size=dict(argstr='-step %f', - ), - stop=dict(argstr='-stop', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unidirectional=dict(argstr='-unidirectional', - ), - use_rk4=dict(argstr='-rk4', - ), + input_map = dict( + act_file=dict(argstr='-act %s', ), + algorithm=dict( + argstr='-algorithm %s', + usedefault=True, + ), + angle=dict(argstr='-angle %f', ), + args=dict(argstr='%s', ), + backtrack=dict(argstr='-backtrack', ), + bval_scale=dict(argstr='-bvalue_scaling %s', ), + crop_at_gmwmi=dict(argstr='-crop_at_gmwmi', ), + cutoff=dict(argstr='-cutoff %f', ), + cutoff_init=dict(argstr='-initcutoff %f', ), + downsample=dict(argstr='-downsample %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict(argstr='-grad %s', ), + grad_fsl=dict(argstr='-fslgrad %s %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_bval=dict(), + in_bvec=dict(argstr='-fslgrad %s %s', ), + in_file=dict( + argstr='%s', + mandatory=True, + position=-2, + ), + init_dir=dict(argstr='-initdirection %f,%f,%f', ), + max_length=dict(argstr='-maxlength %f', ), + max_seed_attempts=dict(argstr='-max_seed_attempts %d', ), + max_tracks=dict(argstr='-maxnum %d', ), + min_length=dict(argstr='-minlength %f', ), + n_samples=dict(argstr='-samples %d', ), + n_tracks=dict(argstr='-number %d', ), + n_trials=dict(argstr='-trials %d', ), + noprecompt=dict(argstr='-noprecomputed', ), + nthreads=dict( + argstr='-nthreads %d', + nohash=True, + ), + out_file=dict( + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + ), + out_seeds=dict(argstr='-output_seeds %s', ), + power=dict(argstr='-power %d', ), + roi_excl=dict(argstr='-exclude %s', ), + roi_incl=dict(argstr='-include %s', ), + roi_mask=dict(argstr='-mask %s', ), + seed_dynamic=dict(argstr='-seed_dynamic %s', ), + seed_gmwmi=dict( + argstr='-seed_gmwmi %s', + requires=['act_file'], + ), + seed_grid_voxel=dict( + argstr='-seed_grid_per_voxel %s %d', + xor=['seed_image', 'seed_rnd_voxel'], + ), + seed_image=dict(argstr='-seed_image %s', ), + seed_rejection=dict(argstr='-seed_rejection %s', ), + seed_rnd_voxel=dict( + argstr='-seed_random_per_voxel %s %d', + xor=['seed_image', 'seed_grid_voxel'], + ), + seed_sphere=dict(argstr='-seed_sphere %f,%f,%f,%f', ), + sph_trait=dict(argstr='%f,%f,%f,%f', ), + step_size=dict(argstr='-step %f', ), + stop=dict(argstr='-stop', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unidirectional=dict(argstr='-unidirectional', ), + use_rk4=dict(argstr='-rk4', ), ) inputs = Tractography.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Tractography_outputs(): - output_map = dict(out_file=dict(), - out_seeds=dict(), + output_map = dict( + out_file=dict(), + out_seeds=dict(), ) outputs = Tractography.output_spec() diff --git a/nipype/interfaces/mrtrix3/tracking.py b/nipype/interfaces/mrtrix3/tracking.py index f2cc9c7c75..d432d4c1fb 100644 --- a/nipype/interfaces/mrtrix3/tracking.py +++ b/nipype/interfaces/mrtrix3/tracking.py @@ -1,7 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- - """ Change directory to provide relative paths for doctests >>> import os @@ -11,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op @@ -20,31 +20,57 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): - sph_trait = traits.Tuple(traits.Float, traits.Float, traits.Float, - traits.Float, argstr='%f,%f,%f,%f') - - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input file to be processed') - - out_file = File('tracked.tck', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output file containing tracks') + sph_trait = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + traits.Float, + argstr='%f,%f,%f,%f') + + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input file to be processed') + + out_file = File( + 'tracked.tck', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output file containing tracks') algorithm = traits.Enum( - 'iFOD2', 'FACT', 'iFOD1', 'Nulldist', 'SD_Stream', 'Tensor_Det', - 'Tensor_Prob', usedefault=True, argstr='-algorithm %s', + 'iFOD2', + 'FACT', + 'iFOD1', + 'Nulldist', + 'SD_Stream', + 'Tensor_Det', + 'Tensor_Prob', + usedefault=True, + argstr='-algorithm %s', desc='tractography algorithm to be used') # ROIs processing options roi_incl = traits.Either( - File(exists=True), sph_trait, argstr='-include %s', + File(exists=True), + sph_trait, + argstr='-include %s', desc=('specify an inclusion region of interest, streamlines must' ' traverse ALL inclusion regions to be accepted')) roi_excl = traits.Either( - File(exists=True), sph_trait, argstr='-exclude %s', + File(exists=True), + sph_trait, + argstr='-exclude %s', desc=('specify an exclusion region of interest, streamlines that' ' enter ANY exclude region will be discarded')) roi_mask = traits.Either( - File(exists=True), sph_trait, argstr='-mask %s', + File(exists=True), + sph_trait, + argstr='-mask %s', desc=('specify a masking region of interest. If defined,' 'streamlines exiting the mask will be truncated')) @@ -93,7 +119,9 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): desc=('track from the seed point in one direction only ' '(default is to track in both directions)')) init_dir = traits.Tuple( - traits.Float, traits.Float, traits.Float, + traits.Float, + traits.Float, + traits.Float, argstr='-initdirection %f,%f,%f', desc=('specify an initial direction for the tracking (this ' 'should be supplied as a vector of 3 comma-separated values')) @@ -105,7 +133,8 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): argstr='-power %d', desc=('raise the FOD to the power specified (default is 1/nsamples)')) n_samples = traits.Int( - 4, argstr='-samples %d', + 4, + argstr='-samples %d', desc=('set the number of FOD samples to take per step for the 2nd ' 'order (iFOD2) method')) use_rk4 = traits.Bool( @@ -122,12 +151,13 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): # Anatomically-Constrained Tractography options act_file = File( - exists=True, argstr='-act %s', + exists=True, + argstr='-act %s', desc=('use the Anatomically-Constrained Tractography framework during' ' tracking; provided image must be in the 5TT ' '(five - tissue - type) format')) - backtrack = traits.Bool(argstr='-backtrack', - desc='allow tracks to be truncated') + backtrack = traits.Bool( + argstr='-backtrack', desc='allow tracks to be truncated') crop_at_gmwmi = traits.Bool( argstr='-crop_at_gmwmi', @@ -136,18 +166,26 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): # Tractography seeding options seed_sphere = traits.Tuple( - traits.Float, traits.Float, traits.Float, traits.Float, - argstr='-seed_sphere %f,%f,%f,%f', desc='spherical seed') - seed_image = File(exists=True, argstr='-seed_image %s', - desc='seed streamlines entirely at random within mask') + traits.Float, + traits.Float, + traits.Float, + traits.Float, + argstr='-seed_sphere %f,%f,%f,%f', + desc='spherical seed') + seed_image = File( + exists=True, + argstr='-seed_image %s', + desc='seed streamlines entirely at random within mask') seed_rnd_voxel = traits.Tuple( - File(exists=True), traits.Int(), + File(exists=True), + traits.Int(), argstr='-seed_random_per_voxel %s %d', xor=['seed_image', 'seed_grid_voxel'], desc=('seed a fixed number of streamlines per voxel in a mask ' 'image; random placement of seeds in each voxel')) seed_grid_voxel = traits.Tuple( - File(exists=True), traits.Int(), + File(exists=True), + traits.Int(), argstr='-seed_grid_per_voxel %s %d', xor=['seed_image', 'seed_rnd_voxel'], desc=('seed a fixed number of streamlines per voxel in a mask ' @@ -155,15 +193,19 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): 'is per axis; so a grid_size of 3 results in 27 seeds per' ' voxel)')) seed_rejection = File( - exists=True, argstr='-seed_rejection %s', + exists=True, + argstr='-seed_rejection %s', desc=('seed from an image using rejection sampling (higher ' 'values = more probable to seed from')) seed_gmwmi = File( - exists=True, argstr='-seed_gmwmi %s', requires=['act_file'], + exists=True, + argstr='-seed_gmwmi %s', + requires=['act_file'], desc=('seed from the grey matter - white matter interface (only ' 'valid if using ACT framework)')) seed_dynamic = File( - exists=True, argstr='-seed_dynamic %s', + exists=True, + argstr='-seed_dynamic %s', desc=('determine seed points dynamically using the SIFT model ' '(must not provide any other seeding mechanism). Note that' ' while this seeding mechanism improves the distribution of' @@ -175,19 +217,20 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): 'algorithm should attempt to find an appropriate tracking' ' direction from a given seed point')) out_seeds = File( - 'out_seeds.nii.gz', argstr='-output_seeds %s', + 'out_seeds.nii.gz', + argstr='-output_seeds %s', desc=('output the seed location of all successful streamlines to' ' a file')) class TractographyOutputSpec(TraitedSpec): out_file = File(exists=True, desc='the output filtered tracks') - out_seeds = File(desc=('output the seed location of all successful' - ' streamlines to a file')) + out_seeds = File( + desc=('output the seed location of all successful' + ' streamlines to a file')) class Tractography(MRTrix3Base): - """ Performs streamlines tractography after selecting the appropriate algorithm. diff --git a/nipype/interfaces/mrtrix3/utils.py b/nipype/interfaces/mrtrix3/utils.py index 9f319456d6..2c02de75e4 100644 --- a/nipype/interfaces/mrtrix3/utils.py +++ b/nipype/interfaces/mrtrix3/utils.py @@ -1,7 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- - """ Change directory to provide relative paths for doctests >>> import os @@ -11,7 +10,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os.path as op @@ -20,13 +20,20 @@ from .base import MRTrix3BaseInputSpec, MRTrix3Base - class BrainMaskInputSpec(MRTrix3BaseInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input diffusion weighted images') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input diffusion weighted images') out_file = File( - 'brainmask.mif', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output brain mask') + 'brainmask.mif', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output brain mask') class BrainMaskOutputSpec(TraitedSpec): @@ -34,7 +41,6 @@ class BrainMaskOutputSpec(TraitedSpec): class BrainMask(CommandLine): - """ Convert a mesh surface to a partial volume estimation image @@ -61,17 +67,30 @@ def _list_outputs(self): class Mesh2PVEInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, - desc='input mesh') - reference = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input reference image') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, + desc='input mesh') + reference = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input reference image') in_first = File( - exists=True, argstr='-first %s', + exists=True, + argstr='-first %s', desc='indicates that the mesh file is provided by FSL FIRST') out_file = File( - 'mesh2volume.nii.gz', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output file containing SH coefficients') + 'mesh2volume.nii.gz', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output file containing SH coefficients') class Mesh2PVEOutputSpec(TraitedSpec): @@ -79,7 +98,6 @@ class Mesh2PVEOutputSpec(TraitedSpec): class Mesh2PVE(CommandLine): - """ Convert a mesh surface to a partial volume estimation image @@ -108,12 +126,22 @@ def _list_outputs(self): class Generate5ttInputSpec(MRTrix3BaseInputSpec): - algorithm = traits.Enum('fsl','gif','freesurfer', argstr='%s', position=-3, - mandatory=True, desc='tissue segmentation algorithm') - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, + algorithm = traits.Enum( + 'fsl', + 'gif', + 'freesurfer', + argstr='%s', + position=-3, + mandatory=True, + desc='tissue segmentation algorithm') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, desc='input image') - out_file = File(argstr='%s', mandatory=True, position=-1, - desc='output image') + out_file = File( + argstr='%s', mandatory=True, position=-1, desc='output image') class Generate5ttOutputSpec(TraitedSpec): @@ -121,7 +149,6 @@ class Generate5ttOutputSpec(TraitedSpec): class Generate5tt(MRTrix3Base): - """ Generate a 5TT image suitable for ACT using the selected algorithm @@ -150,25 +177,37 @@ def _list_outputs(self): class TensorMetricsInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-1, - desc='input DTI image') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-1, + desc='input DTI image') out_fa = File(argstr='-fa %s', desc='output FA file') out_adc = File(argstr='-adc %s', desc='output ADC file') - out_evec = File(argstr='-vector %s', - desc='output selected eigenvector(s) file') - out_eval = File(argstr='-value %s', - desc='output selected eigenvalue(s) file') + out_evec = File( + argstr='-vector %s', desc='output selected eigenvector(s) file') + out_eval = File( + argstr='-value %s', desc='output selected eigenvalue(s) file') component = traits.List( - [1, 2, 3], argstr='-num %s', sep=',', + [1, 2, 3], + argstr='-num %s', + sep=',', desc=('specify the desired eigenvalue/eigenvector(s). Note that ' 'several eigenvalues can be specified as a number sequence')) - in_mask = File(exists=True, argstr='-mask %s', - desc=('only perform computation within the specified binary' - ' brain mask image')) - modulate = traits.Enum('FA', 'none', 'eval', argstr='-modulate %s', - desc=('how to modulate the magnitude of the' - ' eigenvectors')) + in_mask = File( + exists=True, + argstr='-mask %s', + desc=('only perform computation within the specified binary' + ' brain mask image')) + modulate = traits.Enum( + 'FA', + 'none', + 'eval', + argstr='-modulate %s', + desc=('how to modulate the magnitude of the' + ' eigenvectors')) class TensorMetricsOutputSpec(TraitedSpec): @@ -179,7 +218,6 @@ class TensorMetricsOutputSpec(TraitedSpec): class TensorMetrics(CommandLine): - """ Compute metrics from tensors @@ -211,70 +249,125 @@ def _list_outputs(self): class ComputeTDIInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input tractography') - out_file = File('tdi.mif', argstr='%s', usedefault=True, position=-1, - desc='output TDI file') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input tractography') + out_file = File( + 'tdi.mif', + argstr='%s', + usedefault=True, + position=-1, + desc='output TDI file') reference = File( - exists=True, argstr='-template %s', desc='a reference' + exists=True, + argstr='-template %s', + desc='a reference' 'image to be used as template') - vox_size = traits.List(traits.Int, argstr='-vox %s', sep=',', - desc='voxel dimensions') - data_type = traits.Enum('float', 'unsigned int', argstr='-datatype %s', - desc='specify output image data type') + vox_size = traits.List( + traits.Int, argstr='-vox %s', sep=',', desc='voxel dimensions') + data_type = traits.Enum( + 'float', + 'unsigned int', + argstr='-datatype %s', + desc='specify output image data type') use_dec = traits.Bool(argstr='-dec', desc='perform mapping in DEC space') - dixel = File('dixels.txt', argstr='-dixel %s', desc='map streamlines to' - 'dixels within each voxel. Directions are stored as' - 'azimuth elevation pairs.') - max_tod = traits.Int(argstr='-tod %d', desc='generate a Track Orientation ' - 'Distribution (TOD) in each voxel.') - - contrast = traits.Enum('tdi', 'length', 'invlength', 'scalar_map', - 'scalar_map_conut', 'fod_amp', 'curvature', - argstr='-constrast %s', desc='define the desired ' - 'form of contrast for the output image') - in_map = File(exists=True, argstr='-image %s', desc='provide the' - 'scalar image map for generating images with ' - '\'scalar_map\' contrasts, or the SHs image for fod_amp') - - stat_vox = traits.Enum('sum', 'min', 'mean', 'max', argstr='-stat_vox %s', - desc='define the statistic for choosing the final' - 'voxel intesities for a given contrast') + dixel = File( + 'dixels.txt', + argstr='-dixel %s', + desc='map streamlines to' + 'dixels within each voxel. Directions are stored as' + 'azimuth elevation pairs.') + max_tod = traits.Int( + argstr='-tod %d', + desc='generate a Track Orientation ' + 'Distribution (TOD) in each voxel.') + + contrast = traits.Enum( + 'tdi', + 'length', + 'invlength', + 'scalar_map', + 'scalar_map_conut', + 'fod_amp', + 'curvature', + argstr='-constrast %s', + desc='define the desired ' + 'form of contrast for the output image') + in_map = File( + exists=True, + argstr='-image %s', + desc='provide the' + 'scalar image map for generating images with ' + '\'scalar_map\' contrasts, or the SHs image for fod_amp') + + stat_vox = traits.Enum( + 'sum', + 'min', + 'mean', + 'max', + argstr='-stat_vox %s', + desc='define the statistic for choosing the final' + 'voxel intesities for a given contrast') stat_tck = traits.Enum( - 'mean', 'sum', 'min', 'max', 'median', 'mean_nonzero', 'gaussian', - 'ends_min', 'ends_mean', 'ends_max', 'ends_prod', - argstr='-stat_tck %s', desc='define the statistic for choosing ' + 'mean', + 'sum', + 'min', + 'max', + 'median', + 'mean_nonzero', + 'gaussian', + 'ends_min', + 'ends_mean', + 'ends_max', + 'ends_prod', + argstr='-stat_tck %s', + desc='define the statistic for choosing ' 'the contribution to be made by each streamline as a function of' ' the samples taken along their lengths.') fwhm_tck = traits.Float( - argstr='-fwhm_tck %f', desc='define the statistic for choosing the' + argstr='-fwhm_tck %f', + desc='define the statistic for choosing the' ' contribution to be made by each streamline as a function of the ' 'samples taken along their lengths') map_zero = traits.Bool( - argstr='-map_zero', desc='if a streamline has zero contribution based ' + argstr='-map_zero', + desc='if a streamline has zero contribution based ' 'on the contrast & statistic, typically it is not mapped; use this ' 'option to still contribute to the map even if this is the case ' '(these non-contributing voxels can then influence the mean value in ' 'each voxel of the map)') - upsample = traits.Int(argstr='-upsample %d', desc='upsample the tracks by' - ' some ratio using Hermite interpolation before ' - 'mappping') + upsample = traits.Int( + argstr='-upsample %d', + desc='upsample the tracks by' + ' some ratio using Hermite interpolation before ' + 'mappping') precise = traits.Bool( - argstr='-precise', desc='use a more precise streamline mapping ' + argstr='-precise', + desc='use a more precise streamline mapping ' 'strategy, that accurately quantifies the length through each voxel ' '(these lengths are then taken into account during TWI calculation)') - ends_only = traits.Bool(argstr='-ends_only', desc='only map the streamline' - ' endpoints to the image') - - tck_weights = File(exists=True, argstr='-tck_weights_in %s', desc='specify' - ' a text scalar file containing the streamline weights') + ends_only = traits.Bool( + argstr='-ends_only', + desc='only map the streamline' + ' endpoints to the image') + + tck_weights = File( + exists=True, + argstr='-tck_weights_in %s', + desc='specify' + ' a text scalar file containing the streamline weights') nthreads = traits.Int( - argstr='-nthreads %d', desc='number of threads. if zero, the number' - ' of available cpus will be used', nohash=True) + argstr='-nthreads %d', + desc='number of threads. if zero, the number' + ' of available cpus will be used', + nohash=True) class ComputeTDIOutputSpec(TraitedSpec): @@ -282,7 +375,6 @@ class ComputeTDIOutputSpec(TraitedSpec): class ComputeTDI(MRTrix3Base): - """ Use track data as a form of contrast for producing a high-resolution image. @@ -347,22 +439,36 @@ def _list_outputs(self): class TCK2VTKInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, - desc='input tractography') - out_file = File('tracks.vtk', argstr='%s', usedefault=True, position=-1, - desc='output VTK file') + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, + desc='input tractography') + out_file = File( + 'tracks.vtk', + argstr='%s', + usedefault=True, + position=-1, + desc='output VTK file') reference = File( - exists=True, argstr='-image %s', desc='if specified, the properties of' + exists=True, + argstr='-image %s', + desc='if specified, the properties of' ' this image will be used to convert track point positions from real ' '(scanner) coordinates into image coordinates (in mm).') voxel = File( - exists=True, argstr='-image %s', desc='if specified, the properties of' + exists=True, + argstr='-image %s', + desc='if specified, the properties of' ' this image will be used to convert track point positions from real ' '(scanner) coordinates into image coordinates.') nthreads = traits.Int( - argstr='-nthreads %d', desc='number of threads. if zero, the number' - ' of available cpus will be used', nohash=True) + argstr='-nthreads %d', + desc='number of threads. if zero, the number' + ' of available cpus will be used', + nohash=True) class TCK2VTKOutputSpec(TraitedSpec): @@ -370,7 +476,6 @@ class TCK2VTKOutputSpec(TraitedSpec): class TCK2VTK(MRTrix3Base): - """ Convert a track file to a vtk format, cave: coordinates are in XYZ coordinates not reference @@ -398,14 +503,22 @@ def _list_outputs(self): class DWIExtractInputSpec(MRTrix3BaseInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, desc='input image') - out_file = File(argstr='%s', mandatory=True, position=-1, - desc='output image') + out_file = File( + argstr='%s', mandatory=True, position=-1, desc='output image') bzero = traits.Bool(argstr='-bzero', desc='extract b=0 volumes') nobzero = traits.Bool(argstr='-nobzero', desc='extract non b=0 volumes') - singleshell = traits.Bool(argstr='-singleshell', desc='extract volumes with a specific shell') - shell = traits.List(traits.Float, sep=',', argstr='-shell %s', + singleshell = traits.Bool( + argstr='-singleshell', desc='extract volumes with a specific shell') + shell = traits.List( + traits.Float, + sep=',', + argstr='-shell %s', desc='specify one or more gradient shells') @@ -414,7 +527,6 @@ class DWIExtractOutputSpec(TraitedSpec): class DWIExtract(MRTrix3Base): - """ Extract diffusion-weighted volumes, b=0 volumes, or certain shells from a DWI dataset @@ -444,17 +556,38 @@ def _list_outputs(self): class MRConvertInputSpec(MRTrix3BaseInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-2, desc='input image') - out_file = File('dwi.mif', argstr='%s', mandatory=True, position=-1, - usedefault=True, desc='output image') - coord = traits.List(traits.Float, sep=' ', argstr='-coord %s', + out_file = File( + 'dwi.mif', + argstr='%s', + mandatory=True, + position=-1, + usedefault=True, + desc='output image') + coord = traits.List( + traits.Float, + sep=' ', + argstr='-coord %s', desc='extract data at the specified coordinates') - vox = traits.List(traits.Float, sep=',', argstr='-vox %s', + vox = traits.List( + traits.Float, + sep=',', + argstr='-vox %s', desc='change the voxel dimensions') - axes = traits.List(traits.Int, sep=',', argstr='-axes %s', + axes = traits.List( + traits.Int, + sep=',', + argstr='-axes %s', desc='specify the axes that will be used') - scaling = traits.List(traits.Float, sep=',', argstr='-scaling %s', + scaling = traits.List( + traits.Float, + sep=',', + argstr='-scaling %s', desc='specify the data scaling parameter') @@ -463,7 +596,6 @@ class MRConvertOutputSpec(TraitedSpec): class MRConvert(MRTrix3Base): - """ Perform conversion between different file types and optionally extract a subset of the input image @@ -491,14 +623,34 @@ def _list_outputs(self): class MRMathInputSpec(MRTrix3BaseInputSpec): - in_file = File(exists=True, argstr='%s', mandatory=True, position=-3, + in_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=-3, desc='input image') - out_file = File(argstr='%s', mandatory=True, position=-1, - desc='output image') - operation = traits.Enum('mean','median','sum','product','rms','norm', - 'var','std','min','max','absmax','magmax', argstr='%s', position=-2, - mandatory=True, desc='operation to computer along a specified axis') - axis = traits.Int(0, argstr='-axis %d', + out_file = File( + argstr='%s', mandatory=True, position=-1, desc='output image') + operation = traits.Enum( + 'mean', + 'median', + 'sum', + 'product', + 'rms', + 'norm', + 'var', + 'std', + 'min', + 'max', + 'absmax', + 'magmax', + argstr='%s', + position=-2, + mandatory=True, + desc='operation to computer along a specified axis') + axis = traits.Int( + 0, + argstr='-axis %d', desc='specfied axis to perform the operation along') @@ -507,7 +659,6 @@ class MRMathOutputSpec(TraitedSpec): class MRMath(MRTrix3Base): - """ Compute summary statistic on image intensities along a specified axis of a single image @@ -535,4 +686,3 @@ def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = op.abspath(self.inputs.out_file) return outputs - diff --git a/nipype/interfaces/niftyfit/__init__.py b/nipype/interfaces/niftyfit/__init__.py index 61e2bde505..b9d4725496 100644 --- a/nipype/interfaces/niftyfit/__init__.py +++ b/nipype/interfaces/niftyfit/__init__.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The niftyfit module provides classes for interfacing with the `NiftyFit`_ command line tools. diff --git a/nipype/interfaces/niftyfit/asl.py b/nipype/interfaces/niftyfit/asl.py index 8f95a48192..67a944a550 100644 --- a/nipype/interfaces/niftyfit/asl.py +++ b/nipype/interfaces/niftyfit/asl.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The ASL module of niftyfit, which wraps the fitting methods in NiftyFit. @@ -20,27 +19,32 @@ class FitAslInputSpec(CommandLineInputSpec): """ Input Spec for FitAsl. """ desc = 'Filename of the 4D ASL (control/label) source image (mandatory).' - source_file = traits.File(position=1, - exists=True, - argstr='-source %s', - mandatory=True, - desc=desc) + source_file = traits.File( + position=1, + exists=True, + argstr='-source %s', + mandatory=True, + desc=desc) pasl = traits.Bool(desc='Fit PASL ASL data [default]', argstr='-pasl') pcasl = traits.Bool(desc='Fit PCASL ASL data', argstr='-pcasl') # *** Output options: desc = 'Filename of the Cerebral Blood Flow map (in ml/100g/min).' - cbf_file = traits.File(name_source=['source_file'], - name_template='%s_cbf.nii.gz', - argstr='-cbf %s', desc=desc) - error_file = traits.File(name_source=['source_file'], - name_template='%s_error.nii.gz', - argstr='-error %s', - desc='Filename of the CBF error map.') - syn_file = traits.File(name_source=['source_file'], - name_template='%s_syn.nii.gz', - argstr='-syn %s', - desc='Filename of the synthetic ASL data.') + cbf_file = traits.File( + name_source=['source_file'], + name_template='%s_cbf.nii.gz', + argstr='-cbf %s', + desc=desc) + error_file = traits.File( + name_source=['source_file'], + name_template='%s_error.nii.gz', + argstr='-error %s', + desc='Filename of the CBF error map.') + syn_file = traits.File( + name_source=['source_file'], + name_template='%s_syn.nii.gz', + argstr='-syn %s', + desc='Filename of the synthetic ASL data.') # *** Input options (see also fit_qt1 for generic T1 fitting): desc = 'Filename of the estimated input T1 map (in ms).' @@ -51,24 +55,28 @@ class FitAslInputSpec(CommandLineInputSpec): m0mape = traits.File(exists=True, argstr='-m0mape %s', desc=desc) desc = 'Filename of a [1,2,5]s Inversion Recovery volume (T1/M0 fitting \ carried out internally).' + ir_volume = traits.File(exists=True, argstr='-IRvolume %s', desc=desc) desc = 'Output of [1,2,5]s Inversion Recovery fitting.' ir_output = traits.File(exists=True, argstr='-IRoutput %s', desc=desc) # *** Experimental options (Choose those suitable for the model!): - mask = traits.File(position=2, - exists=True, - desc='Filename of image mask.', - argstr='-mask %s') - t1_art_cmp = traits.Float(desc='T1 of arterial component [1650ms].', - argstr='-T1a %f') + mask = traits.File( + position=2, + exists=True, + desc='Filename of image mask.', + argstr='-mask %s') + t1_art_cmp = traits.Float( + desc='T1 of arterial component [1650ms].', argstr='-T1a %f') desc = 'Single plasma/tissue partition coefficient [0.9ml/g].' plasma_coeff = traits.Float(desc=desc, argstr='-L %f') desc = 'Labelling efficiency [0.99 (pasl), 0.85 (pcasl)], ensure any \ background suppression pulses are included in -eff' + eff = traits.Float(desc=desc, argstr='-eff %f') desc = 'Outlier rejection for multi CL volumes (enter z-score threshold \ (e.g. 2.5)) [off].' + out = traits.Float(desc=desc, argstr='-out %f') # *** PCASL options (Choose those suitable for the model!): @@ -78,8 +86,8 @@ class FitAslInputSpec(CommandLineInputSpec): dpld = traits.Float(desc=desc, argstr='-dPLD %f') # *** PASL options (Choose those suitable for the model!): - t_inv1 = traits.Float(desc='Saturation pulse time [800ms].', - argstr='-Tinv1 %f') + t_inv1 = traits.Float( + desc='Saturation pulse time [800ms].', argstr='-Tinv1 %f') t_inv2 = traits.Float(desc='Inversion time [2000ms].', argstr='-Tinv2 %f') desc = 'Difference in inversion time per slice [0ms/slice].' dt_inv2 = traits.Float(desc=desc, argstr='-dTinv2 %f') @@ -91,35 +99,40 @@ class FitAslInputSpec(CommandLineInputSpec): # ATT = traits.Float(desc=desc, argstr='-ATT %f') gm_t1 = traits.Float(desc='T1 of GM [1150ms].', argstr='-gmT1 %f') - gm_plasma = traits.Float(desc='Plasma/GM water partition [0.95ml/g].', - argstr='-gmL %f') + gm_plasma = traits.Float( + desc='Plasma/GM water partition [0.95ml/g].', argstr='-gmL %f') gm_ttt = traits.Float(desc='Time to GM [ATT+0ms].', argstr='-gmTTT %f') wm_t1 = traits.Float(desc='T1 of WM [800ms].', argstr='-wmT1 %f') - wm_plasma = traits.Float(desc='Plasma/WM water partition [0.82ml/g].', - argstr='-wmL %f') + wm_plasma = traits.Float( + desc='Plasma/WM water partition [0.82ml/g].', argstr='-wmL %f') wm_ttt = traits.Float(desc='Time to WM [ATT+0ms].', argstr='-wmTTT %f') # *** Segmentation options: desc = 'Filename of the 4D segmentation (in ASL space) for L/T1 \ estimation and PV correction {WM,GM,CSF}.' + seg = traits.File(exists=True, argstr='-seg %s', desc=desc) desc = 'Use sigmoid to estimate L from T1: L(T1|gmL,wmL) [Off].' sig = traits.Bool(desc=desc, argstr='-sig') desc = 'Simple PV correction (CBF=vg*CBFg + vw*CBFw, with CBFw=f*CBFg) \ [0.25].' + pv0 = traits.Int(desc=desc, argstr='-pv0 %d') pv2 = traits.Int(desc='In plane PV kernel size [3x3].', argstr='-pv2 %d') - pv3 = traits.Tuple(traits.Int, traits.Int, traits.Int, - desc='3D kernel size [3x3x1].', - argstr='-pv3 %d %d %d') + pv3 = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + desc='3D kernel size [3x3x1].', + argstr='-pv3 %d %d %d') desc = 'Multiply CBF by this value (e.g. if CL are mislabelled use -1.0).' mul = traits.Float(desc=desc, argstr='-mul %f') - mulgm = traits.Bool(desc='Multiply CBF by segmentation [Off].', - argstr='-sig') + mulgm = traits.Bool( + desc='Multiply CBF by segmentation [Off].', argstr='-sig') desc = 'Set PV threshold for switching off LSQR [O.05].' pv_threshold = traits.Bool(desc=desc, argstr='-pvthreshold') - segstyle = traits.Bool(desc='Set CBF as [gm,wm] not [wm,gm].', - argstr='-segstyle') + segstyle = traits.Bool( + desc='Set CBF as [gm,wm] not [wm,gm].', argstr='-segstyle') class FitAslOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyfit/base.py b/nipype/interfaces/niftyfit/base.py index 58cbcaed45..87c1d63825 100644 --- a/nipype/interfaces/niftyfit/base.py +++ b/nipype/interfaces/niftyfit/base.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The niftyfit module provide an interface with the niftyfit software developed in TIG, UCL. diff --git a/nipype/interfaces/niftyfit/dwi.py b/nipype/interfaces/niftyfit/dwi.py index 67c5444bbe..7130ba48ef 100644 --- a/nipype/interfaces/niftyfit/dwi.py +++ b/nipype/interfaces/niftyfit/dwi.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The dwi module of niftyfit, which wraps the fitting methods in NiftyFit. @@ -20,198 +19,236 @@ class FitDwiInputSpec(CommandLineInputSpec): """ Input Spec for FitDwi. """ # Inputs options - source_file = traits.File(position=1, - exists=True, - argstr='-source %s', - mandatory=True, - desc='The source image containing the dwi data.') + source_file = traits.File( + position=1, + exists=True, + argstr='-source %s', + mandatory=True, + desc='The source image containing the dwi data.') desc = 'The file containing the bvalues of the source DWI.' - bval_file = traits.File(position=2, - exists=True, - argstr='-bval %s', - mandatory=True, - desc=desc) + bval_file = traits.File( + position=2, exists=True, argstr='-bval %s', mandatory=True, desc=desc) desc = 'The file containing the bvectors of the source DWI.' - bvec_file = traits.File(position=3, - exists=True, - argstr='-bvec %s', - mandatory=True, - desc=desc) - te_file = traits.File(exists=True, - argstr='-TE %s', - desc='Filename of TEs (ms).', - xor=['te_file']) - te_value = traits.File(exists=True, - argstr='-TE %s', - desc='Value of TEs (ms).', - xor=['te_file']) - mask_file = traits.File(exists=True, - desc='The image mask', - argstr='-mask %s') + bvec_file = traits.File( + position=3, exists=True, argstr='-bvec %s', mandatory=True, desc=desc) + te_file = traits.File( + exists=True, + argstr='-TE %s', + desc='Filename of TEs (ms).', + xor=['te_file']) + te_value = traits.File( + exists=True, + argstr='-TE %s', + desc='Value of TEs (ms).', + xor=['te_file']) + mask_file = traits.File( + exists=True, desc='The image mask', argstr='-mask %s') desc = 'Filename of parameter priors for -ball and -nod.' - prior_file = traits.File(exists=True, - argstr='-prior %s', - desc=desc) + prior_file = traits.File(exists=True, argstr='-prior %s', desc=desc) desc = 'Rotate the output tensors according to the q/s form of the image \ (resulting tensors will be in mm coordinates, default: 0).' - rot_sform_flag = traits.Int(desc=desc, - argstr='-rotsform %d') + + rot_sform_flag = traits.Int(desc=desc, argstr='-rotsform %d') # generic output options: - error_file = traits.File(name_source=['source_file'], - name_template='%s_error.nii.gz', - desc='Filename of parameter error maps.', - argstr='-error %s') - res_file = traits.File(name_source=['source_file'], - name_template='%s_resmap.nii.gz', - desc='Filename of model residual map.', - argstr='-res %s') - syn_file = traits.File(name_source=['source_file'], - name_template='%s_syn.nii.gz', - desc='Filename of synthetic image.', - argstr='-syn %s') - nodiff_file = traits.File(name_source=['source_file'], - name_template='%s_no_diff.nii.gz', - desc='Filename of average no diffusion image.', - argstr='-nodiff %s') + error_file = traits.File( + name_source=['source_file'], + name_template='%s_error.nii.gz', + desc='Filename of parameter error maps.', + argstr='-error %s') + res_file = traits.File( + name_source=['source_file'], + name_template='%s_resmap.nii.gz', + desc='Filename of model residual map.', + argstr='-res %s') + syn_file = traits.File( + name_source=['source_file'], + name_template='%s_syn.nii.gz', + desc='Filename of synthetic image.', + argstr='-syn %s') + nodiff_file = traits.File( + name_source=['source_file'], + name_template='%s_no_diff.nii.gz', + desc='Filename of average no diffusion image.', + argstr='-nodiff %s') # Output options, with templated output names based on the source image desc = 'Filename of multi-compartment model parameter map \ (-ivim,-ball,-nod)' - mcmap_file = traits.File(name_source=['source_file'], - name_template='%s_mcmap.nii.gz', - desc=desc, - argstr='-mcmap %s', - requires=['nodv_flag']) + + mcmap_file = traits.File( + name_source=['source_file'], + name_template='%s_mcmap.nii.gz', + desc=desc, + argstr='-mcmap %s', + requires=['nodv_flag']) # Model Specific Output options: - mdmap_file = traits.File(name_source=['source_file'], - name_template='%s_mdmap.nii.gz', - desc='Filename of MD map/ADC', - argstr='-mdmap %s') - famap_file = traits.File(name_source=['source_file'], - name_template='%s_famap.nii.gz', - desc='Filename of FA map', - argstr='-famap %s') - v1map_file = traits.File(name_source=['source_file'], - name_template='%s_v1map.nii.gz', - desc='Filename of PDD map [x,y,z]', - argstr='-v1map %s') - rgbmap_file = traits.File(name_source=['source_file'], - name_template='%s_rgbmap.nii.gz', - desc='Filename of colour-coded FA map', - argstr='-rgbmap %s', - requires=['dti_flag']) + mdmap_file = traits.File( + name_source=['source_file'], + name_template='%s_mdmap.nii.gz', + desc='Filename of MD map/ADC', + argstr='-mdmap %s') + famap_file = traits.File( + name_source=['source_file'], + name_template='%s_famap.nii.gz', + desc='Filename of FA map', + argstr='-famap %s') + v1map_file = traits.File( + name_source=['source_file'], + name_template='%s_v1map.nii.gz', + desc='Filename of PDD map [x,y,z]', + argstr='-v1map %s') + rgbmap_file = traits.File( + name_source=['source_file'], + name_template='%s_rgbmap.nii.gz', + desc='Filename of colour-coded FA map', + argstr='-rgbmap %s', + requires=['dti_flag']) desc = 'Use lower triangular (tenmap2) or diagonal, off-diagonal tensor \ format' - ten_type = traits.Enum('lower-tri', 'diag-off-diag', desc=desc, - usedefault=True) - - tenmap_file = traits.File(name_source=['source_file'], - name_template='%s_tenmap.nii.gz', - desc='Filename of tensor map [diag,offdiag].', - argstr='-tenmap %s', - requires=['dti_flag']) - tenmap2_file = traits.File(name_source=['source_file'], - name_template='%s_tenmap2.nii.gz', - desc='Filename of tensor map [lower tri]', - argstr='-tenmap2 %s', - requires=['dti_flag']) + + ten_type = traits.Enum( + 'lower-tri', 'diag-off-diag', desc=desc, usedefault=True) + + tenmap_file = traits.File( + name_source=['source_file'], + name_template='%s_tenmap.nii.gz', + desc='Filename of tensor map [diag,offdiag].', + argstr='-tenmap %s', + requires=['dti_flag']) + tenmap2_file = traits.File( + name_source=['source_file'], + name_template='%s_tenmap2.nii.gz', + desc='Filename of tensor map [lower tri]', + argstr='-tenmap2 %s', + requires=['dti_flag']) # Methods options desc = 'Fit single exponential to non-directional data [default with \ no b-vectors]' - mono_flag = traits.Bool(desc=desc, - argstr='-mono', - position=4, - xor=['ivim_flag', 'dti_flag', 'ball_flag', - 'ballv_flag', 'nod_flag', 'nodv_flag']) - ivim_flag = traits.Bool(desc='Fit IVIM model to non-directional data.', - argstr='-ivim', - position=4, - xor=['mono_flag', 'dti_flag', 'ball_flag', - 'ballv_flag', 'nod_flag', 'nodv_flag']) + + mono_flag = traits.Bool( + desc=desc, + argstr='-mono', + position=4, + xor=[ + 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag', + 'nodv_flag' + ]) + ivim_flag = traits.Bool( + desc='Fit IVIM model to non-directional data.', + argstr='-ivim', + position=4, + xor=[ + 'mono_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag', + 'nodv_flag' + ]) desc = 'Fit the tensor model [default with b-vectors].' - dti_flag = traits.Bool(desc=desc, - argstr='-dti', - position=4, - xor=['mono_flag', 'ivim_flag', 'ball_flag', - 'ballv_flag', 'nod_flag', 'nodv_flag']) - ball_flag = traits.Bool(desc='Fit the ball and stick model.', - argstr='-ball', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'ballv_flag', 'nod_flag', 'nodv_flag']) + dti_flag = traits.Bool( + desc=desc, + argstr='-dti', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'ball_flag', 'ballv_flag', 'nod_flag', + 'nodv_flag' + ]) + ball_flag = traits.Bool( + desc='Fit the ball and stick model.', + argstr='-ball', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ballv_flag', 'nod_flag', + 'nodv_flag' + ]) desc = 'Fit the ball and stick model with optimised PDD.' - ballv_flag = traits.Bool(desc=desc, - argstr='-ballv', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'ball_flag', 'nod_flag', 'nodv_flag']) - nod_flag = traits.Bool(desc='Fit the NODDI model', - argstr='-nod', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'ball_flag', 'ballv_flag', 'nodv_flag']) - nodv_flag = traits.Bool(desc='Fit the NODDI model with optimised PDD', - argstr='-nodv', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'ball_flag', 'ballv_flag', 'nod_flag']) + ballv_flag = traits.Bool( + desc=desc, + argstr='-ballv', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'nod_flag', + 'nodv_flag' + ]) + nod_flag = traits.Bool( + desc='Fit the NODDI model', + argstr='-nod', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', + 'nodv_flag' + ]) + nodv_flag = traits.Bool( + desc='Fit the NODDI model with optimised PDD', + argstr='-nodv', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', + 'nod_flag' + ]) # Experimental options desc = 'Maximum number of non-linear LSQR iterations [100x2 passes])' maxit_val = traits.Int(desc=desc, argstr='-maxit %d', requires=['gn_flag']) desc = 'LM parameters (initial value, decrease rate) [100,1.2].' - lm_vals = traits.Tuple(traits.Float, traits.Float, - argstr='-lm %f %f', - requires=['gn_flag'], - desc=desc) + lm_vals = traits.Tuple( + traits.Float, + traits.Float, + argstr='-lm %f %f', + requires=['gn_flag'], + desc=desc) desc = 'Use Gauss-Newton algorithm [Levenberg-Marquardt].' gn_flag = traits.Bool(desc=desc, argstr='-gn', xor=['wls_flag']) desc = 'Use Variational Bayes fitting with known prior (currently \ identity covariance...).' + vb_flag = traits.Bool(desc=desc, argstr='-vb') - cov_file = traits.File(exists=True, - desc='Filename of ithe nc*nc covariance matrix [I]', - argstr='-cov %s') + cov_file = traits.File( + exists=True, + desc='Filename of ithe nc*nc covariance matrix [I]', + argstr='-cov %s') wls_flag = traits.Bool(desc=desc, argstr='-wls', xor=['gn_flag']) desc = 'Use location-weighted least squares for DTI fitting [3x3 Gaussian]' swls_val = traits.Float(desc=desc, argstr='-swls %f') - slice_no = traits.Int(desc='Fit to single slice number.', - argstr='-slice %d') - voxel = traits.Tuple(traits.Int, traits.Int, traits.Int, - desc='Fit to single voxel only.', - argstr='-voxel %d %d %d') - diso_val = traits.Float(desc='Isotropic diffusivity for -nod [3e-3]', - argstr='-diso %f') - dpr_val = traits.Float(desc='Parallel diffusivity for -nod [1.7e-3].', - argstr='-dpr %f') - wm_t2_val = traits.Float(desc='White matter T2 value [80ms].', - argstr='-wmT2 %f') - csf_t2_val = traits.Float(desc='CSF T2 value [400ms].', - argstr='-csfT2 %f') + slice_no = traits.Int( + desc='Fit to single slice number.', argstr='-slice %d') + voxel = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + desc='Fit to single voxel only.', + argstr='-voxel %d %d %d') + diso_val = traits.Float( + desc='Isotropic diffusivity for -nod [3e-3]', argstr='-diso %f') + dpr_val = traits.Float( + desc='Parallel diffusivity for -nod [1.7e-3].', argstr='-dpr %f') + wm_t2_val = traits.Float( + desc='White matter T2 value [80ms].', argstr='-wmT2 %f') + csf_t2_val = traits.Float(desc='CSF T2 value [400ms].', argstr='-csfT2 %f') desc = 'Threshold for perfusion/diffsuion effects [100].' perf_thr = traits.Float(desc=desc, argstr='-perfthreshold %f') # MCMC options: - mcout = traits.File(name_source=['source_file'], - name_template='%s_mcout.txt', - desc='Filename of mc samples (ascii text file)', - argstr='-mcout %s') - mcsamples = traits.Int(desc='Number of samples to keep [100].', - argstr='-mcsamples %d') - mcmaxit = traits.Int(desc='Number of iterations to run [10,000].', - argstr='-mcmaxit %d') - acceptance = traits.Float(desc='Fraction of iterations to accept [0.23].', - argstr='-accpetance %f') + mcout = traits.File( + name_source=['source_file'], + name_template='%s_mcout.txt', + desc='Filename of mc samples (ascii text file)', + argstr='-mcout %s') + mcsamples = traits.Int( + desc='Number of samples to keep [100].', argstr='-mcsamples %d') + mcmaxit = traits.Int( + desc='Number of iterations to run [10,000].', argstr='-mcmaxit %d') + acceptance = traits.Float( + desc='Fraction of iterations to accept [0.23].', + argstr='-accpetance %f') class FitDwiOutputSpec(TraitedSpec): """ Output Spec for FitDwi. """ desc = 'Filename of multi-compartment model parameter map \ (-ivim,-ball,-nod)' + mcmap_file = traits.File(desc=desc) error_file = traits.File(desc='Filename of parameter error maps') res_file = traits.File(desc='Filename of model residual map') @@ -225,6 +262,7 @@ class FitDwiOutputSpec(TraitedSpec): tenmap2_file = traits.File(desc='Filename of tensor map [lower tri]') desc = 'Filename of multi-compartment model parameter map \ (-ivim,-ball,-nod).' + mcmap_file = traits.File(desc=desc) mcout = traits.File(desc='Filename of mc samples (ascii text file)') @@ -272,130 +310,151 @@ def _format_arg(self, name, trait_spec, value): class DwiToolInputSpec(CommandLineInputSpec): """ Input Spec for DwiTool. """ desc = 'The source image containing the fitted model.' - source_file = traits.File(position=1, - exists=True, - desc=desc, - argstr='-source %s', - mandatory=True) + source_file = traits.File( + position=1, + exists=True, + desc=desc, + argstr='-source %s', + mandatory=True) desc = 'The file containing the bvalues of the source DWI.' - bval_file = traits.File(position=2, - exists=True, - desc=desc, - argstr='-bval %s', - mandatory=True) + bval_file = traits.File( + position=2, exists=True, desc=desc, argstr='-bval %s', mandatory=True) desc = 'The file containing the bvectors of the source DWI.' - bvec_file = traits.File(position=3, - exists=True, - desc=desc, - argstr='-bvec %s') - b0_file = traits.File(position=4, - exists=True, - desc='The B0 image corresponding to the source DWI', - argstr='-b0 %s') - mask_file = traits.File(position=5, - exists=True, - desc='The image mask', - argstr='-mask %s') + bvec_file = traits.File( + position=3, exists=True, desc=desc, argstr='-bvec %s') + b0_file = traits.File( + position=4, + exists=True, + desc='The B0 image corresponding to the source DWI', + argstr='-b0 %s') + mask_file = traits.File( + position=5, exists=True, desc='The image mask', argstr='-mask %s') # Output options, with templated output names based on the source image desc = 'Filename of multi-compartment model parameter map \ (-ivim,-ball,-nod)' - mcmap_file = traits.File(name_source=['source_file'], - name_template='%s_mcmap.nii.gz', - desc=desc, - argstr='-mcmap %s') + + mcmap_file = traits.File( + name_source=['source_file'], + name_template='%s_mcmap.nii.gz', + desc=desc, + argstr='-mcmap %s') desc = 'Filename of synthetic image. Requires: bvec_file/b0_file.' - syn_file = traits.File(name_source=['source_file'], - name_template='%s_syn.nii.gz', - desc=desc, - argstr='-syn %s', - requires=['bvec_file', 'b0_file']) - mdmap_file = traits.File(name_source=['source_file'], - name_template='%s_mdmap.nii.gz', - desc='Filename of MD map/ADC', - argstr='-mdmap %s') - famap_file = traits.File(name_source=['source_file'], - name_template='%s_famap.nii.gz', - desc='Filename of FA map', - argstr='-famap %s') - v1map_file = traits.File(name_source=['source_file'], - name_template='%s_v1map.nii.gz', - desc='Filename of PDD map [x,y,z]', - argstr='-v1map %s') - rgbmap_file = traits.File(name_source=['source_file'], - name_template='%s_rgbmap.nii.gz', - desc='Filename of colour FA map.', - argstr='-rgbmap %s') - logdti_file = traits.File(name_source=['source_file'], - name_template='%s_logdti2.nii.gz', - desc='Filename of output logdti map.', - argstr='-logdti2 %s') + syn_file = traits.File( + name_source=['source_file'], + name_template='%s_syn.nii.gz', + desc=desc, + argstr='-syn %s', + requires=['bvec_file', 'b0_file']) + mdmap_file = traits.File( + name_source=['source_file'], + name_template='%s_mdmap.nii.gz', + desc='Filename of MD map/ADC', + argstr='-mdmap %s') + famap_file = traits.File( + name_source=['source_file'], + name_template='%s_famap.nii.gz', + desc='Filename of FA map', + argstr='-famap %s') + v1map_file = traits.File( + name_source=['source_file'], + name_template='%s_v1map.nii.gz', + desc='Filename of PDD map [x,y,z]', + argstr='-v1map %s') + rgbmap_file = traits.File( + name_source=['source_file'], + name_template='%s_rgbmap.nii.gz', + desc='Filename of colour FA map.', + argstr='-rgbmap %s') + logdti_file = traits.File( + name_source=['source_file'], + name_template='%s_logdti2.nii.gz', + desc='Filename of output logdti map.', + argstr='-logdti2 %s') # Methods options desc = 'Input is a single exponential to non-directional data \ [default with no b-vectors]' - mono_flag = traits.Bool(desc=desc, - position=6, - argstr='-mono', - xor=['ivim_flag', 'dti_flag', 'dti_flag2', - 'ball_flag', 'ballv_flag', 'nod_flag', - 'nodv_flag']) + + mono_flag = traits.Bool( + desc=desc, + position=6, + argstr='-mono', + xor=[ + 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', + 'nod_flag', 'nodv_flag' + ]) desc = 'Inputs is an IVIM model to non-directional data.' - ivim_flag = traits.Bool(desc=desc, - position=6, - argstr='-ivim', - xor=['mono_flag', 'dti_flag', 'dti_flag2', - 'ball_flag', 'ballv_flag', 'nod_flag', - 'nodv_flag']) - dti_flag = traits.Bool(desc='Input is a tensor model diag/off-diag.', - position=6, - argstr='-dti', - xor=['mono_flag', 'ivim_flag', 'dti_flag2', - 'ball_flag', 'ballv_flag', 'nod_flag', - 'nodv_flag']) - dti_flag2 = traits.Bool(desc='Input is a tensor model lower triangular', - position=6, - argstr='-dti2', - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'ball_flag', 'ballv_flag', 'nod_flag', - 'nodv_flag']) - ball_flag = traits.Bool(desc='Input is a ball and stick model.', - position=6, - argstr='-ball', - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'dti_flag2', 'ballv_flag', 'nod_flag', - 'nodv_flag']) + ivim_flag = traits.Bool( + desc=desc, + position=6, + argstr='-ivim', + xor=[ + 'mono_flag', 'dti_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', + 'nod_flag', 'nodv_flag' + ]) + dti_flag = traits.Bool( + desc='Input is a tensor model diag/off-diag.', + position=6, + argstr='-dti', + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', + 'nod_flag', 'nodv_flag' + ]) + dti_flag2 = traits.Bool( + desc='Input is a tensor model lower triangular', + position=6, + argstr='-dti2', + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', + 'nod_flag', 'nodv_flag' + ]) + ball_flag = traits.Bool( + desc='Input is a ball and stick model.', + position=6, + argstr='-ball', + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ballv_flag', + 'nod_flag', 'nodv_flag' + ]) desc = 'Input is a ball and stick model with optimised PDD.' - ballv_flag = traits.Bool(desc=desc, - position=6, - argstr='-ballv', - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'dti_flag2', 'ball_flag', 'nod_flag', - 'nodv_flag']) - nod_flag = traits.Bool(desc='Input is a NODDI model', - position=6, - argstr='-nod', - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'dti_flag2', 'ball_flag', 'ballv_flag', - 'nodv_flag']) - nodv_flag = traits.Bool(desc='Input is a NODDI model with optimised PDD', - position=6, - argstr='-nodv', - xor=['mono_flag', 'ivim_flag', 'dti_flag', - 'dti_flag2', 'ball_flag', 'ballv_flag', - 'nod_flag']) + ballv_flag = traits.Bool( + desc=desc, + position=6, + argstr='-ballv', + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'nod_flag', 'nodv_flag' + ]) + nod_flag = traits.Bool( + desc='Input is a NODDI model', + position=6, + argstr='-nod', + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'ballv_flag', 'nodv_flag' + ]) + nodv_flag = traits.Bool( + desc='Input is a NODDI model with optimised PDD', + position=6, + argstr='-nodv', + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'ballv_flag', 'nod_flag' + ]) # Experimental options - diso_val = traits.Float(desc='Isotropic diffusivity for -nod [3e-3]', - argstr='-diso %f') - dpr_val = traits.Float(desc='Parallel diffusivity for -nod [1.7e-3].', - argstr='-dpr %f') + diso_val = traits.Float( + desc='Isotropic diffusivity for -nod [3e-3]', argstr='-diso %f') + dpr_val = traits.Float( + desc='Parallel diffusivity for -nod [1.7e-3].', argstr='-dpr %f') class DwiToolOutputSpec(TraitedSpec): """ Output Spec for DwiTool. """ desc = 'Filename of multi-compartment model parameter map \ (-ivim,-ball,-nod)' + mcmap_file = traits.File(desc=desc) syn_file = traits.File(desc='Filename of synthetic image') mdmap_file = traits.File(desc='Filename of MD map/ADC') diff --git a/nipype/interfaces/niftyfit/qt1.py b/nipype/interfaces/niftyfit/qt1.py index b5ccfed88b..45f66f6a8a 100644 --- a/nipype/interfaces/niftyfit/qt1.py +++ b/nipype/interfaces/niftyfit/qt1.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The QT1 module of niftyfit, which wraps the Multi-Echo T1 fitting methods in NiftyFit. @@ -21,119 +20,136 @@ class FitQt1InputSpec(CommandLineInputSpec): """ Input Spec for FitQt1. """ desc = 'Filename of the 4D Multi-Echo T1 source image.' - source_file = File(position=1, - exists=True, - desc=desc, - argstr='-source %s', - mandatory=True) + source_file = File( + position=1, + exists=True, + desc=desc, + argstr='-source %s', + mandatory=True) # Output options: - t1map_file = File(name_source=['source_file'], - name_template='%s_t1map.nii.gz', - argstr='-t1map %s', - desc='Filename of the estimated output T1 map (in ms).') - m0map_file = File(name_source=['source_file'], - name_template='%s_m0map.nii.gz', - argstr='-m0map %s', - desc='Filename of the estimated input M0 map.') + t1map_file = File( + name_source=['source_file'], + name_template='%s_t1map.nii.gz', + argstr='-t1map %s', + desc='Filename of the estimated output T1 map (in ms).') + m0map_file = File( + name_source=['source_file'], + name_template='%s_m0map.nii.gz', + argstr='-m0map %s', + desc='Filename of the estimated input M0 map.') desc = 'Filename of the estimated output multi-parameter map.' - mcmap_file = File(name_source=['source_file'], - name_template='%s_mcmap.nii.gz', - argstr='-mcmap %s', - desc=desc) - comp_file = File(name_source=['source_file'], - name_template='%s_comp.nii.gz', - argstr='-comp %s', - desc='Filename of the estimated multi-component T1 map.') + mcmap_file = File( + name_source=['source_file'], + name_template='%s_mcmap.nii.gz', + argstr='-mcmap %s', + desc=desc) + comp_file = File( + name_source=['source_file'], + name_template='%s_comp.nii.gz', + argstr='-comp %s', + desc='Filename of the estimated multi-component T1 map.') desc = 'Filename of the error map (symmetric matrix, [Diag,OffDiag]).' - error_file = File(name_source=['source_file'], - name_template='%s_error.nii.gz', - argstr='-error %s', - desc=desc) - syn_file = File(name_source=['source_file'], - name_template='%s_syn.nii.gz', - argstr='-syn %s', - desc='Filename of the synthetic ASL data.') - res_file = File(name_source=['source_file'], - name_template='%s_res.nii.gz', - argstr='-res %s', - desc='Filename of the model fit residuals') + error_file = File( + name_source=['source_file'], + name_template='%s_error.nii.gz', + argstr='-error %s', + desc=desc) + syn_file = File( + name_source=['source_file'], + name_template='%s_syn.nii.gz', + argstr='-syn %s', + desc='Filename of the synthetic ASL data.') + res_file = File( + name_source=['source_file'], + name_template='%s_res.nii.gz', + argstr='-res %s', + desc='Filename of the model fit residuals') # Other options: - mask = File(position=2, - exists=True, - desc='Filename of image mask.', - argstr='-mask %s') - prior = File(position=3, - exists=True, - desc='Filename of parameter prior.', - argstr='-prior %s') - te_value = traits.Float(desc='TE Echo Time [0ms!].', argstr='-TE %f', - position=4) - tr_value = traits.Float(desc='TR Repetition Time [10s!].', argstr='-TR %f', - position=5) + mask = File( + position=2, + exists=True, + desc='Filename of image mask.', + argstr='-mask %s') + prior = File( + position=3, + exists=True, + desc='Filename of parameter prior.', + argstr='-prior %s') + te_value = traits.Float( + desc='TE Echo Time [0ms!].', argstr='-TE %f', position=4) + tr_value = traits.Float( + desc='TR Repetition Time [10s!].', argstr='-TR %f', position=5) desc = 'Number of components to fit [1] (currently IR/SR only)' # set position to be ahead of TIs nb_comp = traits.Int(desc=desc, position=6, argstr='-nc %d') desc = 'Set LM parameters (initial value, decrease rate) [100,1.2].' - lm_val = traits.Tuple(traits.Float, traits.Float, - desc=desc, argstr='-lm %f %f', position=7) + lm_val = traits.Tuple( + traits.Float, traits.Float, desc=desc, argstr='-lm %f %f', position=7) desc = 'Use Gauss-Newton algorithm [Levenberg-Marquardt].' gn_flag = traits.Bool(desc=desc, argstr='-gn', position=8) - slice_no = traits.Int(desc='Fit to single slice number.', - argstr='-slice %d', position=9) - voxel = traits.Tuple(traits.Int, traits.Int, traits.Int, - desc='Fit to single voxel only.', - argstr='-voxel %d %d %d', position=10) - maxit = traits.Int(desc='NLSQR iterations [100].', argstr='-maxit %d', - position=11) + slice_no = traits.Int( + desc='Fit to single slice number.', argstr='-slice %d', position=9) + voxel = traits.Tuple( + traits.Int, + traits.Int, + traits.Int, + desc='Fit to single voxel only.', + argstr='-voxel %d %d %d', + position=10) + maxit = traits.Int( + desc='NLSQR iterations [100].', argstr='-maxit %d', position=11) # IR options: - sr_flag = traits.Bool(desc='Saturation Recovery fitting [default].', - argstr='-SR', position=12) - ir_flag = traits.Bool(desc='Inversion Recovery fitting [default].', - argstr='-IR', position=13) - tis = traits.List(traits.Float, - position=14, - desc='Inversion times for T1 data [1s,2s,5s].', - argstr='-TIs %s', - sep=' ') - tis_list = traits.File(exists=True, - argstr='-TIlist %s', - desc='Filename of list of pre-defined TIs.') - t1_list = traits.File(exists=True, - argstr='-T1list %s', - desc='Filename of list of pre-defined T1s') - t1min = traits.Float(desc='Minimum tissue T1 value [400ms].', - argstr='-T1min %f') - t1max = traits.Float(desc='Maximum tissue T1 value [4000ms].', - argstr='-T1max %f') + sr_flag = traits.Bool( + desc='Saturation Recovery fitting [default].', + argstr='-SR', + position=12) + ir_flag = traits.Bool( + desc='Inversion Recovery fitting [default].', + argstr='-IR', + position=13) + tis = traits.List( + traits.Float, + position=14, + desc='Inversion times for T1 data [1s,2s,5s].', + argstr='-TIs %s', + sep=' ') + tis_list = traits.File( + exists=True, + argstr='-TIlist %s', + desc='Filename of list of pre-defined TIs.') + t1_list = traits.File( + exists=True, + argstr='-T1list %s', + desc='Filename of list of pre-defined T1s') + t1min = traits.Float( + desc='Minimum tissue T1 value [400ms].', argstr='-T1min %f') + t1max = traits.Float( + desc='Maximum tissue T1 value [4000ms].', argstr='-T1max %f') # SPGR options spgr = traits.Bool(desc='Spoiled Gradient Echo fitting', argstr='-SPGR') - flips = traits.List(traits.Float, - desc='Flip angles', - argstr='-flips %s', - sep=' ') + flips = traits.List( + traits.Float, desc='Flip angles', argstr='-flips %s', sep=' ') desc = 'Filename of list of pre-defined flip angles (deg).' - flips_list = traits.File(exists=True, - argstr='-fliplist %s', - desc=desc) + flips_list = traits.File(exists=True, argstr='-fliplist %s', desc=desc) desc = 'Filename of B1 estimate for fitting (or include in prior).' - b1map = traits.File(exists=True, - argstr='-b1map %s', - desc=desc) + b1map = traits.File(exists=True, argstr='-b1map %s', desc=desc) # MCMC options: - mcout = traits.File(exists=True, - desc='Filename of mc samples (ascii text file)', - argstr='-mcout %s') - mcsamples = traits.Int(desc='Number of samples to keep [100].', - argstr='-mcsamples %d') - mcmaxit = traits.Int(desc='Number of iterations to run [10,000].', - argstr='-mcmaxit %d') - acceptance = traits.Float(desc='Fraction of iterations to accept [0.23].', - argstr='-acceptance %f') + mcout = traits.File( + exists=True, + desc='Filename of mc samples (ascii text file)', + argstr='-mcout %s') + mcsamples = traits.Int( + desc='Number of samples to keep [100].', argstr='-mcsamples %d') + mcmaxit = traits.Int( + desc='Number of iterations to run [10,000].', argstr='-mcmaxit %d') + acceptance = traits.Float( + desc='Fraction of iterations to accept [0.23].', + argstr='-acceptance %f') class FitQt1OutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyfit/tests/test_asl.py b/nipype/interfaces/niftyfit/tests/test_asl.py index f949e26b76..f703555c16 100644 --- a/nipype/interfaces/niftyfit/tests/test_asl.py +++ b/nipype/interfaces/niftyfit/tests/test_asl.py @@ -11,8 +11,8 @@ from ...niftyreg.tests.test_regutils import no_nifty_tool -@pytest.mark.skipif(no_nifty_tool(cmd='fit_asl'), - reason="niftyfit is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='fit_asl'), reason="niftyfit is not installed") def test_fit_asl(): """ Testing FitAsl interface.""" # Create the test node @@ -55,6 +55,7 @@ def test_fit_asl(): cmd_tmp = '{cmd} -source {in_file} -cbf {cbf} -error {error} \ -seg {seg} -sig -syn {syn} -t1map {t1map}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, diff --git a/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py b/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py index 6c0a773fa6..736a90bd91 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py @@ -4,116 +4,160 @@ def test_DwiTool_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - b0_file=dict(argstr='-b0 %s', - position=4, - ), - ball_flag=dict(argstr='-ball', - position=6, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - ballv_flag=dict(argstr='-ballv', - position=6, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', 'nod_flag', 'nodv_flag'], - ), - bval_file=dict(argstr='-bval %s', - mandatory=True, - position=2, - ), - bvec_file=dict(argstr='-bvec %s', - position=3, - ), - diso_val=dict(argstr='-diso %f', - ), - dpr_val=dict(argstr='-dpr %f', - ), - dti_flag=dict(argstr='-dti', - position=6, - xor=['mono_flag', 'ivim_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - dti_flag2=dict(argstr='-dti2', - position=6, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - famap_file=dict(argstr='-famap %s', - name_source=['source_file'], - name_template='%s_famap.nii.gz', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ivim_flag=dict(argstr='-ivim', - position=6, - xor=['mono_flag', 'dti_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - logdti_file=dict(argstr='-logdti2 %s', - name_source=['source_file'], - name_template='%s_logdti2.nii.gz', - ), - mask_file=dict(argstr='-mask %s', - position=5, - ), - mcmap_file=dict(argstr='-mcmap %s', - name_source=['source_file'], - name_template='%s_mcmap.nii.gz', - ), - mdmap_file=dict(argstr='-mdmap %s', - name_source=['source_file'], - name_template='%s_mdmap.nii.gz', - ), - mono_flag=dict(argstr='-mono', - position=6, - xor=['ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - nod_flag=dict(argstr='-nod', - position=6, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', 'nodv_flag'], - ), - nodv_flag=dict(argstr='-nodv', - position=6, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', 'ballv_flag', 'nod_flag'], - ), - rgbmap_file=dict(argstr='-rgbmap %s', - name_source=['source_file'], - name_template='%s_rgbmap.nii.gz', - ), - source_file=dict(argstr='-source %s', - mandatory=True, - position=1, - ), - syn_file=dict(argstr='-syn %s', - name_source=['source_file'], - name_template='%s_syn.nii.gz', - requires=['bvec_file', 'b0_file'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - v1map_file=dict(argstr='-v1map %s', - name_source=['source_file'], - name_template='%s_v1map.nii.gz', - ), + input_map = dict( + args=dict(argstr='%s', ), + b0_file=dict( + argstr='-b0 %s', + position=4, + ), + ball_flag=dict( + argstr='-ball', + position=6, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', + 'ballv_flag', 'nod_flag', 'nodv_flag' + ], + ), + ballv_flag=dict( + argstr='-ballv', + position=6, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'nod_flag', 'nodv_flag' + ], + ), + bval_file=dict( + argstr='-bval %s', + mandatory=True, + position=2, + ), + bvec_file=dict( + argstr='-bvec %s', + position=3, + ), + diso_val=dict(argstr='-diso %f', ), + dpr_val=dict(argstr='-dpr %f', ), + dti_flag=dict( + argstr='-dti', + position=6, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag2', 'ball_flag', + 'ballv_flag', 'nod_flag', 'nodv_flag' + ], + ), + dti_flag2=dict( + argstr='-dti2', + position=6, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', + 'ballv_flag', 'nod_flag', 'nodv_flag' + ], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + famap_file=dict( + argstr='-famap %s', + name_source=['source_file'], + name_template='%s_famap.nii.gz', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ivim_flag=dict( + argstr='-ivim', + position=6, + xor=[ + 'mono_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'ballv_flag', 'nod_flag', 'nodv_flag' + ], + ), + logdti_file=dict( + argstr='-logdti2 %s', + name_source=['source_file'], + name_template='%s_logdti2.nii.gz', + ), + mask_file=dict( + argstr='-mask %s', + position=5, + ), + mcmap_file=dict( + argstr='-mcmap %s', + name_source=['source_file'], + name_template='%s_mcmap.nii.gz', + ), + mdmap_file=dict( + argstr='-mdmap %s', + name_source=['source_file'], + name_template='%s_mdmap.nii.gz', + ), + mono_flag=dict( + argstr='-mono', + position=6, + xor=[ + 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'ballv_flag', 'nod_flag', 'nodv_flag' + ], + ), + nod_flag=dict( + argstr='-nod', + position=6, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'ballv_flag', 'nodv_flag' + ], + ), + nodv_flag=dict( + argstr='-nodv', + position=6, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'dti_flag2', 'ball_flag', + 'ballv_flag', 'nod_flag' + ], + ), + rgbmap_file=dict( + argstr='-rgbmap %s', + name_source=['source_file'], + name_template='%s_rgbmap.nii.gz', + ), + source_file=dict( + argstr='-source %s', + mandatory=True, + position=1, + ), + syn_file=dict( + argstr='-syn %s', + name_source=['source_file'], + name_template='%s_syn.nii.gz', + requires=['bvec_file', 'b0_file'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + v1map_file=dict( + argstr='-v1map %s', + name_source=['source_file'], + name_template='%s_v1map.nii.gz', + ), ) inputs = DwiTool.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DwiTool_outputs(): - output_map = dict(famap_file=dict(), - logdti_file=dict(), - mcmap_file=dict(), - mdmap_file=dict(), - rgbmap_file=dict(), - syn_file=dict(), - v1map_file=dict(), + output_map = dict( + famap_file=dict(), + logdti_file=dict(), + mcmap_file=dict(), + mdmap_file=dict(), + rgbmap_file=dict(), + syn_file=dict(), + v1map_file=dict(), ) outputs = DwiTool.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py b/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py index db865b495c..753aeab890 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py @@ -4,113 +4,88 @@ def test_FitAsl_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cbf_file=dict(argstr='-cbf %s', - name_source=['source_file'], - name_template='%s_cbf.nii.gz', - ), - dpld=dict(argstr='-dPLD %f', - ), - dt_inv2=dict(argstr='-dTinv2 %f', - ), - eff=dict(argstr='-eff %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - error_file=dict(argstr='-error %s', - name_source=['source_file'], - name_template='%s_error.nii.gz', - ), - gm_plasma=dict(argstr='-gmL %f', - ), - gm_t1=dict(argstr='-gmT1 %f', - ), - gm_ttt=dict(argstr='-gmTTT %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ir_output=dict(argstr='-IRoutput %s', - ), - ir_volume=dict(argstr='-IRvolume %s', - ), - ldd=dict(argstr='-LDD %f', - ), - m0map=dict(argstr='-m0map %s', - ), - m0mape=dict(argstr='-m0mape %s', - ), - mask=dict(argstr='-mask %s', - position=2, - ), - mul=dict(argstr='-mul %f', - ), - mulgm=dict(argstr='-sig', - ), - out=dict(argstr='-out %f', - ), - pasl=dict(argstr='-pasl', - ), - pcasl=dict(argstr='-pcasl', - ), - plasma_coeff=dict(argstr='-L %f', - ), - pld=dict(argstr='-PLD %f', - ), - pv0=dict(argstr='-pv0 %d', - ), - pv2=dict(argstr='-pv2 %d', - ), - pv3=dict(argstr='-pv3 %d %d %d', - ), - pv_threshold=dict(argstr='-pvthreshold', - ), - seg=dict(argstr='-seg %s', - ), - segstyle=dict(argstr='-segstyle', - ), - sig=dict(argstr='-sig', - ), - source_file=dict(argstr='-source %s', - mandatory=True, - position=1, - ), - syn_file=dict(argstr='-syn %s', - name_source=['source_file'], - name_template='%s_syn.nii.gz', - ), - t1_art_cmp=dict(argstr='-T1a %f', - ), - t1map=dict(argstr='-t1map %s', - ), - t_inv1=dict(argstr='-Tinv1 %f', - ), - t_inv2=dict(argstr='-Tinv2 %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - wm_plasma=dict(argstr='-wmL %f', - ), - wm_t1=dict(argstr='-wmT1 %f', - ), - wm_ttt=dict(argstr='-wmTTT %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + cbf_file=dict( + argstr='-cbf %s', + name_source=['source_file'], + name_template='%s_cbf.nii.gz', + ), + dpld=dict(argstr='-dPLD %f', ), + dt_inv2=dict(argstr='-dTinv2 %f', ), + eff=dict(argstr='-eff %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + error_file=dict( + argstr='-error %s', + name_source=['source_file'], + name_template='%s_error.nii.gz', + ), + gm_plasma=dict(argstr='-gmL %f', ), + gm_t1=dict(argstr='-gmT1 %f', ), + gm_ttt=dict(argstr='-gmTTT %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ir_output=dict(argstr='-IRoutput %s', ), + ir_volume=dict(argstr='-IRvolume %s', ), + ldd=dict(argstr='-LDD %f', ), + m0map=dict(argstr='-m0map %s', ), + m0mape=dict(argstr='-m0mape %s', ), + mask=dict( + argstr='-mask %s', + position=2, + ), + mul=dict(argstr='-mul %f', ), + mulgm=dict(argstr='-sig', ), + out=dict(argstr='-out %f', ), + pasl=dict(argstr='-pasl', ), + pcasl=dict(argstr='-pcasl', ), + plasma_coeff=dict(argstr='-L %f', ), + pld=dict(argstr='-PLD %f', ), + pv0=dict(argstr='-pv0 %d', ), + pv2=dict(argstr='-pv2 %d', ), + pv3=dict(argstr='-pv3 %d %d %d', ), + pv_threshold=dict(argstr='-pvthreshold', ), + seg=dict(argstr='-seg %s', ), + segstyle=dict(argstr='-segstyle', ), + sig=dict(argstr='-sig', ), + source_file=dict( + argstr='-source %s', + mandatory=True, + position=1, + ), + syn_file=dict( + argstr='-syn %s', + name_source=['source_file'], + name_template='%s_syn.nii.gz', + ), + t1_art_cmp=dict(argstr='-T1a %f', ), + t1map=dict(argstr='-t1map %s', ), + t_inv1=dict(argstr='-Tinv1 %f', ), + t_inv2=dict(argstr='-Tinv2 %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + wm_plasma=dict(argstr='-wmL %f', ), + wm_t1=dict(argstr='-wmT1 %f', ), + wm_ttt=dict(argstr='-wmTTT %f', ), ) inputs = FitAsl.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FitAsl_outputs(): - output_map = dict(cbf_file=dict(), - error_file=dict(), - syn_file=dict(), + output_map = dict( + cbf_file=dict(), + error_file=dict(), + syn_file=dict(), ) outputs = FitAsl.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py b/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py index 96e8fd736f..1412daa220 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py @@ -4,183 +4,217 @@ def test_FitDwi_inputs(): - input_map = dict(acceptance=dict(argstr='-accpetance %f', - ), - args=dict(argstr='%s', - ), - ball_flag=dict(argstr='-ball', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - ballv_flag=dict(argstr='-ballv', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'nod_flag', 'nodv_flag'], - ), - bval_file=dict(argstr='-bval %s', - mandatory=True, - position=2, - ), - bvec_file=dict(argstr='-bvec %s', - mandatory=True, - position=3, - ), - cov_file=dict(argstr='-cov %s', - ), - csf_t2_val=dict(argstr='-csfT2 %f', - ), - diso_val=dict(argstr='-diso %f', - ), - dpr_val=dict(argstr='-dpr %f', - ), - dti_flag=dict(argstr='-dti', - position=4, - xor=['mono_flag', 'ivim_flag', 'ball_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - error_file=dict(argstr='-error %s', - name_source=['source_file'], - name_template='%s_error.nii.gz', - ), - famap_file=dict(argstr='-famap %s', - name_source=['source_file'], - name_template='%s_famap.nii.gz', - ), - gn_flag=dict(argstr='-gn', - xor=['wls_flag'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ivim_flag=dict(argstr='-ivim', - position=4, - xor=['mono_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - lm_vals=dict(argstr='-lm %f %f', - requires=['gn_flag'], - ), - mask_file=dict(argstr='-mask %s', - ), - maxit_val=dict(argstr='-maxit %d', - requires=['gn_flag'], - ), - mcmap_file=dict(argstr='-mcmap %s', - name_source=['source_file'], - name_template='%s_mcmap.nii.gz', - requires=['nodv_flag'], - ), - mcmaxit=dict(argstr='-mcmaxit %d', - ), - mcout=dict(argstr='-mcout %s', - name_source=['source_file'], - name_template='%s_mcout.txt', - ), - mcsamples=dict(argstr='-mcsamples %d', - ), - mdmap_file=dict(argstr='-mdmap %s', - name_source=['source_file'], - name_template='%s_mdmap.nii.gz', - ), - mono_flag=dict(argstr='-mono', - position=4, - xor=['ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag', 'nodv_flag'], - ), - nod_flag=dict(argstr='-nod', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nodv_flag'], - ), - nodiff_file=dict(argstr='-nodiff %s', - name_source=['source_file'], - name_template='%s_no_diff.nii.gz', - ), - nodv_flag=dict(argstr='-nodv', - position=4, - xor=['mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag'], - ), - perf_thr=dict(argstr='-perfthreshold %f', - ), - prior_file=dict(argstr='-prior %s', - ), - res_file=dict(argstr='-res %s', - name_source=['source_file'], - name_template='%s_resmap.nii.gz', - ), - rgbmap_file=dict(argstr='-rgbmap %s', - name_source=['source_file'], - name_template='%s_rgbmap.nii.gz', - requires=['dti_flag'], - ), - rot_sform_flag=dict(argstr='-rotsform %d', - ), - slice_no=dict(argstr='-slice %d', - ), - source_file=dict(argstr='-source %s', - mandatory=True, - position=1, - ), - swls_val=dict(argstr='-swls %f', - ), - syn_file=dict(argstr='-syn %s', - name_source=['source_file'], - name_template='%s_syn.nii.gz', - ), - te_file=dict(argstr='-TE %s', - xor=['te_file'], - ), - te_value=dict(argstr='-TE %s', - xor=['te_file'], - ), - ten_type=dict(usedefault=True, - ), - tenmap2_file=dict(argstr='-tenmap2 %s', - name_source=['source_file'], - name_template='%s_tenmap2.nii.gz', - requires=['dti_flag'], - ), - tenmap_file=dict(argstr='-tenmap %s', - name_source=['source_file'], - name_template='%s_tenmap.nii.gz', - requires=['dti_flag'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - v1map_file=dict(argstr='-v1map %s', - name_source=['source_file'], - name_template='%s_v1map.nii.gz', - ), - vb_flag=dict(argstr='-vb', - ), - voxel=dict(argstr='-voxel %d %d %d', - ), - wls_flag=dict(argstr='-wls', - xor=['gn_flag'], - ), - wm_t2_val=dict(argstr='-wmT2 %f', - ), + input_map = dict( + acceptance=dict(argstr='-accpetance %f', ), + args=dict(argstr='%s', ), + ball_flag=dict( + argstr='-ball', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ballv_flag', 'nod_flag', + 'nodv_flag' + ], + ), + ballv_flag=dict( + argstr='-ballv', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', 'nod_flag', + 'nodv_flag' + ], + ), + bval_file=dict( + argstr='-bval %s', + mandatory=True, + position=2, + ), + bvec_file=dict( + argstr='-bvec %s', + mandatory=True, + position=3, + ), + cov_file=dict(argstr='-cov %s', ), + csf_t2_val=dict(argstr='-csfT2 %f', ), + diso_val=dict(argstr='-diso %f', ), + dpr_val=dict(argstr='-dpr %f', ), + dti_flag=dict( + argstr='-dti', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'ball_flag', 'ballv_flag', + 'nod_flag', 'nodv_flag' + ], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + error_file=dict( + argstr='-error %s', + name_source=['source_file'], + name_template='%s_error.nii.gz', + ), + famap_file=dict( + argstr='-famap %s', + name_source=['source_file'], + name_template='%s_famap.nii.gz', + ), + gn_flag=dict( + argstr='-gn', + xor=['wls_flag'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ivim_flag=dict( + argstr='-ivim', + position=4, + xor=[ + 'mono_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag', + 'nodv_flag' + ], + ), + lm_vals=dict( + argstr='-lm %f %f', + requires=['gn_flag'], + ), + mask_file=dict(argstr='-mask %s', ), + maxit_val=dict( + argstr='-maxit %d', + requires=['gn_flag'], + ), + mcmap_file=dict( + argstr='-mcmap %s', + name_source=['source_file'], + name_template='%s_mcmap.nii.gz', + requires=['nodv_flag'], + ), + mcmaxit=dict(argstr='-mcmaxit %d', ), + mcout=dict( + argstr='-mcout %s', + name_source=['source_file'], + name_template='%s_mcout.txt', + ), + mcsamples=dict(argstr='-mcsamples %d', ), + mdmap_file=dict( + argstr='-mdmap %s', + name_source=['source_file'], + name_template='%s_mdmap.nii.gz', + ), + mono_flag=dict( + argstr='-mono', + position=4, + xor=[ + 'ivim_flag', 'dti_flag', 'ball_flag', 'ballv_flag', 'nod_flag', + 'nodv_flag' + ], + ), + nod_flag=dict( + argstr='-nod', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', + 'ballv_flag', 'nodv_flag' + ], + ), + nodiff_file=dict( + argstr='-nodiff %s', + name_source=['source_file'], + name_template='%s_no_diff.nii.gz', + ), + nodv_flag=dict( + argstr='-nodv', + position=4, + xor=[ + 'mono_flag', 'ivim_flag', 'dti_flag', 'ball_flag', + 'ballv_flag', 'nod_flag' + ], + ), + perf_thr=dict(argstr='-perfthreshold %f', ), + prior_file=dict(argstr='-prior %s', ), + res_file=dict( + argstr='-res %s', + name_source=['source_file'], + name_template='%s_resmap.nii.gz', + ), + rgbmap_file=dict( + argstr='-rgbmap %s', + name_source=['source_file'], + name_template='%s_rgbmap.nii.gz', + requires=['dti_flag'], + ), + rot_sform_flag=dict(argstr='-rotsform %d', ), + slice_no=dict(argstr='-slice %d', ), + source_file=dict( + argstr='-source %s', + mandatory=True, + position=1, + ), + swls_val=dict(argstr='-swls %f', ), + syn_file=dict( + argstr='-syn %s', + name_source=['source_file'], + name_template='%s_syn.nii.gz', + ), + te_file=dict( + argstr='-TE %s', + xor=['te_file'], + ), + te_value=dict( + argstr='-TE %s', + xor=['te_file'], + ), + ten_type=dict(usedefault=True, ), + tenmap2_file=dict( + argstr='-tenmap2 %s', + name_source=['source_file'], + name_template='%s_tenmap2.nii.gz', + requires=['dti_flag'], + ), + tenmap_file=dict( + argstr='-tenmap %s', + name_source=['source_file'], + name_template='%s_tenmap.nii.gz', + requires=['dti_flag'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + v1map_file=dict( + argstr='-v1map %s', + name_source=['source_file'], + name_template='%s_v1map.nii.gz', + ), + vb_flag=dict(argstr='-vb', ), + voxel=dict(argstr='-voxel %d %d %d', ), + wls_flag=dict( + argstr='-wls', + xor=['gn_flag'], + ), + wm_t2_val=dict(argstr='-wmT2 %f', ), ) inputs = FitDwi.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FitDwi_outputs(): - output_map = dict(error_file=dict(), - famap_file=dict(), - mcmap_file=dict(), - mcout=dict(), - mdmap_file=dict(), - nodiff_file=dict(), - res_file=dict(), - rgbmap_file=dict(), - syn_file=dict(), - tenmap2_file=dict(), - tenmap_file=dict(), - v1map_file=dict(), + output_map = dict( + error_file=dict(), + famap_file=dict(), + mcmap_file=dict(), + mcout=dict(), + mdmap_file=dict(), + nodiff_file=dict(), + res_file=dict(), + rgbmap_file=dict(), + syn_file=dict(), + tenmap2_file=dict(), + tenmap_file=dict(), + v1map_file=dict(), ) outputs = FitDwi.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py b/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py index 32d1cb7b03..55bf9390ef 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py @@ -4,131 +4,144 @@ def test_FitQt1_inputs(): - input_map = dict(acceptance=dict(argstr='-acceptance %f', - ), - args=dict(argstr='%s', - ), - b1map=dict(argstr='-b1map %s', - ), - comp_file=dict(argstr='-comp %s', - name_source=['source_file'], - name_template='%s_comp.nii.gz', - ), - environ=dict(nohash=True, - usedefault=True, - ), - error_file=dict(argstr='-error %s', - name_source=['source_file'], - name_template='%s_error.nii.gz', - ), - flips=dict(argstr='-flips %s', - sep=' ', - ), - flips_list=dict(argstr='-fliplist %s', - ), - gn_flag=dict(argstr='-gn', - position=8, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ir_flag=dict(argstr='-IR', - position=13, - ), - lm_val=dict(argstr='-lm %f %f', - position=7, - ), - m0map_file=dict(argstr='-m0map %s', - name_source=['source_file'], - name_template='%s_m0map.nii.gz', - ), - mask=dict(argstr='-mask %s', - position=2, - ), - maxit=dict(argstr='-maxit %d', - position=11, - ), - mcmap_file=dict(argstr='-mcmap %s', - name_source=['source_file'], - name_template='%s_mcmap.nii.gz', - ), - mcmaxit=dict(argstr='-mcmaxit %d', - ), - mcout=dict(argstr='-mcout %s', - ), - mcsamples=dict(argstr='-mcsamples %d', - ), - nb_comp=dict(argstr='-nc %d', - position=6, - ), - prior=dict(argstr='-prior %s', - position=3, - ), - res_file=dict(argstr='-res %s', - name_source=['source_file'], - name_template='%s_res.nii.gz', - ), - slice_no=dict(argstr='-slice %d', - position=9, - ), - source_file=dict(argstr='-source %s', - mandatory=True, - position=1, - ), - spgr=dict(argstr='-SPGR', - ), - sr_flag=dict(argstr='-SR', - position=12, - ), - syn_file=dict(argstr='-syn %s', - name_source=['source_file'], - name_template='%s_syn.nii.gz', - ), - t1_list=dict(argstr='-T1list %s', - ), - t1map_file=dict(argstr='-t1map %s', - name_source=['source_file'], - name_template='%s_t1map.nii.gz', - ), - t1max=dict(argstr='-T1max %f', - ), - t1min=dict(argstr='-T1min %f', - ), - te_value=dict(argstr='-TE %f', - position=4, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tis=dict(argstr='-TIs %s', - position=14, - sep=' ', - ), - tis_list=dict(argstr='-TIlist %s', - ), - tr_value=dict(argstr='-TR %f', - position=5, - ), - voxel=dict(argstr='-voxel %d %d %d', - position=10, - ), + input_map = dict( + acceptance=dict(argstr='-acceptance %f', ), + args=dict(argstr='%s', ), + b1map=dict(argstr='-b1map %s', ), + comp_file=dict( + argstr='-comp %s', + name_source=['source_file'], + name_template='%s_comp.nii.gz', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + error_file=dict( + argstr='-error %s', + name_source=['source_file'], + name_template='%s_error.nii.gz', + ), + flips=dict( + argstr='-flips %s', + sep=' ', + ), + flips_list=dict(argstr='-fliplist %s', ), + gn_flag=dict( + argstr='-gn', + position=8, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ir_flag=dict( + argstr='-IR', + position=13, + ), + lm_val=dict( + argstr='-lm %f %f', + position=7, + ), + m0map_file=dict( + argstr='-m0map %s', + name_source=['source_file'], + name_template='%s_m0map.nii.gz', + ), + mask=dict( + argstr='-mask %s', + position=2, + ), + maxit=dict( + argstr='-maxit %d', + position=11, + ), + mcmap_file=dict( + argstr='-mcmap %s', + name_source=['source_file'], + name_template='%s_mcmap.nii.gz', + ), + mcmaxit=dict(argstr='-mcmaxit %d', ), + mcout=dict(argstr='-mcout %s', ), + mcsamples=dict(argstr='-mcsamples %d', ), + nb_comp=dict( + argstr='-nc %d', + position=6, + ), + prior=dict( + argstr='-prior %s', + position=3, + ), + res_file=dict( + argstr='-res %s', + name_source=['source_file'], + name_template='%s_res.nii.gz', + ), + slice_no=dict( + argstr='-slice %d', + position=9, + ), + source_file=dict( + argstr='-source %s', + mandatory=True, + position=1, + ), + spgr=dict(argstr='-SPGR', ), + sr_flag=dict( + argstr='-SR', + position=12, + ), + syn_file=dict( + argstr='-syn %s', + name_source=['source_file'], + name_template='%s_syn.nii.gz', + ), + t1_list=dict(argstr='-T1list %s', ), + t1map_file=dict( + argstr='-t1map %s', + name_source=['source_file'], + name_template='%s_t1map.nii.gz', + ), + t1max=dict(argstr='-T1max %f', ), + t1min=dict(argstr='-T1min %f', ), + te_value=dict( + argstr='-TE %f', + position=4, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tis=dict( + argstr='-TIs %s', + position=14, + sep=' ', + ), + tis_list=dict(argstr='-TIlist %s', ), + tr_value=dict( + argstr='-TR %f', + position=5, + ), + voxel=dict( + argstr='-voxel %d %d %d', + position=10, + ), ) inputs = FitQt1.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FitQt1_outputs(): - output_map = dict(comp_file=dict(), - error_file=dict(), - m0map_file=dict(), - mcmap_file=dict(), - res_file=dict(), - syn_file=dict(), - t1map_file=dict(), + output_map = dict( + comp_file=dict(), + error_file=dict(), + m0map_file=dict(), + mcmap_file=dict(), + res_file=dict(), + syn_file=dict(), + t1map_file=dict(), ) outputs = FitQt1.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py b/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py index 1365775b56..59af812d2b 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py @@ -4,22 +4,24 @@ def test_NiftyFitCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = NiftyFitCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/niftyfit/tests/test_dwi.py b/nipype/interfaces/niftyfit/tests/test_dwi.py index 5b7d0f7348..270d9c666a 100644 --- a/nipype/interfaces/niftyfit/tests/test_dwi.py +++ b/nipype/interfaces/niftyfit/tests/test_dwi.py @@ -10,8 +10,8 @@ from ...niftyreg.tests.test_regutils import no_nifty_tool -@pytest.mark.skipif(no_nifty_tool(cmd='fit_dwi'), - reason="niftyfit is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='fit_dwi'), reason="niftyfit is not installed") def test_fit_dwi(): """ Testing FitDwi interface.""" # Create a node object @@ -58,8 +58,8 @@ def test_fit_dwi(): assert fit_dwi.cmdline == expected_cmd -@pytest.mark.skipif(no_nifty_tool(cmd='dwi_tool'), - reason="niftyfit is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='dwi_tool'), reason="niftyfit is not installed") def test_dwi_tool(): """ Testing DwiTool interface.""" # Create a node object @@ -89,6 +89,7 @@ def test_dwi_tool(): cmd_tmp = '{cmd} -source {in_file} -bval {bval} -bvec {bvec} -b0 {b0} \ -mask {mask} -dti -famap {fa} -logdti2 {log} -mcmap {mc} -mdmap {md} \ -rgbmap {rgb} -syn {syn} -v1map {v1}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, diff --git a/nipype/interfaces/niftyfit/tests/test_qt1.py b/nipype/interfaces/niftyfit/tests/test_qt1.py index e2e78ed37d..894017e654 100644 --- a/nipype/interfaces/niftyfit/tests/test_qt1.py +++ b/nipype/interfaces/niftyfit/tests/test_qt1.py @@ -10,8 +10,8 @@ from ..qt1 import FitQt1 -@pytest.mark.skipif(no_nifty_tool(cmd='fit_qt1'), - reason="niftyfit is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='fit_qt1'), reason="niftyfit is not installed") def test_fit_qt1(): """ Testing FitQt1 interface.""" # Create a node object @@ -31,6 +31,7 @@ def test_fit_qt1(): cmd_tmp = '{cmd} -source {in_file} -comp {comp} -error {error} -m0map \ {map0} -mcmap {cmap} -res {res} -syn {syn} -t1map {t1map}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, @@ -53,6 +54,7 @@ def test_fit_qt1(): cmd_tmp = '{cmd} -source {in_file} -IR -TIs 1.0 2.0 5.0 \ -comp {comp} -error {error} -m0map {map0} -mcmap {cmap} -res {res} \ -syn {syn} -t1map {t1map}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, @@ -75,6 +77,7 @@ def test_fit_qt1(): cmd_tmp = '{cmd} -source {in_file} -comp {comp} -error {error} \ -flips 2.0 4.0 8.0 -m0map {map0} -mcmap {cmap} -res {res} -SPGR -syn {syn} \ -t1map {t1map}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, diff --git a/nipype/interfaces/niftyreg/__init__.py b/nipype/interfaces/niftyreg/__init__.py index 04c066dcae..9854ebaea3 100644 --- a/nipype/interfaces/niftyreg/__init__.py +++ b/nipype/interfaces/niftyreg/__init__.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The niftyreg module provides classes for interfacing with the `NiftyReg `_ command line tools. diff --git a/nipype/interfaces/niftyreg/base.py b/nipype/interfaces/niftyreg/base.py index 47859c9ec9..65d95b0c59 100644 --- a/nipype/interfaces/niftyreg/base.py +++ b/nipype/interfaces/niftyreg/base.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The niftyreg module provides classes for interfacing with `niftyreg `_ command line tools. @@ -37,9 +36,11 @@ def get_custom_path(command, env_dir='NIFTYREGDIR'): class NiftyRegCommandInputSpec(CommandLineInputSpec): """Input Spec for niftyreg interfaces.""" # Set the number of omp thread to use - omp_core_val = traits.Int(int(os.environ.get('OMP_NUM_THREADS', '1')), - desc='Number of openmp thread to use', - argstr='-omp %i', usedefault=True) + omp_core_val = traits.Int( + int(os.environ.get('OMP_NUM_THREADS', '1')), + desc='Number of openmp thread to use', + argstr='-omp %i', + usedefault=True) class NiftyRegCommand(CommandLine): diff --git a/nipype/interfaces/niftyreg/reg.py b/nipype/interfaces/niftyreg/reg.py index bbc49ee2f2..7096d5f5f3 100644 --- a/nipype/interfaces/niftyreg/reg.py +++ b/nipype/interfaces/niftyreg/reg.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The reg module provides classes for interfacing with the `niftyreg `_ registration command line tools. @@ -29,100 +28,97 @@ class RegAladinInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegAladin. """ # Input reference file - ref_file = File(exists=True, - desc='The input reference/target image', - argstr='-ref %s', - mandatory=True) + ref_file = File( + exists=True, + desc='The input reference/target image', + argstr='-ref %s', + mandatory=True) # Input floating file - flo_file = File(exists=True, - desc='The input floating/source image', - argstr='-flo %s', - mandatory=True) + flo_file = File( + exists=True, + desc='The input floating/source image', + argstr='-flo %s', + mandatory=True) # No symmetric flag - nosym_flag = traits.Bool(argstr='-noSym', - desc='Turn off symmetric registration') + nosym_flag = traits.Bool( + argstr='-noSym', desc='Turn off symmetric registration') # Rigid only registration - rig_only_flag = traits.Bool(argstr='-rigOnly', - desc='Do only a rigid registration') + rig_only_flag = traits.Bool( + argstr='-rigOnly', desc='Do only a rigid registration') # Directly optimise affine flag desc = 'Directly optimise the affine parameters' - aff_direct_flag = traits.Bool(argstr='-affDirect', - desc=desc) + aff_direct_flag = traits.Bool(argstr='-affDirect', desc=desc) # Input affine - in_aff_file = File(exists=True, - desc='The input affine transformation', - argstr='-inaff %s') + in_aff_file = File( + exists=True, + desc='The input affine transformation', + argstr='-inaff %s') # Input reference mask - rmask_file = File(exists=True, - desc='The input reference mask', - argstr='-rmask %s') + rmask_file = File( + exists=True, desc='The input reference mask', argstr='-rmask %s') # Input floating mask - fmask_file = File(exists=True, - desc='The input floating mask', - argstr='-fmask %s') + fmask_file = File( + exists=True, desc='The input floating mask', argstr='-fmask %s') # Maximum number of iterations - maxit_val = traits.Range(desc='Maximum number of iterations', - argstr='-maxit %d', low=0) + maxit_val = traits.Range( + desc='Maximum number of iterations', argstr='-maxit %d', low=0) # Multiresolution levels - ln_val = traits.Range(desc='Number of resolution levels to create', - argstr='-ln %d', low=0) + ln_val = traits.Range( + desc='Number of resolution levels to create', argstr='-ln %d', low=0) # Number of resolution levels to process - lp_val = traits.Range(desc='Number of resolution levels to perform', - argstr='-lp %d', low=0) + lp_val = traits.Range( + desc='Number of resolution levels to perform', argstr='-lp %d', low=0) # Smoothing to apply on reference image desc = 'Amount of smoothing to apply to reference image' - smoo_r_val = traits.Float(desc=desc, - argstr='-smooR %f') + smoo_r_val = traits.Float(desc=desc, argstr='-smooR %f') # Smoothing to apply on floating image desc = 'Amount of smoothing to apply to floating image' - smoo_f_val = traits.Float(desc=desc, - argstr='-smooF %f') + smoo_f_val = traits.Float(desc=desc, argstr='-smooF %f') # Use nifti header to initialise transformation desc = 'Use nifti header to initialise transformation' - nac_flag = traits.Bool(desc=desc, - argstr='-nac') + nac_flag = traits.Bool(desc=desc, argstr='-nac') # Use the input masks centre of mass to initialise the transformation desc = 'Use the masks centre of mass to initialise the transformation' - cog_flag = traits.Bool(desc=desc, - argstr='-cog') + cog_flag = traits.Bool(desc=desc, argstr='-cog') # Percent of blocks that are considered active. - v_val = traits.Range(desc='Percent of blocks that are active', - argstr='-pv %d', low=0) + v_val = traits.Range( + desc='Percent of blocks that are active', argstr='-pv %d', low=0) # Percent of inlier blocks - i_val = traits.Range(desc='Percent of inlier blocks', argstr='-pi %d', - low=0) + i_val = traits.Range( + desc='Percent of inlier blocks', argstr='-pi %d', low=0) # Lower threshold on reference image - ref_low_val = traits.Float(desc='Lower threshold value on reference image', - argstr='-refLowThr %f') + ref_low_val = traits.Float( + desc='Lower threshold value on reference image', + argstr='-refLowThr %f') # Upper threshold on reference image - ref_up_val = traits.Float(desc='Upper threshold value on reference image', - argstr='-refUpThr %f') + ref_up_val = traits.Float( + desc='Upper threshold value on reference image', argstr='-refUpThr %f') # Lower threshold on floating image - flo_low_val = traits.Float(desc='Lower threshold value on floating image', - argstr='-floLowThr %f') + flo_low_val = traits.Float( + desc='Lower threshold value on floating image', argstr='-floLowThr %f') # Upper threshold on floating image - flo_up_val = traits.Float(desc='Upper threshold value on floating image', - argstr='-floUpThr %f') + flo_up_val = traits.Float( + desc='Upper threshold value on floating image', argstr='-floUpThr %f') # Platform to use - platform_val = traits.Int(desc='Platform index', - argstr='-platf %i') + platform_val = traits.Int(desc='Platform index', argstr='-platf %i') # Platform to use - gpuid_val = traits.Int(desc='Device to use id', - argstr='-gpuid %i') + gpuid_val = traits.Int(desc='Device to use id', argstr='-gpuid %i') # Verbosity off - verbosity_off_flag = traits.Bool(argstr='-voff', - desc='Turn off verbose output') + verbosity_off_flag = traits.Bool( + argstr='-voff', desc='Turn off verbose output') # Affine output transformation matrix file - aff_file = File(name_source=['flo_file'], - name_template='%s_aff.txt', - desc='The output affine matrix file', - argstr='-aff %s') + aff_file = File( + name_source=['flo_file'], + name_template='%s_aff.txt', + desc='The output affine matrix file', + argstr='-aff %s') # Result warped image file - res_file = File(name_source=['flo_file'], - name_template='%s_res.nii.gz', - desc='The affine transformed floating image', - argstr='-res %s') + res_file = File( + name_source=['flo_file'], + name_template='%s_res.nii.gz', + desc='The affine transformed floating image', + argstr='-res %s') class RegAladinOutputSpec(TraitedSpec): @@ -173,30 +169,33 @@ def _list_outputs(self): class RegF3DInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegF3D. """ # Input reference file - ref_file = File(exists=True, - desc='The input reference/target image', - argstr='-ref %s', - mandatory=True) + ref_file = File( + exists=True, + desc='The input reference/target image', + argstr='-ref %s', + mandatory=True) # Input floating file - flo_file = File(exists=True, - desc='The input floating/source image', - argstr='-flo %s', - mandatory=True) + flo_file = File( + exists=True, + desc='The input floating/source image', + argstr='-flo %s', + mandatory=True) # Input Affine file - aff_file = File(exists=True, - desc='The input affine transformation file', - argstr='-aff %s') + aff_file = File( + exists=True, + desc='The input affine transformation file', + argstr='-aff %s') # Input cpp file - incpp_file = File(exists=True, - desc='The input cpp transformation file', - argstr='-incpp %s') + incpp_file = File( + exists=True, + desc='The input cpp transformation file', + argstr='-incpp %s') # Reference mask - rmask_file = File(exists=True, - desc='Reference image mask', - argstr='-rmask %s') + rmask_file = File( + exists=True, desc='Reference image mask', argstr='-rmask %s') # Smoothing kernel for reference desc = 'Smoothing kernel width for reference image' @@ -206,51 +205,52 @@ class RegF3DInputSpec(NiftyRegCommandInputSpec): flo_smooth_val = traits.Float(desc=desc, argstr='-smooF %f') # Lower threshold for reference image - rlwth_thr_val = traits.Float(desc='Lower threshold for reference image', - argstr='--rLwTh %f') + rlwth_thr_val = traits.Float( + desc='Lower threshold for reference image', argstr='--rLwTh %f') # Upper threshold for reference image - rupth_thr_val = traits.Float(desc='Upper threshold for reference image', - argstr='--rUpTh %f') + rupth_thr_val = traits.Float( + desc='Upper threshold for reference image', argstr='--rUpTh %f') # Lower threshold for reference image - flwth_thr_val = traits.Float(desc='Lower threshold for floating image', - argstr='--fLwTh %f') + flwth_thr_val = traits.Float( + desc='Lower threshold for floating image', argstr='--fLwTh %f') # Upper threshold for reference image - fupth_thr_val = traits.Float(desc='Upper threshold for floating image', - argstr='--fUpTh %f') + fupth_thr_val = traits.Float( + desc='Upper threshold for floating image', argstr='--fUpTh %f') # Lower threshold for reference image desc = 'Lower threshold for reference image at the specified time point' - rlwth2_thr_val = traits.Tuple(traits.Range(low=0), traits.Float, - desc=desc, argstr='-rLwTh %d %f') + rlwth2_thr_val = traits.Tuple( + traits.Range(low=0), traits.Float, desc=desc, argstr='-rLwTh %d %f') # Upper threshold for reference image desc = 'Upper threshold for reference image at the specified time point' - rupth2_thr_val = traits.Tuple(traits.Range(low=0), traits.Float, - desc=desc, argstr='-rUpTh %d %f') + rupth2_thr_val = traits.Tuple( + traits.Range(low=0), traits.Float, desc=desc, argstr='-rUpTh %d %f') # Lower threshold for reference image desc = 'Lower threshold for floating image at the specified time point' - flwth2_thr_val = traits.Tuple(traits.Range(low=0), traits.Float, - desc=desc, argstr='-fLwTh %d %f') + flwth2_thr_val = traits.Tuple( + traits.Range(low=0), traits.Float, desc=desc, argstr='-fLwTh %d %f') # Upper threshold for reference image desc = 'Upper threshold for floating image at the specified time point' - fupth2_thr_val = traits.Tuple(traits.Range(low=0), traits.Float, - desc=desc, argstr='-fUpTh %d %f') + fupth2_thr_val = traits.Tuple( + traits.Range(low=0), traits.Float, desc=desc, argstr='-fUpTh %d %f') # Final grid spacing along the 3 axes - sx_val = traits.Float(desc='Final grid spacing along the x axes', - argstr='-sx %f') - sy_val = traits.Float(desc='Final grid spacing along the y axes', - argstr='-sy %f') - sz_val = traits.Float(desc='Final grid spacing along the z axes', - argstr='-sz %f') + sx_val = traits.Float( + desc='Final grid spacing along the x axes', argstr='-sx %f') + sy_val = traits.Float( + desc='Final grid spacing along the y axes', argstr='-sy %f') + sz_val = traits.Float( + desc='Final grid spacing along the z axes', argstr='-sz %f') # Regularisation options be_val = traits.Float(desc='Bending energy value', argstr='-be %f') - le_val = traits.Float(desc='Linear elasticity penalty term', - argstr='-le %f') - jl_val = traits.Float(desc='Log of jacobian of deformation penalty value', - argstr='-jl %f') + le_val = traits.Float( + desc='Linear elasticity penalty term', argstr='-le %f') + jl_val = traits.Float( + desc='Log of jacobian of deformation penalty value', argstr='-jl %f') desc = 'Do not approximate the log of jacobian penalty at control points \ only' + no_app_jl_flag = traits.Bool(argstr='-noAppJL', desc=desc) # Similarity measure options @@ -262,57 +262,63 @@ class RegF3DInputSpec(NiftyRegCommandInputSpec): fbn_val = traits.Range(low=0, desc=desc, argstr='--fbn %d') desc = 'Number of bins in the histogram for reference image for given \ time point' - rbn2_val = traits.Tuple(traits.Range(low=0), traits.Range(low=0), - desc=desc, argstr='-rbn %d %d') + + rbn2_val = traits.Tuple( + traits.Range(low=0), + traits.Range(low=0), + desc=desc, + argstr='-rbn %d %d') desc = 'Number of bins in the histogram for reference image for given \ time point' - fbn2_val = traits.Tuple(traits.Range(low=0), traits.Range(low=0), - desc=desc, argstr='-fbn %d %d') - lncc_val = traits.Float(desc='SD of the Gaussian for computing LNCC', - argstr='--lncc %f') + fbn2_val = traits.Tuple( + traits.Range(low=0), + traits.Range(low=0), + desc=desc, + argstr='-fbn %d %d') + + lncc_val = traits.Float( + desc='SD of the Gaussian for computing LNCC', argstr='--lncc %f') desc = 'SD of the Gaussian for computing LNCC for a given time point' - lncc2_val = traits.Tuple(traits.Range(low=0), traits.Float, - desc=desc, argstr='-lncc %d %f') + lncc2_val = traits.Tuple( + traits.Range(low=0), traits.Float, desc=desc, argstr='-lncc %d %f') - ssd_flag = traits.Bool(desc='Use SSD as the similarity measure', - argstr='--ssd') + ssd_flag = traits.Bool( + desc='Use SSD as the similarity measure', argstr='--ssd') desc = 'Use SSD as the similarity measure for a given time point' ssd2_flag = traits.Range(low=0, desc=desc, argstr='-ssd %d') - kld_flag = traits.Bool(desc='Use KL divergence as the similarity measure', - argstr='--kld') + kld_flag = traits.Bool( + desc='Use KL divergence as the similarity measure', argstr='--kld') desc = 'Use KL divergence as the similarity measure for a given time point' kld2_flag = traits.Range(low=0, desc=desc, argstr='-kld %d') amc_flag = traits.Bool(desc='Use additive NMI', argstr='-amc') - nox_flag = traits.Bool(desc="Don't optimise in x direction", - argstr='-nox') - noy_flag = traits.Bool(desc="Don't optimise in y direction", - argstr='-noy') - noz_flag = traits.Bool(desc="Don't optimise in z direction", - argstr='-noz') + nox_flag = traits.Bool(desc="Don't optimise in x direction", argstr='-nox') + noy_flag = traits.Bool(desc="Don't optimise in y direction", argstr='-noy') + noz_flag = traits.Bool(desc="Don't optimise in z direction", argstr='-noz') # Optimization options - maxit_val = traits.Range(low=0, argstr='-maxit %d', - desc='Maximum number of iterations per level') - ln_val = traits.Range(low=0, argstr='-ln %d', - desc='Number of resolution levels to create') - lp_val = traits.Range(low=0, argstr='-lp %d', - desc='Number of resolution levels to perform') - nopy_flag = traits.Bool(desc='Do not use the multiresolution approach', - argstr='-nopy') - noconj_flag = traits.Bool(desc='Use simple GD optimization', - argstr='-noConj') + maxit_val = traits.Range( + low=0, + argstr='-maxit %d', + desc='Maximum number of iterations per level') + ln_val = traits.Range( + low=0, argstr='-ln %d', desc='Number of resolution levels to create') + lp_val = traits.Range( + low=0, argstr='-lp %d', desc='Number of resolution levels to perform') + nopy_flag = traits.Bool( + desc='Do not use the multiresolution approach', argstr='-nopy') + noconj_flag = traits.Bool( + desc='Use simple GD optimization', argstr='-noConj') desc = 'Add perturbation steps after each optimization step' pert_val = traits.Range(low=0, desc=desc, argstr='-pert %d') # F3d2 options - vel_flag = traits.Bool(desc='Use velocity field integration', - argstr='-vel') - fmask_file = File(exists=True, - desc='Floating image mask', - argstr='-fmask %s') + vel_flag = traits.Bool( + desc='Use velocity field integration', argstr='-vel') + fmask_file = File( + exists=True, desc='Floating image mask', argstr='-fmask %s') # Other options desc = 'Kernel width for smoothing the metric gradient' @@ -320,19 +326,21 @@ class RegF3DInputSpec(NiftyRegCommandInputSpec): # Padding value pad_val = traits.Float(desc='Padding value', argstr='-pad %f') # verbosity off - verbosity_off_flag = traits.Bool(argstr='-voff', - desc='Turn off verbose output') + verbosity_off_flag = traits.Bool( + argstr='-voff', desc='Turn off verbose output') # Output CPP image file - cpp_file = File(name_source=['flo_file'], - name_template='%s_cpp.nii.gz', - desc='The output CPP file', - argstr='-cpp %s') + cpp_file = File( + name_source=['flo_file'], + name_template='%s_cpp.nii.gz', + desc='The output CPP file', + argstr='-cpp %s') # Output warped image file - res_file = File(name_source=['flo_file'], - name_template='%s_res.nii.gz', - desc='The output resampled image', - argstr='-res %s') + res_file = File( + name_source=['flo_file'], + name_template='%s_res.nii.gz', + desc='The output resampled image', + argstr='-res %s') class RegF3DOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyreg/regutils.py b/nipype/interfaces/niftyreg/regutils.py index 4bbb73c687..7c3ed28eaf 100644 --- a/nipype/interfaces/niftyreg/regutils.py +++ b/nipype/interfaces/niftyreg/regutils.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """The regutils module provides classes for interfacing with the `niftyreg `_ utility command line tools. @@ -28,37 +27,45 @@ class RegResampleInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegResample. """ # Input reference file - ref_file = File(exists=True, - desc='The input reference/target image', - argstr='-ref %s', - mandatory=True) + ref_file = File( + exists=True, + desc='The input reference/target image', + argstr='-ref %s', + mandatory=True) # Input floating file - flo_file = File(exists=True, - desc='The input floating/source image', - argstr='-flo %s', - mandatory=True) + flo_file = File( + exists=True, + desc='The input floating/source image', + argstr='-flo %s', + mandatory=True) # Input deformation field - trans_file = File(exists=True, - desc='The input transformation file', - argstr='-trans %s') + trans_file = File( + exists=True, desc='The input transformation file', argstr='-trans %s') - type = traits.Enum('res', 'blank', - argstr='-%s', - position=-2, - usedefault=True, - desc='Type of output') + type = traits.Enum( + 'res', + 'blank', + argstr='-%s', + position=-2, + usedefault=True, + desc='Type of output') # Output file name - out_file = File(name_source=['flo_file'], - name_template='%s', - argstr='%s', - position=-1, - desc='The output filename of the transformed image') + out_file = File( + name_source=['flo_file'], + name_template='%s', + argstr='%s', + position=-1, + desc='The output filename of the transformed image') # Interpolation type - inter_val = traits.Enum('NN', 'LIN', 'CUB', 'SINC', - desc='Interpolation type', - argstr='-inter %d') + inter_val = traits.Enum( + 'NN', + 'LIN', + 'CUB', + 'SINC', + desc='Interpolation type', + argstr='-inter %d') # Padding value pad_val = traits.Float(desc='Padding value', argstr='-pad %f') @@ -67,14 +74,16 @@ class RegResampleInputSpec(NiftyRegCommandInputSpec): tensor_flag = traits.Bool(desc='Resample Tensor Map', argstr='-tensor ') # Verbosity off - verbosity_off_flag = traits.Bool(argstr='-voff', - desc='Turn off verbose output') + verbosity_off_flag = traits.Bool( + argstr='-voff', desc='Turn off verbose output') # PSF flag desc = 'Perform the resampling in two steps to resample an image to a \ lower resolution' + psf_flag = traits.Bool(argstr='-psf', desc=desc) desc = 'Minimise the matrix metric (0) or the determinant (1) when \ estimating the PSF [0]' + psf_alg = traits.Enum(0, 1, argstr='-psf_alg %d', desc=desc) @@ -128,24 +137,27 @@ class RegJacobianInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegJacobian. """ # Reference file name desc = 'Reference/target file (required if specifying CPP transformations.' - ref_file = File(exists=True, - desc=desc, - argstr='-ref %s') + ref_file = File(exists=True, desc=desc, argstr='-ref %s') # Input transformation file - trans_file = File(exists=True, - desc='The input non-rigid transformation', - argstr='-trans %s', - mandatory=True) - type = traits.Enum('jac', 'jacL', 'jacM', - usedefault=True, - argstr='-%s', - position=-2, - desc='Type of jacobian outcome') - out_file = File(name_source=['trans_file'], - name_template='%s', - desc='The output jacobian determinant file name', - argstr='%s', - position=-1) + trans_file = File( + exists=True, + desc='The input non-rigid transformation', + argstr='-trans %s', + mandatory=True) + type = traits.Enum( + 'jac', + 'jacL', + 'jacM', + usedefault=True, + argstr='-%s', + position=-2, + desc='Type of jacobian outcome') + out_file = File( + name_source=['trans_file'], + name_template='%s', + desc='The output jacobian determinant file name', + argstr='%s', + position=-1) class RegJacobianOutputSpec(TraitedSpec): @@ -186,28 +198,31 @@ def _overload_extension(self, value, name=None): class RegToolsInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegTools. """ # Input image file - in_file = File(exists=True, - desc='The input image file path', - argstr='-in %s', - mandatory=True) + in_file = File( + exists=True, + desc='The input image file path', + argstr='-in %s', + mandatory=True) # Output file path - out_file = File(name_source=['in_file'], - name_template='%s_tools.nii.gz', - desc='The output file name', - argstr='-out %s') + out_file = File( + name_source=['in_file'], + name_template='%s_tools.nii.gz', + desc='The output file name', + argstr='-out %s') # Make the output image isotropic iso_flag = traits.Bool(argstr='-iso', desc='Make output image isotropic') # Set scale, slope to 0 and 1. - noscl_flag = traits.Bool(argstr='-noscl', - desc='Set scale, slope to 0 and 1') + noscl_flag = traits.Bool( + argstr='-noscl', desc='Set scale, slope to 0 and 1') # Values outside the mask are set to NaN - mask_file = File(exists=True, - desc='Values outside the mask are set to NaN', - argstr='-nan %s') + mask_file = File( + exists=True, + desc='Values outside the mask are set to NaN', + argstr='-nan %s') # Threshold the input image desc = 'Binarise the input image with the given threshold' @@ -217,50 +232,68 @@ class RegToolsInputSpec(NiftyRegCommandInputSpec): bin_flag = traits.Bool(argstr='-bin', desc='Binarise the input image') # Compute the mean RMS between the two images - rms_val = File(exists=True, - desc='Compute the mean RMS between the images', - argstr='-rms %s') + rms_val = File( + exists=True, + desc='Compute the mean RMS between the images', + argstr='-rms %s') # Perform division by image or value - div_val = traits.Either(traits.Float, File(exists=True), - desc='Divide the input by image or value', - argstr='-div %s') + div_val = traits.Either( + traits.Float, + File(exists=True), + desc='Divide the input by image or value', + argstr='-div %s') # Perform multiplication by image or value - mul_val = traits.Either(traits.Float, File(exists=True), - desc='Multiply the input by image or value', - argstr='-mul %s') + mul_val = traits.Either( + traits.Float, + File(exists=True), + desc='Multiply the input by image or value', + argstr='-mul %s') # Perform addition by image or value - add_val = traits.Either(traits.Float, File(exists=True), - desc='Add to the input image or value', - argstr='-add %s') + add_val = traits.Either( + traits.Float, + File(exists=True), + desc='Add to the input image or value', + argstr='-add %s') # Perform subtraction by image or value - sub_val = traits.Either(traits.Float, File(exists=True), - desc='Add to the input image or value', - argstr='-sub %s') + sub_val = traits.Either( + traits.Float, + File(exists=True), + desc='Add to the input image or value', + argstr='-sub %s') # Downsample the image by a factor of 2. - down_flag = traits.Bool(desc='Downsample the image by a factor of 2', - argstr='-down') + down_flag = traits.Bool( + desc='Downsample the image by a factor of 2', argstr='-down') # Smoothing using spline kernel desc = 'Smooth the input image using a cubic spline kernel' - smo_s_val = traits.Tuple(traits.Float, traits.Float, traits.Float, - desc=desc, - argstr='-smoS %f %f %f') + smo_s_val = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + desc=desc, + argstr='-smoS %f %f %f') # Change the resolution of the input image - chg_res_val = traits.Tuple(traits.Float, traits.Float, traits.Float, - desc='Change the resolution of the input image', - argstr='-chgres %f %f %f') + chg_res_val = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + desc='Change the resolution of the input image', + argstr='-chgres %f %f %f') # Smoothing using Gaussian kernel desc = 'Smooth the input image using a Gaussian kernel' - smo_g_val = traits.Tuple(traits.Float, traits.Float, traits.Float, - desc=desc, - argstr='-smoG %f %f %f') + smo_g_val = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + desc=desc, + argstr='-smoG %f %f %f') class RegToolsOutputSpec(TraitedSpec): @@ -296,74 +329,94 @@ class RegTools(NiftyRegCommand): class RegAverageInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegAverage. """ - avg_files = traits.List(File(exist=True), - position=1, - argstr='-avg %s', - sep=' ', - xor=['avg_lts_files', 'avg_ref_file', - 'demean1_ref_file', 'demean2_ref_file', - 'demean3_ref_file', 'warp_files'], - desc='Averaging of images/affine transformations') + avg_files = traits.List( + File(exist=True), + position=1, + argstr='-avg %s', + sep=' ', + xor=[ + 'avg_lts_files', 'avg_ref_file', 'demean1_ref_file', + 'demean2_ref_file', 'demean3_ref_file', 'warp_files' + ], + desc='Averaging of images/affine transformations') desc = 'Robust average of affine transformations' - avg_lts_files = traits.List(File(exist=True), - position=1, - argstr='-avg_lts %s', - sep=' ', - xor=['avg_files', 'avg_ref_file', - 'demean1_ref_file', 'demean2_ref_file', - 'demean3_ref_file', 'warp_files'], - desc=desc) + avg_lts_files = traits.List( + File(exist=True), + position=1, + argstr='-avg_lts %s', + sep=' ', + xor=[ + 'avg_files', 'avg_ref_file', 'demean1_ref_file', + 'demean2_ref_file', 'demean3_ref_file', 'warp_files' + ], + desc=desc) desc = 'All input images are resampled into the space of \ and averaged. A cubic spline interpolation scheme is used for resampling' - avg_ref_file = File(position=1, - argstr='-avg_tran %s', - xor=['avg_files', 'avg_lts_files', 'demean1_ref_file', - 'demean2_ref_file', 'demean3_ref_file'], - requires=['warp_files'], - desc=desc) + + avg_ref_file = File( + position=1, + argstr='-avg_tran %s', + xor=[ + 'avg_files', 'avg_lts_files', 'demean1_ref_file', + 'demean2_ref_file', 'demean3_ref_file' + ], + requires=['warp_files'], + desc=desc) desc = 'Average images and demean average image that have affine \ transformations to a common space' - demean1_ref_file = File(position=1, - argstr='-demean1 %s', - xor=['avg_files', 'avg_lts_files', 'avg_ref_file', - 'demean2_ref_file', 'demean3_ref_file'], - requires=['warp_files'], - desc=desc) + + demean1_ref_file = File( + position=1, + argstr='-demean1 %s', + xor=[ + 'avg_files', 'avg_lts_files', 'avg_ref_file', 'demean2_ref_file', + 'demean3_ref_file' + ], + requires=['warp_files'], + desc=desc) desc = 'Average images and demean average image that have non-rigid \ transformations to a common space' - demean2_ref_file = File(position=1, - argstr='-demean2 %s', - xor=['avg_files', 'avg_lts_files', 'avg_ref_file', - 'demean1_ref_file', 'demean3_ref_file'], - requires=['warp_files'], - desc=desc) + + demean2_ref_file = File( + position=1, + argstr='-demean2 %s', + xor=[ + 'avg_files', 'avg_lts_files', 'avg_ref_file', 'demean1_ref_file', + 'demean3_ref_file' + ], + requires=['warp_files'], + desc=desc) desc = 'Average images and demean average image that have linear and \ non-rigid transformations to a common space' - demean3_ref_file = File(position=1, - argstr='-demean3 %s', - xor=['avg_files', 'avg_lts_files', 'avg_ref_file', - 'demean1_ref_file', 'demean2_ref_file'], - requires=['warp_files'], - desc=desc) + + demean3_ref_file = File( + position=1, + argstr='-demean3 %s', + xor=[ + 'avg_files', 'avg_lts_files', 'avg_ref_file', 'demean1_ref_file', + 'demean2_ref_file' + ], + requires=['warp_files'], + desc=desc) desc = 'transformation files and floating image pairs/triplets to the \ reference space' - warp_files = traits.List(File(exist=True), - position=-1, - argstr='%s', - sep=' ', - xor=['avg_files', 'avg_lts_files'], - desc=desc) - out_file = File(genfile=True, - position=0, - desc='Output file name', - argstr='%s') + warp_files = traits.List( + File(exist=True), + position=-1, + argstr='%s', + sep=' ', + xor=['avg_files', 'avg_lts_files'], + desc=desc) + + out_file = File( + genfile=True, position=0, desc='Output file name', argstr='%s') class RegAverageOutputSpec(TraitedSpec): @@ -447,147 +500,181 @@ def cmdline(self): class RegTransformInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegTransform. """ - ref1_file = File(exists=True, - desc='The input reference/target image', - argstr='-ref %s', - position=0) - - ref2_file = File(exists=True, - desc='The input second reference/target image', - argstr='-ref2 %s', - position=1, - requires=['ref1_file']) - - def_input = File(exists=True, - argstr='-def %s', - position=-2, - desc='Compute deformation field from transformation', - xor=['disp_input', 'flow_input', 'comp_input', - 'upd_s_form_input', 'inv_aff_input', - 'inv_nrr_input', 'half_input', 'make_aff_input', - 'aff_2_rig_input', 'flirt_2_nr_input']) - - disp_input = File(exists=True, - argstr='-disp %s', - position=-2, - desc='Compute displacement field from transformation', - xor=['def_input', 'flow_input', 'comp_input', - 'upd_s_form_input', 'inv_aff_input', - 'inv_nrr_input', 'half_input', 'make_aff_input', - 'aff_2_rig_input', 'flirt_2_nr_input']) - - flow_input = File(exists=True, - argstr='-flow %s', - position=-2, - desc='Compute flow field from spline SVF', - xor=['def_input', 'disp_input', 'comp_input', - 'upd_s_form_input', 'inv_aff_input', - 'inv_nrr_input', 'half_input', 'make_aff_input', - 'aff_2_rig_input', 'flirt_2_nr_input']) - - comp_input = File(exists=True, - argstr='-comp %s', - position=-3, - desc='compose two transformations', - xor=['def_input', 'disp_input', 'flow_input', - 'upd_s_form_input', 'inv_aff_input', - 'inv_nrr_input', 'half_input', 'make_aff_input', - 'aff_2_rig_input', 'flirt_2_nr_input'], - requires=['comp_input2']) - - comp_input2 = File(exists=True, - argstr='%s', - position=-2, - desc='compose two transformations') + ref1_file = File( + exists=True, + desc='The input reference/target image', + argstr='-ref %s', + position=0) + + ref2_file = File( + exists=True, + desc='The input second reference/target image', + argstr='-ref2 %s', + position=1, + requires=['ref1_file']) + + def_input = File( + exists=True, + argstr='-def %s', + position=-2, + desc='Compute deformation field from transformation', + xor=[ + 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', + 'aff_2_rig_input', 'flirt_2_nr_input' + ]) + + disp_input = File( + exists=True, + argstr='-disp %s', + position=-2, + desc='Compute displacement field from transformation', + xor=[ + 'def_input', 'flow_input', 'comp_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', + 'aff_2_rig_input', 'flirt_2_nr_input' + ]) + + flow_input = File( + exists=True, + argstr='-flow %s', + position=-2, + desc='Compute flow field from spline SVF', + xor=[ + 'def_input', 'disp_input', 'comp_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', + 'aff_2_rig_input', 'flirt_2_nr_input' + ]) + + comp_input = File( + exists=True, + argstr='-comp %s', + position=-3, + desc='compose two transformations', + xor=[ + 'def_input', 'disp_input', 'flow_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', + 'aff_2_rig_input', 'flirt_2_nr_input' + ], + requires=['comp_input2']) + + comp_input2 = File( + exists=True, + argstr='%s', + position=-2, + desc='compose two transformations') desc = 'Update s-form using the affine transformation' - upd_s_form_input = File(exists=True, - argstr='-updSform %s', - position=-3, - desc=desc, - xor=['def_input', 'disp_input', 'flow_input', - 'comp_input', 'inv_aff_input', - 'inv_nrr_input', 'half_input', - 'make_aff_input', 'aff_2_rig_input', - 'flirt_2_nr_input'], - requires=['upd_s_form_input2']) + upd_s_form_input = File( + exists=True, + argstr='-updSform %s', + position=-3, + desc=desc, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', + 'aff_2_rig_input', 'flirt_2_nr_input' + ], + requires=['upd_s_form_input2']) desc = 'Update s-form using the affine transformation' - upd_s_form_input2 = File(exists=True, - argstr='%s', - position=-2, - desc=desc, - requires=['upd_s_form_input']) - - inv_aff_input = File(exists=True, - argstr='-invAff %s', - position=-2, - desc='Invert an affine transformation', - xor=['def_input', 'disp_input', 'flow_input', - 'comp_input', 'upd_s_form_input', - 'inv_nrr_input', 'half_input', 'make_aff_input', - 'aff_2_rig_input', 'flirt_2_nr_input']) - - inv_nrr_input = traits.Tuple(File(exists=True), File(exists=True), - desc='Invert a non-linear transformation', - argstr='-invNrr %s %s', - position=-2, - xor=['def_input', 'disp_input', 'flow_input', - 'comp_input', 'upd_s_form_input', - 'inv_aff_input', 'half_input', - 'make_aff_input', 'aff_2_rig_input', - 'flirt_2_nr_input']) - - half_input = File(exists=True, - argstr='-half %s', - position=-2, - desc='Half way to the input transformation', - xor=['def_input', 'disp_input', 'flow_input', - 'comp_input', 'upd_s_form_input', - 'inv_aff_input', 'inv_nrr_input', 'make_aff_input', - 'aff_2_rig_input', 'flirt_2_nr_input']) + upd_s_form_input2 = File( + exists=True, + argstr='%s', + position=-2, + desc=desc, + requires=['upd_s_form_input']) + + inv_aff_input = File( + exists=True, + argstr='-invAff %s', + position=-2, + desc='Invert an affine transformation', + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ]) + + inv_nrr_input = traits.Tuple( + File(exists=True), + File(exists=True), + desc='Invert a non-linear transformation', + argstr='-invNrr %s %s', + position=-2, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ]) + + half_input = File( + exists=True, + argstr='-half %s', + position=-2, + desc='Half way to the input transformation', + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ]) argstr_tmp = '-makeAff %f %f %f %f %f %f %f %f %f %f %f %f' - make_aff_input = traits.Tuple(traits.Float, traits.Float, traits.Float, - traits.Float, traits.Float, traits.Float, - traits.Float, traits.Float, traits.Float, - traits.Float, traits.Float, traits.Float, - argstr=argstr_tmp, - position=-2, - desc='Make an affine transformation matrix', - xor=['def_input', 'disp_input', 'flow_input', - 'comp_input', 'upd_s_form_input', - 'inv_aff_input', 'inv_nrr_input', - 'half_input', 'aff_2_rig_input', - 'flirt_2_nr_input']) + make_aff_input = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + argstr=argstr_tmp, + position=-2, + desc='Make an affine transformation matrix', + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'aff_2_rig_input', 'flirt_2_nr_input' + ]) desc = 'Extract the rigid component from affine transformation' - aff_2_rig_input = File(exists=True, - argstr='-aff2rig %s', - position=-2, - desc=desc, - xor=['def_input', 'disp_input', 'flow_input', - 'comp_input', 'upd_s_form_input', - 'inv_aff_input', 'inv_nrr_input', 'half_input', - 'make_aff_input', 'flirt_2_nr_input']) + aff_2_rig_input = File( + exists=True, + argstr='-aff2rig %s', + position=-2, + desc=desc, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'flirt_2_nr_input' + ]) desc = 'Convert a FLIRT affine transformation to niftyreg affine \ transformation' - flirt_2_nr_input = traits.Tuple(File(exists=True), File(exists=True), - File(exists=True), - argstr='-flirtAff2NR %s %s %s', - position=-2, - desc=desc, - xor=['def_input', 'disp_input', - 'flow_input', 'comp_input', - 'upd_s_form_input', 'inv_aff_input', - 'inv_nrr_input', 'half_input', - 'make_aff_input', 'aff_2_rig_input']) - - out_file = File(genfile=True, - position=-1, - argstr='%s', - desc='transformation file to write') + + flirt_2_nr_input = traits.Tuple( + File(exists=True), + File(exists=True), + File(exists=True), + argstr='-flirtAff2NR %s %s %s', + position=-2, + desc=desc, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input' + ]) + + out_file = File( + genfile=True, + position=-1, + argstr='%s', + desc='transformation file to write') class RegTransformOutputSpec(TraitedSpec): @@ -619,12 +706,14 @@ class RegTransform(NiftyRegCommand): _suffix = '_trans' def _find_input(self): - inputs = [self.inputs.def_input, self.inputs.disp_input, - self.inputs.flow_input, self.inputs.comp_input, - self.inputs.comp_input2, self.inputs.upd_s_form_input, - self.inputs.inv_aff_input, self.inputs.inv_nrr_input, - self.inputs.half_input, self.inputs.make_aff_input, - self.inputs.aff_2_rig_input, self.inputs.flirt_2_nr_input] + inputs = [ + self.inputs.def_input, self.inputs.disp_input, + self.inputs.flow_input, self.inputs.comp_input, + self.inputs.comp_input2, self.inputs.upd_s_form_input, + self.inputs.inv_aff_input, self.inputs.inv_nrr_input, + self.inputs.half_input, self.inputs.make_aff_input, + self.inputs.aff_2_rig_input, self.inputs.flirt_2_nr_input + ] entries = [] for entry in inputs: if isdefined(entry): @@ -639,8 +728,8 @@ def _find_input(self): def _gen_filename(self, name): if name == 'out_file': if isdefined(self.inputs.make_aff_input): - return self._gen_fname('matrix', suffix=self._suffix, - ext='.txt') + return self._gen_fname( + 'matrix', suffix=self._suffix, ext='.txt') if isdefined(self.inputs.comp_input) and \ isdefined(self.inputs.comp_input2): @@ -648,23 +737,25 @@ def _gen_filename(self, name): _, _, ext2 = split_filename(self.inputs.comp_input2) if ext1 in ['.nii', '.nii.gz', '.hdr', '.img', '.img.gz'] or \ ext2 in ['.nii', '.nii.gz', '.hdr', '.img', '.img.gz']: - return self._gen_fname(bn1, suffix=self._suffix, - ext='.nii.gz') + return self._gen_fname( + bn1, suffix=self._suffix, ext='.nii.gz') else: return self._gen_fname(bn1, suffix=self._suffix, ext=ext1) if isdefined(self.inputs.flirt_2_nr_input): - return self._gen_fname(self.inputs.flirt_2_nr_input[0], - suffix=self._suffix, ext='.txt') + return self._gen_fname( + self.inputs.flirt_2_nr_input[0], + suffix=self._suffix, + ext='.txt') input_to_use = self._find_input() _, _, ext = split_filename(input_to_use) if ext not in ['.nii', '.nii.gz', '.hdr', '.img', '.img.gz']: - return self._gen_fname(input_to_use, suffix=self._suffix, - ext=ext) + return self._gen_fname( + input_to_use, suffix=self._suffix, ext=ext) else: - return self._gen_fname(input_to_use, suffix=self._suffix, - ext='.nii.gz') + return self._gen_fname( + input_to_use, suffix=self._suffix, ext='.nii.gz') return None @@ -682,23 +773,30 @@ def _list_outputs(self): class RegMeasureInputSpec(NiftyRegCommandInputSpec): """ Input Spec for RegMeasure. """ # Input reference file - ref_file = File(exists=True, - desc='The input reference/target image', - argstr='-ref %s', - mandatory=True) + ref_file = File( + exists=True, + desc='The input reference/target image', + argstr='-ref %s', + mandatory=True) # Input floating file - flo_file = File(exists=True, - desc='The input floating/source image', - argstr='-flo %s', - mandatory=True) - measure_type = traits.Enum('ncc', 'lncc', 'nmi', 'ssd', - mandatory=True, - argstr='-%s', - desc='Measure of similarity to compute') - out_file = File(name_source=['flo_file'], - name_template='%s', - argstr='-out %s', - desc='The output text file containing the measure') + flo_file = File( + exists=True, + desc='The input floating/source image', + argstr='-flo %s', + mandatory=True) + measure_type = traits.Enum( + 'ncc', + 'lncc', + 'nmi', + 'ssd', + mandatory=True, + argstr='-%s', + desc='Measure of similarity to compute') + out_file = File( + name_source=['flo_file'], + name_template='%s', + argstr='-out %s', + desc='The output text file containing the measure') class RegMeasureOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py b/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py index ee4b020bd0..95dce2c82e 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py @@ -4,25 +4,28 @@ def test_NiftyRegCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = NiftyRegCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py b/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py index d177916034..0a55d07566 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py @@ -4,91 +4,76 @@ def test_RegAladin_inputs(): - input_map = dict(aff_direct_flag=dict(argstr='-affDirect', - ), - aff_file=dict(argstr='-aff %s', - name_source=['flo_file'], - name_template='%s_aff.txt', - ), - args=dict(argstr='%s', - ), - cog_flag=dict(argstr='-cog', - ), - environ=dict(nohash=True, - usedefault=True, - ), - flo_file=dict(argstr='-flo %s', - mandatory=True, - ), - flo_low_val=dict(argstr='-floLowThr %f', - ), - flo_up_val=dict(argstr='-floUpThr %f', - ), - fmask_file=dict(argstr='-fmask %s', - ), - gpuid_val=dict(argstr='-gpuid %i', - ), - i_val=dict(argstr='-pi %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_aff_file=dict(argstr='-inaff %s', - ), - ln_val=dict(argstr='-ln %d', - ), - lp_val=dict(argstr='-lp %d', - ), - maxit_val=dict(argstr='-maxit %d', - ), - nac_flag=dict(argstr='-nac', - ), - nosym_flag=dict(argstr='-noSym', - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - platform_val=dict(argstr='-platf %i', - ), - ref_file=dict(argstr='-ref %s', - mandatory=True, - ), - ref_low_val=dict(argstr='-refLowThr %f', - ), - ref_up_val=dict(argstr='-refUpThr %f', - ), - res_file=dict(argstr='-res %s', - name_source=['flo_file'], - name_template='%s_res.nii.gz', - ), - rig_only_flag=dict(argstr='-rigOnly', - ), - rmask_file=dict(argstr='-rmask %s', - ), - smoo_f_val=dict(argstr='-smooF %f', - ), - smoo_r_val=dict(argstr='-smooR %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - v_val=dict(argstr='-pv %d', - ), - verbosity_off_flag=dict(argstr='-voff', - ), + input_map = dict( + aff_direct_flag=dict(argstr='-affDirect', ), + aff_file=dict( + argstr='-aff %s', + name_source=['flo_file'], + name_template='%s_aff.txt', + ), + args=dict(argstr='%s', ), + cog_flag=dict(argstr='-cog', ), + environ=dict( + nohash=True, + usedefault=True, + ), + flo_file=dict( + argstr='-flo %s', + mandatory=True, + ), + flo_low_val=dict(argstr='-floLowThr %f', ), + flo_up_val=dict(argstr='-floUpThr %f', ), + fmask_file=dict(argstr='-fmask %s', ), + gpuid_val=dict(argstr='-gpuid %i', ), + i_val=dict(argstr='-pi %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_aff_file=dict(argstr='-inaff %s', ), + ln_val=dict(argstr='-ln %d', ), + lp_val=dict(argstr='-lp %d', ), + maxit_val=dict(argstr='-maxit %d', ), + nac_flag=dict(argstr='-nac', ), + nosym_flag=dict(argstr='-noSym', ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + platform_val=dict(argstr='-platf %i', ), + ref_file=dict( + argstr='-ref %s', + mandatory=True, + ), + ref_low_val=dict(argstr='-refLowThr %f', ), + ref_up_val=dict(argstr='-refUpThr %f', ), + res_file=dict( + argstr='-res %s', + name_source=['flo_file'], + name_template='%s_res.nii.gz', + ), + rig_only_flag=dict(argstr='-rigOnly', ), + rmask_file=dict(argstr='-rmask %s', ), + smoo_f_val=dict(argstr='-smooF %f', ), + smoo_r_val=dict(argstr='-smooR %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + v_val=dict(argstr='-pv %d', ), + verbosity_off_flag=dict(argstr='-voff', ), ) inputs = RegAladin.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegAladin_outputs(): - output_map = dict(aff_file=dict(), - avg_output=dict(), - res_file=dict(), + output_map = dict( + aff_file=dict(), + avg_output=dict(), + res_file=dict(), ) outputs = RegAladin.output_spec() diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py b/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py index 7898d68cd3..d1feaa998d 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py @@ -4,71 +4,98 @@ def test_RegAverage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - avg_files=dict(argstr='-avg %s', - position=1, - sep=' ', - xor=['avg_lts_files', 'avg_ref_file', 'demean1_ref_file', 'demean2_ref_file', 'demean3_ref_file', 'warp_files'], - ), - avg_lts_files=dict(argstr='-avg_lts %s', - position=1, - sep=' ', - xor=['avg_files', 'avg_ref_file', 'demean1_ref_file', 'demean2_ref_file', 'demean3_ref_file', 'warp_files'], - ), - avg_ref_file=dict(argstr='-avg_tran %s', - position=1, - requires=['warp_files'], - xor=['avg_files', 'avg_lts_files', 'demean1_ref_file', 'demean2_ref_file', 'demean3_ref_file'], - ), - demean1_ref_file=dict(argstr='-demean1 %s', - position=1, - requires=['warp_files'], - xor=['avg_files', 'avg_lts_files', 'avg_ref_file', 'demean2_ref_file', 'demean3_ref_file'], - ), - demean2_ref_file=dict(argstr='-demean2 %s', - position=1, - requires=['warp_files'], - xor=['avg_files', 'avg_lts_files', 'avg_ref_file', 'demean1_ref_file', 'demean3_ref_file'], - ), - demean3_ref_file=dict(argstr='-demean3 %s', - position=1, - requires=['warp_files'], - xor=['avg_files', 'avg_lts_files', 'avg_ref_file', 'demean1_ref_file', 'demean2_ref_file'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - out_file=dict(argstr='%s', - genfile=True, - position=0, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warp_files=dict(argstr='%s', - position=-1, - sep=' ', - xor=['avg_files', 'avg_lts_files'], - ), + input_map = dict( + args=dict(argstr='%s', ), + avg_files=dict( + argstr='-avg %s', + position=1, + sep=' ', + xor=[ + 'avg_lts_files', 'avg_ref_file', 'demean1_ref_file', + 'demean2_ref_file', 'demean3_ref_file', 'warp_files' + ], + ), + avg_lts_files=dict( + argstr='-avg_lts %s', + position=1, + sep=' ', + xor=[ + 'avg_files', 'avg_ref_file', 'demean1_ref_file', + 'demean2_ref_file', 'demean3_ref_file', 'warp_files' + ], + ), + avg_ref_file=dict( + argstr='-avg_tran %s', + position=1, + requires=['warp_files'], + xor=[ + 'avg_files', 'avg_lts_files', 'demean1_ref_file', + 'demean2_ref_file', 'demean3_ref_file' + ], + ), + demean1_ref_file=dict( + argstr='-demean1 %s', + position=1, + requires=['warp_files'], + xor=[ + 'avg_files', 'avg_lts_files', 'avg_ref_file', + 'demean2_ref_file', 'demean3_ref_file' + ], + ), + demean2_ref_file=dict( + argstr='-demean2 %s', + position=1, + requires=['warp_files'], + xor=[ + 'avg_files', 'avg_lts_files', 'avg_ref_file', + 'demean1_ref_file', 'demean3_ref_file' + ], + ), + demean3_ref_file=dict( + argstr='-demean3 %s', + position=1, + requires=['warp_files'], + xor=[ + 'avg_files', 'avg_lts_files', 'avg_ref_file', + 'demean1_ref_file', 'demean2_ref_file' + ], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + out_file=dict( + argstr='%s', + genfile=True, + position=0, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warp_files=dict( + argstr='%s', + position=-1, + sep=' ', + xor=['avg_files', 'avg_lts_files'], + ), ) inputs = RegAverage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegAverage_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RegAverage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py b/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py index ba4301e756..9e152e1fbe 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py @@ -4,141 +4,102 @@ def test_RegF3D_inputs(): - input_map = dict(aff_file=dict(argstr='-aff %s', - ), - amc_flag=dict(argstr='-amc', - ), - args=dict(argstr='%s', - ), - be_val=dict(argstr='-be %f', - ), - cpp_file=dict(argstr='-cpp %s', - name_source=['flo_file'], - name_template='%s_cpp.nii.gz', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fbn2_val=dict(argstr='-fbn %d %d', - ), - fbn_val=dict(argstr='--fbn %d', - ), - flo_file=dict(argstr='-flo %s', - mandatory=True, - ), - flo_smooth_val=dict(argstr='-smooF %f', - ), - flwth2_thr_val=dict(argstr='-fLwTh %d %f', - ), - flwth_thr_val=dict(argstr='--fLwTh %f', - ), - fmask_file=dict(argstr='-fmask %s', - ), - fupth2_thr_val=dict(argstr='-fUpTh %d %f', - ), - fupth_thr_val=dict(argstr='--fUpTh %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - incpp_file=dict(argstr='-incpp %s', - ), - jl_val=dict(argstr='-jl %f', - ), - kld2_flag=dict(argstr='-kld %d', - ), - kld_flag=dict(argstr='--kld', - ), - le_val=dict(argstr='-le %f', - ), - ln_val=dict(argstr='-ln %d', - ), - lncc2_val=dict(argstr='-lncc %d %f', - ), - lncc_val=dict(argstr='--lncc %f', - ), - lp_val=dict(argstr='-lp %d', - ), - maxit_val=dict(argstr='-maxit %d', - ), - nmi_flag=dict(argstr='--nmi', - ), - no_app_jl_flag=dict(argstr='-noAppJL', - ), - noconj_flag=dict(argstr='-noConj', - ), - nopy_flag=dict(argstr='-nopy', - ), - nox_flag=dict(argstr='-nox', - ), - noy_flag=dict(argstr='-noy', - ), - noz_flag=dict(argstr='-noz', - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - pad_val=dict(argstr='-pad %f', - ), - pert_val=dict(argstr='-pert %d', - ), - rbn2_val=dict(argstr='-rbn %d %d', - ), - rbn_val=dict(argstr='--rbn %d', - ), - ref_file=dict(argstr='-ref %s', - mandatory=True, - ), - ref_smooth_val=dict(argstr='-smooR %f', - ), - res_file=dict(argstr='-res %s', - name_source=['flo_file'], - name_template='%s_res.nii.gz', - ), - rlwth2_thr_val=dict(argstr='-rLwTh %d %f', - ), - rlwth_thr_val=dict(argstr='--rLwTh %f', - ), - rmask_file=dict(argstr='-rmask %s', - ), - rupth2_thr_val=dict(argstr='-rUpTh %d %f', - ), - rupth_thr_val=dict(argstr='--rUpTh %f', - ), - smooth_grad_val=dict(argstr='-smoothGrad %f', - ), - ssd2_flag=dict(argstr='-ssd %d', - ), - ssd_flag=dict(argstr='--ssd', - ), - sx_val=dict(argstr='-sx %f', - ), - sy_val=dict(argstr='-sy %f', - ), - sz_val=dict(argstr='-sz %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vel_flag=dict(argstr='-vel', - ), - verbosity_off_flag=dict(argstr='-voff', - ), + input_map = dict( + aff_file=dict(argstr='-aff %s', ), + amc_flag=dict(argstr='-amc', ), + args=dict(argstr='%s', ), + be_val=dict(argstr='-be %f', ), + cpp_file=dict( + argstr='-cpp %s', + name_source=['flo_file'], + name_template='%s_cpp.nii.gz', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fbn2_val=dict(argstr='-fbn %d %d', ), + fbn_val=dict(argstr='--fbn %d', ), + flo_file=dict( + argstr='-flo %s', + mandatory=True, + ), + flo_smooth_val=dict(argstr='-smooF %f', ), + flwth2_thr_val=dict(argstr='-fLwTh %d %f', ), + flwth_thr_val=dict(argstr='--fLwTh %f', ), + fmask_file=dict(argstr='-fmask %s', ), + fupth2_thr_val=dict(argstr='-fUpTh %d %f', ), + fupth_thr_val=dict(argstr='--fUpTh %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + incpp_file=dict(argstr='-incpp %s', ), + jl_val=dict(argstr='-jl %f', ), + kld2_flag=dict(argstr='-kld %d', ), + kld_flag=dict(argstr='--kld', ), + le_val=dict(argstr='-le %f', ), + ln_val=dict(argstr='-ln %d', ), + lncc2_val=dict(argstr='-lncc %d %f', ), + lncc_val=dict(argstr='--lncc %f', ), + lp_val=dict(argstr='-lp %d', ), + maxit_val=dict(argstr='-maxit %d', ), + nmi_flag=dict(argstr='--nmi', ), + no_app_jl_flag=dict(argstr='-noAppJL', ), + noconj_flag=dict(argstr='-noConj', ), + nopy_flag=dict(argstr='-nopy', ), + nox_flag=dict(argstr='-nox', ), + noy_flag=dict(argstr='-noy', ), + noz_flag=dict(argstr='-noz', ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + pad_val=dict(argstr='-pad %f', ), + pert_val=dict(argstr='-pert %d', ), + rbn2_val=dict(argstr='-rbn %d %d', ), + rbn_val=dict(argstr='--rbn %d', ), + ref_file=dict( + argstr='-ref %s', + mandatory=True, + ), + ref_smooth_val=dict(argstr='-smooR %f', ), + res_file=dict( + argstr='-res %s', + name_source=['flo_file'], + name_template='%s_res.nii.gz', + ), + rlwth2_thr_val=dict(argstr='-rLwTh %d %f', ), + rlwth_thr_val=dict(argstr='--rLwTh %f', ), + rmask_file=dict(argstr='-rmask %s', ), + rupth2_thr_val=dict(argstr='-rUpTh %d %f', ), + rupth_thr_val=dict(argstr='--rUpTh %f', ), + smooth_grad_val=dict(argstr='-smoothGrad %f', ), + ssd2_flag=dict(argstr='-ssd %d', ), + ssd_flag=dict(argstr='--ssd', ), + sx_val=dict(argstr='-sx %f', ), + sy_val=dict(argstr='-sy %f', ), + sz_val=dict(argstr='-sz %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vel_flag=dict(argstr='-vel', ), + verbosity_off_flag=dict(argstr='-voff', ), ) inputs = RegF3D.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegF3D_outputs(): - output_map = dict(avg_output=dict(), - cpp_file=dict(), - invcpp_file=dict(), - invres_file=dict(), - res_file=dict(), + output_map = dict( + avg_output=dict(), + cpp_file=dict(), + invcpp_file=dict(), + invres_file=dict(), + res_file=dict(), ) outputs = RegF3D.output_spec() diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py b/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py index fd4d81b6a1..036b0bb3e8 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py @@ -4,46 +4,49 @@ def test_RegJacobian_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - out_file=dict(argstr='%s', - name_source=['trans_file'], - name_template='%s', - position=-1, - ), - ref_file=dict(argstr='-ref %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trans_file=dict(argstr='-trans %s', - mandatory=True, - ), - type=dict(argstr='-%s', - position=-2, - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + out_file=dict( + argstr='%s', + name_source=['trans_file'], + name_template='%s', + position=-1, + ), + ref_file=dict(argstr='-ref %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trans_file=dict( + argstr='-trans %s', + mandatory=True, + ), + type=dict( + argstr='-%s', + position=-2, + usedefault=True, + ), ) inputs = RegJacobian.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegJacobian_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RegJacobian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py b/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py index 11b1248e6d..b2e2cb55ff 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py @@ -4,45 +4,50 @@ def test_RegMeasure_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - flo_file=dict(argstr='-flo %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - measure_type=dict(argstr='-%s', - mandatory=True, - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - out_file=dict(argstr='-out %s', - name_source=['flo_file'], - name_template='%s', - ), - ref_file=dict(argstr='-ref %s', - mandatory=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + flo_file=dict( + argstr='-flo %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + measure_type=dict( + argstr='-%s', + mandatory=True, + ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + out_file=dict( + argstr='-out %s', + name_source=['flo_file'], + name_template='%s', + ), + ref_file=dict( + argstr='-ref %s', + mandatory=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = RegMeasure.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegMeasure_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RegMeasure.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py b/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py index 7efa3c5068..56855c7494 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py @@ -4,61 +4,59 @@ def test_RegResample_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - flo_file=dict(argstr='-flo %s', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inter_val=dict(argstr='-inter %d', - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - out_file=dict(argstr='%s', - name_source=['flo_file'], - name_template='%s', - position=-1, - ), - pad_val=dict(argstr='-pad %f', - ), - psf_alg=dict(argstr='-psf_alg %d', - ), - psf_flag=dict(argstr='-psf', - ), - ref_file=dict(argstr='-ref %s', - mandatory=True, - ), - tensor_flag=dict(argstr='-tensor ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trans_file=dict(argstr='-trans %s', - ), - type=dict(argstr='-%s', - position=-2, - usedefault=True, - ), - verbosity_off_flag=dict(argstr='-voff', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + flo_file=dict( + argstr='-flo %s', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inter_val=dict(argstr='-inter %d', ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + out_file=dict( + argstr='%s', + name_source=['flo_file'], + name_template='%s', + position=-1, + ), + pad_val=dict(argstr='-pad %f', ), + psf_alg=dict(argstr='-psf_alg %d', ), + psf_flag=dict(argstr='-psf', ), + ref_file=dict( + argstr='-ref %s', + mandatory=True, + ), + tensor_flag=dict(argstr='-tensor ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trans_file=dict(argstr='-trans %s', ), + type=dict( + argstr='-%s', + position=-2, + usedefault=True, + ), + verbosity_off_flag=dict(argstr='-voff', ), ) inputs = RegResample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegResample_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RegResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py b/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py index 8b8c371638..97ea5e6c92 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py @@ -4,67 +4,56 @@ def test_RegTools_inputs(): - input_map = dict(add_val=dict(argstr='-add %s', - ), - args=dict(argstr='%s', - ), - bin_flag=dict(argstr='-bin', - ), - chg_res_val=dict(argstr='-chgres %f %f %f', - ), - div_val=dict(argstr='-div %s', - ), - down_flag=dict(argstr='-down', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - ), - iso_flag=dict(argstr='-iso', - ), - mask_file=dict(argstr='-nan %s', - ), - mul_val=dict(argstr='-mul %s', - ), - noscl_flag=dict(argstr='-noscl', - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - out_file=dict(argstr='-out %s', - name_source=['in_file'], - name_template='%s_tools.nii.gz', - ), - rms_val=dict(argstr='-rms %s', - ), - smo_g_val=dict(argstr='-smoG %f %f %f', - ), - smo_s_val=dict(argstr='-smoS %f %f %f', - ), - sub_val=dict(argstr='-sub %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thr_val=dict(argstr='-thr %f', - ), + input_map = dict( + add_val=dict(argstr='-add %s', ), + args=dict(argstr='%s', ), + bin_flag=dict(argstr='-bin', ), + chg_res_val=dict(argstr='-chgres %f %f %f', ), + div_val=dict(argstr='-div %s', ), + down_flag=dict(argstr='-down', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + ), + iso_flag=dict(argstr='-iso', ), + mask_file=dict(argstr='-nan %s', ), + mul_val=dict(argstr='-mul %s', ), + noscl_flag=dict(argstr='-noscl', ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + out_file=dict( + argstr='-out %s', + name_source=['in_file'], + name_template='%s_tools.nii.gz', + ), + rms_val=dict(argstr='-rms %s', ), + smo_g_val=dict(argstr='-smoG %f %f %f', ), + smo_s_val=dict(argstr='-smoS %f %f %f', ), + sub_val=dict(argstr='-sub %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thr_val=dict(argstr='-thr %f', ), ) inputs = RegTools.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegTools_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RegTools.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py b/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py index 3730a8b42d..24222a7d7d 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py @@ -4,96 +4,157 @@ def test_RegTransform_inputs(): - input_map = dict(aff_2_rig_input=dict(argstr='-aff2rig %s', - position=-2, - xor=['def_input', 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'flirt_2_nr_input'], - ), - args=dict(argstr='%s', - ), - comp_input=dict(argstr='-comp %s', - position=-3, - requires=['comp_input2'], - xor=['def_input', 'disp_input', 'flow_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - comp_input2=dict(argstr='%s', - position=-2, - ), - def_input=dict(argstr='-def %s', - position=-2, - xor=['disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - disp_input=dict(argstr='-disp %s', - position=-2, - xor=['def_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - environ=dict(nohash=True, - usedefault=True, - ), - flirt_2_nr_input=dict(argstr='-flirtAff2NR %s %s %s', - position=-2, - xor=['def_input', 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'aff_2_rig_input'], - ), - flow_input=dict(argstr='-flow %s', - position=-2, - xor=['def_input', 'disp_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - half_input=dict(argstr='-half %s', - position=-2, - xor=['def_input', 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inv_aff_input=dict(argstr='-invAff %s', - position=-2, - xor=['def_input', 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - inv_nrr_input=dict(argstr='-invNrr %s %s', - position=-2, - xor=['def_input', 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'half_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - make_aff_input=dict(argstr='-makeAff %f %f %f %f %f %f %f %f %f %f %f %f', - position=-2, - xor=['def_input', 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - omp_core_val=dict(argstr='-omp %i', - usedefault=True, - ), - out_file=dict(argstr='%s', - genfile=True, - position=-1, - ), - ref1_file=dict(argstr='-ref %s', - position=0, - ), - ref2_file=dict(argstr='-ref2 %s', - position=1, - requires=['ref1_file'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upd_s_form_input=dict(argstr='-updSform %s', - position=-3, - requires=['upd_s_form_input2'], - xor=['def_input', 'disp_input', 'flow_input', 'comp_input', 'inv_aff_input', 'inv_nrr_input', 'half_input', 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input'], - ), - upd_s_form_input2=dict(argstr='%s', - position=-2, - requires=['upd_s_form_input'], - ), + input_map = dict( + aff_2_rig_input=dict( + argstr='-aff2rig %s', + position=-2, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', + 'half_input', 'make_aff_input', 'flirt_2_nr_input' + ], + ), + args=dict(argstr='%s', ), + comp_input=dict( + argstr='-comp %s', + position=-3, + requires=['comp_input2'], + xor=[ + 'def_input', 'disp_input', 'flow_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + comp_input2=dict( + argstr='%s', + position=-2, + ), + def_input=dict( + argstr='-def %s', + position=-2, + xor=[ + 'disp_input', 'flow_input', 'comp_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + disp_input=dict( + argstr='-disp %s', + position=-2, + xor=[ + 'def_input', 'flow_input', 'comp_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flirt_2_nr_input=dict( + argstr='-flirtAff2NR %s %s %s', + position=-2, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', + 'half_input', 'make_aff_input', 'aff_2_rig_input' + ], + ), + flow_input=dict( + argstr='-flow %s', + position=-2, + xor=[ + 'def_input', 'disp_input', 'comp_input', 'upd_s_form_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + half_input=dict( + argstr='-half %s', + position=-2, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inv_aff_input=dict( + argstr='-invAff %s', + position=-2, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + inv_nrr_input=dict( + argstr='-invNrr %s %s', + position=-2, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + make_aff_input=dict( + argstr='-makeAff %f %f %f %f %f %f %f %f %f %f %f %f', + position=-2, + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'upd_s_form_input', 'inv_aff_input', 'inv_nrr_input', + 'half_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + omp_core_val=dict( + argstr='-omp %i', + usedefault=True, + ), + out_file=dict( + argstr='%s', + genfile=True, + position=-1, + ), + ref1_file=dict( + argstr='-ref %s', + position=0, + ), + ref2_file=dict( + argstr='-ref2 %s', + position=1, + requires=['ref1_file'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upd_s_form_input=dict( + argstr='-updSform %s', + position=-3, + requires=['upd_s_form_input2'], + xor=[ + 'def_input', 'disp_input', 'flow_input', 'comp_input', + 'inv_aff_input', 'inv_nrr_input', 'half_input', + 'make_aff_input', 'aff_2_rig_input', 'flirt_2_nr_input' + ], + ), + upd_s_form_input2=dict( + argstr='%s', + position=-2, + requires=['upd_s_form_input'], + ), ) inputs = RegTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RegTransform_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = RegTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_reg.py b/nipype/interfaces/niftyreg/tests/test_reg.py index eb5566f46f..862760139e 100644 --- a/nipype/interfaces/niftyreg/tests/test_reg.py +++ b/nipype/interfaces/niftyreg/tests/test_reg.py @@ -35,6 +35,7 @@ def test_reg_aladin(): cmd_tmp = '{cmd} -aff {aff} -flo {flo} -omp 4 -ref {ref} -res {res} \ -rmask {rmask}' + expected_cmd = cmd_tmp.format( cmd=get_custom_path('reg_aladin'), aff='im2_aff.txt', @@ -76,6 +77,7 @@ def test_reg_f3d(): cmd_tmp = '{cmd} -be 0.100000 -cpp {cpp} -flo {flo} -le 0.100000 -omp 4 \ -ref {ref} -res {res} -rmask {rmask} -vel' + expected_cmd = cmd_tmp.format( cmd=get_custom_path('reg_f3d'), cpp='im2_cpp.nii.gz', diff --git a/nipype/interfaces/niftyreg/tests/test_regutils.py b/nipype/interfaces/niftyreg/tests/test_regutils.py index 763cb2f443..918d556ab2 100644 --- a/nipype/interfaces/niftyreg/tests/test_regutils.py +++ b/nipype/interfaces/niftyreg/tests/test_regutils.py @@ -6,10 +6,8 @@ from ....utils.filemanip import which from ....testing import example_data -from .. import ( - get_custom_path, RegAverage, RegResample, RegJacobian, - RegTools, RegMeasure, RegTransform -) +from .. import (get_custom_path, RegAverage, RegResample, RegJacobian, + RegTools, RegMeasure, RegTransform) def no_nifty_tool(cmd=None): @@ -43,6 +41,7 @@ def test_reg_resample_res(): cmd_tmp = '{cmd} -flo {flo} -inter 1 -omp 4 -ref {ref} -trans {trans} \ -res {res}' + expected_cmd = cmd_tmp.format( cmd=get_custom_path('reg_resample'), flo=flo_file, @@ -63,6 +62,7 @@ def test_reg_resample_res(): cmd_tmp = '{cmd} -flo {flo} -inter 1 -omp 4 -ref {ref} -trans {trans} \ -blank {blank}' + expected_cmd = cmd_tmp.format( cmd=get_custom_path('reg_resample'), flo=flo_file, @@ -207,14 +207,14 @@ def test_reg_average(): expected_argv = '%s %s -avg %s %s %s -omp 1' % ( get_custom_path('reg_average'), - os.path.join(os.getcwd(), 'avg_out.nii.gz'), - one_file, two_file, three_file) + os.path.join(os.getcwd(), 'avg_out.nii.gz'), one_file, two_file, + three_file) assert argv.decode('utf-8') == expected_argv # Test command line with text file - expected_cmd = ('%s --cmd_file %s' - % (get_custom_path('reg_average'), reg_average_cmd)) + expected_cmd = ('%s --cmd_file %s' % (get_custom_path('reg_average'), + reg_average_cmd)) assert generated_cmd == expected_cmd @@ -235,8 +235,8 @@ def test_reg_average(): expected_argv = '%s %s -avg %s %s %s -omp 1' % ( get_custom_path('reg_average'), - os.path.join(os.getcwd(), 'avg_out.txt'), - one_file, two_file, three_file) + os.path.join(os.getcwd(), 'avg_out.txt'), one_file, two_file, + three_file) assert argv.decode('utf-8') == expected_argv @@ -255,10 +255,10 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = ('%s %s -avg_lts %s %s %s -omp 1' - % (get_custom_path('reg_average'), - os.path.join(os.getcwd(), 'avg_out.txt'), - one_file, two_file, three_file)) + expected_argv = ('%s %s -avg_lts %s %s %s -omp 1' % + (get_custom_path('reg_average'), + os.path.join(os.getcwd(), 'avg_out.txt'), one_file, + two_file, three_file)) assert argv.decode('utf-8') == expected_argv @@ -271,9 +271,9 @@ def test_reg_average(): trans1_file = example_data('roi01.nii') trans2_file = example_data('roi02.nii') trans3_file = example_data('roi03.nii') - nr_average_4.inputs.warp_files = [trans1_file, one_file, - trans2_file, two_file, - trans3_file, three_file] + nr_average_4.inputs.warp_files = [ + trans1_file, one_file, trans2_file, two_file, trans3_file, three_file + ] nr_average_4.inputs.avg_ref_file = ref_file nr_average_4.inputs.omp_core_val = 1 generated_cmd = nr_average_4.cmdline @@ -284,11 +284,11 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = ('%s %s -avg_tran %s -omp 1 %s %s %s %s %s %s' - % (get_custom_path('reg_average'), - os.path.join(os.getcwd(), 'avg_out.nii.gz'), - ref_file, trans1_file, one_file, trans2_file, two_file, - trans3_file, three_file)) + expected_argv = ('%s %s -avg_tran %s -omp 1 %s %s %s %s %s %s' % + (get_custom_path('reg_average'), + os.path.join(os.getcwd(), 'avg_out.nii.gz'), ref_file, + trans1_file, one_file, trans2_file, two_file, + trans3_file, three_file)) assert argv.decode('utf-8') == expected_argv @@ -304,9 +304,10 @@ def test_reg_average(): trans1_file = example_data('roi01.nii') trans2_file = example_data('roi02.nii') trans3_file = example_data('roi03.nii') - nr_average_5.inputs.warp_files = [aff1_file, trans1_file, one_file, - aff2_file, trans2_file, two_file, - aff3_file, trans3_file, three_file] + nr_average_5.inputs.warp_files = [ + aff1_file, trans1_file, one_file, aff2_file, trans2_file, two_file, + aff3_file, trans3_file, three_file + ] nr_average_5.inputs.demean3_ref_file = ref_file nr_average_5.inputs.omp_core_val = 1 generated_cmd = nr_average_5.cmdline @@ -317,13 +318,11 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = ('%s %s -demean3 %s -omp 1 %s %s %s %s %s %s %s %s %s' - % (get_custom_path('reg_average'), - os.path.join(os.getcwd(), 'avg_out.nii.gz'), - ref_file, - aff1_file, trans1_file, one_file, - aff2_file, trans2_file, two_file, - aff3_file, trans3_file, three_file)) + expected_argv = ('%s %s -demean3 %s -omp 1 %s %s %s %s %s %s %s %s %s' % + (get_custom_path('reg_average'), + os.path.join(os.getcwd(), 'avg_out.nii.gz'), ref_file, + aff1_file, trans1_file, one_file, aff2_file, trans2_file, + two_file, aff3_file, trans3_file, three_file)) assert argv.decode('utf-8') == expected_argv diff --git a/nipype/interfaces/niftyseg/__init__.py b/nipype/interfaces/niftyseg/__init__.py index 0cbb101aba..14b391edd5 100644 --- a/nipype/interfaces/niftyseg/__init__.py +++ b/nipype/interfaces/niftyseg/__init__.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The niftyseg module provides classes for interfacing with the `NIFTYSEG `_ command line tools. diff --git a/nipype/interfaces/niftyseg/base.py b/nipype/interfaces/niftyseg/base.py index a84fb9eb62..d68bbcc73b 100644 --- a/nipype/interfaces/niftyseg/base.py +++ b/nipype/interfaces/niftyseg/base.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The niftyseg module provides classes for interfacing with `niftyseg `_ command line tools. @@ -16,7 +15,8 @@ -------- See the docstrings of the individual classes for examples. """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from ..niftyfit.base import NiftyFitCommand diff --git a/nipype/interfaces/niftyseg/em.py b/nipype/interfaces/niftyseg/em.py index f2e7359677..47c0659b30 100644 --- a/nipype/interfaces/niftyseg/em.py +++ b/nipype/interfaces/niftyseg/em.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ Nipype interface for seg_EM. @@ -27,81 +26,95 @@ class EMInputSpec(CommandLineInputSpec): """Input Spec for EM.""" - in_file = File(argstr='-in %s', - exists=True, - mandatory=True, - desc='Input image to segment', - position=4) - - mask_file = File(argstr='-mask %s', - exists=True, - desc='Filename of the ROI for label fusion') + in_file = File( + argstr='-in %s', + exists=True, + mandatory=True, + desc='Input image to segment', + position=4) + + mask_file = File( + argstr='-mask %s', + exists=True, + desc='Filename of the ROI for label fusion') # Priors - no_prior = traits.Int(argstr='-nopriors %s', - mandatory=True, - desc='Number of classes to use without prior', - xor=['prior_4D', 'priors']) - - prior_4D = File(argstr='-prior4D %s', - exists=True, - mandatory=True, - desc='4D file containing the priors', - xor=['no_prior', 'priors']) - - priors = InputMultiPath(argstr='%s', - mandatory=True, - desc='List of priors filepaths.', - xor=['no_prior', 'prior_4D']) + no_prior = traits.Int( + argstr='-nopriors %s', + mandatory=True, + desc='Number of classes to use without prior', + xor=['prior_4D', 'priors']) + + prior_4D = File( + argstr='-prior4D %s', + exists=True, + mandatory=True, + desc='4D file containing the priors', + xor=['no_prior', 'priors']) + + priors = InputMultiPath( + argstr='%s', + mandatory=True, + desc='List of priors filepaths.', + xor=['no_prior', 'prior_4D']) # iterations - max_iter = traits.Int(argstr='-max_iter %s', default=100, - desc='Maximum number of iterations') + max_iter = traits.Int( + argstr='-max_iter %s', + default=100, + desc='Maximum number of iterations') - min_iter = traits.Int(argstr='-min_iter %s', default=0, - desc='Minimun number of iterations') + min_iter = traits.Int( + argstr='-min_iter %s', default=0, desc='Minimun number of iterations') # other options - bc_order_val = traits.Int(argstr='-bc_order %s', default=3, - desc='Polynomial order for the bias field') + bc_order_val = traits.Int( + argstr='-bc_order %s', + default=3, + desc='Polynomial order for the bias field') - mrf_beta_val = traits.Float(argstr='-mrf_beta %s', - desc='Weight of the Markov Random Field') + mrf_beta_val = traits.Float( + argstr='-mrf_beta %s', desc='Weight of the Markov Random Field') desc = 'Bias field correction will run only if the ratio of improvement \ is below bc_thresh. (default=0 [OFF])' + bc_thresh_val = traits.Float(argstr='-bc_thresh %s', default=0, desc=desc) desc = 'Amount of regularization over the diagonal of the covariance \ matrix [above 1]' + reg_val = traits.Float(argstr='-reg %s', desc=desc) desc = 'Outlier detection as in (Van Leemput TMI 2003). is the \ Mahalanobis threshold [recommended between 3 and 7] is a convergence \ ratio below which the outlier detection is going to be done [recommended 0.01]' - outlier_val = traits.Tuple(traits.Float(), traits.Float(), - argstr='-outlier %s %s', - desc=desc) + + outlier_val = traits.Tuple( + traits.Float(), traits.Float(), argstr='-outlier %s %s', desc=desc) desc = 'Relax Priors [relaxation factor: 00 (recommended=2.0)] /only 3D/' - relax_priors = traits.Tuple(traits.Float(), traits.Float(), - argstr='-rf %s %s', - desc=desc) + + relax_priors = traits.Tuple( + traits.Float(), traits.Float(), argstr='-rf %s %s', desc=desc) # outputs - out_file = File(name_source=['in_file'], - name_template='%s_em.nii.gz', - argstr='-out %s', - desc='Output segmentation') - out_bc_file = File(name_source=['in_file'], - name_template='%s_bc_em.nii.gz', - argstr='-bc_out %s', - desc='Output bias corrected image') - out_outlier_file = File(name_source=['in_file'], - name_template='%s_outlier_em.nii.gz', - argstr='-out_outlier %s', - desc='Output outlierness image') + out_file = File( + name_source=['in_file'], + name_template='%s_em.nii.gz', + argstr='-out %s', + desc='Output segmentation') + out_bc_file = File( + name_source=['in_file'], + name_template='%s_bc_em.nii.gz', + argstr='-bc_out %s', + desc='Output bias corrected image') + out_outlier_file = File( + name_source=['in_file'], + name_template='%s_outlier_em.nii.gz', + argstr='-out_outlier %s', + desc='Output outlierness image') class EMOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyseg/label_fusion.py b/nipype/interfaces/niftyseg/label_fusion.py index c1637cb258..471458b743 100644 --- a/nipype/interfaces/niftyseg/label_fusion.py +++ b/nipype/interfaces/niftyseg/label_fusion.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The fusion module provides higher-level interfaces to some of the operations that can be performed with the seg_LabFusion command-line program. @@ -23,51 +22,55 @@ from ..niftyreg.base import get_custom_path from ...utils.filemanip import load_json, save_json, split_filename - warn = warnings.warn warnings.filterwarnings('always', category=UserWarning) class LabelFusionInput(CommandLineInputSpec): """Input Spec for LabelFusion.""" - in_file = File(argstr='-in %s', - exists=True, - mandatory=True, - position=1, - desc='Filename of the 4D integer label image.') - - template_file = File(exists=True, - desc='Registered templates (4D Image)') - - file_to_seg = File(exists=True, - mandatory=True, - desc='Original image to segment (3D Image)') - - mask_file = File(argstr='-mask %s', - exists=True, - desc='Filename of the ROI for label fusion') - - out_file = File(argstr='-out %s', - name_source=['in_file'], - name_template='%s', - desc='Output consensus segmentation') - - prob_flag = traits.Bool(desc='Probabilistic/Fuzzy segmented image', - argstr='-outProb') + in_file = File( + argstr='-in %s', + exists=True, + mandatory=True, + position=1, + desc='Filename of the 4D integer label image.') + + template_file = File(exists=True, desc='Registered templates (4D Image)') + + file_to_seg = File( + exists=True, + mandatory=True, + desc='Original image to segment (3D Image)') + + mask_file = File( + argstr='-mask %s', + exists=True, + desc='Filename of the ROI for label fusion') + + out_file = File( + argstr='-out %s', + name_source=['in_file'], + name_template='%s', + desc='Output consensus segmentation') + + prob_flag = traits.Bool( + desc='Probabilistic/Fuzzy segmented image', argstr='-outProb') desc = 'Verbose level [0 = off, 1 = on, 2 = debug] (default = 0)' - verbose = traits.Enum('0', '1', '2', - desc=desc, - argstr='-v %s') + verbose = traits.Enum('0', '1', '2', desc=desc, argstr='-v %s') desc = 'Only consider non-consensus voxels to calculate statistics' unc = traits.Bool(desc=desc, argstr='-unc') - classifier_type = traits.Enum('STEPS', 'STAPLE', 'MV', 'SBA', - argstr='-%s', - mandatory=True, - position=2, - desc='Type of Classifier Fusion.') + classifier_type = traits.Enum( + 'STEPS', + 'STAPLE', + 'MV', + 'SBA', + argstr='-%s', + mandatory=True, + position=2, + desc='Type of Classifier Fusion.') desc = "Gaussian kernel size in mm to compute the local similarity" kernel_size = traits.Float(desc=desc) @@ -75,11 +78,15 @@ class LabelFusionInput(CommandLineInputSpec): template_num = traits.Int(desc='Number of labels to use') # STAPLE and MV options - sm_ranking = traits.Enum('ALL', 'GNCC', 'ROINCC', 'LNCC', - argstr='-%s', - usedefault=True, - position=3, - desc='Ranking for STAPLE and MV') + sm_ranking = traits.Enum( + 'ALL', + 'GNCC', + 'ROINCC', + 'LNCC', + argstr='-%s', + usedefault=True, + position=3, + desc='Ranking for STAPLE and MV') dilation_roi = traits.Int(desc='Dilation of the ROI ( d>=1 )') @@ -91,12 +98,11 @@ class LabelFusionInput(CommandLineInputSpec): prob_update_flag = traits.Bool(desc=desc, argstr='-prop_update') desc = 'Value of P and Q [ 0 < (P,Q) < 1 ] (default = 0.99 0.99)' - set_pq = traits.Tuple(traits.Float, traits.Float, - argstr='-setPQ %f %f', - desc=desc) + set_pq = traits.Tuple( + traits.Float, traits.Float, argstr='-setPQ %f %f', desc=desc) - mrf_value = traits.Float(argstr='-MRF_beta %f', - desc='MRF prior strength (between 0 and 5)') + mrf_value = traits.Float( + argstr='-MRF_beta %f', desc='MRF prior strength (between 0 and 5)') desc = 'Maximum number of iterations (default = 15).' max_iter = traits.Int(argstr='-max_iter %d', desc=desc) @@ -177,14 +183,17 @@ def get_steps_args(self): if not isdefined(self.inputs.template_file): err = "LabelFusion requires a value for input 'template_file' \ when 'classifier_type' is set to 'STEPS'." + raise NipypeInterfaceError(err) if not isdefined(self.inputs.kernel_size): err = "LabelFusion requires a value for input 'kernel_size' when \ 'classifier_type' is set to 'STEPS'." + raise NipypeInterfaceError(err) if not isdefined(self.inputs.template_num): err = "LabelFusion requires a value for input 'template_num' when \ 'classifier_type' is set to 'STEPS'." + raise NipypeInterfaceError(err) return "-STEPS %f %d %s %s" % (self.inputs.kernel_size, self.inputs.template_num, @@ -202,20 +211,22 @@ def get_staple_args(self, ranking): if not isdefined(self.inputs.template_file): err = "LabelFusion requires a value for input 'tramplate_file' \ when 'classifier_type' is set to '%s' and 'sm_ranking' is set to '%s'." + raise NipypeInterfaceError(err % (classtype, ranking)) if not isdefined(self.inputs.template_num): err = "LabelFusion requires a value for input 'template-num' when \ 'classifier_type' is set to '%s' and 'sm_ranking' is set to '%s'." + raise NipypeInterfaceError(err % (classtype, ranking)) if ranking == 'GNCC': if not isdefined(self.inputs.template_num): err = "LabelFusion requires a value for input 'template_num' \ when 'classifier_type' is set to '%s' and 'sm_ranking' is set to '%s'." + raise NipypeInterfaceError(err % (classtype, ranking)) - return "-%s %d %s %s" % (ranking, - self.inputs.template_num, + return "-%s %d %s %s" % (ranking, self.inputs.template_num, self.inputs.file_to_seg, self.inputs.template_file) @@ -223,15 +234,16 @@ def get_staple_args(self, ranking): if not isdefined(self.inputs.dilation_roi): err = "LabelFusion requires a value for input 'dilation_roi' \ when 'classifier_type' is set to '%s' and 'sm_ranking' is set to '%s'." + raise NipypeInterfaceError(err % (classtype, ranking)) elif self.inputs.dilation_roi < 1: err = "The 'dilation_roi' trait of a LabelFusionInput \ instance must be an integer >= 1, but a value of '%s' was specified." + raise NipypeInterfaceError(err % self.inputs.dilation_roi) - return "-%s %d %d %s %s" % (ranking, - self.inputs.dilation_roi, + return "-%s %d %d %s %s" % (ranking, self.inputs.dilation_roi, self.inputs.template_num, self.inputs.file_to_seg, self.inputs.template_file) @@ -239,10 +251,10 @@ def get_staple_args(self, ranking): if not isdefined(self.inputs.kernel_size): err = "LabelFusion requires a value for input 'kernel_size' \ when 'classifier_type' is set to '%s' and 'sm_ranking' is set to '%s'." + raise NipypeInterfaceError(err % (classtype, ranking)) - return "-%s %f %d %s %s" % (ranking, - self.inputs.kernel_size, + return "-%s %f %d %s %s" % (ranking, self.inputs.kernel_size, self.inputs.template_num, self.inputs.file_to_seg, self.inputs.template_file) @@ -256,30 +268,32 @@ def _overload_extension(self, value, name=None): class CalcTopNCCInputSpec(CommandLineInputSpec): """Input Spec for CalcTopNCC.""" - in_file = File(argstr='-target %s', - exists=True, - mandatory=True, - desc='Target file', - position=1) - - num_templates = traits.Int(argstr='-templates %s', - mandatory=True, - position=2, - desc='Number of Templates') - - in_templates = traits.List(File(exists=True), - argstr="%s", - position=3, - mandatory=True) - - top_templates = traits.Int(argstr='-n %s', - mandatory=True, - position=4, - desc='Number of Top Templates') - - mask_file = File(argstr='-mask %s', - exists=True, - desc='Filename of the ROI for label fusion') + in_file = File( + argstr='-target %s', + exists=True, + mandatory=True, + desc='Target file', + position=1) + + num_templates = traits.Int( + argstr='-templates %s', + mandatory=True, + position=2, + desc='Number of Templates') + + in_templates = traits.List( + File(exists=True), argstr="%s", position=3, mandatory=True) + + top_templates = traits.Int( + argstr='-n %s', + mandatory=True, + position=4, + desc='Number of Top Templates') + + mask_file = File( + argstr='-mask %s', + exists=True, + desc='Filename of the ROI for label fusion') class CalcTopNCCOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyseg/lesions.py b/nipype/interfaces/niftyseg/lesions.py index 489837e6dd..028e751f2e 100644 --- a/nipype/interfaces/niftyseg/lesions.py +++ b/nipype/interfaces/niftyseg/lesions.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ Nipype interface for seg_FillLesions. @@ -25,7 +24,6 @@ from .base import NiftySegCommand from ..niftyreg.base import get_custom_path - warn = warnings.warn warnings.filterwarnings('always', category=UserWarning) @@ -33,17 +31,27 @@ class FillLesionsInputSpec(CommandLineInputSpec): """Input Spec for FillLesions.""" # Mandatory input arguments - in_file = File(argstr='-i %s', exists=True, mandatory=True, - desc='Input image to fill lesions', position=1) - - lesion_mask = File(argstr='-l %s', exists=True, mandatory=True, - desc='Lesion mask', position=2) + in_file = File( + argstr='-i %s', + exists=True, + mandatory=True, + desc='Input image to fill lesions', + position=1) + + lesion_mask = File( + argstr='-l %s', + exists=True, + mandatory=True, + desc='Lesion mask', + position=2) # Output file name - out_file = File(name_source=['in_file'], - name_template='%s_lesions_filled.nii.gz', - desc='The output filename of the fill lesions results', - argstr='-o %s', position=3) + out_file = File( + name_source=['in_file'], + name_template='%s_lesions_filled.nii.gz', + desc='The output filename of the fill lesions results', + argstr='-o %s', + position=3) # Optional arguments desc = "Dilate the mask times (in voxels, by default 0)" @@ -51,14 +59,17 @@ class FillLesionsInputSpec(CommandLineInputSpec): desc = 'Percentage of minimum number of voxels between patches \ (by default 0.5).' + match = traits.Float(desc=desc, argstr='-match %f') desc = 'Minimum percentage of valid voxels in target patch \ (by default 0).' + search = traits.Float(desc=desc, argstr='-search %f') desc = 'Smoothing by (in minimal 6-neighbourhood voxels \ (by default 0.1)).' + smooth = traits.Float(desc=desc, argstr='-smo %f') desc = 'Search regions size respect biggest patch size (by default 4).' @@ -74,20 +85,21 @@ class FillLesionsInputSpec(CommandLineInputSpec): multiresolution/hierarchical inpainting part, this part needs to be done \ with some external software such as reg_tools and reg_resample from NiftyReg. \ By default it uses the method presented in Prados et al. (Neuroimage 2016)." + other = traits.Bool(desc=desc, argstr='-other') - use_2d = traits.Bool(desc='Uses 2D patches in the Z axis, by default 3D.', - argstr='-2D') + use_2d = traits.Bool( + desc='Uses 2D patches in the Z axis, by default 3D.', argstr='-2D') - debug = traits.Bool(desc='Save all intermidium files (by default OFF).', - argstr='-debug') + debug = traits.Bool( + desc='Save all intermidium files (by default OFF).', argstr='-debug') desc = 'Set output (char, short, int, uchar, ushort, uint, \ float, double).' + out_datatype = traits.String(desc=desc, argstr='-odt %s') - verbose = traits.Bool(desc='Verbose (by default OFF).', - argstr='-v') + verbose = traits.Bool(desc='Verbose (by default OFF).', argstr='-v') class FillLesionsOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyseg/maths.py b/nipype/interfaces/niftyseg/maths.py index b8a5c0a1b8..46295bc6bc 100644 --- a/nipype/interfaces/niftyseg/maths.py +++ b/nipype/interfaces/niftyseg/maths.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ Nipype interface for seg_maths. @@ -30,24 +29,31 @@ class MathsInput(CommandLineInputSpec): """Input Spec for seg_maths interfaces.""" - in_file = File(position=2, - argstr='%s', - exists=True, - mandatory=True, - desc='image to operate on') - - out_file = File(name_source=['in_file'], - name_template='%s', - position=-2, - argstr='%s', - desc='image to write') + in_file = File( + position=2, + argstr='%s', + exists=True, + mandatory=True, + desc='image to operate on') + + out_file = File( + name_source=['in_file'], + name_template='%s', + position=-2, + argstr='%s', + desc='image to write') desc = 'datatype to use for output (default uses input type)' - output_datatype = traits.Enum('float', 'char', 'int', 'short', - 'double', 'input', - position=-3, - argstr='-odt %s', - desc=desc) + output_datatype = traits.Enum( + 'float', + 'char', + 'int', + 'short', + 'double', + 'input', + position=-3, + argstr='-odt %s', + desc=desc) class MathsOutput(TraitedSpec): @@ -90,13 +96,34 @@ def _overload_extension(self, value, name=None): class UnaryMathsInput(MathsInput): """Input Spec for seg_maths Unary operations.""" - operation = traits.Enum('sqrt', 'exp', 'log', 'recip', 'abs', 'bin', - 'otsu', 'lconcomp', 'concomp6', 'concomp26', - 'fill', 'euc', 'tpmax', 'tmean', 'tmax', 'tmin', - 'splitlab', 'removenan', 'isnan', 'subsamp2', - 'scl', '4to5', 'range', - argstr='-%s', position=4, mandatory=True, - desc='operation to perform') + operation = traits.Enum( + 'sqrt', + 'exp', + 'log', + 'recip', + 'abs', + 'bin', + 'otsu', + 'lconcomp', + 'concomp6', + 'concomp26', + 'fill', + 'euc', + 'tpmax', + 'tmean', + 'tmax', + 'tmin', + 'splitlab', + 'removenan', + 'isnan', + 'subsamp2', + 'scl', + '4to5', + 'range', + argstr='-%s', + position=4, + mandatory=True, + desc='operation to perform') class UnaryMaths(MathsCommand): @@ -203,35 +230,55 @@ class UnaryMaths(MathsCommand): class BinaryMathsInput(MathsInput): """Input Spec for seg_maths Binary operations.""" - operation = traits.Enum('mul', 'div', 'add', 'sub', 'pow', 'thr', 'uthr', - 'smo', 'edge', 'sobel3', 'sobel5', 'min', 'smol', - 'geo', 'llsnorm', 'masknan', 'hdr_copy', - 'splitinter', - mandatory=True, - argstr='-%s', - position=4, - desc='operation to perform') - - operand_file = File(exists=True, - argstr='%s', - mandatory=True, - position=5, - xor=['operand_value', 'operand_str'], - desc='second image to perform operation with') - - operand_value = traits.Float(argstr='%.8f', - mandatory=True, - position=5, - xor=['operand_file', 'operand_str'], - desc='float value to perform operation with') + operation = traits.Enum( + 'mul', + 'div', + 'add', + 'sub', + 'pow', + 'thr', + 'uthr', + 'smo', + 'edge', + 'sobel3', + 'sobel5', + 'min', + 'smol', + 'geo', + 'llsnorm', + 'masknan', + 'hdr_copy', + 'splitinter', + mandatory=True, + argstr='-%s', + position=4, + desc='operation to perform') + + operand_file = File( + exists=True, + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value', 'operand_str'], + desc='second image to perform operation with') + + operand_value = traits.Float( + argstr='%.8f', + mandatory=True, + position=5, + xor=['operand_file', 'operand_str'], + desc='float value to perform operation with') desc = 'string value to perform operation splitinter' - operand_str = traits.Enum('x', 'y', 'z', - argstr='%s', - mandatory=True, - position=5, - xor=['operand_value', 'operand_file'], - desc=desc) + operand_str = traits.Enum( + 'x', + 'y', + 'z', + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value', 'operand_file'], + desc=desc) class BinaryMaths(MathsCommand): @@ -335,12 +382,15 @@ def _format_arg(self, opt, spec, val): if opt == 'operand_str' and self.inputs.operation != 'splitinter': err = 'operand_str set but with an operation different than \ "splitinter"' + raise NipypeInterfaceError(err) if opt == 'operation': # Only float - if val in ['pow', 'thr', 'uthr', 'smo', 'edge', 'sobel3', 'sobel5', - 'smol']: + if val in [ + 'pow', 'thr', 'uthr', 'smo', 'edge', 'sobel3', 'sobel5', + 'smol' + ]: if not isdefined(self.inputs.operand_value): err = 'operand_value not set for {0}.'.format(val) raise NipypeInterfaceError(err) @@ -372,16 +422,23 @@ def _overload_extension(self, value, name=None): class BinaryMathsInputInteger(MathsInput): """Input Spec for seg_maths Binary operations that require integer.""" - operation = traits.Enum('dil', 'ero', 'tp', 'equal', 'pad', 'crop', - mandatory=True, - argstr='-%s', - position=4, - desc='operation to perform') - - operand_value = traits.Int(argstr='%d', - mandatory=True, - position=5, - desc='int value to perform operation with') + operation = traits.Enum( + 'dil', + 'ero', + 'tp', + 'equal', + 'pad', + 'crop', + mandatory=True, + argstr='-%s', + position=4, + desc='operation to perform') + + operand_value = traits.Int( + argstr='%d', + mandatory=True, + position=5, + desc='int value to perform operation with') class BinaryMathsInteger(MathsCommand): @@ -443,39 +500,46 @@ class BinaryMathsInteger(MathsCommand): class TupleMathsInput(MathsInput): """Input Spec for seg_maths Tuple operations.""" - operation = traits.Enum('lncc', 'lssd', 'lltsnorm', - mandatory=True, - argstr='-%s', - position=4, - desc='operation to perform') - - operand_file1 = File(exists=True, - argstr='%s', - mandatory=True, - position=5, - xor=['operand_value1'], - desc='image to perform operation 1 with') + operation = traits.Enum( + 'lncc', + 'lssd', + 'lltsnorm', + mandatory=True, + argstr='-%s', + position=4, + desc='operation to perform') + + operand_file1 = File( + exists=True, + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value1'], + desc='image to perform operation 1 with') desc = 'float value to perform operation 1 with' - operand_value1 = traits.Float(argstr='%.8f', - mandatory=True, - position=5, - xor=['operand_file1'], - desc=desc) - - operand_file2 = File(exists=True, - argstr='%s', - mandatory=True, - position=6, - xor=['operand_value2'], - desc='image to perform operation 2 with') + operand_value1 = traits.Float( + argstr='%.8f', + mandatory=True, + position=5, + xor=['operand_file1'], + desc=desc) + + operand_file2 = File( + exists=True, + argstr='%s', + mandatory=True, + position=6, + xor=['operand_value2'], + desc='image to perform operation 2 with') desc = 'float value to perform operation 2 with' - operand_value2 = traits.Float(argstr='%.8f', - mandatory=True, - position=6, - xor=['operand_file2'], - desc=desc) + operand_value2 = traits.Float( + argstr='%.8f', + mandatory=True, + position=6, + xor=['operand_file2'], + desc=desc) class TupleMaths(MathsCommand): @@ -540,15 +604,12 @@ class TupleMaths(MathsCommand): class MergeInput(MathsInput): """Input Spec for seg_maths merge operation.""" - dimension = traits.Int(mandatory=True, - desc='Dimension to merge the images.') + dimension = traits.Int( + mandatory=True, desc='Dimension to merge the images.') desc = 'List of images to merge to the working image .' - merge_files = traits.List(File(exists=True), - argstr='%s', - mandatory=True, - position=4, - desc=desc) + merge_files = traits.List( + File(exists=True), argstr='%s', mandatory=True, position=4, desc=desc) class Merge(MathsCommand): diff --git a/nipype/interfaces/niftyseg/patchmatch.py b/nipype/interfaces/niftyseg/patchmatch.py index 207764f086..7aa3a5ae88 100644 --- a/nipype/interfaces/niftyseg/patchmatch.py +++ b/nipype/interfaces/niftyseg/patchmatch.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The fusion module provides higher-level interfaces to some of the operations that can be performed with the seg_DetectLesions command-line program. @@ -19,7 +18,6 @@ from .base import NiftySegCommand from ..niftyreg.base import get_custom_path - warn = warnings.warn warnings.filterwarnings('always', category=UserWarning) @@ -27,49 +25,51 @@ class PatchMatchInputSpec(CommandLineInputSpec): """Input Spec for PatchMatch.""" # Mandatory input arguments - in_file = File(argstr='-i %s', - exists=True, - mandatory=True, - desc='Input image to segment', - position=1) - - mask_file = File(argstr='-m %s', - exists=True, - mandatory=True, - desc='Input mask for the area where applies PatchMatch', - position=2) - - database_file = File(argstr='-db %s', - exists=True, - mandatory=True, - desc='Database with the segmentations', - position=3) + in_file = File( + argstr='-i %s', + exists=True, + mandatory=True, + desc='Input image to segment', + position=1) + + mask_file = File( + argstr='-m %s', + exists=True, + mandatory=True, + desc='Input mask for the area where applies PatchMatch', + position=2) + + database_file = File( + argstr='-db %s', + exists=True, + mandatory=True, + desc='Database with the segmentations', + position=3) # Output file name - out_file = File(name_source=['in_file'], - name_template='%s_pm.nii.gz', - desc='The output filename of the patchmatch results', - argstr='-o %s', - position=4) + out_file = File( + name_source=['in_file'], + name_template='%s_pm.nii.gz', + desc='The output filename of the patchmatch results', + argstr='-o %s', + position=4) # Optional arguments - patch_size = traits.Int(desc="Patch size, #voxels", - argstr='-size %i') + patch_size = traits.Int(desc="Patch size, #voxels", argstr='-size %i') desc = "Constrained search area size, number of times bigger than the \ patchsize" - cs_size = traits.Int(desc=desc, - argstr='-cs %i') - match_num = traits.Int(desc="Number of better matching", - argstr='-match %i') + cs_size = traits.Int(desc=desc, argstr='-cs %i') + + match_num = traits.Int( + desc="Number of better matching", argstr='-match %i') - pm_num = traits.Int(desc="Number of patchmatch executions", - argstr='-pm %i') + pm_num = traits.Int( + desc="Number of patchmatch executions", argstr='-pm %i') desc = "Number of iterations for the patchmatch algorithm" - it_num = traits.Int(desc=desc, - argstr='-it %i') + it_num = traits.Int(desc=desc, argstr='-it %i') class PatchMatchOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/niftyseg/stats.py b/nipype/interfaces/niftyseg/stats.py index cef03b6177..5f57779f35 100644 --- a/nipype/interfaces/niftyseg/stats.py +++ b/nipype/interfaces/niftyseg/stats.py @@ -1,6 +1,5 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ The stats module provides higher-level interfaces to some of the operations that can be performed with the niftyseg stats (seg_stats) command-line program. @@ -22,22 +21,22 @@ class StatsInput(CommandLineInputSpec): """Input Spec for seg_stats interfaces.""" - in_file = File(position=2, - argstr='%s', - exists=True, - mandatory=True, - desc='image to operate on') + in_file = File( + position=2, + argstr='%s', + exists=True, + mandatory=True, + desc='image to operate on') # Constrains - mask_file = File(exists=True, - position=-2, - argstr='-m %s', - desc='statistics within the masked area') + mask_file = File( + exists=True, + position=-2, + argstr='-m %s', + desc='statistics within the masked area') desc = 'Only estimate statistics if voxel is larger than ' - larger_voxel = traits.Float(argstr='-t %f', - position=-3, - desc=desc) + larger_voxel = traits.Float(argstr='-t %f', position=-3, desc=desc) class StatsOutput(TraitedSpec): @@ -87,12 +86,28 @@ def _list_outputs(self): class UnaryStatsInput(StatsInput): """Input Spec for seg_stats unary operations.""" - operation = traits.Enum('r', 'R', 'a', 's', 'v', 'vl', 'vp', 'n', 'np', - 'e', 'ne', 'x', 'X', 'c', 'B', 'xvox', 'xdim', - argstr='-%s', - position=4, - mandatory=True, - desc='operation to perform') + operation = traits.Enum( + 'r', + 'R', + 'a', + 's', + 'v', + 'vl', + 'vp', + 'n', + 'np', + 'e', + 'ne', + 'x', + 'X', + 'c', + 'B', + 'xvox', + 'xdim', + argstr='-%s', + position=4, + mandatory=True, + desc='operation to perform') class UnaryStats(StatsCommand): @@ -176,25 +191,36 @@ class UnaryStats(StatsCommand): class BinaryStatsInput(StatsInput): """Input Spec for seg_stats Binary operations.""" - operation = traits.Enum('p', 'sa', 'ss', 'svp', 'al', 'd', 'ncc', 'nmi', - 'Vl', 'Nl', - mandatory=True, - argstr='-%s', - position=4, - desc='operation to perform') - - operand_file = File(exists=True, - argstr="%s", - mandatory=True, - position=5, - xor=["operand_value"], - desc="second image to perform operation with") - - operand_value = traits.Float(argstr='%.8f', - mandatory=True, - position=5, - xor=["operand_file"], - desc='value to perform operation with') + operation = traits.Enum( + 'p', + 'sa', + 'ss', + 'svp', + 'al', + 'd', + 'ncc', + 'nmi', + 'Vl', + 'Nl', + mandatory=True, + argstr='-%s', + position=4, + desc='operation to perform') + + operand_file = File( + exists=True, + argstr="%s", + mandatory=True, + position=5, + xor=["operand_value"], + desc="second image to perform operation with") + + operand_value = traits.Float( + argstr='%.8f', + mandatory=True, + position=5, + xor=["operand_file"], + desc='value to perform operation with') class BinaryStats(StatsCommand): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py index 5a4a5cd3f3..6a13dae3ac 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py @@ -4,60 +4,67 @@ def test_BinaryMaths_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - operand_file=dict(argstr='%s', - mandatory=True, - position=5, - xor=['operand_value', 'operand_str'], - ), - operand_str=dict(argstr='%s', - mandatory=True, - position=5, - xor=['operand_value', 'operand_file'], - ), - operand_value=dict(argstr='%.8f', - mandatory=True, - position=5, - xor=['operand_file', 'operand_str'], - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s', - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + operand_file=dict( + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value', 'operand_str'], + ), + operand_str=dict( + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value', 'operand_file'], + ), + operand_value=dict( + argstr='%.8f', + mandatory=True, + position=5, + xor=['operand_file', 'operand_str'], + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s', + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BinaryMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BinaryMaths_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = BinaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py index b8ea1f87f7..8e22535d2e 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py @@ -4,49 +4,54 @@ def test_BinaryMathsInteger_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - operand_value=dict(argstr='%d', - mandatory=True, - position=5, - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s', - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + operand_value=dict( + argstr='%d', + mandatory=True, + position=5, + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s', + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BinaryMathsInteger.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BinaryMathsInteger_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = BinaryMathsInteger.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py b/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py index dce54af8dc..e5db899662 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py @@ -4,53 +4,59 @@ def test_BinaryStats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - larger_voxel=dict(argstr='-t %f', - position=-3, - ), - mask_file=dict(argstr='-m %s', - position=-2, - ), - operand_file=dict(argstr='%s', - mandatory=True, - position=5, - xor=['operand_value'], - ), - operand_value=dict(argstr='%.8f', - mandatory=True, - position=5, - xor=['operand_file'], - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + larger_voxel=dict( + argstr='-t %f', + position=-3, + ), + mask_file=dict( + argstr='-m %s', + position=-2, + ), + operand_file=dict( + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value'], + ), + operand_value=dict( + argstr='%.8f', + mandatory=True, + position=5, + xor=['operand_file'], + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BinaryStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BinaryStats_outputs(): - output_map = dict(output=dict(), - ) + output_map = dict(output=dict(), ) outputs = BinaryStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py b/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py index 201f15153a..c2a06f89b4 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py @@ -4,47 +4,50 @@ def test_CalcTopNCC_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-target %s', - mandatory=True, - position=1, - ), - in_templates=dict(argstr='%s', - mandatory=True, - position=3, - ), - mask_file=dict(argstr='-mask %s', - ), - num_templates=dict(argstr='-templates %s', - mandatory=True, - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - top_templates=dict(argstr='-n %s', - mandatory=True, - position=4, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-target %s', + mandatory=True, + position=1, + ), + in_templates=dict( + argstr='%s', + mandatory=True, + position=3, + ), + mask_file=dict(argstr='-mask %s', ), + num_templates=dict( + argstr='-templates %s', + mandatory=True, + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + top_templates=dict( + argstr='-n %s', + mandatory=True, + position=4, + ), ) inputs = CalcTopNCC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CalcTopNCC_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = CalcTopNCC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_EM.py b/nipype/interfaces/niftyseg/tests/test_auto_EM.py index 9790ad9757..715a3cadac 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_EM.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_EM.py @@ -4,76 +4,76 @@ def test_EM_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bc_order_val=dict(argstr='-bc_order %s', - ), - bc_thresh_val=dict(argstr='-bc_thresh %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - position=4, - ), - mask_file=dict(argstr='-mask %s', - ), - max_iter=dict(argstr='-max_iter %s', - ), - min_iter=dict(argstr='-min_iter %s', - ), - mrf_beta_val=dict(argstr='-mrf_beta %s', - ), - no_prior=dict(argstr='-nopriors %s', - mandatory=True, - xor=['prior_4D', 'priors'], - ), - out_bc_file=dict(argstr='-bc_out %s', - name_source=['in_file'], - name_template='%s_bc_em.nii.gz', - ), - out_file=dict(argstr='-out %s', - name_source=['in_file'], - name_template='%s_em.nii.gz', - ), - out_outlier_file=dict(argstr='-out_outlier %s', - name_source=['in_file'], - name_template='%s_outlier_em.nii.gz', - ), - outlier_val=dict(argstr='-outlier %s %s', - ), - prior_4D=dict(argstr='-prior4D %s', - mandatory=True, - xor=['no_prior', 'priors'], - ), - priors=dict(argstr='%s', - mandatory=True, - xor=['no_prior', 'prior_4D'], - ), - reg_val=dict(argstr='-reg %s', - ), - relax_priors=dict(argstr='-rf %s %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bc_order_val=dict(argstr='-bc_order %s', ), + bc_thresh_val=dict(argstr='-bc_thresh %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + position=4, + ), + mask_file=dict(argstr='-mask %s', ), + max_iter=dict(argstr='-max_iter %s', ), + min_iter=dict(argstr='-min_iter %s', ), + mrf_beta_val=dict(argstr='-mrf_beta %s', ), + no_prior=dict( + argstr='-nopriors %s', + mandatory=True, + xor=['prior_4D', 'priors'], + ), + out_bc_file=dict( + argstr='-bc_out %s', + name_source=['in_file'], + name_template='%s_bc_em.nii.gz', + ), + out_file=dict( + argstr='-out %s', + name_source=['in_file'], + name_template='%s_em.nii.gz', + ), + out_outlier_file=dict( + argstr='-out_outlier %s', + name_source=['in_file'], + name_template='%s_outlier_em.nii.gz', + ), + outlier_val=dict(argstr='-outlier %s %s', ), + prior_4D=dict( + argstr='-prior4D %s', + mandatory=True, + xor=['no_prior', 'priors'], + ), + priors=dict( + argstr='%s', + mandatory=True, + xor=['no_prior', 'prior_4D'], + ), + reg_val=dict(argstr='-reg %s', ), + relax_priors=dict(argstr='-rf %s %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = EM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EM_outputs(): - output_map = dict(out_bc_file=dict(), - out_file=dict(), - out_outlier_file=dict(), + output_map = dict( + out_bc_file=dict(), + out_file=dict(), + out_outlier_file=dict(), ) outputs = EM.output_spec() diff --git a/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py b/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py index a95651bf61..3928040987 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py @@ -4,66 +4,57 @@ def test_FillLesions_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bin_mask=dict(argstr='-mask %s', - ), - cwf=dict(argstr='-cwf %f', - ), - debug=dict(argstr='-debug', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_dilation=dict(argstr='-dil %d', - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=1, - ), - lesion_mask=dict(argstr='-l %s', - mandatory=True, - position=2, - ), - match=dict(argstr='-match %f', - ), - other=dict(argstr='-other', - ), - out_datatype=dict(argstr='-odt %s', - ), - out_file=dict(argstr='-o %s', - name_source=['in_file'], - name_template='%s_lesions_filled.nii.gz', - position=3, - ), - search=dict(argstr='-search %f', - ), - size=dict(argstr='-size %d', - ), - smooth=dict(argstr='-smo %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - use_2d=dict(argstr='-2D', - ), - verbose=dict(argstr='-v', - ), + input_map = dict( + args=dict(argstr='%s', ), + bin_mask=dict(argstr='-mask %s', ), + cwf=dict(argstr='-cwf %f', ), + debug=dict(argstr='-debug', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_dilation=dict(argstr='-dil %d', ), + in_file=dict( + argstr='-i %s', + mandatory=True, + position=1, + ), + lesion_mask=dict( + argstr='-l %s', + mandatory=True, + position=2, + ), + match=dict(argstr='-match %f', ), + other=dict(argstr='-other', ), + out_datatype=dict(argstr='-odt %s', ), + out_file=dict( + argstr='-o %s', + name_source=['in_file'], + name_template='%s_lesions_filled.nii.gz', + position=3, + ), + search=dict(argstr='-search %f', ), + size=dict(argstr='-size %d', ), + smooth=dict(argstr='-smo %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + use_2d=dict(argstr='-2D', ), + verbose=dict(argstr='-v', ), ) inputs = FillLesions.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FillLesions_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = FillLesions.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py b/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py index 3530644d7d..29741f98f1 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py @@ -4,73 +4,65 @@ def test_LabelFusion_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - classifier_type=dict(argstr='-%s', - mandatory=True, - position=2, - ), - conv=dict(argstr='-conv %f', - ), - dilation_roi=dict(), - environ=dict(nohash=True, - usedefault=True, - ), - file_to_seg=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - position=1, - ), - kernel_size=dict(), - mask_file=dict(argstr='-mask %s', - ), - max_iter=dict(argstr='-max_iter %d', - ), - mrf_value=dict(argstr='-MRF_beta %f', - ), - out_file=dict(argstr='-out %s', - name_source=['in_file'], - name_template='%s', - ), - prob_flag=dict(argstr='-outProb', - ), - prob_update_flag=dict(argstr='-prop_update', - ), - proportion=dict(argstr='-prop %s', - ), - set_pq=dict(argstr='-setPQ %f %f', - ), - sm_ranking=dict(argstr='-%s', - position=3, - usedefault=True, - ), - template_file=dict(), - template_num=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - unc=dict(argstr='-unc', - ), - unc_thresh=dict(argstr='-uncthres %f', - ), - verbose=dict(argstr='-v %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + classifier_type=dict( + argstr='-%s', + mandatory=True, + position=2, + ), + conv=dict(argstr='-conv %f', ), + dilation_roi=dict(), + environ=dict( + nohash=True, + usedefault=True, + ), + file_to_seg=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + position=1, + ), + kernel_size=dict(), + mask_file=dict(argstr='-mask %s', ), + max_iter=dict(argstr='-max_iter %d', ), + mrf_value=dict(argstr='-MRF_beta %f', ), + out_file=dict( + argstr='-out %s', + name_source=['in_file'], + name_template='%s', + ), + prob_flag=dict(argstr='-outProb', ), + prob_update_flag=dict(argstr='-prop_update', ), + proportion=dict(argstr='-prop %s', ), + set_pq=dict(argstr='-setPQ %f %f', ), + sm_ranking=dict( + argstr='-%s', + position=3, + usedefault=True, + ), + template_file=dict(), + template_num=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + unc=dict(argstr='-unc', ), + unc_thresh=dict(argstr='-uncthres %f', ), + verbose=dict(argstr='-v %s', ), ) inputs = LabelFusion.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LabelFusion_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = LabelFusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py b/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py index 67435c1def..537c75a9dd 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py @@ -4,41 +4,44 @@ def test_MathsCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s', - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s', + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MathsCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MathsCommand_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MathsCommand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_Merge.py b/nipype/interfaces/niftyseg/tests/test_auto_Merge.py index 4d13929b23..f97d9beacf 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_Merge.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_Merge.py @@ -4,47 +4,50 @@ def test_Merge_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - dimension=dict(mandatory=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - merge_files=dict(argstr='%s', - mandatory=True, - position=4, - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s', - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + dimension=dict(mandatory=True, ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + merge_files=dict( + argstr='%s', + mandatory=True, + position=4, + ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s', + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Merge.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Merge_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py b/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py index d7483fc228..0847ec5feb 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py @@ -4,22 +4,24 @@ def test_NiftySegCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = NiftySegCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/niftyseg/tests/test_auto_PatchMatch.py b/nipype/interfaces/niftyseg/tests/test_auto_PatchMatch.py deleted file mode 100644 index ba6ea5a40c..0000000000 --- a/nipype/interfaces/niftyseg/tests/test_auto_PatchMatch.py +++ /dev/null @@ -1,61 +0,0 @@ -# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT -from __future__ import unicode_literals -from ..patchmatch import PatchMatch - - -def test_PatchMatch_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cs_size=dict(argstr='-cs %i', - ), - database_file=dict(argstr='-db %s', - mandatory=True, - position=3, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - position=1, - ), - it_num=dict(argstr='-it %i', - ), - mask_file=dict(argstr='-m %s', - mandatory=True, - position=2, - ), - match_num=dict(argstr='-match %i', - ), - out_file=dict(argstr='-o %s', - name_source=['in_file'], - name_template='%s_pm.nii.gz', - position=4, - ), - patch_size=dict(argstr='-size %i', - ), - pm_num=dict(argstr='-pm %i', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - ) - inputs = PatchMatch.input_spec() - - for key, metadata in list(input_map.items()): - for metakey, value in list(metadata.items()): - assert getattr(inputs.traits()[key], metakey) == value - - -def test_PatchMatch_outputs(): - output_map = dict(out_file=dict(), - ) - outputs = PatchMatch.output_spec() - - for key, metadata in list(output_map.items()): - for metakey, value in list(metadata.items()): - assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py b/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py index 6ca821c52f..082c629f03 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py @@ -4,39 +4,42 @@ def test_StatsCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - larger_voxel=dict(argstr='-t %f', - position=-3, - ), - mask_file=dict(argstr='-m %s', - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + larger_voxel=dict( + argstr='-t %f', + position=-3, + ), + mask_file=dict( + argstr='-m %s', + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = StatsCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_StatsCommand_outputs(): - output_map = dict(output=dict(), - ) + output_map = dict(output=dict(), ) outputs = StatsCommand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py b/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py index 702b3961d9..a0cd9d4809 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py @@ -4,65 +4,73 @@ def test_TupleMaths_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - operand_file1=dict(argstr='%s', - mandatory=True, - position=5, - xor=['operand_value1'], - ), - operand_file2=dict(argstr='%s', - mandatory=True, - position=6, - xor=['operand_value2'], - ), - operand_value1=dict(argstr='%.8f', - mandatory=True, - position=5, - xor=['operand_file1'], - ), - operand_value2=dict(argstr='%.8f', - mandatory=True, - position=6, - xor=['operand_file2'], - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s', - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + operand_file1=dict( + argstr='%s', + mandatory=True, + position=5, + xor=['operand_value1'], + ), + operand_file2=dict( + argstr='%s', + mandatory=True, + position=6, + xor=['operand_value2'], + ), + operand_value1=dict( + argstr='%.8f', + mandatory=True, + position=5, + xor=['operand_file1'], + ), + operand_value2=dict( + argstr='%.8f', + mandatory=True, + position=6, + xor=['operand_file2'], + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s', + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TupleMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TupleMaths_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = TupleMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py b/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py index c5144bbc65..c6c1505c7a 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py @@ -4,45 +4,49 @@ def test_UnaryMaths_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - out_file=dict(argstr='%s', - name_source=['in_file'], - name_template='%s', - position=-2, - ), - output_datatype=dict(argstr='-odt %s', - position=-3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + out_file=dict( + argstr='%s', + name_source=['in_file'], + name_template='%s', + position=-2, + ), + output_datatype=dict( + argstr='-odt %s', + position=-3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = UnaryMaths.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_UnaryMaths_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = UnaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py b/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py index 81bea6f18b..ea8dee29d3 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py @@ -4,43 +4,47 @@ def test_UnaryStats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - larger_voxel=dict(argstr='-t %f', - position=-3, - ), - mask_file=dict(argstr='-m %s', - position=-2, - ), - operation=dict(argstr='-%s', - mandatory=True, - position=4, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + larger_voxel=dict( + argstr='-t %f', + position=-3, + ), + mask_file=dict( + argstr='-m %s', + position=-2, + ), + operation=dict( + argstr='-%s', + mandatory=True, + position=4, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = UnaryStats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_UnaryStats_outputs(): - output_map = dict(output=dict(), - ) + output_map = dict(output=dict(), ) outputs = UnaryStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_em_interfaces.py b/nipype/interfaces/niftyseg/tests/test_em_interfaces.py index b95d574357..f4c56da2fe 100644 --- a/nipype/interfaces/niftyseg/tests/test_em_interfaces.py +++ b/nipype/interfaces/niftyseg/tests/test_em_interfaces.py @@ -9,8 +9,8 @@ from .. import EM -@pytest.mark.skipif(no_nifty_tool(cmd='seg_EM'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_EM'), reason="niftyseg is not installed") def test_seg_em(): # Create a node object @@ -31,6 +31,7 @@ def test_seg_em(): cmd_tmp = '{cmd} -in {in_file} -nopriors 4 -bc_out {bc_out} -out \ {out_file} -out_outlier {out_outlier}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, diff --git a/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py b/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py index ae2500a7d2..9fe82ac544 100644 --- a/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py +++ b/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py @@ -9,8 +9,8 @@ from .. import PatchMatch -@pytest.mark.skipif(no_nifty_tool(cmd='seg_PatchMatch'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_PatchMatch'), reason="niftyseg is not installed") def test_seg_patchmatch(): # Create a node object diff --git a/nipype/interfaces/niftyseg/tests/test_label_fusion.py b/nipype/interfaces/niftyseg/tests/test_label_fusion.py index 6f41086531..fdc186d6c2 100644 --- a/nipype/interfaces/niftyseg/tests/test_label_fusion.py +++ b/nipype/interfaces/niftyseg/tests/test_label_fusion.py @@ -9,8 +9,8 @@ from .. import LabelFusion, CalcTopNCC -@pytest.mark.skipif(no_nifty_tool(cmd='seg_LabFusion'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_LabFusion'), reason="niftyseg is not installed") def test_seg_lab_fusion(): """ Test interfaces for seg_labfusion""" # Create a node object @@ -37,6 +37,7 @@ def test_seg_lab_fusion(): cmd_tmp = '{cmd} -in {in_file} -STEPS 2.000000 2 {file_to_seg} \ {template_file} -out {out_file}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, @@ -48,8 +49,8 @@ def test_seg_lab_fusion(): assert steps.cmdline == expected_cmd # Staple - staple = LabelFusion(kernel_size=2.0, template_num=2, - classifier_type='STAPLE') + staple = LabelFusion( + kernel_size=2.0, template_num=2, classifier_type='STAPLE') in_file = example_data('im1.nii') file_to_seg = example_data('im2.nii') template_file = example_data('im3.nii') @@ -69,8 +70,11 @@ def test_seg_lab_fusion(): assert staple.cmdline == expected_cmd # Assign some input data - mv_node = LabelFusion(template_num=2, classifier_type='MV', - sm_ranking='ROINCC', dilation_roi=2) + mv_node = LabelFusion( + template_num=2, + classifier_type='MV', + sm_ranking='ROINCC', + dilation_roi=2) in_file = example_data('im1.nii') file_to_seg = example_data('im2.nii') template_file = example_data('im3.nii') @@ -80,6 +84,7 @@ def test_seg_lab_fusion(): cmd_tmp = '{cmd} -in {in_file} -MV -ROINCC 2 2 {file_to_seg} \ {template_file} -out {out_file}' + expected_cmd = cmd_tmp.format( cmd=cmd, in_file=in_file, @@ -91,8 +96,8 @@ def test_seg_lab_fusion(): assert mv_node.cmdline == expected_cmd -@pytest.mark.skipif(no_nifty_tool(cmd='seg_CalcTopNCC'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_CalcTopNCC'), reason="niftyseg is not installed") def test_seg_calctopncc(): """ Test interfaces for seg_CalctoNCC""" # Create a node object diff --git a/nipype/interfaces/niftyseg/tests/test_lesions.py b/nipype/interfaces/niftyseg/tests/test_lesions.py index aaca2df0ba..24b7e82cd7 100644 --- a/nipype/interfaces/niftyseg/tests/test_lesions.py +++ b/nipype/interfaces/niftyseg/tests/test_lesions.py @@ -9,8 +9,8 @@ from .. import FillLesions -@pytest.mark.skipif(no_nifty_tool(cmd='seg_FillLesions'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_FillLesions'), reason="niftyseg is not installed") def test_seg_filllesions(): # Create a node object diff --git a/nipype/interfaces/niftyseg/tests/test_maths.py b/nipype/interfaces/niftyseg/tests/test_maths.py index 38dc765f10..0680a8a481 100644 --- a/nipype/interfaces/niftyseg/tests/test_maths.py +++ b/nipype/interfaces/niftyseg/tests/test_maths.py @@ -6,13 +6,11 @@ from ....testing import example_data from ...niftyreg import get_custom_path from ...niftyreg.tests.test_regutils import no_nifty_tool -from .. import (UnaryMaths, BinaryMaths, - BinaryMathsInteger, TupleMaths, - Merge) +from .. import (UnaryMaths, BinaryMaths, BinaryMathsInteger, TupleMaths, Merge) -@pytest.mark.skipif(no_nifty_tool(cmd='seg_maths'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_maths'), reason="niftyseg is not installed") def test_unary_maths(): # Create a node object @@ -33,15 +31,13 @@ def test_unary_maths(): unarym.inputs.output_datatype = 'float' expected_cmd = '{cmd} {in_file} -otsu -odt float {out_file}'.format( - cmd=cmd, - in_file=in_file, - out_file='im1_otsu.nii') + cmd=cmd, in_file=in_file, out_file='im1_otsu.nii') assert unarym.cmdline == expected_cmd -@pytest.mark.skipif(no_nifty_tool(cmd='seg_maths'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_maths'), reason="niftyseg is not installed") def test_binary_maths(): # Create a node object @@ -64,15 +60,13 @@ def test_binary_maths(): cmd_tmp = '{cmd} {in_file} -sub 2.00000000 -odt float {out_file}' expected_cmd = cmd_tmp.format( - cmd=cmd, - in_file=in_file, - out_file='im1_sub.nii') + cmd=cmd, in_file=in_file, out_file='im1_sub.nii') assert binarym.cmdline == expected_cmd -@pytest.mark.skipif(no_nifty_tool(cmd='seg_maths'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_maths'), reason="niftyseg is not installed") def test_int_binary_maths(): # Create a node object @@ -94,15 +88,13 @@ def test_int_binary_maths(): ibinarym.inputs.output_datatype = 'float' expected_cmd = '{cmd} {in_file} -dil 2 -odt float {out_file}'.format( - cmd=cmd, - in_file=in_file, - out_file='im1_dil.nii') + cmd=cmd, in_file=in_file, out_file='im1_dil.nii') assert ibinarym.cmdline == expected_cmd -@pytest.mark.skipif(no_nifty_tool(cmd='seg_maths'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_maths'), reason="niftyseg is not installed") def test_tuple_maths(): # Create a node object @@ -127,16 +119,13 @@ def test_tuple_maths(): cmd_tmp = '{cmd} {in_file} -lncc {op} 2.00000000 -odt float {out_file}' expected_cmd = cmd_tmp.format( - cmd=cmd, - in_file=in_file, - op=op_file, - out_file='im1_lncc.nii') + cmd=cmd, in_file=in_file, op=op_file, out_file='im1_lncc.nii') assert tuplem.cmdline == expected_cmd -@pytest.mark.skipif(no_nifty_tool(cmd='seg_maths'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_maths'), reason="niftyseg is not installed") def test_merge(): # Create a node object diff --git a/nipype/interfaces/niftyseg/tests/test_stats.py b/nipype/interfaces/niftyseg/tests/test_stats.py index cd0948d1ae..91c234e98d 100644 --- a/nipype/interfaces/niftyseg/tests/test_stats.py +++ b/nipype/interfaces/niftyseg/tests/test_stats.py @@ -9,8 +9,8 @@ from .. import UnaryStats, BinaryStats -@pytest.mark.skipif(no_nifty_tool(cmd='seg_stats'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_stats'), reason="niftyseg is not installed") def test_unary_stats(): """ Test for the seg_stats interfaces """ # Create a node object @@ -29,15 +29,13 @@ def test_unary_stats(): unarys.inputs.in_file = in_file unarys.inputs.operation = 'a' - expected_cmd = '{cmd} {in_file} -a'.format( - cmd=cmd, - in_file=in_file) + expected_cmd = '{cmd} {in_file} -a'.format(cmd=cmd, in_file=in_file) assert unarys.cmdline == expected_cmd -@pytest.mark.skipif(no_nifty_tool(cmd='seg_stats'), - reason="niftyseg is not installed") +@pytest.mark.skipif( + no_nifty_tool(cmd='seg_stats'), reason="niftyseg is not installed") def test_binary_stats(): """ Test for the seg_stats interfaces """ # Create a node object @@ -58,7 +56,6 @@ def test_binary_stats(): binarys.inputs.operation = 'sa' expected_cmd = '{cmd} {in_file} -sa 2.00000000'.format( - cmd=cmd, - in_file=in_file) + cmd=cmd, in_file=in_file) assert binarys.cmdline == expected_cmd diff --git a/nipype/interfaces/nilearn.py b/nipype/interfaces/nilearn.py index db47b57e8b..3492e2e233 100644 --- a/nipype/interfaces/nilearn.py +++ b/nipype/interfaces/nilearn.py @@ -23,40 +23,59 @@ BaseInterfaceInputSpec, File, InputMultiPath) IFLOGGER = logging.getLogger('interface') + class SignalExtractionInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True, desc='4-D fMRI nii file') - label_files = InputMultiPath(File(exists=True), mandatory=True, - desc='a 3-D label image, with 0 denoting ' - 'background, or a list of 3-D probability ' - 'maps (one per label) or the equivalent 4D ' - 'file.') - class_labels = traits.List(mandatory=True, - desc='Human-readable labels for each segment ' - 'in the label file, in order. The length of ' - 'class_labels must be equal to the number of ' - 'segments (background excluded). This list ' - 'corresponds to the class labels in label_file ' - 'in ascending order') - out_file = File('signals.tsv', usedefault=True, exists=False, - desc='The name of the file to output to. ' - 'signals.tsv by default') - incl_shared_variance = traits.Bool(True, usedefault=True, desc='By default ' - '(True), returns simple time series calculated from each ' - 'region independently (e.g., for noise regression). If ' - 'False, returns unique signals for each region, discarding ' - 'shared variance (e.g., for connectivity. Only has effect ' - 'with 4D probability maps.') - include_global = traits.Bool(False, usedefault=True, - desc='If True, include an extra column ' - 'labeled "GlobalSignal", with values calculated from the entire brain ' - '(instead of just regions).') - detrend = traits.Bool(False, usedefault=True, desc='If True, perform detrending using nilearn.') + label_files = InputMultiPath( + File(exists=True), + mandatory=True, + desc='a 3-D label image, with 0 denoting ' + 'background, or a list of 3-D probability ' + 'maps (one per label) or the equivalent 4D ' + 'file.') + class_labels = traits.List( + mandatory=True, + desc='Human-readable labels for each segment ' + 'in the label file, in order. The length of ' + 'class_labels must be equal to the number of ' + 'segments (background excluded). This list ' + 'corresponds to the class labels in label_file ' + 'in ascending order') + out_file = File( + 'signals.tsv', + usedefault=True, + exists=False, + desc='The name of the file to output to. ' + 'signals.tsv by default') + incl_shared_variance = traits.Bool( + True, + usedefault=True, + desc='By default ' + '(True), returns simple time series calculated from each ' + 'region independently (e.g., for noise regression). If ' + 'False, returns unique signals for each region, discarding ' + 'shared variance (e.g., for connectivity. Only has effect ' + 'with 4D probability maps.') + include_global = traits.Bool( + False, + usedefault=True, + desc='If True, include an extra column ' + 'labeled "GlobalSignal", with values calculated from the entire brain ' + '(instead of just regions).') + detrend = traits.Bool( + False, + usedefault=True, + desc='If True, perform detrending using nilearn.') + class SignalExtractionOutputSpec(TraitedSpec): - out_file = File(exists=True, desc='tsv file containing the computed ' - 'signals, with as many columns as there are labels and as ' - 'many rows as there are timepoints in in_file, plus a ' - 'header row with values from class_labels') + out_file = File( + exists=True, + desc='tsv file containing the computed ' + 'signals, with as many columns as there are labels and as ' + 'many rows as there are timepoints in in_file, plus a ' + 'header row with values from class_labels') + class SignalExtraction(BaseInterface): ''' @@ -83,11 +102,13 @@ def _run_interface(self, runtime): signals.append(masker.fit_transform(self.inputs.in_file)) region_signals = np.hstack(signals) - output = np.vstack((self.inputs.class_labels, region_signals.astype(str))) + output = np.vstack((self.inputs.class_labels, + region_signals.astype(str))) # save output self._results['out_file'] = os.path.abspath(self.inputs.out_file) - np.savetxt(self._results['out_file'], output, fmt=b'%s', delimiter='\t') + np.savetxt( + self._results['out_file'], output, fmt=b'%s', delimiter='\t') return runtime def _process_inputs(self): @@ -100,21 +121,24 @@ def _process_inputs(self): maskers = [] # determine form of label files, choose appropriate nilearn masker - if np.amax(label_data.get_data()) > 1: # 3d label file + if np.amax(label_data.get_data()) > 1: # 3d label file n_labels = np.amax(label_data.get_data()) maskers.append(nl.NiftiLabelsMasker(label_data)) - else: # 4d labels + else: # 4d labels n_labels = label_data.get_data().shape[3] - if self.inputs.incl_shared_variance: # 4d labels, independent computation + if self.inputs.incl_shared_variance: # 4d labels, independent computation for img in nli.iter_img(label_data): - maskers.append(nl.NiftiMapsMasker(self._4d(img.get_data(), img.affine))) - else: # 4d labels, one computation fitting all + maskers.append( + nl.NiftiMapsMasker( + self._4d(img.get_data(), img.affine))) + else: # 4d labels, one computation fitting all maskers.append(nl.NiftiMapsMasker(label_data)) # check label list size if not np.isclose(int(n_labels), n_labels): - raise ValueError('The label files {} contain invalid value {}. Check input.' - .format(self.inputs.label_files, n_labels)) + raise ValueError( + 'The label files {} contain invalid value {}. Check input.' + .format(self.inputs.label_files, n_labels)) if len(self.inputs.class_labels) != n_labels: raise ValueError('The length of class_labels {} does not ' @@ -124,10 +148,13 @@ def _process_inputs(self): self.inputs.label_files)) if self.inputs.include_global: - global_label_data = label_data.get_data().sum(axis=3) # sum across all regions - global_label_data = np.rint(global_label_data).astype(int).clip(0, 1) # binarize + global_label_data = label_data.get_data().sum( + axis=3) # sum across all regions + global_label_data = np.rint(global_label_data).astype(int).clip( + 0, 1) # binarize global_label_data = self._4d(global_label_data, label_data.affine) - global_masker = nl.NiftiLabelsMasker(global_label_data, detrend=self.inputs.detrend) + global_masker = nl.NiftiLabelsMasker( + global_label_data, detrend=self.inputs.detrend) maskers.insert(0, global_masker) self.inputs.class_labels.insert(0, 'GlobalSignal') diff --git a/nipype/interfaces/nipy/model.py b/nipype/interfaces/nipy/model.py index 58c07b5b95..7df9cb609d 100644 --- a/nipype/interfaces/nipy/model.py +++ b/nipype/interfaces/nipy/model.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, str, bytes import os @@ -29,36 +30,54 @@ from nipy.modalities.fmri.experimental_paradigm import BlockParadigm - class FitGLMInputSpec(BaseInterfaceInputSpec): - session_info = traits.List(minlen=1, maxlen=1, mandatory=True, - desc=('Session specific information generated by' - ' ``modelgen.SpecifyModel``, FitGLM does ' - 'not support multiple runs uless they are ' - 'concatenated (see SpecifyModel options)')) - hrf_model = traits.Enum('Canonical', 'Canonical With Derivative', 'FIR', - desc=("that specifies the hemodynamic reponse " - "function it can be 'Canonical', 'Canonical " - "With Derivative' or 'FIR'"), usedefault=True) - drift_model = traits.Enum("Cosine", "Polynomial", "Blank", - desc=("string that specifies the desired drift " - "model, to be chosen among 'Polynomial', " - "'Cosine', 'Blank'"), usedefault=True) + session_info = traits.List( + minlen=1, + maxlen=1, + mandatory=True, + desc=('Session specific information generated by' + ' ``modelgen.SpecifyModel``, FitGLM does ' + 'not support multiple runs uless they are ' + 'concatenated (see SpecifyModel options)')) + hrf_model = traits.Enum( + 'Canonical', + 'Canonical With Derivative', + 'FIR', + desc=("that specifies the hemodynamic reponse " + "function it can be 'Canonical', 'Canonical " + "With Derivative' or 'FIR'"), + usedefault=True) + drift_model = traits.Enum( + "Cosine", + "Polynomial", + "Blank", + desc=("string that specifies the desired drift " + "model, to be chosen among 'Polynomial', " + "'Cosine', 'Blank'"), + usedefault=True) TR = traits.Float(mandatory=True) - model = traits.Enum("ar1", "spherical", - desc=("autoregressive mode is available only for the " - "kalman method"), usedefault=True) - method = traits.Enum("kalman", "ols", - desc=("method to fit the model, ols or kalma; kalman " - "is more time consuming but it supports " - "autoregressive model"), usedefault=True) - mask = traits.File(exists=True, - desc=("restrict the fitting only to the region defined " - "by this mask")) - normalize_design_matrix = traits.Bool(False, - desc=("normalize (zscore) the " - "regressors before fitting"), - usedefault=True) + model = traits.Enum( + "ar1", + "spherical", + desc=("autoregressive mode is available only for the " + "kalman method"), + usedefault=True) + method = traits.Enum( + "kalman", + "ols", + desc=("method to fit the model, ols or kalma; kalman " + "is more time consuming but it supports " + "autoregressive model"), + usedefault=True) + mask = traits.File( + exists=True, + desc=("restrict the fitting only to the region defined " + "by this mask")) + normalize_design_matrix = traits.Bool( + False, + desc=("normalize (zscore) the " + "regressors before fitting"), + usedefault=True) save_residuals = traits.Bool(False, usedefault=True) plot_design_matrix = traits.Bool(False, usedefault=True) @@ -123,7 +142,8 @@ def _run_interface(self, runtime): reg_vals = np.zeros((nscans, len(reg_names))) for i in range(len(reg_names)): - reg_vals[:, i] = np.array(session_info[0]['regress'][i]['val']).reshape(1, -1) + reg_vals[:, i] = np.array( + session_info[0]['regress'][i]['val']).reshape(1, -1) frametimes = np.linspace(0, (nscans - 1) * self.inputs.TR, nscans) @@ -140,18 +160,22 @@ def _run_interface(self, runtime): duration += cond['duration'] if conditions: - paradigm = BlockParadigm(con_id=conditions, onset=onsets, duration=duration) + paradigm = BlockParadigm( + con_id=conditions, onset=onsets, duration=duration) else: paradigm = None - design_matrix, self._reg_names = dm.dmtx_light(frametimes, paradigm, drift_model=drift_model, hfcut=hpf, - hrf_model=self.inputs.hrf_model, - add_regs=reg_vals, - add_reg_names=reg_names - ) + design_matrix, self._reg_names = dm.dmtx_light( + frametimes, + paradigm, + drift_model=drift_model, + hfcut=hpf, + hrf_model=self.inputs.hrf_model, + add_regs=reg_vals, + add_reg_names=reg_names) if self.inputs.normalize_design_matrix: for i in range(len(self._reg_names) - 1): - design_matrix[:, i] = ((design_matrix[:, i] - - design_matrix[:, i].mean()) / + design_matrix[:, i] = (( + design_matrix[:, i] - design_matrix[:, i].mean()) / design_matrix[:, i].std()) if self.inputs.plot_design_matrix: @@ -162,10 +186,14 @@ def _run_interface(self, runtime): pylab.clf() glm = GLM.GeneralLinearModel() - glm.fit(timeseries.T, design_matrix, method=self.inputs.method, model=self.inputs.model) + glm.fit( + timeseries.T, + design_matrix, + method=self.inputs.method, + model=self.inputs.model) self._beta_file = os.path.abspath("beta.nii") - beta = np.zeros(mask.shape + (glm.beta.shape[0],)) + beta = np.zeros(mask.shape + (glm.beta.shape[0], )) beta[mask, :] = glm.beta.T nb.save(nb.Nifti1Image(beta, nii.affine), self._beta_file) @@ -176,10 +204,11 @@ def _run_interface(self, runtime): if self.inputs.save_residuals: explained = np.dot(design_matrix, glm.beta) - residuals = np.zeros(mask.shape + (nscans,)) + residuals = np.zeros(mask.shape + (nscans, )) residuals[mask, :] = timeseries - explained.T self._residuals_file = os.path.abspath("residuals.nii") - nb.save(nb.Nifti1Image(residuals, nii.affine), self._residuals_file) + nb.save( + nb.Nifti1Image(residuals, nii.affine), self._residuals_file) self._nvbeta = glm.nvbeta self._dof = glm.dof @@ -213,34 +242,34 @@ def _list_outputs(self): class EstimateContrastInputSpec(BaseInterfaceInputSpec): contrasts = traits.List( - traits.Either(traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('F'), - traits.List(traits.Either(traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float), - traits.List(traits.Float)))))), + traits.Either( + traits.Tuple(traits.Str, traits.Enum('T'), traits.List(traits.Str), + traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('T'), traits.List(traits.Str), + traits.List(traits.Float), traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('F'), + traits.List( + traits.Either( + traits.Tuple(traits.Str, traits.Enum('T'), + traits.List(traits.Str), + traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('T'), + traits.List(traits.Str), + traits.List(traits.Float), + traits.List(traits.Float)))))), desc="""List of contrasts with each contrast being a list of the form: [('name', 'stat', [condition list], [weight list], [session list])]. if session list is None or not provided, all sessions are used. For F contrasts, the condition list should contain previously defined - T-contrasts.""", mandatory=True) - beta = File(exists=True, desc="beta coefficients of the fitted model", mandatory=True) + T-contrasts.""", + mandatory=True) + beta = File( + exists=True, + desc="beta coefficients of the fitted model", + mandatory=True) nvbeta = traits.Any(mandatory=True) - s2 = File(exists=True, desc="squared variance of the residuals", mandatory=True) + s2 = File( + exists=True, desc="squared variance of the residuals", mandatory=True) dof = traits.Any(desc="degrees of freedom", mandatory=True) constants = traits.Any(mandatory=True) axis = traits.Any(mandatory=True) @@ -285,7 +314,6 @@ def _run_interface(self, runtime): self._z_maps = [] for contrast_def in self.inputs.contrasts: name = contrast_def[0] - _ = contrast_def[1] contrast = np.zeros(len(reg_names)) for i, reg_name in enumerate(reg_names): diff --git a/nipype/interfaces/nipy/preprocess.py b/nipype/interfaces/nipy/preprocess.py index c4b3ece2f1..a3566e07a9 100644 --- a/nipype/interfaces/nipy/preprocess.py +++ b/nipype/interfaces/nipy/preprocess.py @@ -7,7 +7,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -19,10 +20,8 @@ from ...utils import NUMPY_MMAP from ...utils.filemanip import split_filename, fname_presuffix -from ..base import (TraitedSpec, BaseInterface, traits, - BaseInterfaceInputSpec, isdefined, File, - InputMultiPath, OutputMultiPath) - +from ..base import (TraitedSpec, BaseInterface, traits, BaseInterfaceInputSpec, + isdefined, File, InputMultiPath, OutputMultiPath) have_nipy = True try: @@ -35,13 +34,15 @@ nipy_version = nipy.__version__ - class ComputeMaskInputSpec(BaseInterfaceInputSpec): - mean_volume = File(exists=True, mandatory=True, - desc="mean EPI image, used to compute the threshold for the mask") - reference_volume = File(exists=True, - desc=("reference volume used to compute the mask. " - "If none is give, the mean volume is used.")) + mean_volume = File( + exists=True, + mandatory=True, + desc="mean EPI image, used to compute the threshold for the mask") + reference_volume = File( + exists=True, + desc=("reference volume used to compute the mask. " + "If none is give, the mean volume is used.")) m = traits.Float(desc="lower fraction of the histogram to be discarded") M = traits.Float(desc="upper fraction of the histogram to be discarded") cc = traits.Bool(desc="Keep only the largest connected component") @@ -58,8 +59,10 @@ class ComputeMask(BaseInterface): def _run_interface(self, runtime): from nipy.labs.mask import compute_mask args = {} - for key in [k for k, _ in list(self.inputs.items()) - if k not in BaseInterfaceInputSpec().trait_names()]: + for key in [ + k for k, _ in list(self.inputs.items()) + if k not in BaseInterfaceInputSpec().trait_names() + ]: value = getattr(self.inputs, key) if isdefined(value): if key in ['mean_volume', 'reference_volume']: @@ -70,8 +73,9 @@ def _run_interface(self, runtime): brain_mask = compute_mask(**args) _, name, ext = split_filename(self.inputs.mean_volume) self._brain_mask_path = os.path.abspath("%s_mask.%s" % (name, ext)) - nb.save(nb.Nifti1Image(brain_mask.astype(np.uint8), nii.affine), - self._brain_mask_path) + nb.save( + nb.Nifti1Image(brain_mask.astype(np.uint8), nii.affine), + self._brain_mask_path) return runtime @@ -83,44 +87,49 @@ def _list_outputs(self): class FmriRealign4dInputSpec(BaseInterfaceInputSpec): - in_file = InputMultiPath(File(exists=True), - mandatory=True, - desc="File to realign") - tr = traits.Float(desc="TR in seconds", - mandatory=True) - slice_order = traits.List(traits.Int(), - desc=('0 based slice order. This would be equivalent to entering' - 'np.argsort(spm_slice_order) for this field. This effects' - 'interleaved acquisition. This field will be deprecated in' - 'future Nipy releases and be replaced by actual slice' - 'acquisition times.'), - requires=["time_interp"]) + in_file = InputMultiPath( + File(exists=True), mandatory=True, desc="File to realign") + tr = traits.Float(desc="TR in seconds", mandatory=True) + slice_order = traits.List( + traits.Int(), + desc=('0 based slice order. This would be equivalent to entering' + 'np.argsort(spm_slice_order) for this field. This effects' + 'interleaved acquisition. This field will be deprecated in' + 'future Nipy releases and be replaced by actual slice' + 'acquisition times.'), + requires=["time_interp"]) tr_slices = traits.Float(desc="TR slices", requires=['time_interp']) - start = traits.Float(0.0, usedefault=True, - desc="time offset into TR to align slices to") - time_interp = traits.Enum(True, requires=["slice_order"], - desc="Assume smooth changes across time e.g.,\ + start = traits.Float( + 0.0, usedefault=True, desc="time offset into TR to align slices to") + time_interp = traits.Enum( + True, + requires=["slice_order"], + desc="Assume smooth changes across time e.g.,\ fmri series. If you don't want slice timing \ correction set this to undefined") - loops = InputMultiPath([5], traits.Int, usedefault=True, - desc="loops within each run") - between_loops = InputMultiPath([5], traits.Int, - usedefault=True, desc="loops used to \ + loops = InputMultiPath( + [5], traits.Int, usedefault=True, desc="loops within each run") + between_loops = InputMultiPath( + [5], + traits.Int, + usedefault=True, + desc="loops used to \ realign different \ runs") - speedup = InputMultiPath([5], traits.Int, - usedefault=True, - desc="successive image \ + speedup = InputMultiPath( + [5], + traits.Int, + usedefault=True, + desc="successive image \ sub-sampling factors \ for acceleration") class FmriRealign4dOutputSpec(TraitedSpec): - out_file = OutputMultiPath(File(exists=True), - desc="Realigned files") - par_file = OutputMultiPath(File(exists=True), - desc="Motion parameter files") + out_file = OutputMultiPath(File(exists=True), desc="Realigned files") + par_file = OutputMultiPath( + File(exists=True), desc="Motion parameter files") class FmriRealign4d(BaseInterface): @@ -165,35 +174,42 @@ def _run_interface(self, runtime): else: TR_slices = self.inputs.tr_slices - R = FR4d(all_ims, tr=self.inputs.tr, - slice_order=self.inputs.slice_order, - tr_slices=TR_slices, - time_interp=self.inputs.time_interp, - start=self.inputs.start) + R = FR4d( + all_ims, + tr=self.inputs.tr, + slice_order=self.inputs.slice_order, + tr_slices=TR_slices, + time_interp=self.inputs.time_interp, + start=self.inputs.start) - R.estimate(loops=list(self.inputs.loops), - between_loops=list(self.inputs.between_loops), - speedup=list(self.inputs.speedup)) + R.estimate( + loops=list(self.inputs.loops), + between_loops=list(self.inputs.between_loops), + speedup=list(self.inputs.speedup)) corr_run = R.resample() self._out_file_path = [] self._par_file_path = [] for j, corr in enumerate(corr_run): - self._out_file_path.append(os.path.abspath('corr_%s.nii.gz' % - (split_filename(self.inputs.in_file[j])[1]))) + self._out_file_path.append( + os.path.abspath('corr_%s.nii.gz' % + (split_filename(self.inputs.in_file[j])[1]))) save_image(corr, self._out_file_path[j]) - self._par_file_path.append(os.path.abspath('%s.par' % - (os.path.split(self.inputs.in_file[j])[1]))) + self._par_file_path.append( + os.path.abspath('%s.par' % + (os.path.split(self.inputs.in_file[j])[1]))) mfile = open(self._par_file_path[j], 'w') motion = R._transforms[j] # nipy does not encode euler angles. return in original form of # translation followed by rotation vector see: # http://en.wikipedia.org/wiki/Rodrigues'_rotation_formula for i, mo in enumerate(motion): - params = ['%.10f' % item for item in np.hstack((mo.translation, - mo.rotation))] + params = [ + '%.10f' % item + for item in np.hstack((mo.translation, mo.rotation)) + ] string = ' '.join(params) + '\n' mfile.write(string) mfile.close() @@ -209,41 +225,44 @@ def _list_outputs(self): class SpaceTimeRealignerInputSpec(BaseInterfaceInputSpec): - in_file = InputMultiPath(File(exists=True), - mandatory=True, min_ver='0.4.0.dev', - desc="File to realign") + in_file = InputMultiPath( + File(exists=True), + mandatory=True, + min_ver='0.4.0.dev', + desc="File to realign") tr = traits.Float(desc="TR in seconds", requires=['slice_times']) - slice_times = traits.Either(traits.List(traits.Float()), - traits.Enum('asc_alt_2', 'asc_alt_2_1', - 'asc_alt_half', 'asc_alt_siemens', - 'ascending', 'desc_alt_2', - 'desc_alt_half', 'descending'), - desc=('Actual slice acquisition times.')) - slice_info = traits.Either(traits.Int, - traits.List(min_len=2, max_len=2), - desc=('Single integer or length 2 sequence ' - 'If int, the axis in `images` that is the ' - 'slice axis. In a 4D image, this will ' - 'often be axis = 2. If a 2 sequence, then' - ' elements are ``(slice_axis, ' - 'slice_direction)``, where ``slice_axis`` ' - 'is the slice axis in the image as above, ' - 'and ``slice_direction`` is 1 if the ' - 'slices were acquired slice 0 first, slice' - ' -1 last, or -1 if acquired slice -1 ' - 'first, slice 0 last. If `slice_info` is ' - 'an int, assume ' - '``slice_direction`` == 1.'), - requires=['slice_times'], - ) + slice_times = traits.Either( + traits.List(traits.Float()), + traits.Enum('asc_alt_2', 'asc_alt_2_1', 'asc_alt_half', + 'asc_alt_siemens', 'ascending', 'desc_alt_2', + 'desc_alt_half', 'descending'), + desc=('Actual slice acquisition times.')) + slice_info = traits.Either( + traits.Int, + traits.List(min_len=2, max_len=2), + desc=('Single integer or length 2 sequence ' + 'If int, the axis in `images` that is the ' + 'slice axis. In a 4D image, this will ' + 'often be axis = 2. If a 2 sequence, then' + ' elements are ``(slice_axis, ' + 'slice_direction)``, where ``slice_axis`` ' + 'is the slice axis in the image as above, ' + 'and ``slice_direction`` is 1 if the ' + 'slices were acquired slice 0 first, slice' + ' -1 last, or -1 if acquired slice -1 ' + 'first, slice 0 last. If `slice_info` is ' + 'an int, assume ' + '``slice_direction`` == 1.'), + requires=['slice_times'], + ) class SpaceTimeRealignerOutputSpec(TraitedSpec): - out_file = OutputMultiPath(File(exists=True), - desc="Realigned files") - par_file = OutputMultiPath(File(exists=True), - desc=("Motion parameter files. Angles are not " - "euler angles")) + out_file = OutputMultiPath(File(exists=True), desc="Realigned files") + par_file = OutputMultiPath( + File(exists=True), + desc=("Motion parameter files. Angles are not " + "euler angles")) class SpaceTimeRealigner(BaseInterface): @@ -298,11 +317,12 @@ def _run_interface(self, runtime): R = SpaceRealign(all_ims) else: from nipy.algorithms.registration import SpaceTimeRealign - R = SpaceTimeRealign(all_ims, - tr=self.inputs.tr, - slice_times=self.inputs.slice_times, - slice_info=self.inputs.slice_info, - ) + R = SpaceTimeRealign( + all_ims, + tr=self.inputs.tr, + slice_times=self.inputs.slice_times, + slice_info=self.inputs.slice_info, + ) R.estimate(refscan=None) @@ -311,20 +331,24 @@ def _run_interface(self, runtime): self._par_file_path = [] for j, corr in enumerate(corr_run): - self._out_file_path.append(os.path.abspath('corr_%s.nii.gz' % - (split_filename(self.inputs.in_file[j])[1]))) + self._out_file_path.append( + os.path.abspath('corr_%s.nii.gz' % + (split_filename(self.inputs.in_file[j])[1]))) save_image(corr, self._out_file_path[j]) - self._par_file_path.append(os.path.abspath('%s.par' % - (os.path.split(self.inputs.in_file[j])[1]))) + self._par_file_path.append( + os.path.abspath('%s.par' % + (os.path.split(self.inputs.in_file[j])[1]))) mfile = open(self._par_file_path[j], 'w') motion = R._transforms[j] # nipy does not encode euler angles. return in original form of # translation followed by rotation vector see: # http://en.wikipedia.org/wiki/Rodrigues'_rotation_formula for i, mo in enumerate(motion): - params = ['%.10f' % item for item in np.hstack((mo.translation, - mo.rotation))] + params = [ + '%.10f' % item + for item in np.hstack((mo.translation, mo.rotation)) + ] string = ' '.join(params) + '\n' mfile.write(string) mfile.close() @@ -339,18 +363,16 @@ def _list_outputs(self): class TrimInputSpec(BaseInterfaceInputSpec): - in_file = File( - exists=True, mandatory=True, - desc="EPI image to trim") - begin_index = traits.Int( - 0, usedefault=True, - desc='first volume') + in_file = File(exists=True, mandatory=True, desc="EPI image to trim") + begin_index = traits.Int(0, usedefault=True, desc='first volume') end_index = traits.Int( - 0, usedefault=True, + 0, + usedefault=True, desc='last volume indexed as in python (and 0 for last)') out_file = File(desc='output filename') suffix = traits.Str( - '_trim', usedefault=True, + '_trim', + usedefault=True, desc='suffix for out_file to use if no out_file provided') diff --git a/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py b/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py index 401f2b0f62..eca67782a4 100644 --- a/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py +++ b/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py @@ -4,27 +4,25 @@ def test_ComputeMask_inputs(): - input_map = dict(M=dict(), - cc=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - m=dict(), - mean_volume=dict(mandatory=True, - ), - reference_volume=dict(), + input_map = dict( + M=dict(), + cc=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + m=dict(), + mean_volume=dict(mandatory=True, ), + reference_volume=dict(), ) inputs = ComputeMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ComputeMask_outputs(): - output_map = dict(brain_mask=dict(), - ) + output_map = dict(brain_mask=dict(), ) outputs = ComputeMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py b/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py index 78f6d02c03..7859137a7a 100644 --- a/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py +++ b/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py @@ -4,39 +4,32 @@ def test_EstimateContrast_inputs(): - input_map = dict(axis=dict(mandatory=True, - ), - beta=dict(mandatory=True, - ), - constants=dict(mandatory=True, - ), - contrasts=dict(mandatory=True, - ), - dof=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask=dict(), - nvbeta=dict(mandatory=True, - ), - reg_names=dict(mandatory=True, - ), - s2=dict(mandatory=True, - ), + input_map = dict( + axis=dict(mandatory=True, ), + beta=dict(mandatory=True, ), + constants=dict(mandatory=True, ), + contrasts=dict(mandatory=True, ), + dof=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask=dict(), + nvbeta=dict(mandatory=True, ), + reg_names=dict(mandatory=True, ), + s2=dict(mandatory=True, ), ) inputs = EstimateContrast.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EstimateContrast_outputs(): - output_map = dict(p_maps=dict(), - stat_maps=dict(), - z_maps=dict(), + output_map = dict( + p_maps=dict(), + stat_maps=dict(), + z_maps=dict(), ) outputs = EstimateContrast.output_spec() diff --git a/nipype/interfaces/nipy/tests/test_auto_FitGLM.py b/nipype/interfaces/nipy/tests/test_auto_FitGLM.py index 5aca7d345c..0a473e2187 100644 --- a/nipype/interfaces/nipy/tests/test_auto_FitGLM.py +++ b/nipype/interfaces/nipy/tests/test_auto_FitGLM.py @@ -4,47 +4,39 @@ def test_FitGLM_inputs(): - input_map = dict(TR=dict(mandatory=True, - ), - drift_model=dict(usedefault=True, - ), - hrf_model=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask=dict(), - method=dict(usedefault=True, - ), - model=dict(usedefault=True, - ), - normalize_design_matrix=dict(usedefault=True, - ), - plot_design_matrix=dict(usedefault=True, - ), - save_residuals=dict(usedefault=True, - ), - session_info=dict(mandatory=True, - ), + input_map = dict( + TR=dict(mandatory=True, ), + drift_model=dict(usedefault=True, ), + hrf_model=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask=dict(), + method=dict(usedefault=True, ), + model=dict(usedefault=True, ), + normalize_design_matrix=dict(usedefault=True, ), + plot_design_matrix=dict(usedefault=True, ), + save_residuals=dict(usedefault=True, ), + session_info=dict(mandatory=True, ), ) inputs = FitGLM.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FitGLM_outputs(): - output_map = dict(a=dict(), - axis=dict(), - beta=dict(), - constants=dict(), - dof=dict(), - nvbeta=dict(), - reg_names=dict(), - residuals=dict(), - s2=dict(), + output_map = dict( + a=dict(), + axis=dict(), + beta=dict(), + constants=dict(), + dof=dict(), + nvbeta=dict(), + reg_names=dict(), + residuals=dict(), + s2=dict(), ) outputs = FitGLM.output_spec() diff --git a/nipype/interfaces/nipy/tests/test_auto_FmriRealign4d.py b/nipype/interfaces/nipy/tests/test_auto_FmriRealign4d.py index 0360e53df0..eea799c486 100644 --- a/nipype/interfaces/nipy/tests/test_auto_FmriRealign4d.py +++ b/nipype/interfaces/nipy/tests/test_auto_FmriRealign4d.py @@ -4,39 +4,31 @@ def test_FmriRealign4d_inputs(): - input_map = dict(between_loops=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - loops=dict(usedefault=True, - ), - slice_order=dict(requires=['time_interp'], - ), - speedup=dict(usedefault=True, - ), - start=dict(usedefault=True, - ), - time_interp=dict(requires=['slice_order'], - ), - tr=dict(mandatory=True, - ), - tr_slices=dict(requires=['time_interp'], - ), + input_map = dict( + between_loops=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + loops=dict(usedefault=True, ), + slice_order=dict(requires=['time_interp'], ), + speedup=dict(usedefault=True, ), + start=dict(usedefault=True, ), + time_interp=dict(requires=['slice_order'], ), + tr=dict(mandatory=True, ), + tr_slices=dict(requires=['time_interp'], ), ) inputs = FmriRealign4d.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FmriRealign4d_outputs(): - output_map = dict(out_file=dict(), - par_file=dict(), + output_map = dict( + out_file=dict(), + par_file=dict(), ) outputs = FmriRealign4d.output_spec() diff --git a/nipype/interfaces/nipy/tests/test_auto_Similarity.py b/nipype/interfaces/nipy/tests/test_auto_Similarity.py index d65cf36b02..a3c9979715 100644 --- a/nipype/interfaces/nipy/tests/test_auto_Similarity.py +++ b/nipype/interfaces/nipy/tests/test_auto_Similarity.py @@ -4,29 +4,25 @@ def test_Similarity_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask1=dict(), - mask2=dict(), - metric=dict(usedefault=True, - ), - volume1=dict(mandatory=True, - ), - volume2=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask1=dict(), + mask2=dict(), + metric=dict(usedefault=True, ), + volume1=dict(mandatory=True, ), + volume2=dict(mandatory=True, ), ) inputs = Similarity.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Similarity_outputs(): - output_map = dict(similarity=dict(), - ) + output_map = dict(similarity=dict(), ) outputs = Similarity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py b/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py index 358bd6efa8..2c7ee897a6 100644 --- a/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py +++ b/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py @@ -4,29 +4,29 @@ def test_SpaceTimeRealigner_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - min_ver='0.4.0.dev', - ), - slice_info=dict(requires=['slice_times'], - ), - slice_times=dict(), - tr=dict(requires=['slice_times'], - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + mandatory=True, + min_ver='0.4.0.dev', + ), + slice_info=dict(requires=['slice_times'], ), + slice_times=dict(), + tr=dict(requires=['slice_times'], ), ) inputs = SpaceTimeRealigner.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SpaceTimeRealigner_outputs(): - output_map = dict(out_file=dict(), - par_file=dict(), + output_map = dict( + out_file=dict(), + par_file=dict(), ) outputs = SpaceTimeRealigner.output_spec() diff --git a/nipype/interfaces/nipy/tests/test_auto_Trim.py b/nipype/interfaces/nipy/tests/test_auto_Trim.py index 0d2ad9063b..0726c84c5c 100644 --- a/nipype/interfaces/nipy/tests/test_auto_Trim.py +++ b/nipype/interfaces/nipy/tests/test_auto_Trim.py @@ -4,30 +4,25 @@ def test_Trim_inputs(): - input_map = dict(begin_index=dict(usedefault=True, - ), - end_index=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - out_file=dict(), - suffix=dict(usedefault=True, - ), + input_map = dict( + begin_index=dict(usedefault=True, ), + end_index=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + out_file=dict(), + suffix=dict(usedefault=True, ), ) inputs = Trim.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Trim_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Trim.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/utils.py b/nipype/interfaces/nipy/utils.py index 0b1c6a2091..781263f317 100644 --- a/nipype/interfaces/nipy/utils.py +++ b/nipype/interfaces/nipy/utils.py @@ -7,14 +7,15 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import warnings import nibabel as nb from ...utils.misc import package_check -from ..base import (TraitedSpec, BaseInterface, traits, - BaseInterfaceInputSpec, File, isdefined) +from ..base import (TraitedSpec, BaseInterface, traits, BaseInterfaceInputSpec, + File, isdefined) have_nipy = True try: @@ -26,22 +27,23 @@ from nipy.algorithms.registration.affine import Affine - class SimilarityInputSpec(BaseInterfaceInputSpec): volume1 = File(exists=True, desc="3D volume", mandatory=True) volume2 = File(exists=True, desc="3D volume", mandatory=True) mask1 = File(exists=True, desc="3D volume") mask2 = File(exists=True, desc="3D volume") - metric = traits.Either(traits.Enum('cc', 'cr', 'crl1', 'mi', 'nmi', 'slr'), - traits.Callable(), - desc="""str or callable + metric = traits.Either( + traits.Enum('cc', 'cr', 'crl1', 'mi', 'nmi', 'slr'), + traits.Callable(), + desc="""str or callable Cost-function for assessing image similarity. If a string, one of 'cc': correlation coefficient, 'cr': correlation ratio, 'crl1': L1-norm based correlation ratio, 'mi': mutual information, 'nmi': normalized mutual information, 'slr': supervised log-likelihood ratio. If a callable, it should take a two-dimensional array representing the image joint -histogram as an input and return a float.""", usedefault=True) +histogram as an input and return a float.""", + usedefault=True) class SimilarityOutputSpec(TraitedSpec): @@ -92,11 +94,12 @@ def _run_interface(self, runtime): else: mask2 = None - histreg = HistogramRegistration(from_img=vol1_nii, - to_img=vol2_nii, - similarity=self.inputs.metric, - from_mask=mask1, - to_mask=mask2) + histreg = HistogramRegistration( + from_img=vol1_nii, + to_img=vol2_nii, + similarity=self.inputs.metric, + from_mask=mask1, + to_mask=mask2) self._similarity = histreg.eval(Affine()) return runtime diff --git a/nipype/interfaces/nitime/analysis.py b/nipype/interfaces/nitime/analysis.py index ee34271044..36c550ca27 100644 --- a/nipype/interfaces/nitime/analysis.py +++ b/nipype/interfaces/nitime/analysis.py @@ -10,7 +10,8 @@ - nitime.viz.drawmatrix_channels """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import zip, object, open import numpy as np @@ -18,9 +19,8 @@ from ...utils.misc import package_check from ...utils.filemanip import fname_presuffix -from ..base import (TraitedSpec, File, Undefined, traits, - BaseInterface, isdefined, BaseInterfaceInputSpec) - +from ..base import (TraitedSpec, File, Undefined, traits, BaseInterface, + isdefined, BaseInterfaceInputSpec) have_nitime = True try: @@ -38,56 +38,79 @@ class CoherenceAnalyzerInputSpec(BaseInterfaceInputSpec): # Input either csv file, or time-series object and use _xor_inputs to # discriminate _xor_inputs = ('in_file', 'in_TS') - in_file = File(desc=('csv file with ROIs on the columns and ' - 'time-points on the rows. ROI names at the top row'), - exists=True, - requires=('TR',)) + in_file = File( + desc=('csv file with ROIs on the columns and ' + 'time-points on the rows. ROI names at the top row'), + exists=True, + requires=('TR', )) # If you gave just a file name, you need to specify the sampling_rate: - TR = traits.Float(desc=('The TR used to collect the data' - 'in your csv file ')) + TR = traits.Float( + desc=('The TR used to collect the data' + 'in your csv file ')) in_TS = traits.Any(desc='a nitime TimeSeries object') - NFFT = traits.Range(low=32, value=64, usedefault=True, - desc=('This is the size of the window used for ' - 'the spectral estimation. Use values between ' - '32 and the number of samples in your time-series.' - '(Defaults to 64.)')) - n_overlap = traits.Range(low=0, value=0, usedefault=True, - desc=('The number of samples which overlap' - 'between subsequent windows.(Defaults to 0)')) - - frequency_range = traits.List(value=[0.02, 0.15], usedefault=True, - minlen=2, - maxlen=2, - desc=('The range of frequencies over' - 'which the analysis will average.' - '[low,high] (Default [0.02,0.15]')) - - output_csv_file = File(desc='File to write outputs (coherence,time-delay) with file-names: file_name_ {coherence,timedelay}') - - output_figure_file = File(desc='File to write output figures (coherence,time-delay) with file-names: file_name_{coherence,timedelay}. Possible formats: .png,.svg,.pdf,.jpg,...') - - figure_type = traits.Enum('matrix', 'network', usedefault=True, - desc=("The type of plot to generate, where " - "'matrix' denotes a matrix image and" - "'network' denotes a graph representation." - " Default: 'matrix'")) + NFFT = traits.Range( + low=32, + value=64, + usedefault=True, + desc=('This is the size of the window used for ' + 'the spectral estimation. Use values between ' + '32 and the number of samples in your time-series.' + '(Defaults to 64.)')) + n_overlap = traits.Range( + low=0, + value=0, + usedefault=True, + desc=('The number of samples which overlap' + 'between subsequent windows.(Defaults to 0)')) + + frequency_range = traits.List( + value=[0.02, 0.15], + usedefault=True, + minlen=2, + maxlen=2, + desc=('The range of frequencies over' + 'which the analysis will average.' + '[low,high] (Default [0.02,0.15]')) + + output_csv_file = File( + desc= + 'File to write outputs (coherence,time-delay) with file-names: file_name_ {coherence,timedelay}' + ) + + output_figure_file = File( + desc= + 'File to write output figures (coherence,time-delay) with file-names: file_name_{coherence,timedelay}. Possible formats: .png,.svg,.pdf,.jpg,...' + ) + + figure_type = traits.Enum( + 'matrix', + 'network', + usedefault=True, + desc=("The type of plot to generate, where " + "'matrix' denotes a matrix image and" + "'network' denotes a graph representation." + " Default: 'matrix'")) class CoherenceAnalyzerOutputSpec(TraitedSpec): - coherence_array = traits.Array(desc=('The pairwise coherence values' - 'between the ROIs')) + coherence_array = traits.Array( + desc=('The pairwise coherence values' + 'between the ROIs')) - timedelay_array = traits.Array(desc=('The pairwise time delays between the' - 'ROIs (in seconds)')) + timedelay_array = traits.Array( + desc=('The pairwise time delays between the' + 'ROIs (in seconds)')) - coherence_csv = File(desc=('A csv file containing the pairwise ' - 'coherence values')) + coherence_csv = File( + desc=('A csv file containing the pairwise ' + 'coherence values')) - timedelay_csv = File(desc=('A csv file containing the pairwise ' - 'time delay values')) + timedelay_csv = File( + desc=('A csv file containing the pairwise ' + 'time delay values')) coherence_fig = File(desc=('Figure representing coherence values')) timedelay_fig = File(desc=('Figure representing coherence values')) @@ -112,9 +135,12 @@ def _read_csv(self): # Check that input conforms to expectations: first_row = open(self.inputs.in_file).readline() if not first_row[1].isalpha(): - raise ValueError("First row of in_file should contain ROI names as strings of characters") + raise ValueError( + "First row of in_file should contain ROI names as strings of characters" + ) - roi_names = open(self.inputs.in_file).readline().replace('\"', '').strip('\n').split(',') + roi_names = open(self.inputs.in_file).readline().replace( + '\"', '').strip('\n').split(',') # Transpose, so that the time is the last dimension: data = np.loadtxt(self.inputs.in_file, skiprows=1, delimiter=',').T @@ -124,9 +150,8 @@ def _csv2ts(self): """ Read data from the in_file and generate a nitime TimeSeries object""" data, roi_names = self._read_csv() - TS = TimeSeries(data=data, - sampling_interval=self.inputs.TR, - time_unit='s') + TS = TimeSeries( + data=data, sampling_interval=self.inputs.TR, time_unit='s') TS.metadata = dict(ROIs=roi_names) @@ -150,13 +175,16 @@ def _run_interface(self, runtime): else: self.ROIs = TS.metadata['ROIs'] - A = nta.CoherenceAnalyzer(TS, - method=dict(this_method='welch', - NFFT=self.inputs.NFFT, - n_overlap=self.inputs.n_overlap)) + A = nta.CoherenceAnalyzer( + TS, + method=dict( + this_method='welch', + NFFT=self.inputs.NFFT, + n_overlap=self.inputs.n_overlap)) - freq_idx = np.where((A.frequencies > self.inputs.frequency_range[0]) * - (A.frequencies < self.inputs.frequency_range[1]))[0] + freq_idx = np.where( + (A.frequencies > self.inputs.frequency_range[0]) * + (A.frequencies < self.inputs.frequency_range[1]))[0] # Get the coherence matrix from the analyzer, averaging on the last # (frequency) dimension: (roi X roi array) @@ -179,20 +207,25 @@ def _list_outputs(self): outputs['timedelay_array'] = self.delay # Conditional - if isdefined(self.inputs.output_csv_file) and hasattr(self, 'coherence'): + if isdefined(self.inputs.output_csv_file) and hasattr( + self, 'coherence'): # we need to make a function that we call here that writes the # coherence values to this file "coherence_csv" and makes the # time_delay csv file?? self._make_output_files() - outputs['coherence_csv'] = fname_presuffix(self.inputs.output_csv_file, suffix='_coherence') + outputs['coherence_csv'] = fname_presuffix( + self.inputs.output_csv_file, suffix='_coherence') - outputs['timedelay_csv'] = fname_presuffix(self.inputs.output_csv_file, suffix='_delay') + outputs['timedelay_csv'] = fname_presuffix( + self.inputs.output_csv_file, suffix='_delay') - if isdefined(self.inputs.output_figure_file) and hasattr(self, - 'coherence'): + if isdefined(self.inputs.output_figure_file) and hasattr( + self, 'coherence'): self._make_output_figures() - outputs['coherence_fig'] = fname_presuffix(self.inputs.output_figure_file, suffix='_coherence') - outputs['timedelay_fig'] = fname_presuffix(self.inputs.output_figure_file, suffix='_delay') + outputs['coherence_fig'] = fname_presuffix( + self.inputs.output_figure_file, suffix='_coherence') + outputs['timedelay_fig'] = fname_presuffix( + self.inputs.output_figure_file, suffix='_delay') return outputs @@ -204,8 +237,9 @@ def _make_output_files(self): tmp_f = tempfile.mkstemp()[1] np.savetxt(tmp_f, this[0], delimiter=',') - fid = open(fname_presuffix(self.inputs.output_csv_file, - suffix='_%s' % this[1]), 'w+') + fid = open( + fname_presuffix( + self.inputs.output_csv_file, suffix='_%s' % this[1]), 'w+') # this writes ROIs as header line fid.write(',' + ','.join(self.ROIs) + '\n') # this writes ROI and data to a line @@ -220,31 +254,33 @@ def _make_output_figures(self): """ if self.inputs.figure_type == 'matrix': - fig_coh = viz.drawmatrix_channels(self.coherence, - channel_names=self.ROIs, - color_anchor=0) + fig_coh = viz.drawmatrix_channels( + self.coherence, channel_names=self.ROIs, color_anchor=0) - fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file, - suffix='_coherence')) + fig_coh.savefig( + fname_presuffix( + self.inputs.output_figure_file, suffix='_coherence')) - fig_dt = viz.drawmatrix_channels(self.delay, - channel_names=self.ROIs, - color_anchor=0) + fig_dt = viz.drawmatrix_channels( + self.delay, channel_names=self.ROIs, color_anchor=0) - fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file, - suffix='_delay')) + fig_dt.savefig( + fname_presuffix( + self.inputs.output_figure_file, suffix='_delay')) else: - fig_coh = viz.drawgraph_channels(self.coherence, - channel_names=self.ROIs) + fig_coh = viz.drawgraph_channels( + self.coherence, channel_names=self.ROIs) - fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file, - suffix='_coherence')) + fig_coh.savefig( + fname_presuffix( + self.inputs.output_figure_file, suffix='_coherence')) - fig_dt = viz.drawgraph_channels(self.delay, - channel_names=self.ROIs) + fig_dt = viz.drawgraph_channels( + self.delay, channel_names=self.ROIs) - fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file, - suffix='_delay')) + fig_dt.savefig( + fname_presuffix( + self.inputs.output_figure_file, suffix='_delay')) class GetTimeSeriesInputSpec(object): diff --git a/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py b/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py index 159907b978..37cc19d41b 100644 --- a/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py +++ b/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py @@ -4,39 +4,35 @@ def test_CoherenceAnalyzer_inputs(): - input_map = dict(NFFT=dict(usedefault=True, - ), - TR=dict(), - figure_type=dict(usedefault=True, - ), - frequency_range=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_TS=dict(), - in_file=dict(requires=('TR',), - ), - n_overlap=dict(usedefault=True, - ), - output_csv_file=dict(), - output_figure_file=dict(), + input_map = dict( + NFFT=dict(usedefault=True, ), + TR=dict(), + figure_type=dict(usedefault=True, ), + frequency_range=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_TS=dict(), + in_file=dict(requires=('TR', ), ), + n_overlap=dict(usedefault=True, ), + output_csv_file=dict(), + output_figure_file=dict(), ) inputs = CoherenceAnalyzer.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CoherenceAnalyzer_outputs(): - output_map = dict(coherence_array=dict(), - coherence_csv=dict(), - coherence_fig=dict(), - timedelay_array=dict(), - timedelay_csv=dict(), - timedelay_fig=dict(), + output_map = dict( + coherence_array=dict(), + coherence_csv=dict(), + coherence_fig=dict(), + timedelay_array=dict(), + timedelay_csv=dict(), + timedelay_fig=dict(), ) outputs = CoherenceAnalyzer.output_spec() diff --git a/nipype/interfaces/nitime/tests/test_nitime.py b/nipype/interfaces/nitime/tests/test_nitime.py index d37fea4f4f..daea1a177b 100644 --- a/nipype/interfaces/nitime/tests/test_nitime.py +++ b/nipype/interfaces/nitime/tests/test_nitime.py @@ -21,7 +21,8 @@ def test_read_csv(): CA = nitime.CoherenceAnalyzer() CA.inputs.TR = 1.89 # bogus value just to pass traits test CA.inputs.in_file = example_data('fmri_timeseries_nolabels.csv') - with pytest.raises(ValueError): CA._read_csv() + with pytest.raises(ValueError): + CA._read_csv() CA.inputs.in_file = example_data('fmri_timeseries.csv') data, roi_names = CA._read_csv() @@ -64,14 +65,18 @@ def test_coherence_analysis(tmpdir): assert (CA._csv2ts().data == T.data).all() T.metadata['roi'] = roi_names - C = nta.CoherenceAnalyzer(T, method=dict(this_method='welch', - NFFT=CA.inputs.NFFT, - n_overlap=CA.inputs.n_overlap)) + C = nta.CoherenceAnalyzer( + T, + method=dict( + this_method='welch', + NFFT=CA.inputs.NFFT, + n_overlap=CA.inputs.n_overlap)) freq_idx = np.where((C.frequencies > CA.inputs.frequency_range[0]) * (C.frequencies < CA.inputs.frequency_range[1]))[0] # Extract the coherence and average across these frequency bands: - coh = np.mean(C.coherence[:, :, freq_idx], -1) # Averaging on the last dimension + # Averaging is done on the last dimension + coh = np.mean(C.coherence[:, :, freq_idx], -1) assert (o.outputs.coherence_array == coh).all() diff --git a/nipype/interfaces/petpvc.py b/nipype/interfaces/petpvc.py index dbb3a25d1a..c26dd4d588 100644 --- a/nipype/interfaces/petpvc.py +++ b/nipype/interfaces/petpvc.py @@ -8,7 +8,8 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os @@ -16,47 +17,53 @@ from ..utils.filemanip import fname_presuffix from ..external.due import BibTeX -pvc_methods = ['GTM', - 'IY', - 'IY+RL', - 'IY+VC', - 'LABBE', - 'LABBE+MTC', - 'LABBE+MTC+RL', - 'LABBE+MTC+VC', - 'LABBE+RBV', - 'LABBE+RBV+RL', - 'LABBE+RBV+VC', - 'MG', - 'MG+RL', - 'MG+VC', - 'MTC', - 'MTC+RL', - 'MTC+VC', - 'RBV', - 'RBV+RL', - 'RBV+VC', - 'RL', - 'VC'] +pvc_methods = [ + 'GTM', 'IY', 'IY+RL', 'IY+VC', 'LABBE', 'LABBE+MTC', 'LABBE+MTC+RL', + 'LABBE+MTC+VC', 'LABBE+RBV', 'LABBE+RBV+RL', 'LABBE+RBV+VC', 'MG', 'MG+RL', + 'MG+VC', 'MTC', 'MTC+RL', 'MTC+VC', 'RBV', 'RBV+RL', 'RBV+VC', 'RL', 'VC' +] class PETPVCInputSpec(CommandLineInputSpec): - in_file = File(desc="PET image file", exists=True, mandatory=True, argstr="-i %s") - out_file = File(desc="Output file", genfile=True, hash_files=False, argstr="-o %s") - mask_file = File(desc="Mask image file", exists=True, mandatory=True, argstr="-m %s") - pvc = traits.Enum(pvc_methods, desc="Desired PVC method", mandatory=True, argstr="-p %s") - fwhm_x = traits.Float(desc="The full-width at half maximum in mm along x-axis", mandatory=True, argstr="-x %.4f") - fwhm_y = traits.Float(desc="The full-width at half maximum in mm along y-axis", mandatory=True, argstr="-y %.4f") - fwhm_z = traits.Float(desc="The full-width at half maximum in mm along z-axis", mandatory=True, argstr="-z %.4f") - debug = traits.Bool (desc="Prints debug information", usedefault=True, default_value=False, argstr="-d") - n_iter = traits.Int (desc="Number of iterations", default_value=10, argstr="-n %d") - n_deconv = traits.Int (desc="Number of deconvolution iterations", default_value=10, argstr="-k %d") - alpha = traits.Float(desc="Alpha value", default_value=1.5, argstr="-a %.4f") - stop_crit = traits.Float(desc="Stopping criterion", default_value=0.01, argstr="-a %.4f") + in_file = File( + desc="PET image file", exists=True, mandatory=True, argstr="-i %s") + out_file = File( + desc="Output file", genfile=True, hash_files=False, argstr="-o %s") + mask_file = File( + desc="Mask image file", exists=True, mandatory=True, argstr="-m %s") + pvc = traits.Enum( + pvc_methods, desc="Desired PVC method", mandatory=True, argstr="-p %s") + fwhm_x = traits.Float( + desc="The full-width at half maximum in mm along x-axis", + mandatory=True, + argstr="-x %.4f") + fwhm_y = traits.Float( + desc="The full-width at half maximum in mm along y-axis", + mandatory=True, + argstr="-y %.4f") + fwhm_z = traits.Float( + desc="The full-width at half maximum in mm along z-axis", + mandatory=True, + argstr="-z %.4f") + debug = traits.Bool( + desc="Prints debug information", + usedefault=True, + default_value=False, + argstr="-d") + n_iter = traits.Int( + desc="Number of iterations", default_value=10, argstr="-n %d") + n_deconv = traits.Int( + desc="Number of deconvolution iterations", + default_value=10, + argstr="-k %d") + alpha = traits.Float( + desc="Alpha value", default_value=1.5, argstr="-a %.4f") + stop_crit = traits.Float( + desc="Stopping criterion", default_value=0.01, argstr="-a %.4f") class PETPVCOutputSpec(TraitedSpec): - out_file = File(desc = "Output file") + out_file = File(desc="Output file") class PETPVC(CommandLine): @@ -147,35 +154,43 @@ class PETPVC(CommandLine): output_spec = PETPVCOutputSpec _cmd = 'petpvc' - references_ = [{'entry': BibTeX("@article{0031-9155-61-22-7975," - "author={Benjamin A Thomas and Vesna Cuplov and Alexandre Bousse and " - "Adriana Mendes and Kris Thielemans and Brian F Hutton and Kjell Erlandsson}," - "title={PETPVC: a toolbox for performing partial volume correction " - "techniques in positron emission tomography}," - "journal={Physics in Medicine and Biology}," - "volume={61}," - "number={22}," - "pages={7975}," - "url={http://stacks.iop.org/0031-9155/61/i=22/a=7975}," - "doi={http://dx.doi.org/10.1088/0031-9155/61/22/7975}," - "year={2016}," - "}"), - 'description': 'PETPVC software implementation publication', - 'tags': ['implementation'], - }] + references_ = [{ + 'entry': + BibTeX( + "@article{0031-9155-61-22-7975," + "author={Benjamin A Thomas and Vesna Cuplov and Alexandre Bousse and " + "Adriana Mendes and Kris Thielemans and Brian F Hutton and Kjell Erlandsson}," + "title={PETPVC: a toolbox for performing partial volume correction " + "techniques in positron emission tomography}," + "journal={Physics in Medicine and Biology}," + "volume={61}," + "number={22}," + "pages={7975}," + "url={http://stacks.iop.org/0031-9155/61/i=22/a=7975}," + "doi={http://dx.doi.org/10.1088/0031-9155/61/22/7975}," + "year={2016}," + "}"), + 'description': + 'PETPVC software implementation publication', + 'tags': ['implementation'], + }] def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = self.inputs.out_file if not isdefined(outputs['out_file']): method_name = self.inputs.pvc.lower() - outputs['out_file'] = self._gen_fname(self.inputs.in_file, - suffix='_{}_pvc'.format(method_name)) + outputs['out_file'] = self._gen_fname( + self.inputs.in_file, suffix='_{}_pvc'.format(method_name)) outputs['out_file'] = os.path.abspath(outputs['out_file']) return outputs - def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, + def _gen_fname(self, + basename, + cwd=None, + suffix=None, + change_ext=True, ext='.nii.gz'): """Generate a filename based on the given parameters. @@ -214,8 +229,8 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, suffix = ext if suffix is None: suffix = '' - fname = fname_presuffix(basename, suffix=suffix, - use_ext=False, newpath=cwd) + fname = fname_presuffix( + basename, suffix=suffix, use_ext=False, newpath=cwd) return fname def _gen_filename(self, name): diff --git a/nipype/interfaces/quickshear.py b/nipype/interfaces/quickshear.py index a0e9c79a1c..4b0f8dd01c 100644 --- a/nipype/interfaces/quickshear.py +++ b/nipype/interfaces/quickshear.py @@ -14,16 +14,30 @@ class QuickshearInputSpec(CommandLineInputSpec): - in_file = File(exists=True, position=1, argstr='%s', mandatory=True, - desc="neuroimage to deface") - mask_file = File(exists=True, position=2, argstr='%s', desc="brain mask", - mandatory=True) - out_file = File(name_template="%s_defaced", name_source='in_file', - position=3, argstr='%s', desc="defaced output image", - keep_extension=True) - buff = traits.Int(position=4, argstr='%d', - desc='buffer size (in voxels) between shearing ' - 'plane and the brain') + in_file = File( + exists=True, + position=1, + argstr='%s', + mandatory=True, + desc="neuroimage to deface") + mask_file = File( + exists=True, + position=2, + argstr='%s', + desc="brain mask", + mandatory=True) + out_file = File( + name_template="%s_defaced", + name_source='in_file', + position=3, + argstr='%s', + desc="defaced output image", + keep_extension=True) + buff = traits.Int( + position=4, + argstr='%d', + desc='buffer size (in voxels) between shearing ' + 'plane and the brain') class QuickshearOutputSpec(TraitedSpec): @@ -69,15 +83,15 @@ class Quickshear(CommandLine): input_spec = QuickshearInputSpec output_spec = QuickshearOutputSpec - references_ = [ - {'entry': - BibTeX('@inproceedings{Schimke2011,' - 'address = {San Francisco},' - 'author = {Schimke, Nakeisha and Hale, John},' - 'booktitle = {Proceedings of the 2nd USENIX Conference on ' - 'Health Security and Privacy},' - 'title = {{Quickshear Defacing for Neuroimages}},' - 'year = {2011},' - 'month = sep}'), - 'tags': ['implementation'], - }] + references_ = [{ + 'entry': + BibTeX('@inproceedings{Schimke2011,' + 'address = {San Francisco},' + 'author = {Schimke, Nakeisha and Hale, John},' + 'booktitle = {Proceedings of the 2nd USENIX Conference on ' + 'Health Security and Privacy},' + 'title = {{Quickshear Defacing for Neuroimages}},' + 'year = {2011},' + 'month = sep}'), + 'tags': ['implementation'], + }] diff --git a/nipype/interfaces/semtools/brains/__init__.py b/nipype/interfaces/semtools/brains/__init__.py index 20c87b7dda..ebfab84bf3 100644 --- a/nipype/interfaces/semtools/brains/__init__.py +++ b/nipype/interfaces/semtools/brains/__init__.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import from .segmentation import SimilarityIndex, BRAINSTalairach, BRAINSTalairachMask -from .utilities import HistogramMatchingFilter, GenerateEdgeMapImage, GeneratePurePlugMask +from .utilities import (HistogramMatchingFilter, GenerateEdgeMapImage, + GeneratePurePlugMask) from .classify import BRAINSPosteriorToContinuousClass diff --git a/nipype/interfaces/semtools/brains/classify.py b/nipype/interfaces/semtools/brains/classify.py index 26b7c97dda..89bb74f039 100644 --- a/nipype/interfaces/semtools/brains/classify.py +++ b/nipype/interfaces/semtools/brains/classify.py @@ -11,22 +11,46 @@ class BRAINSPosteriorToContinuousClassInputSpec(CommandLineInputSpec): - inputWhiteVolume = File(desc="White Matter Posterior Volume", exists=True, argstr="--inputWhiteVolume %s") - inputBasalGmVolume = File(desc="Basal Grey Matter Posterior Volume", exists=True, argstr="--inputBasalGmVolume %s") - inputSurfaceGmVolume = File(desc="Surface Grey Matter Posterior Volume", exists=True, argstr="--inputSurfaceGmVolume %s") - inputCsfVolume = File(desc="CSF Posterior Volume", exists=True, argstr="--inputCsfVolume %s") - inputVbVolume = File(desc="Venous Blood Posterior Volume", exists=True, argstr="--inputVbVolume %s") - inputCrblGmVolume = File(desc="Cerebellum Grey Matter Posterior Volume", exists=True, argstr="--inputCrblGmVolume %s") - inputCrblWmVolume = File(desc="Cerebellum White Matter Posterior Volume", exists=True, argstr="--inputCrblWmVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Continuous Tissue Classified Image", argstr="--outputVolume %s") + inputWhiteVolume = File( + desc="White Matter Posterior Volume", + exists=True, + argstr="--inputWhiteVolume %s") + inputBasalGmVolume = File( + desc="Basal Grey Matter Posterior Volume", + exists=True, + argstr="--inputBasalGmVolume %s") + inputSurfaceGmVolume = File( + desc="Surface Grey Matter Posterior Volume", + exists=True, + argstr="--inputSurfaceGmVolume %s") + inputCsfVolume = File( + desc="CSF Posterior Volume", exists=True, argstr="--inputCsfVolume %s") + inputVbVolume = File( + desc="Venous Blood Posterior Volume", + exists=True, + argstr="--inputVbVolume %s") + inputCrblGmVolume = File( + desc="Cerebellum Grey Matter Posterior Volume", + exists=True, + argstr="--inputCrblGmVolume %s") + inputCrblWmVolume = File( + desc="Cerebellum White Matter Posterior Volume", + exists=True, + argstr="--inputCrblWmVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output Continuous Tissue Classified Image", + argstr="--outputVolume %s") class BRAINSPosteriorToContinuousClassOutputSpec(TraitedSpec): - outputVolume = File(desc="Output Continuous Tissue Classified Image", exists=True) + outputVolume = File( + desc="Output Continuous Tissue Classified Image", exists=True) class BRAINSPosteriorToContinuousClass(SEMLikeCommandLine): - """title: Tissue Classification category: BRAINS.Classify diff --git a/nipype/interfaces/semtools/brains/segmentation.py b/nipype/interfaces/semtools/brains/segmentation.py index 8de2d5e7d6..fae5e4f1a2 100644 --- a/nipype/interfaces/semtools/brains/segmentation.py +++ b/nipype/interfaces/semtools/brains/segmentation.py @@ -11,10 +11,22 @@ class SimilarityIndexInputSpec(CommandLineInputSpec): - outputCSVFilename = File(desc="output CSV Filename", exists=True, argstr="--outputCSVFilename %s") - ANNContinuousVolume = File(desc="ANN Continuous volume to be compared to the manual volume", exists=True, argstr="--ANNContinuousVolume %s") - inputManualVolume = File(desc="input manual(reference) volume", exists=True, argstr="--inputManualVolume %s") - thresholdInterval = traits.Float(desc="Threshold interval to compute similarity index between zero and one", argstr="--thresholdInterval %f") + outputCSVFilename = File( + desc="output CSV Filename", + exists=True, + argstr="--outputCSVFilename %s") + ANNContinuousVolume = File( + desc="ANN Continuous volume to be compared to the manual volume", + exists=True, + argstr="--ANNContinuousVolume %s") + inputManualVolume = File( + desc="input manual(reference) volume", + exists=True, + argstr="--inputManualVolume %s") + thresholdInterval = traits.Float( + desc= + "Threshold interval to compute similarity index between zero and one", + argstr="--thresholdInterval %f") class SimilarityIndexOutputSpec(TraitedSpec): @@ -22,7 +34,6 @@ class SimilarityIndexOutputSpec(TraitedSpec): class SimilarityIndex(SEMLikeCommandLine): - """title: BRAINSCut:SimilarityIndexComputation category: BRAINS.Segmentation @@ -45,26 +56,50 @@ class SimilarityIndex(SEMLikeCommandLine): class BRAINSTalairachInputSpec(CommandLineInputSpec): - AC = InputMultiPath(traits.Float, desc="Location of AC Point ", sep=",", argstr="--AC %s") + AC = InputMultiPath( + traits.Float, desc="Location of AC Point ", sep=",", argstr="--AC %s") ACisIndex = traits.Bool(desc="AC Point is Index", argstr="--ACisIndex ") - PC = InputMultiPath(traits.Float, desc="Location of PC Point ", sep=",", argstr="--PC %s") + PC = InputMultiPath( + traits.Float, desc="Location of PC Point ", sep=",", argstr="--PC %s") PCisIndex = traits.Bool(desc="PC Point is Index", argstr="--PCisIndex ") - SLA = InputMultiPath(traits.Float, desc="Location of SLA Point ", sep=",", argstr="--SLA %s") + SLA = InputMultiPath( + traits.Float, + desc="Location of SLA Point ", + sep=",", + argstr="--SLA %s") SLAisIndex = traits.Bool(desc="SLA Point is Index", argstr="--SLAisIndex ") - IRP = InputMultiPath(traits.Float, desc="Location of IRP Point ", sep=",", argstr="--IRP %s") + IRP = InputMultiPath( + traits.Float, + desc="Location of IRP Point ", + sep=",", + argstr="--IRP %s") IRPisIndex = traits.Bool(desc="IRP Point is Index", argstr="--IRPisIndex ") - inputVolume = File(desc="Input image used to define physical space of images", exists=True, argstr="--inputVolume %s") - outputBox = traits.Either(traits.Bool, File(), hash_files=False, desc="Name of the resulting Talairach Bounding Box file", argstr="--outputBox %s") - outputGrid = traits.Either(traits.Bool, File(), hash_files=False, desc="Name of the resulting Talairach Grid file", argstr="--outputGrid %s") + inputVolume = File( + desc="Input image used to define physical space of images", + exists=True, + argstr="--inputVolume %s") + outputBox = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Name of the resulting Talairach Bounding Box file", + argstr="--outputBox %s") + outputGrid = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Name of the resulting Talairach Grid file", + argstr="--outputGrid %s") class BRAINSTalairachOutputSpec(TraitedSpec): - outputBox = File(desc="Name of the resulting Talairach Bounding Box file", exists=True) - outputGrid = File(desc="Name of the resulting Talairach Grid file", exists=True) + outputBox = File( + desc="Name of the resulting Talairach Bounding Box file", exists=True) + outputGrid = File( + desc="Name of the resulting Talairach Grid file", exists=True) class BRAINSTalairach(SEMLikeCommandLine): - """title: BRAINS Talairach category: BRAINS.Segmentation @@ -91,20 +126,40 @@ class BRAINSTalairach(SEMLikeCommandLine): class BRAINSTalairachMaskInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Input image used to define physical space of resulting mask", exists=True, argstr="--inputVolume %s") - talairachParameters = File(desc="Name of the Talairach parameter file.", exists=True, argstr="--talairachParameters %s") - talairachBox = File(desc="Name of the Talairach box file.", exists=True, argstr="--talairachBox %s") - hemisphereMode = traits.Enum("left", "right", "both", desc="Mode for box creation: left, right, both", argstr="--hemisphereMode %s") - expand = traits.Bool(desc="Expand exterior box to include surface CSF", argstr="--expand ") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output filename for the resulting binary image", argstr="--outputVolume %s") + inputVolume = File( + desc="Input image used to define physical space of resulting mask", + exists=True, + argstr="--inputVolume %s") + talairachParameters = File( + desc="Name of the Talairach parameter file.", + exists=True, + argstr="--talairachParameters %s") + talairachBox = File( + desc="Name of the Talairach box file.", + exists=True, + argstr="--talairachBox %s") + hemisphereMode = traits.Enum( + "left", + "right", + "both", + desc="Mode for box creation: left, right, both", + argstr="--hemisphereMode %s") + expand = traits.Bool( + desc="Expand exterior box to include surface CSF", argstr="--expand ") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output filename for the resulting binary image", + argstr="--outputVolume %s") class BRAINSTalairachMaskOutputSpec(TraitedSpec): - outputVolume = File(desc="Output filename for the resulting binary image", exists=True) + outputVolume = File( + desc="Output filename for the resulting binary image", exists=True) class BRAINSTalairachMask(SEMLikeCommandLine): - """title: Talairach Mask category: BRAINS.Segmentation diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py index 1c2f7ce2cb..d52a1a7805 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py @@ -4,46 +4,40 @@ def test_BRAINSPosteriorToContinuousClass_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBasalGmVolume=dict(argstr='--inputBasalGmVolume %s', - ), - inputCrblGmVolume=dict(argstr='--inputCrblGmVolume %s', - ), - inputCrblWmVolume=dict(argstr='--inputCrblWmVolume %s', - ), - inputCsfVolume=dict(argstr='--inputCsfVolume %s', - ), - inputSurfaceGmVolume=dict(argstr='--inputSurfaceGmVolume %s', - ), - inputVbVolume=dict(argstr='--inputVbVolume %s', - ), - inputWhiteVolume=dict(argstr='--inputWhiteVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBasalGmVolume=dict(argstr='--inputBasalGmVolume %s', ), + inputCrblGmVolume=dict(argstr='--inputCrblGmVolume %s', ), + inputCrblWmVolume=dict(argstr='--inputCrblWmVolume %s', ), + inputCsfVolume=dict(argstr='--inputCsfVolume %s', ), + inputSurfaceGmVolume=dict(argstr='--inputSurfaceGmVolume %s', ), + inputVbVolume=dict(argstr='--inputVbVolume %s', ), + inputWhiteVolume=dict(argstr='--inputWhiteVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSPosteriorToContinuousClass.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSPosteriorToContinuousClass_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSPosteriorToContinuousClass.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py index 1168288a8b..eee6069119 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py @@ -4,57 +4,60 @@ def test_BRAINSTalairach_inputs(): - input_map = dict(AC=dict(argstr='--AC %s', - sep=',', - ), - ACisIndex=dict(argstr='--ACisIndex ', - ), - IRP=dict(argstr='--IRP %s', - sep=',', - ), - IRPisIndex=dict(argstr='--IRPisIndex ', - ), - PC=dict(argstr='--PC %s', - sep=',', - ), - PCisIndex=dict(argstr='--PCisIndex ', - ), - SLA=dict(argstr='--SLA %s', - sep=',', - ), - SLAisIndex=dict(argstr='--SLAisIndex ', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputBox=dict(argstr='--outputBox %s', - hash_files=False, - ), - outputGrid=dict(argstr='--outputGrid %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + AC=dict( + argstr='--AC %s', + sep=',', + ), + ACisIndex=dict(argstr='--ACisIndex ', ), + IRP=dict( + argstr='--IRP %s', + sep=',', + ), + IRPisIndex=dict(argstr='--IRPisIndex ', ), + PC=dict( + argstr='--PC %s', + sep=',', + ), + PCisIndex=dict(argstr='--PCisIndex ', ), + SLA=dict( + argstr='--SLA %s', + sep=',', + ), + SLAisIndex=dict(argstr='--SLAisIndex ', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputBox=dict( + argstr='--outputBox %s', + hash_files=False, + ), + outputGrid=dict( + argstr='--outputGrid %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSTalairach.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSTalairach_outputs(): - output_map = dict(outputBox=dict(), - outputGrid=dict(), + output_map = dict( + outputBox=dict(), + outputGrid=dict(), ) outputs = BRAINSTalairach.output_spec() diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py index 6638bd2e5e..b57994f6a7 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py @@ -4,42 +4,38 @@ def test_BRAINSTalairachMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - expand=dict(argstr='--expand ', - ), - hemisphereMode=dict(argstr='--hemisphereMode %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - talairachBox=dict(argstr='--talairachBox %s', - ), - talairachParameters=dict(argstr='--talairachParameters %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + expand=dict(argstr='--expand ', ), + hemisphereMode=dict(argstr='--hemisphereMode %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + talairachBox=dict(argstr='--talairachBox %s', ), + talairachParameters=dict(argstr='--talairachParameters %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSTalairachMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSTalairachMask_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSTalairachMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py b/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py index cfee35cd08..3e9358a4b2 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py @@ -4,49 +4,46 @@ def test_GenerateEdgeMapImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMRVolumes=dict(argstr='--inputMRVolumes %s...', - ), - inputMask=dict(argstr='--inputMask %s', - ), - lowerPercentileMatching=dict(argstr='--lowerPercentileMatching %f', - ), - maximumOutputRange=dict(argstr='--maximumOutputRange %d', - ), - minimumOutputRange=dict(argstr='--minimumOutputRange %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputEdgeMap=dict(argstr='--outputEdgeMap %s', - hash_files=False, - ), - outputMaximumGradientImage=dict(argstr='--outputMaximumGradientImage %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upperPercentileMatching=dict(argstr='--upperPercentileMatching %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMRVolumes=dict(argstr='--inputMRVolumes %s...', ), + inputMask=dict(argstr='--inputMask %s', ), + lowerPercentileMatching=dict(argstr='--lowerPercentileMatching %f', ), + maximumOutputRange=dict(argstr='--maximumOutputRange %d', ), + minimumOutputRange=dict(argstr='--minimumOutputRange %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputEdgeMap=dict( + argstr='--outputEdgeMap %s', + hash_files=False, + ), + outputMaximumGradientImage=dict( + argstr='--outputMaximumGradientImage %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upperPercentileMatching=dict(argstr='--upperPercentileMatching %f', ), ) inputs = GenerateEdgeMapImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateEdgeMapImage_outputs(): - output_map = dict(outputEdgeMap=dict(), - outputMaximumGradientImage=dict(), + output_map = dict( + outputEdgeMap=dict(), + outputMaximumGradientImage=dict(), ) outputs = GenerateEdgeMapImage.output_spec() diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py b/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py index 48c4aca838..e3d4464e0e 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py @@ -4,39 +4,39 @@ def test_GeneratePurePlugMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputImageModalities=dict(argstr='--inputImageModalities %s...', - ), - numberOfSubSamples=dict(argstr='--numberOfSubSamples %s', - sep=',', - ), - outputMaskFile=dict(argstr='--outputMaskFile %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--threshold %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputImageModalities=dict(argstr='--inputImageModalities %s...', ), + numberOfSubSamples=dict( + argstr='--numberOfSubSamples %s', + sep=',', + ), + outputMaskFile=dict( + argstr='--outputMaskFile %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='--threshold %f', ), ) inputs = GeneratePurePlugMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GeneratePurePlugMask_outputs(): - output_map = dict(outputMaskFile=dict(), - ) + output_map = dict(outputMaskFile=dict(), ) outputs = GeneratePurePlugMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py b/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py index ac921cb7f6..99b5617534 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py @@ -4,50 +4,42 @@ def test_HistogramMatchingFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - histogramAlgorithm=dict(argstr='--histogramAlgorithm %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBinaryVolume=dict(argstr='--inputBinaryVolume %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - referenceBinaryVolume=dict(argstr='--referenceBinaryVolume %s', - ), - referenceVolume=dict(argstr='--referenceVolume %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), - writeHistogram=dict(argstr='--writeHistogram %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + histogramAlgorithm=dict(argstr='--histogramAlgorithm %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBinaryVolume=dict(argstr='--inputBinaryVolume %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + referenceBinaryVolume=dict(argstr='--referenceBinaryVolume %s', ), + referenceVolume=dict(argstr='--referenceVolume %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), + writeHistogram=dict(argstr='--writeHistogram %s', ), ) inputs = HistogramMatchingFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_HistogramMatchingFilter_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = HistogramMatchingFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py b/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py index e9ddc61051..099454f73a 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py @@ -4,34 +4,31 @@ def test_SimilarityIndex_inputs(): - input_map = dict(ANNContinuousVolume=dict(argstr='--ANNContinuousVolume %s', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputManualVolume=dict(argstr='--inputManualVolume %s', - ), - outputCSVFilename=dict(argstr='--outputCSVFilename %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresholdInterval=dict(argstr='--thresholdInterval %f', - ), + input_map = dict( + ANNContinuousVolume=dict(argstr='--ANNContinuousVolume %s', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputManualVolume=dict(argstr='--inputManualVolume %s', ), + outputCSVFilename=dict(argstr='--outputCSVFilename %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresholdInterval=dict(argstr='--thresholdInterval %f', ), ) inputs = SimilarityIndex.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SimilarityIndex_outputs(): output_map = dict() outputs = SimilarityIndex.output_spec() diff --git a/nipype/interfaces/semtools/brains/utilities.py b/nipype/interfaces/semtools/brains/utilities.py index 577975e10a..d794c9c587 100644 --- a/nipype/interfaces/semtools/brains/utilities.py +++ b/nipype/interfaces/semtools/brains/utilities.py @@ -11,16 +11,41 @@ class HistogramMatchingFilterInputSpec(CommandLineInputSpec): - inputVolume = File(desc="The Input image to be computed for statistics", exists=True, argstr="--inputVolume %s") - referenceVolume = File(desc="The Input image to be computed for statistics", exists=True, argstr="--referenceVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Image File Name", argstr="--outputVolume %s") - referenceBinaryVolume = File(desc="referenceBinaryVolume", exists=True, argstr="--referenceBinaryVolume %s") - inputBinaryVolume = File(desc="inputBinaryVolume", exists=True, argstr="--inputBinaryVolume %s") - numberOfMatchPoints = traits.Int(desc=" number of histogram matching points", argstr="--numberOfMatchPoints %d") - numberOfHistogramBins = traits.Int(desc=" number of histogram bin", argstr="--numberOfHistogramBins %d") - writeHistogram = traits.Str(desc=" decide if histogram data would be written with prefixe of the file name", argstr="--writeHistogram %s") - histogramAlgorithm = traits.Enum("OtsuHistogramMatching", desc=" histogram algrithm selection", argstr="--histogramAlgorithm %s") - verbose = traits.Bool(desc=" verbose mode running for debbuging", argstr="--verbose ") + inputVolume = File( + desc="The Input image to be computed for statistics", + exists=True, + argstr="--inputVolume %s") + referenceVolume = File( + desc="The Input image to be computed for statistics", + exists=True, + argstr="--referenceVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output Image File Name", + argstr="--outputVolume %s") + referenceBinaryVolume = File( + desc="referenceBinaryVolume", + exists=True, + argstr="--referenceBinaryVolume %s") + inputBinaryVolume = File( + desc="inputBinaryVolume", exists=True, argstr="--inputBinaryVolume %s") + numberOfMatchPoints = traits.Int( + desc=" number of histogram matching points", + argstr="--numberOfMatchPoints %d") + numberOfHistogramBins = traits.Int( + desc=" number of histogram bin", argstr="--numberOfHistogramBins %d") + writeHistogram = traits.Str( + desc= + " decide if histogram data would be written with prefixe of the file name", + argstr="--writeHistogram %s") + histogramAlgorithm = traits.Enum( + "OtsuHistogramMatching", + desc=" histogram algrithm selection", + argstr="--histogramAlgorithm %s") + verbose = traits.Bool( + desc=" verbose mode running for debbuging", argstr="--verbose ") class HistogramMatchingFilterOutputSpec(TraitedSpec): @@ -28,7 +53,6 @@ class HistogramMatchingFilterOutputSpec(TraitedSpec): class HistogramMatchingFilter(SEMLikeCommandLine): - """title: Write Out Image Intensities category: BRAINS.Utilities @@ -47,24 +71,58 @@ class HistogramMatchingFilter(SEMLikeCommandLine): _outputs_filenames = {'outputVolume': 'outputVolume.nii'} _redirect_x = False + class GenerateEdgeMapImageInputSpec(CommandLineInputSpec): - inputMRVolumes = InputMultiPath(File(exists=True), desc="List of input structural MR volumes to create the maximum edgemap", argstr="--inputMRVolumes %s...") - inputMask = File(desc="Input mask file name. If set, image histogram percentiles will be calculated within the mask", exists=True, argstr="--inputMask %s") - minimumOutputRange = traits.Int(desc="Map lower quantile and below to minimum output range. It should be a small number greater than zero. Default is 1", argstr="--minimumOutputRange %d") - maximumOutputRange = traits.Int(desc="Map upper quantile and above to maximum output range. Default is 255 that is the maximum range of unsigned char", argstr="--maximumOutputRange %d") - lowerPercentileMatching = traits.Float(desc="Map lower quantile and below to minOutputRange. It should be a value between zero and one", argstr="--lowerPercentileMatching %f") - upperPercentileMatching = traits.Float(desc="Map upper quantile and above to maxOutputRange. It should be a value between zero and one", argstr="--upperPercentileMatching %f") - outputEdgeMap = traits.Either(traits.Bool, File(), hash_files=False, desc="output edgemap file name", argstr="--outputEdgeMap %s") - outputMaximumGradientImage = traits.Either(traits.Bool, File(), hash_files=False, desc="output gradient image file name", argstr="--outputMaximumGradientImage %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputMRVolumes = InputMultiPath( + File(exists=True), + desc= + "List of input structural MR volumes to create the maximum edgemap", + argstr="--inputMRVolumes %s...") + inputMask = File( + desc= + "Input mask file name. If set, image histogram percentiles will be calculated within the mask", + exists=True, + argstr="--inputMask %s") + minimumOutputRange = traits.Int( + desc= + "Map lower quantile and below to minimum output range. It should be a small number greater than zero. Default is 1", + argstr="--minimumOutputRange %d") + maximumOutputRange = traits.Int( + desc= + "Map upper quantile and above to maximum output range. Default is 255 that is the maximum range of unsigned char", + argstr="--maximumOutputRange %d") + lowerPercentileMatching = traits.Float( + desc= + "Map lower quantile and below to minOutputRange. It should be a value between zero and one", + argstr="--lowerPercentileMatching %f") + upperPercentileMatching = traits.Float( + desc= + "Map upper quantile and above to maxOutputRange. It should be a value between zero and one", + argstr="--upperPercentileMatching %f") + outputEdgeMap = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="output edgemap file name", + argstr="--outputEdgeMap %s") + outputMaximumGradientImage = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="output gradient image file name", + argstr="--outputMaximumGradientImage %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class GenerateEdgeMapImageOutputSpec(TraitedSpec): outputEdgeMap = File(desc="(required) output file name", exists=True) - outputMaximumGradientImage = File(desc="output gradient image file name", exists=True) + outputMaximumGradientImage = File( + desc="output gradient image file name", exists=True) -class GenerateEdgeMapImage(SEMLikeCommandLine): +class GenerateEdgeMapImage(SEMLikeCommandLine): """title: GenerateEdgeMapImage category: BRAINS.Utilities @@ -80,21 +138,41 @@ class GenerateEdgeMapImage(SEMLikeCommandLine): input_spec = GenerateEdgeMapImageInputSpec output_spec = GenerateEdgeMapImageOutputSpec _cmd = " GenerateEdgeMapImage " - _outputs_filenames = {'outputEdgeMap': 'outputEdgeMap', 'outputMaximumGradientImage': 'outputMaximumGradientImage'} + _outputs_filenames = { + 'outputEdgeMap': 'outputEdgeMap', + 'outputMaximumGradientImage': 'outputMaximumGradientImage' + } _redirect_x = False + class GeneratePurePlugMaskInputSpec(CommandLineInputSpec): - inputImageModalities = InputMultiPath(File(exists=True), desc="List of input image file names to create pure plugs mask", argstr="--inputImageModalities %s...") - threshold = traits.Float(desc="threshold value to define class membership", argstr="--threshold %f") - numberOfSubSamples = InputMultiPath(traits.Int, desc="Number of continous index samples taken at each direction of lattice space for each plug volume", sep=",", argstr="--numberOfSubSamples %s") - outputMaskFile = traits.Either(traits.Bool, File(), hash_files=False, desc="Output binary mask file name", argstr="--outputMaskFile %s") + inputImageModalities = InputMultiPath( + File(exists=True), + desc="List of input image file names to create pure plugs mask", + argstr="--inputImageModalities %s...") + threshold = traits.Float( + desc="threshold value to define class membership", + argstr="--threshold %f") + numberOfSubSamples = InputMultiPath( + traits.Int, + desc= + "Number of continous index samples taken at each direction of lattice space for each plug volume", + sep=",", + argstr="--numberOfSubSamples %s") + outputMaskFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output binary mask file name", + argstr="--outputMaskFile %s") class GeneratePurePlugMaskOutputSpec(TraitedSpec): - outputMaskFile = File(desc="(required) Output binary mask file name", exists=True) + outputMaskFile = File( + desc="(required) Output binary mask file name", exists=True) -class GeneratePurePlugMask(SEMLikeCommandLine): +class GeneratePurePlugMask(SEMLikeCommandLine): """title: GeneratePurePlugMask category: BRAINS.Utilities diff --git a/nipype/interfaces/semtools/converters.py b/nipype/interfaces/semtools/converters.py index 64954fba1c..de638935e5 100644 --- a/nipype/interfaces/semtools/converters.py +++ b/nipype/interfaces/semtools/converters.py @@ -11,9 +11,17 @@ class DWISimpleCompareInputSpec(CommandLineInputSpec): - inputVolume1 = File(desc="First input volume (.nhdr or .nrrd)", exists=True, argstr="--inputVolume1 %s") - inputVolume2 = File(desc="Second input volume (.nhdr or .nrrd)", exists=True, argstr="--inputVolume2 %s") - checkDWIData = traits.Bool(desc="check for existence of DWI data, and if present, compare it", argstr="--checkDWIData ") + inputVolume1 = File( + desc="First input volume (.nhdr or .nrrd)", + exists=True, + argstr="--inputVolume1 %s") + inputVolume2 = File( + desc="Second input volume (.nhdr or .nrrd)", + exists=True, + argstr="--inputVolume2 %s") + checkDWIData = traits.Bool( + desc="check for existence of DWI data, and if present, compare it", + argstr="--checkDWIData ") class DWISimpleCompareOutputSpec(TraitedSpec): @@ -21,7 +29,6 @@ class DWISimpleCompareOutputSpec(TraitedSpec): class DWISimpleCompare(SEMLikeCommandLine): - """title: Nrrd DWI comparison category: Converters @@ -48,8 +55,14 @@ class DWISimpleCompare(SEMLikeCommandLine): class DWICompareInputSpec(CommandLineInputSpec): - inputVolume1 = File(desc="First input volume (.nhdr or .nrrd)", exists=True, argstr="--inputVolume1 %s") - inputVolume2 = File(desc="Second input volume (.nhdr or .nrrd)", exists=True, argstr="--inputVolume2 %s") + inputVolume1 = File( + desc="First input volume (.nhdr or .nrrd)", + exists=True, + argstr="--inputVolume1 %s") + inputVolume2 = File( + desc="Second input volume (.nhdr or .nrrd)", + exists=True, + argstr="--inputVolume2 %s") class DWICompareOutputSpec(TraitedSpec): @@ -57,7 +70,6 @@ class DWICompareOutputSpec(TraitedSpec): class DWICompare(SEMLikeCommandLine): - """title: Nrrd DWI comparison category: Converters diff --git a/nipype/interfaces/semtools/diffusion/__init__.py b/nipype/interfaces/semtools/diffusion/__init__.py index 100af56cbd..215cfa41d7 100644 --- a/nipype/interfaces/semtools/diffusion/__init__.py +++ b/nipype/interfaces/semtools/diffusion/__init__.py @@ -2,5 +2,14 @@ from __future__ import absolute_import from .diffusion import dtiaverage, dtiestim, dtiprocess, DWIConvert from .tractography import * -from .gtract import gtractTransformToDisplacementField, gtractInvertBSplineTransform, gtractConcatDwi, gtractAverageBvalues, gtractCoregBvalues, gtractResampleAnisotropy, gtractResampleCodeImage, gtractCopyImageOrientation, gtractCreateGuideFiber, gtractAnisotropyMap, gtractClipAnisotropy, gtractResampleB0, gtractInvertRigidTransform, gtractImageConformity, compareTractInclusion, gtractFastMarchingTracking, gtractInvertDisplacementField, gtractCoRegAnatomy, gtractResampleDWIInPlace, gtractCostFastMarching, gtractFiberTracking, extractNrrdVectorIndex, gtractResampleFibers, gtractTensor +from .gtract import ( + gtractTransformToDisplacementField, gtractInvertBSplineTransform, + gtractConcatDwi, gtractAverageBvalues, gtractCoregBvalues, + gtractResampleAnisotropy, gtractResampleCodeImage, + gtractCopyImageOrientation, gtractCreateGuideFiber, gtractAnisotropyMap, + gtractClipAnisotropy, gtractResampleB0, gtractInvertRigidTransform, + gtractImageConformity, compareTractInclusion, gtractFastMarchingTracking, + gtractInvertDisplacementField, gtractCoRegAnatomy, + gtractResampleDWIInPlace, gtractCostFastMarching, gtractFiberTracking, + extractNrrdVectorIndex, gtractResampleFibers, gtractTensor) from .maxcurvature import maxcurvature diff --git a/nipype/interfaces/semtools/diffusion/diffusion.py b/nipype/interfaces/semtools/diffusion/diffusion.py index f449964da0..af943a04fb 100644 --- a/nipype/interfaces/semtools/diffusion/diffusion.py +++ b/nipype/interfaces/semtools/diffusion/diffusion.py @@ -11,9 +11,20 @@ class dtiaverageInputSpec(CommandLineInputSpec): - inputs = InputMultiPath(File(exists=True), desc="List of all the tensor fields to be averaged", argstr="--inputs %s...") - tensor_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Averaged tensor volume", argstr="--tensor_output %s") - DTI_double = traits.Bool(desc="Tensor components are saved as doubles (cannot be visualized in Slicer)", argstr="--DTI_double ") + inputs = InputMultiPath( + File(exists=True), + desc="List of all the tensor fields to be averaged", + argstr="--inputs %s...") + tensor_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Averaged tensor volume", + argstr="--tensor_output %s") + DTI_double = traits.Bool( + desc= + "Tensor components are saved as doubles (cannot be visualized in Slicer)", + argstr="--DTI_double ") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") @@ -22,7 +33,6 @@ class dtiaverageOutputSpec(TraitedSpec): class dtiaverage(SEMLikeCommandLine): - """title: DTIAverage (DTIProcess) category: Diffusion.Diffusion Tensor Images.CommandLineOnly @@ -52,38 +62,110 @@ class dtiaverage(SEMLikeCommandLine): class dtiestimInputSpec(CommandLineInputSpec): - dwi_image = File(desc="DWI image volume (required)", exists=True, argstr="--dwi_image %s") - tensor_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Tensor OutputImage", argstr="--tensor_output %s") - B0 = traits.Either(traits.Bool, File(), hash_files=False, desc="Baseline image, average of all baseline images", argstr="--B0 %s") - idwi = traits.Either(traits.Bool, File(), hash_files=False, desc="idwi output image. Image with isotropic diffusion-weighted information = geometric mean of diffusion images", argstr="--idwi %s") - B0_mask_output = traits.Either(traits.Bool, File(), hash_files=False, desc="B0 mask used for the estimation. B0 thresholded either with the -t option value or the automatic OTSU value", argstr="--B0_mask_output %s") - brain_mask = File(desc="Brain mask. Image where for every voxel == 0 the tensors are not estimated. Be aware that in addition a threshold based masking will be performed by default. If such an additional threshold masking is NOT desired, then use option -t 0.", - exists=True, argstr="--brain_mask %s") - bad_region_mask = File(desc="Bad region mask. Image where for every voxel > 0 the tensors are not estimated", exists=True, argstr="--bad_region_mask %s") - method = traits.Enum("lls", "wls", "nls", "ml", desc="Esitmation method (lls:linear least squares, wls:weighted least squares, nls:non-linear least squares, ml:maximum likelihood)", argstr="--method %s") - correction = traits.Enum("none", "zero", "abs", "nearest", desc="Correct the tensors if computed tensor is not semi-definite positive", argstr="--correction %s") - threshold = traits.Int(desc="Baseline threshold for estimation. If not specified calculated using an OTSU threshold on the baseline image.", argstr="--threshold %d") - weight_iterations = traits.Int(desc="Number of iterations to recaluate weightings from tensor estimate", argstr="--weight_iterations %d") - step = traits.Float(desc="Gradient descent step size (for nls and ml methods)", argstr="--step %f") + dwi_image = File( + desc="DWI image volume (required)", + exists=True, + argstr="--dwi_image %s") + tensor_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Tensor OutputImage", + argstr="--tensor_output %s") + B0 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Baseline image, average of all baseline images", + argstr="--B0 %s") + idwi = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "idwi output image. Image with isotropic diffusion-weighted information = geometric mean of diffusion images", + argstr="--idwi %s") + B0_mask_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "B0 mask used for the estimation. B0 thresholded either with the -t option value or the automatic OTSU value", + argstr="--B0_mask_output %s") + brain_mask = File( + desc= + "Brain mask. Image where for every voxel == 0 the tensors are not estimated. Be aware that in addition a threshold based masking will be performed by default. If such an additional threshold masking is NOT desired, then use option -t 0.", + exists=True, + argstr="--brain_mask %s") + bad_region_mask = File( + desc= + "Bad region mask. Image where for every voxel > 0 the tensors are not estimated", + exists=True, + argstr="--bad_region_mask %s") + method = traits.Enum( + "lls", + "wls", + "nls", + "ml", + desc= + "Esitmation method (lls:linear least squares, wls:weighted least squares, nls:non-linear least squares, ml:maximum likelihood)", + argstr="--method %s") + correction = traits.Enum( + "none", + "zero", + "abs", + "nearest", + desc= + "Correct the tensors if computed tensor is not semi-definite positive", + argstr="--correction %s") + threshold = traits.Int( + desc= + "Baseline threshold for estimation. If not specified calculated using an OTSU threshold on the baseline image.", + argstr="--threshold %d") + weight_iterations = traits.Int( + desc= + "Number of iterations to recaluate weightings from tensor estimate", + argstr="--weight_iterations %d") + step = traits.Float( + desc="Gradient descent step size (for nls and ml methods)", + argstr="--step %f") sigma = traits.Float(argstr="--sigma %f") - DTI_double = traits.Bool(desc="Tensor components are saved as doubles (cannot be visualized in Slicer)", argstr="--DTI_double ") + DTI_double = traits.Bool( + desc= + "Tensor components are saved as doubles (cannot be visualized in Slicer)", + argstr="--DTI_double ") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") - defaultTensor = InputMultiPath(traits.Float, desc="Default tensor used if estimated tensor is below a given threshold", sep=",", argstr="--defaultTensor %s") + defaultTensor = InputMultiPath( + traits.Float, + desc= + "Default tensor used if estimated tensor is below a given threshold", + sep=",", + argstr="--defaultTensor %s") shiftNeg = traits.Bool( - desc="Shift eigenvalues so all are positive (accounts for bad tensors related to noise or acquisition error). This is the same option as the one available in DWIToDTIEstimation in Slicer (but instead of just adding the minimum eigenvalue to all the eigenvalues if it is smaller than 0, we use a coefficient to have stictly positive eigenvalues", argstr="--shiftNeg ") + desc= + "Shift eigenvalues so all are positive (accounts for bad tensors related to noise or acquisition error). This is the same option as the one available in DWIToDTIEstimation in Slicer (but instead of just adding the minimum eigenvalue to all the eigenvalues if it is smaller than 0, we use a coefficient to have stictly positive eigenvalues", + argstr="--shiftNeg ") shiftNegCoeff = traits.Float( - desc="Shift eigenvalues so all are positive (accounts for bad tensors related to noise or acquisition error). Instead of just adding the minimum eigenvalue to all the eigenvalues if it is smaller than 0, we use a coefficient to have stictly positive eigenvalues. Coefficient must be between 1.0 and 1.001 (included).", argstr="--shiftNegCoeff %f") + desc= + "Shift eigenvalues so all are positive (accounts for bad tensors related to noise or acquisition error). Instead of just adding the minimum eigenvalue to all the eigenvalues if it is smaller than 0, we use a coefficient to have stictly positive eigenvalues. Coefficient must be between 1.0 and 1.001 (included).", + argstr="--shiftNegCoeff %f") class dtiestimOutputSpec(TraitedSpec): tensor_output = File(desc="Tensor OutputImage", exists=True) - B0 = File(desc="Baseline image, average of all baseline images", exists=True) - idwi = File(desc="idwi output image. Image with isotropic diffusion-weighted information = geometric mean of diffusion images", exists=True) - B0_mask_output = File(desc="B0 mask used for the estimation. B0 thresholded either with the -t option value or the automatic OTSU value", exists=True) + B0 = File( + desc="Baseline image, average of all baseline images", exists=True) + idwi = File( + desc= + "idwi output image. Image with isotropic diffusion-weighted information = geometric mean of diffusion images", + exists=True) + B0_mask_output = File( + desc= + "B0 mask used for the estimation. B0 thresholded either with the -t option value or the automatic OTSU value", + exists=True) class dtiestim(SEMLikeCommandLine): - """title: DTIEstim (DTIProcess) category: Diffusion.Diffusion Weighted Images @@ -129,62 +211,207 @@ class dtiestim(SEMLikeCommandLine): input_spec = dtiestimInputSpec output_spec = dtiestimOutputSpec _cmd = " dtiestim " - _outputs_filenames = {'B0': 'B0.nii', 'idwi': 'idwi.nii', 'tensor_output': 'tensor_output.nii', 'B0_mask_output': 'B0_mask_output.nii'} + _outputs_filenames = { + 'B0': 'B0.nii', + 'idwi': 'idwi.nii', + 'tensor_output': 'tensor_output.nii', + 'B0_mask_output': 'B0_mask_output.nii' + } _redirect_x = False class dtiprocessInputSpec(CommandLineInputSpec): - dti_image = File(desc="DTI tensor volume", exists=True, argstr="--dti_image %s") - fa_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Fractional Anisotropy output file", argstr="--fa_output %s") - md_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Mean Diffusivity output file", argstr="--md_output %s") + dti_image = File( + desc="DTI tensor volume", exists=True, argstr="--dti_image %s") + fa_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Fractional Anisotropy output file", + argstr="--fa_output %s") + md_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Mean Diffusivity output file", + argstr="--md_output %s") sigma = traits.Float(desc="Scale of gradients", argstr="--sigma %f") - fa_gradient_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Fractional Anisotropy Gradient output file", argstr="--fa_gradient_output %s") - fa_gradmag_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Fractional Anisotropy Gradient Magnitude output file", argstr="--fa_gradmag_output %s") - color_fa_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Color Fractional Anisotropy output file", argstr="--color_fa_output %s") - principal_eigenvector_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Principal Eigenvectors Output", argstr="--principal_eigenvector_output %s") - negative_eigenvector_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Negative Eigenvectors Output: create a binary image where if any of the eigen value is below zero, the voxel is set to 1, otherwise 0.", argstr="--negative_eigenvector_output %s") - frobenius_norm_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Frobenius Norm Output", argstr="--frobenius_norm_output %s") - lambda1_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Axial Diffusivity - Lambda 1 (largest eigenvalue) output", argstr="--lambda1_output %s") - lambda2_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Lambda 2 (middle eigenvalue) output", argstr="--lambda2_output %s") - lambda3_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Lambda 3 (smallest eigenvalue) output", argstr="--lambda3_output %s") - RD_output = traits.Either(traits.Bool, File(), hash_files=False, desc="RD (Radial Diffusivity 1/2*(lambda2+lambda3)) output", argstr="--RD_output %s") - rot_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Rotated tensor output file. Must also specify the dof file.", argstr="--rot_output %s") - affineitk_file = File(desc="Transformation file for affine transformation. ITK format.", exists=True, argstr="--affineitk_file %s") - dof_file = File(desc="Transformation file for affine transformation. This can be ITK format (or the outdated RView).", exists=True, argstr="--dof_file %s") - newdof_file = File(desc="Transformation file for affine transformation. RView NEW format. (txt file output of dof2mat)", exists=True, argstr="--newdof_file %s") - mask = File(desc="Mask tensors. Specify --outmask if you want to save the masked tensor field, otherwise the mask is applied just for the current processing ", exists=True, argstr="--mask %s") - outmask = traits.Either(traits.Bool, File(), hash_files=False, desc="Name of the masked tensor field.", argstr="--outmask %s") - hField = traits.Bool(desc="forward and inverse transformations are h-fields instead of displacement fields", argstr="--hField ") - forward = File(desc="Forward transformation. Assumed to be a deformation field in world coordinates, unless the --h-field option is specified.", exists=True, argstr="--forward %s") - deformation_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Warped tensor field based on a deformation field. This option requires the --forward,-F transformation to be specified.", argstr="--deformation_output %s") - interpolation = traits.Enum("nearestneighbor", "linear", "cubic", desc="Interpolation type (nearestneighbor, linear, cubic)", argstr="--interpolation %s") - reorientation = traits.Enum("fs", "ppd", desc="Reorientation type (fs, ppd)", argstr="--reorientation %s") - correction = traits.Enum("none", "zero", "abs", "nearest", desc="Correct the tensors if computed tensor is not semi-definite positive", argstr="--correction %s") - scalar_float = traits.Bool(desc="Write scalar [FA,MD] as unscaled float (with their actual values, otherwise scaled by 10 000). Also causes FA to be unscaled [0..1].", argstr="--scalar_float ") - DTI_double = traits.Bool(desc="Tensor components are saved as doubles (cannot be visualized in Slicer)", argstr="--DTI_double ") + fa_gradient_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Fractional Anisotropy Gradient output file", + argstr="--fa_gradient_output %s") + fa_gradmag_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Fractional Anisotropy Gradient Magnitude output file", + argstr="--fa_gradmag_output %s") + color_fa_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Color Fractional Anisotropy output file", + argstr="--color_fa_output %s") + principal_eigenvector_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Principal Eigenvectors Output", + argstr="--principal_eigenvector_output %s") + negative_eigenvector_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Negative Eigenvectors Output: create a binary image where if any of the eigen value is below zero, the voxel is set to 1, otherwise 0.", + argstr="--negative_eigenvector_output %s") + frobenius_norm_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Frobenius Norm Output", + argstr="--frobenius_norm_output %s") + lambda1_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Axial Diffusivity - Lambda 1 (largest eigenvalue) output", + argstr="--lambda1_output %s") + lambda2_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Lambda 2 (middle eigenvalue) output", + argstr="--lambda2_output %s") + lambda3_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Lambda 3 (smallest eigenvalue) output", + argstr="--lambda3_output %s") + RD_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="RD (Radial Diffusivity 1/2*(lambda2+lambda3)) output", + argstr="--RD_output %s") + rot_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Rotated tensor output file. Must also specify the dof file.", + argstr="--rot_output %s") + affineitk_file = File( + desc="Transformation file for affine transformation. ITK format.", + exists=True, + argstr="--affineitk_file %s") + dof_file = File( + desc= + "Transformation file for affine transformation. This can be ITK format (or the outdated RView).", + exists=True, + argstr="--dof_file %s") + newdof_file = File( + desc= + "Transformation file for affine transformation. RView NEW format. (txt file output of dof2mat)", + exists=True, + argstr="--newdof_file %s") + mask = File( + desc= + "Mask tensors. Specify --outmask if you want to save the masked tensor field, otherwise the mask is applied just for the current processing ", + exists=True, + argstr="--mask %s") + outmask = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Name of the masked tensor field.", + argstr="--outmask %s") + hField = traits.Bool( + desc= + "forward and inverse transformations are h-fields instead of displacement fields", + argstr="--hField ") + forward = File( + desc= + "Forward transformation. Assumed to be a deformation field in world coordinates, unless the --h-field option is specified.", + exists=True, + argstr="--forward %s") + deformation_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Warped tensor field based on a deformation field. This option requires the --forward,-F transformation to be specified.", + argstr="--deformation_output %s") + interpolation = traits.Enum( + "nearestneighbor", + "linear", + "cubic", + desc="Interpolation type (nearestneighbor, linear, cubic)", + argstr="--interpolation %s") + reorientation = traits.Enum( + "fs", + "ppd", + desc="Reorientation type (fs, ppd)", + argstr="--reorientation %s") + correction = traits.Enum( + "none", + "zero", + "abs", + "nearest", + desc= + "Correct the tensors if computed tensor is not semi-definite positive", + argstr="--correction %s") + scalar_float = traits.Bool( + desc= + "Write scalar [FA,MD] as unscaled float (with their actual values, otherwise scaled by 10 000). Also causes FA to be unscaled [0..1].", + argstr="--scalar_float ") + DTI_double = traits.Bool( + desc= + "Tensor components are saved as doubles (cannot be visualized in Slicer)", + argstr="--DTI_double ") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") class dtiprocessOutputSpec(TraitedSpec): fa_output = File(desc="Fractional Anisotropy output file", exists=True) md_output = File(desc="Mean Diffusivity output file", exists=True) - fa_gradient_output = File(desc="Fractional Anisotropy Gradient output file", exists=True) - fa_gradmag_output = File(desc="Fractional Anisotropy Gradient Magnitude output file", exists=True) - color_fa_output = File(desc="Color Fractional Anisotropy output file", exists=True) - principal_eigenvector_output = File(desc="Principal Eigenvectors Output", exists=True) - negative_eigenvector_output = File(desc="Negative Eigenvectors Output: create a binary image where if any of the eigen value is below zero, the voxel is set to 1, otherwise 0.", exists=True) + fa_gradient_output = File( + desc="Fractional Anisotropy Gradient output file", exists=True) + fa_gradmag_output = File( + desc="Fractional Anisotropy Gradient Magnitude output file", + exists=True) + color_fa_output = File( + desc="Color Fractional Anisotropy output file", exists=True) + principal_eigenvector_output = File( + desc="Principal Eigenvectors Output", exists=True) + negative_eigenvector_output = File( + desc= + "Negative Eigenvectors Output: create a binary image where if any of the eigen value is below zero, the voxel is set to 1, otherwise 0.", + exists=True) frobenius_norm_output = File(desc="Frobenius Norm Output", exists=True) - lambda1_output = File(desc="Axial Diffusivity - Lambda 1 (largest eigenvalue) output", exists=True) - lambda2_output = File(desc="Lambda 2 (middle eigenvalue) output", exists=True) - lambda3_output = File(desc="Lambda 3 (smallest eigenvalue) output", exists=True) - RD_output = File(desc="RD (Radial Diffusivity 1/2*(lambda2+lambda3)) output", exists=True) - rot_output = File(desc="Rotated tensor output file. Must also specify the dof file.", exists=True) + lambda1_output = File( + desc="Axial Diffusivity - Lambda 1 (largest eigenvalue) output", + exists=True) + lambda2_output = File( + desc="Lambda 2 (middle eigenvalue) output", exists=True) + lambda3_output = File( + desc="Lambda 3 (smallest eigenvalue) output", exists=True) + RD_output = File( + desc="RD (Radial Diffusivity 1/2*(lambda2+lambda3)) output", + exists=True) + rot_output = File( + desc="Rotated tensor output file. Must also specify the dof file.", + exists=True) outmask = File(desc="Name of the masked tensor field.", exists=True) - deformation_output = File(desc="Warped tensor field based on a deformation field. This option requires the --forward,-F transformation to be specified.", exists=True) + deformation_output = File( + desc= + "Warped tensor field based on a deformation field. This option requires the --forward,-F transformation to be specified.", + exists=True) class dtiprocess(SEMLikeCommandLine): - """title: DTIProcess (DTIProcess) category: Diffusion.Diffusion Tensor Images @@ -220,45 +447,132 @@ class dtiprocess(SEMLikeCommandLine): input_spec = dtiprocessInputSpec output_spec = dtiprocessOutputSpec _cmd = " dtiprocess " - _outputs_filenames = {'fa_gradmag_output': 'fa_gradmag_output.nii', 'fa_gradient_output': 'fa_gradient_output.nii', 'lambda1_output': 'lambda1_output.nii', 'lambda2_output': 'lambda2_output.nii', 'color_fa_output': 'color_fa_output.nii', 'fa_output': 'fa_output.nii', 'frobenius_norm_output': 'frobenius_norm_output.nii', - 'principal_eigenvector_output': 'principal_eigenvector_output.nii', 'outmask': 'outmask.nii', 'lambda3_output': 'lambda3_output.nii', 'negative_eigenvector_output': 'negative_eigenvector_output.nii', 'md_output': 'md_output.nii', 'RD_output': 'RD_output.nii', 'deformation_output': 'deformation_output.nii', 'rot_output': 'rot_output.nii'} + _outputs_filenames = { + 'fa_gradmag_output': 'fa_gradmag_output.nii', + 'fa_gradient_output': 'fa_gradient_output.nii', + 'lambda1_output': 'lambda1_output.nii', + 'lambda2_output': 'lambda2_output.nii', + 'color_fa_output': 'color_fa_output.nii', + 'fa_output': 'fa_output.nii', + 'frobenius_norm_output': 'frobenius_norm_output.nii', + 'principal_eigenvector_output': 'principal_eigenvector_output.nii', + 'outmask': 'outmask.nii', + 'lambda3_output': 'lambda3_output.nii', + 'negative_eigenvector_output': 'negative_eigenvector_output.nii', + 'md_output': 'md_output.nii', + 'RD_output': 'RD_output.nii', + 'deformation_output': 'deformation_output.nii', + 'rot_output': 'rot_output.nii' + } _redirect_x = False class DWIConvertInputSpec(CommandLineInputSpec): - conversionMode = traits.Enum("DicomToNrrd", "DicomToFSL", "NrrdToFSL", "FSLToNrrd", - desc="Determine which conversion to perform. DicomToNrrd (default): Convert DICOM series to NRRD DicomToFSL: Convert DICOM series to NIfTI File + gradient/bvalue text files NrrdToFSL: Convert DWI NRRD file to NIfTI File + gradient/bvalue text files FSLToNrrd: Convert NIfTI File + gradient/bvalue text files to NRRD file.", argstr="--conversionMode %s") - inputVolume = File(desc="Input DWI volume -- not used for DicomToNrrd mode.", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output filename (.nhdr or .nrrd)", argstr="--outputVolume %s") - inputDicomDirectory = Directory(desc="Directory holding Dicom series", exists=True, argstr="--inputDicomDirectory %s") - fslNIFTIFile = File(desc="4D NIfTI file containing gradient volumes", exists=True, argstr="--fslNIFTIFile %s") - inputBValues = File(desc="The B Values are stored in FSL .bval text file format", exists=True, argstr="--inputBValues %s") - inputBVectors = File(desc="The Gradient Vectors are stored in FSL .bvec text file format", exists=True, argstr="--inputBVectors %s") - outputBValues = traits.Either(traits.Bool, File(), hash_files=False, desc="The B Values are stored in FSL .bval text file format (defaults to .bval)", argstr="--outputBValues %s") - outputBVectors = traits.Either(traits.Bool, File(), hash_files=False, desc="The Gradient Vectors are stored in FSL .bvec text file format (defaults to .bvec)", argstr="--outputBVectors %s") - fMRI = traits.Bool(desc="Output a NRRD file, but without gradients", argstr="--fMRI ") + conversionMode = traits.Enum( + "DicomToNrrd", + "DicomToFSL", + "NrrdToFSL", + "FSLToNrrd", + desc= + "Determine which conversion to perform. DicomToNrrd (default): Convert DICOM series to NRRD DicomToFSL: Convert DICOM series to NIfTI File + gradient/bvalue text files NrrdToFSL: Convert DWI NRRD file to NIfTI File + gradient/bvalue text files FSLToNrrd: Convert NIfTI File + gradient/bvalue text files to NRRD file.", + argstr="--conversionMode %s") + inputVolume = File( + desc="Input DWI volume -- not used for DicomToNrrd mode.", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output filename (.nhdr or .nrrd)", + argstr="--outputVolume %s") + inputDicomDirectory = Directory( + desc="Directory holding Dicom series", + exists=True, + argstr="--inputDicomDirectory %s") + fslNIFTIFile = File( + desc="4D NIfTI file containing gradient volumes", + exists=True, + argstr="--fslNIFTIFile %s") + inputBValues = File( + desc="The B Values are stored in FSL .bval text file format", + exists=True, + argstr="--inputBValues %s") + inputBVectors = File( + desc="The Gradient Vectors are stored in FSL .bvec text file format", + exists=True, + argstr="--inputBVectors %s") + outputBValues = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The B Values are stored in FSL .bval text file format (defaults to .bval)", + argstr="--outputBValues %s") + outputBVectors = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The Gradient Vectors are stored in FSL .bvec text file format (defaults to .bvec)", + argstr="--outputBVectors %s") + fMRI = traits.Bool( + desc="Output a NRRD file, but without gradients", argstr="--fMRI ") writeProtocolGradientsFile = traits.Bool( - desc="Write the protocol gradients to a file suffixed by \'.txt\' as they were specified in the procol by multiplying each diffusion gradient direction by the measurement frame. This file is for debugging purposes only, the format is not fixed, and will likely change as debugging of new dicom formats is necessary.", argstr="--writeProtocolGradientsFile ") - useIdentityMeaseurementFrame = traits.Bool(desc="Adjust all the gradients so that the measurement frame is an identity matrix.", argstr="--useIdentityMeaseurementFrame ") + desc= + "Write the protocol gradients to a file suffixed by \'.txt\' as they were specified in the procol by multiplying each diffusion gradient direction by the measurement frame. This file is for debugging purposes only, the format is not fixed, and will likely change as debugging of new dicom formats is necessary.", + argstr="--writeProtocolGradientsFile ") + useIdentityMeaseurementFrame = traits.Bool( + desc= + "Adjust all the gradients so that the measurement frame is an identity matrix.", + argstr="--useIdentityMeaseurementFrame ") useBMatrixGradientDirections = traits.Bool( - desc="Fill the nhdr header with the gradient directions and bvalues computed out of the BMatrix. Only changes behavior for Siemens data. In some cases the standard public gradients are not properly computed. The gradients can emperically computed from the private BMatrix fields. In some cases the private BMatrix is consistent with the public grandients, but not in all cases, when it exists BMatrix is usually most robust.", argstr="--useBMatrixGradientDirections ") - outputDirectory = traits.Either(traits.Bool, Directory(), hash_files=False, desc="Directory holding the output NRRD file", argstr="--outputDirectory %s") - gradientVectorFile = traits.Either(traits.Bool, File(), hash_files=False, desc="Text file giving gradient vectors", argstr="--gradientVectorFile %s") - smallGradientThreshold = traits.Float(desc="If a gradient magnitude is greater than 0 and less than smallGradientThreshold, then DWIConvert will display an error message and quit, unless the useBMatrixGradientDirections option is set.", argstr="--smallGradientThreshold %f") - allowLossyConversion = traits.Bool(desc="The only supported output type is \'short\'. Conversion from images of a different type may cause data loss due to rounding or truncation. Use with caution!", argstr="--allowLossyConversion ") - transposeInputBVectors = traits.Bool(desc="FSL input BVectors are expected to be encoded in the input file as one vector per line. If it is not the case, use this option to transpose the file as it is read.", argstr="--transposeInputBVectors ") + desc= + "Fill the nhdr header with the gradient directions and bvalues computed out of the BMatrix. Only changes behavior for Siemens data. In some cases the standard public gradients are not properly computed. The gradients can emperically computed from the private BMatrix fields. In some cases the private BMatrix is consistent with the public grandients, but not in all cases, when it exists BMatrix is usually most robust.", + argstr="--useBMatrixGradientDirections ") + outputDirectory = traits.Either( + traits.Bool, + Directory(), + hash_files=False, + desc="Directory holding the output NRRD file", + argstr="--outputDirectory %s") + gradientVectorFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Text file giving gradient vectors", + argstr="--gradientVectorFile %s") + smallGradientThreshold = traits.Float( + desc= + "If a gradient magnitude is greater than 0 and less than smallGradientThreshold, then DWIConvert will display an error message and quit, unless the useBMatrixGradientDirections option is set.", + argstr="--smallGradientThreshold %f") + allowLossyConversion = traits.Bool( + desc= + "The only supported output type is \'short\'. Conversion from images of a different type may cause data loss due to rounding or truncation. Use with caution!", + argstr="--allowLossyConversion ") + transposeInputBVectors = traits.Bool( + desc= + "FSL input BVectors are expected to be encoded in the input file as one vector per line. If it is not the case, use this option to transpose the file as it is read.", + argstr="--transposeInputBVectors ") class DWIConvertOutputSpec(TraitedSpec): outputVolume = File(desc="Output filename (.nhdr or .nrrd)", exists=True) - outputBValues = File(desc="The B Values are stored in FSL .bval text file format (defaults to .bval)", exists=True) - outputBVectors = File(desc="The Gradient Vectors are stored in FSL .bvec text file format (defaults to .bvec)", exists=True) - outputDirectory = Directory(desc="Directory holding the output NRRD file", exists=True) - gradientVectorFile = File(desc="Text file giving gradient vectors", exists=True) + outputBValues = File( + desc= + "The B Values are stored in FSL .bval text file format (defaults to .bval)", + exists=True) + outputBVectors = File( + desc= + "The Gradient Vectors are stored in FSL .bvec text file format (defaults to .bvec)", + exists=True) + outputDirectory = Directory( + desc="Directory holding the output NRRD file", exists=True) + gradientVectorFile = File( + desc="Text file giving gradient vectors", exists=True) class DWIConvert(SEMLikeCommandLine): - """title: DWIConverter category: Diffusion.Diffusion Data Conversion @@ -280,5 +594,11 @@ class DWIConvert(SEMLikeCommandLine): input_spec = DWIConvertInputSpec output_spec = DWIConvertOutputSpec _cmd = " DWIConvert " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'outputDirectory': 'outputDirectory', 'outputBValues': 'outputBValues.bval', 'gradientVectorFile': 'gradientVectorFile', 'outputBVectors': 'outputBVectors.bvec'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'outputDirectory': 'outputDirectory', + 'outputBValues': 'outputBValues.bval', + 'gradientVectorFile': 'gradientVectorFile', + 'outputBVectors': 'outputBVectors.bvec' + } _redirect_x = False diff --git a/nipype/interfaces/semtools/diffusion/gtract.py b/nipype/interfaces/semtools/diffusion/gtract.py index d4f05b6630..999c898599 100644 --- a/nipype/interfaces/semtools/diffusion/gtract.py +++ b/nipype/interfaces/semtools/diffusion/gtract.py @@ -11,18 +11,32 @@ class gtractTransformToDisplacementFieldInputSpec(CommandLineInputSpec): - inputTransform = File(desc="Input Transform File Name", exists=True, argstr="--inputTransform %s") - inputReferenceVolume = File(desc="Required: input image file name to exemplify the anatomical space over which to vcl_express the transform as a displacement field.", exists=True, argstr="--inputReferenceVolume %s") - outputDeformationFieldVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output deformation field", argstr="--outputDeformationFieldVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputTransform = File( + desc="Input Transform File Name", + exists=True, + argstr="--inputTransform %s") + inputReferenceVolume = File( + desc= + "Required: input image file name to exemplify the anatomical space over which to vcl_express the transform as a displacement field.", + exists=True, + argstr="--inputReferenceVolume %s") + outputDeformationFieldVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output deformation field", + argstr="--outputDeformationFieldVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractTransformToDisplacementFieldOutputSpec(TraitedSpec): - outputDeformationFieldVolume = File(desc="Output deformation field", exists=True) + outputDeformationFieldVolume = File( + desc="Output deformation field", exists=True) class gtractTransformToDisplacementField(SEMLikeCommandLine): - """title: Create Displacement Field category: Diffusion.GTRACT @@ -44,24 +58,44 @@ class gtractTransformToDisplacementField(SEMLikeCommandLine): input_spec = gtractTransformToDisplacementFieldInputSpec output_spec = gtractTransformToDisplacementFieldOutputSpec _cmd = " gtractTransformToDisplacementField " - _outputs_filenames = {'outputDeformationFieldVolume': 'outputDeformationFieldVolume.nii'} + _outputs_filenames = { + 'outputDeformationFieldVolume': 'outputDeformationFieldVolume.nii' + } _redirect_x = False class gtractInvertBSplineTransformInputSpec(CommandLineInputSpec): - inputReferenceVolume = File(desc="Required: input image file name to exemplify the anatomical space to interpolate over.", exists=True, argstr="--inputReferenceVolume %s") - inputTransform = File(desc="Required: input B-Spline transform file name", exists=True, argstr="--inputTransform %s") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output transform file name", argstr="--outputTransform %s") - landmarkDensity = InputMultiPath(traits.Int, desc="Number of landmark subdivisions in all 3 directions", sep=",", argstr="--landmarkDensity %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputReferenceVolume = File( + desc= + "Required: input image file name to exemplify the anatomical space to interpolate over.", + exists=True, + argstr="--inputReferenceVolume %s") + inputTransform = File( + desc="Required: input B-Spline transform file name", + exists=True, + argstr="--inputTransform %s") + outputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output transform file name", + argstr="--outputTransform %s") + landmarkDensity = InputMultiPath( + traits.Int, + desc="Number of landmark subdivisions in all 3 directions", + sep=",", + argstr="--landmarkDensity %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractInvertBSplineTransformOutputSpec(TraitedSpec): - outputTransform = File(desc="Required: output transform file name", exists=True) + outputTransform = File( + desc="Required: output transform file name", exists=True) class gtractInvertBSplineTransform(SEMLikeCommandLine): - """title: B-Spline Transform Inversion category: Diffusion.GTRACT @@ -88,18 +122,35 @@ class gtractInvertBSplineTransform(SEMLikeCommandLine): class gtractConcatDwiInputSpec(CommandLineInputSpec): - inputVolume = InputMultiPath(File(exists=True), desc="Required: input file containing the first diffusion weighted image", argstr="--inputVolume %s...") - ignoreOrigins = traits.Bool(desc="If image origins are different force all images to origin of first image", argstr="--ignoreOrigins ") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the combined diffusion weighted images.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = InputMultiPath( + File(exists=True), + desc= + "Required: input file containing the first diffusion weighted image", + argstr="--inputVolume %s...") + ignoreOrigins = traits.Bool( + desc= + "If image origins are different force all images to origin of first image", + argstr="--ignoreOrigins ") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the combined diffusion weighted images.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractConcatDwiOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the combined diffusion weighted images.", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the combined diffusion weighted images.", + exists=True) class gtractConcatDwi(SEMLikeCommandLine): - """title: Concat DWI Images category: Diffusion.GTRACT @@ -126,19 +177,38 @@ class gtractConcatDwi(SEMLikeCommandLine): class gtractAverageBvaluesInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image file name containing multiple baseline gradients to average", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing directly averaged baseline images", argstr="--outputVolume %s") - directionsTolerance = traits.Float(desc="Tolerance for matching identical gradient direction pairs", argstr="--directionsTolerance %f") - averageB0only = traits.Bool(desc="Average only baseline gradients. All other gradient directions are not averaged, but retained in the outputVolume", argstr="--averageB0only ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc= + "Required: input image file name containing multiple baseline gradients to average", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing directly averaged baseline images", + argstr="--outputVolume %s") + directionsTolerance = traits.Float( + desc="Tolerance for matching identical gradient direction pairs", + argstr="--directionsTolerance %f") + averageB0only = traits.Bool( + desc= + "Average only baseline gradients. All other gradient directions are not averaged, but retained in the outputVolume", + argstr="--averageB0only ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractAverageBvaluesOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing directly averaged baseline images", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing directly averaged baseline images", + exists=True) class gtractAverageBvalues(SEMLikeCommandLine): - """title: Average B-Values category: Diffusion.GTRACT @@ -165,33 +235,88 @@ class gtractAverageBvalues(SEMLikeCommandLine): class gtractCoregBvaluesInputSpec(CommandLineInputSpec): - movingVolume = File(desc="Required: input moving image file name. In order to register gradients within a scan to its first gradient, set the movingVolume and fixedVolume as the same image.", exists=True, argstr="--movingVolume %s") - fixedVolume = File(desc="Required: input fixed image file name. It is recommended that this image should either contain or be a b0 image.", exists=True, argstr="--fixedVolume %s") - fixedVolumeIndex = traits.Int(desc="Index in the fixed image for registration. It is recommended that this image should be a b0 image.", argstr="--fixedVolumeIndex %d") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing moving images individually resampled and fit to the specified fixed image index.", argstr="--outputVolume %s") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Registration 3D transforms concatenated in a single output file. There are no tools that can use this, but can be used for debugging purposes.", argstr="--outputTransform %s") - eddyCurrentCorrection = traits.Bool(desc="Flag to perform eddy current corection in addition to motion correction (recommended)", argstr="--eddyCurrentCorrection ") - numberOfIterations = traits.Int(desc="Number of iterations in each 3D fit", argstr="--numberOfIterations %d") + movingVolume = File( + desc= + "Required: input moving image file name. In order to register gradients within a scan to its first gradient, set the movingVolume and fixedVolume as the same image.", + exists=True, + argstr="--movingVolume %s") + fixedVolume = File( + desc= + "Required: input fixed image file name. It is recommended that this image should either contain or be a b0 image.", + exists=True, + argstr="--fixedVolume %s") + fixedVolumeIndex = traits.Int( + desc= + "Index in the fixed image for registration. It is recommended that this image should be a b0 image.", + argstr="--fixedVolumeIndex %d") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing moving images individually resampled and fit to the specified fixed image index.", + argstr="--outputVolume %s") + outputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Registration 3D transforms concatenated in a single output file. There are no tools that can use this, but can be used for debugging purposes.", + argstr="--outputTransform %s") + eddyCurrentCorrection = traits.Bool( + desc= + "Flag to perform eddy current corection in addition to motion correction (recommended)", + argstr="--eddyCurrentCorrection ") + numberOfIterations = traits.Int( + desc="Number of iterations in each 3D fit", + argstr="--numberOfIterations %d") numberOfSpatialSamples = traits.Int( - desc="The number of voxels sampled for mutual information computation. Increase this for a slower, more careful fit. NOTE that it is suggested to use samplingPercentage instead of this option. However, if set, it overwrites the samplingPercentage option. ", argstr="--numberOfSpatialSamples %d") + desc= + "The number of voxels sampled for mutual information computation. Increase this for a slower, more careful fit. NOTE that it is suggested to use samplingPercentage instead of this option. However, if set, it overwrites the samplingPercentage option. ", + argstr="--numberOfSpatialSamples %d") samplingPercentage = traits.Float( - desc="This is a number in (0.0,1.0] interval that shows the percentage of the input fixed image voxels that are sampled for mutual information computation. Increase this for a slower, more careful fit. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation. The default is to use approximately 5% of voxels (for backwards compatibility 5% ~= 500000/(256*256*256)). Typical values range from 1% for low detail images to 20% for high detail images.", argstr="--samplingPercentage %f") - relaxationFactor = traits.Float(desc="Fraction of gradient from Jacobian to attempt to move in each 3D fit step (adjust when eddyCurrentCorrection is enabled; suggested value = 0.25)", argstr="--relaxationFactor %f") - maximumStepSize = traits.Float(desc="Maximum permitted step size to move in each 3D fit step (adjust when eddyCurrentCorrection is enabled; suggested value = 0.1)", argstr="--maximumStepSize %f") - minimumStepSize = traits.Float(desc="Minimum required step size to move in each 3D fit step without converging -- decrease this to make the fit more exacting", argstr="--minimumStepSize %f") - spatialScale = traits.Float(desc="How much to scale up changes in position compared to unit rotational changes in radians -- decrease this to put more rotation in the fit", argstr="--spatialScale %f") - registerB0Only = traits.Bool(desc="Register the B0 images only", argstr="--registerB0Only ") - debugLevel = traits.Int(desc="Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", argstr="--debugLevel %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + desc= + "This is a number in (0.0,1.0] interval that shows the percentage of the input fixed image voxels that are sampled for mutual information computation. Increase this for a slower, more careful fit. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation. The default is to use approximately 5% of voxels (for backwards compatibility 5% ~= 500000/(256*256*256)). Typical values range from 1% for low detail images to 20% for high detail images.", + argstr="--samplingPercentage %f") + relaxationFactor = traits.Float( + desc= + "Fraction of gradient from Jacobian to attempt to move in each 3D fit step (adjust when eddyCurrentCorrection is enabled; suggested value = 0.25)", + argstr="--relaxationFactor %f") + maximumStepSize = traits.Float( + desc= + "Maximum permitted step size to move in each 3D fit step (adjust when eddyCurrentCorrection is enabled; suggested value = 0.1)", + argstr="--maximumStepSize %f") + minimumStepSize = traits.Float( + desc= + "Minimum required step size to move in each 3D fit step without converging -- decrease this to make the fit more exacting", + argstr="--minimumStepSize %f") + spatialScale = traits.Float( + desc= + "How much to scale up changes in position compared to unit rotational changes in radians -- decrease this to put more rotation in the fit", + argstr="--spatialScale %f") + registerB0Only = traits.Bool( + desc="Register the B0 images only", argstr="--registerB0Only ") + debugLevel = traits.Int( + desc= + "Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", + argstr="--debugLevel %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractCoregBvaluesOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing moving images individually resampled and fit to the specified fixed image index.", exists=True) - outputTransform = File(desc="Registration 3D transforms concatenated in a single output file. There are no tools that can use this, but can be used for debugging purposes.", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing moving images individually resampled and fit to the specified fixed image index.", + exists=True) + outputTransform = File( + desc= + "Registration 3D transforms concatenated in a single output file. There are no tools that can use this, but can be used for debugging purposes.", + exists=True) class gtractCoregBvalues(SEMLikeCommandLine): - """title: Coregister B-Values category: Diffusion.GTRACT @@ -213,25 +338,52 @@ class gtractCoregBvalues(SEMLikeCommandLine): input_spec = gtractCoregBvaluesInputSpec output_spec = gtractCoregBvaluesOutputSpec _cmd = " gtractCoregBvalues " - _outputs_filenames = {'outputVolume': 'outputVolume.nrrd', 'outputTransform': 'outputTransform.h5'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nrrd', + 'outputTransform': 'outputTransform.h5' + } _redirect_x = False class gtractResampleAnisotropyInputSpec(CommandLineInputSpec): - inputAnisotropyVolume = File(desc="Required: input file containing the anisotropy image", exists=True, argstr="--inputAnisotropyVolume %s") - inputAnatomicalVolume = File(desc="Required: input file containing the anatomical image whose characteristics will be cloned.", exists=True, argstr="--inputAnatomicalVolume %s") - inputTransform = File(desc="Required: input Rigid OR Bspline transform file name", exists=True, argstr="--inputTransform %s") - transformType = traits.Enum("Rigid", "B-Spline", desc="Transform type: Rigid, B-Spline", argstr="--transformType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the resampled transformed anisotropy image.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputAnisotropyVolume = File( + desc="Required: input file containing the anisotropy image", + exists=True, + argstr="--inputAnisotropyVolume %s") + inputAnatomicalVolume = File( + desc= + "Required: input file containing the anatomical image whose characteristics will be cloned.", + exists=True, + argstr="--inputAnatomicalVolume %s") + inputTransform = File( + desc="Required: input Rigid OR Bspline transform file name", + exists=True, + argstr="--inputTransform %s") + transformType = traits.Enum( + "Rigid", + "B-Spline", + desc="Transform type: Rigid, B-Spline", + argstr="--transformType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the resampled transformed anisotropy image.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractResampleAnisotropyOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the resampled transformed anisotropy image.", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the resampled transformed anisotropy image.", + exists=True) class gtractResampleAnisotropy(SEMLikeCommandLine): - """title: Resample Anisotropy category: Diffusion.GTRACT @@ -258,20 +410,47 @@ class gtractResampleAnisotropy(SEMLikeCommandLine): class gtractResampleCodeImageInputSpec(CommandLineInputSpec): - inputCodeVolume = File(desc="Required: input file containing the code image", exists=True, argstr="--inputCodeVolume %s") - inputReferenceVolume = File(desc="Required: input file containing the standard image to clone the characteristics of.", exists=True, argstr="--inputReferenceVolume %s") - inputTransform = File(desc="Required: input Rigid or Inverse-B-Spline transform file name", exists=True, argstr="--inputTransform %s") - transformType = traits.Enum("Rigid", "Affine", "B-Spline", "Inverse-B-Spline", "None", desc="Transform type: Rigid or Inverse-B-Spline", argstr="--transformType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the resampled code image in acquisition space.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputCodeVolume = File( + desc="Required: input file containing the code image", + exists=True, + argstr="--inputCodeVolume %s") + inputReferenceVolume = File( + desc= + "Required: input file containing the standard image to clone the characteristics of.", + exists=True, + argstr="--inputReferenceVolume %s") + inputTransform = File( + desc="Required: input Rigid or Inverse-B-Spline transform file name", + exists=True, + argstr="--inputTransform %s") + transformType = traits.Enum( + "Rigid", + "Affine", + "B-Spline", + "Inverse-B-Spline", + "None", + desc="Transform type: Rigid or Inverse-B-Spline", + argstr="--transformType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the resampled code image in acquisition space.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractResampleCodeImageOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the resampled code image in acquisition space.", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the resampled code image in acquisition space.", + exists=True) class gtractResampleCodeImage(SEMLikeCommandLine): - """title: Resample Code Image category: Diffusion.GTRACT @@ -298,18 +477,35 @@ class gtractResampleCodeImage(SEMLikeCommandLine): class gtractCopyImageOrientationInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input file containing the signed short image to reorient without resampling.", exists=True, argstr="--inputVolume %s") - inputReferenceVolume = File(desc="Required: input file containing orietation that will be cloned.", exists=True, argstr="--inputReferenceVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD or Nifti file containing the reoriented image in reference image space.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc= + "Required: input file containing the signed short image to reorient without resampling.", + exists=True, + argstr="--inputVolume %s") + inputReferenceVolume = File( + desc="Required: input file containing orietation that will be cloned.", + exists=True, + argstr="--inputReferenceVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD or Nifti file containing the reoriented image in reference image space.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractCopyImageOrientationOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD or Nifti file containing the reoriented image in reference image space.", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD or Nifti file containing the reoriented image in reference image space.", + exists=True) class gtractCopyImageOrientation(SEMLikeCommandLine): - """title: Copy Image Orientation category: Diffusion.GTRACT @@ -336,19 +532,34 @@ class gtractCopyImageOrientation(SEMLikeCommandLine): class gtractCreateGuideFiberInputSpec(CommandLineInputSpec): - inputFiber = File(desc="Required: input fiber tract file name", exists=True, argstr="--inputFiber %s") - numberOfPoints = traits.Int(desc="Number of points in output guide fiber", argstr="--numberOfPoints %d") - outputFiber = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output guide fiber file name", argstr="--outputFiber %s") - writeXMLPolyDataFile = traits.Bool(desc="Flag to make use of XML files when reading and writing vtkPolyData.", argstr="--writeXMLPolyDataFile ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputFiber = File( + desc="Required: input fiber tract file name", + exists=True, + argstr="--inputFiber %s") + numberOfPoints = traits.Int( + desc="Number of points in output guide fiber", + argstr="--numberOfPoints %d") + outputFiber = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output guide fiber file name", + argstr="--outputFiber %s") + writeXMLPolyDataFile = traits.Bool( + desc= + "Flag to make use of XML files when reading and writing vtkPolyData.", + argstr="--writeXMLPolyDataFile ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractCreateGuideFiberOutputSpec(TraitedSpec): - outputFiber = File(desc="Required: output guide fiber file name", exists=True) + outputFiber = File( + desc="Required: output guide fiber file name", exists=True) class gtractCreateGuideFiber(SEMLikeCommandLine): - """title: Create Guide Fiber category: Diffusion.GTRACT @@ -375,18 +586,40 @@ class gtractCreateGuideFiber(SEMLikeCommandLine): class gtractAnisotropyMapInputSpec(CommandLineInputSpec): - inputTensorVolume = File(desc="Required: input file containing the diffusion tensor image", exists=True, argstr="--inputTensorVolume %s") - anisotropyType = traits.Enum("ADC", "FA", "RA", "VR", "AD", "RD", "LI", desc="Anisotropy Mapping Type: ADC, FA, RA, VR, AD, RD, LI", argstr="--anisotropyType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the selected kind of anisotropy scalar.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputTensorVolume = File( + desc="Required: input file containing the diffusion tensor image", + exists=True, + argstr="--inputTensorVolume %s") + anisotropyType = traits.Enum( + "ADC", + "FA", + "RA", + "VR", + "AD", + "RD", + "LI", + desc="Anisotropy Mapping Type: ADC, FA, RA, VR, AD, RD, LI", + argstr="--anisotropyType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the selected kind of anisotropy scalar.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractAnisotropyMapOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the selected kind of anisotropy scalar.", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the selected kind of anisotropy scalar.", + exists=True) class gtractAnisotropyMap(SEMLikeCommandLine): - """title: Anisotropy Map category: Diffusion.GTRACT @@ -413,19 +646,36 @@ class gtractAnisotropyMap(SEMLikeCommandLine): class gtractClipAnisotropyInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image file name", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the clipped anisotropy image", argstr="--outputVolume %s") - clipFirstSlice = traits.Bool(desc="Clip the first slice of the anisotropy image", argstr="--clipFirstSlice ") - clipLastSlice = traits.Bool(desc="Clip the last slice of the anisotropy image", argstr="--clipLastSlice ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="Required: input image file name", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the clipped anisotropy image", + argstr="--outputVolume %s") + clipFirstSlice = traits.Bool( + desc="Clip the first slice of the anisotropy image", + argstr="--clipFirstSlice ") + clipLastSlice = traits.Bool( + desc="Clip the last slice of the anisotropy image", + argstr="--clipLastSlice ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractClipAnisotropyOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the clipped anisotropy image", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the clipped anisotropy image", + exists=True) class gtractClipAnisotropy(SEMLikeCommandLine): - """title: Clip Anisotropy category: Diffusion.GTRACT @@ -452,21 +702,47 @@ class gtractClipAnisotropy(SEMLikeCommandLine): class gtractResampleB0InputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input file containing the 4D image", exists=True, argstr="--inputVolume %s") - inputAnatomicalVolume = File(desc="Required: input file containing the anatomical image defining the origin, spacing and size of the resampled image (template)", exists=True, argstr="--inputAnatomicalVolume %s") - inputTransform = File(desc="Required: input Rigid OR Bspline transform file name", exists=True, argstr="--inputTransform %s") - vectorIndex = traits.Int(desc="Index in the diffusion weighted image set for the B0 image", argstr="--vectorIndex %d") - transformType = traits.Enum("Rigid", "B-Spline", desc="Transform type: Rigid, B-Spline", argstr="--transformType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the resampled input image.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="Required: input file containing the 4D image", + exists=True, + argstr="--inputVolume %s") + inputAnatomicalVolume = File( + desc= + "Required: input file containing the anatomical image defining the origin, spacing and size of the resampled image (template)", + exists=True, + argstr="--inputAnatomicalVolume %s") + inputTransform = File( + desc="Required: input Rigid OR Bspline transform file name", + exists=True, + argstr="--inputTransform %s") + vectorIndex = traits.Int( + desc="Index in the diffusion weighted image set for the B0 image", + argstr="--vectorIndex %d") + transformType = traits.Enum( + "Rigid", + "B-Spline", + desc="Transform type: Rigid, B-Spline", + argstr="--transformType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the resampled input image.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractResampleB0OutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the resampled input image.", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the resampled input image.", + exists=True) class gtractResampleB0(SEMLikeCommandLine): - """title: Resample B0 category: Diffusion.GTRACT @@ -493,17 +769,27 @@ class gtractResampleB0(SEMLikeCommandLine): class gtractInvertRigidTransformInputSpec(CommandLineInputSpec): - inputTransform = File(desc="Required: input rigid transform file name", exists=True, argstr="--inputTransform %s") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output transform file name", argstr="--outputTransform %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputTransform = File( + desc="Required: input rigid transform file name", + exists=True, + argstr="--inputTransform %s") + outputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output transform file name", + argstr="--outputTransform %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractInvertRigidTransformOutputSpec(TraitedSpec): - outputTransform = File(desc="Required: output transform file name", exists=True) + outputTransform = File( + desc="Required: output transform file name", exists=True) class gtractInvertRigidTransform(SEMLikeCommandLine): - """title: Rigid Transform Inversion category: Diffusion.GTRACT @@ -530,18 +816,36 @@ class gtractInvertRigidTransform(SEMLikeCommandLine): class gtractImageConformityInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input file containing the signed short image to reorient without resampling.", exists=True, argstr="--inputVolume %s") - inputReferenceVolume = File(desc="Required: input file containing the standard image to clone the characteristics of.", exists=True, argstr="--inputReferenceVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output Nrrd or Nifti file containing the reoriented image in reference image space.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc= + "Required: input file containing the signed short image to reorient without resampling.", + exists=True, + argstr="--inputVolume %s") + inputReferenceVolume = File( + desc= + "Required: input file containing the standard image to clone the characteristics of.", + exists=True, + argstr="--inputReferenceVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output Nrrd or Nifti file containing the reoriented image in reference image space.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractImageConformityOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output Nrrd or Nifti file containing the reoriented image in reference image space.", exists=True) + outputVolume = File( + desc= + "Required: name of output Nrrd or Nifti file containing the reoriented image in reference image space.", + exists=True) class gtractImageConformity(SEMLikeCommandLine): - """title: Image Conformity category: Diffusion.GTRACT @@ -568,14 +872,34 @@ class gtractImageConformity(SEMLikeCommandLine): class compareTractInclusionInputSpec(CommandLineInputSpec): - testFiber = File(desc="Required: test fiber tract file name", exists=True, argstr="--testFiber %s") - standardFiber = File(desc="Required: standard fiber tract file name", exists=True, argstr="--standardFiber %s") - closeness = traits.Float(desc="Closeness of every test fiber to some fiber in the standard tract, computed as a sum of squares of spatial differences of standard points", argstr="--closeness %f") - numberOfPoints = traits.Int(desc="Number of points in comparison fiber pairs", argstr="--numberOfPoints %d") - testForBijection = traits.Bool(desc="Flag to apply the closeness criterion both ways", argstr="--testForBijection ") - testForFiberCardinality = traits.Bool(desc="Flag to require the same number of fibers in both tracts", argstr="--testForFiberCardinality ") - writeXMLPolyDataFile = traits.Bool(desc="Flag to make use of XML files when reading and writing vtkPolyData.", argstr="--writeXMLPolyDataFile ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + testFiber = File( + desc="Required: test fiber tract file name", + exists=True, + argstr="--testFiber %s") + standardFiber = File( + desc="Required: standard fiber tract file name", + exists=True, + argstr="--standardFiber %s") + closeness = traits.Float( + desc= + "Closeness of every test fiber to some fiber in the standard tract, computed as a sum of squares of spatial differences of standard points", + argstr="--closeness %f") + numberOfPoints = traits.Int( + desc="Number of points in comparison fiber pairs", + argstr="--numberOfPoints %d") + testForBijection = traits.Bool( + desc="Flag to apply the closeness criterion both ways", + argstr="--testForBijection ") + testForFiberCardinality = traits.Bool( + desc="Flag to require the same number of fibers in both tracts", + argstr="--testForFiberCardinality ") + writeXMLPolyDataFile = traits.Bool( + desc= + "Flag to make use of XML files when reading and writing vtkPolyData.", + argstr="--writeXMLPolyDataFile ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class compareTractInclusionOutputSpec(TraitedSpec): @@ -583,7 +907,6 @@ class compareTractInclusionOutputSpec(TraitedSpec): class compareTractInclusion(SEMLikeCommandLine): - """title: Compare Tracts category: Diffusion.GTRACT @@ -610,28 +933,65 @@ class compareTractInclusion(SEMLikeCommandLine): class gtractFastMarchingTrackingInputSpec(CommandLineInputSpec): - inputTensorVolume = File(desc="Required: input tensor image file name", exists=True, argstr="--inputTensorVolume %s") - inputAnisotropyVolume = File(desc="Required: input anisotropy image file name", exists=True, argstr="--inputAnisotropyVolume %s") - inputCostVolume = File(desc="Required: input vcl_cost image file name", exists=True, argstr="--inputCostVolume %s") - inputStartingSeedsLabelMapVolume = File(desc="Required: input starting seeds LabelMap image file name", exists=True, argstr="--inputStartingSeedsLabelMapVolume %s") - startingSeedsLabel = traits.Int(desc="Label value for Starting Seeds", argstr="--startingSeedsLabel %d") - outputTract = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", argstr="--outputTract %s") - writeXMLPolyDataFile = traits.Bool(desc="Flag to make use of the XML format for vtkPolyData fiber tracts.", argstr="--writeXMLPolyDataFile ") - numberOfIterations = traits.Int(desc="Number of iterations used for the optimization", argstr="--numberOfIterations %d") - seedThreshold = traits.Float(desc="Anisotropy threshold used for seed selection", argstr="--seedThreshold %f") - trackingThreshold = traits.Float(desc="Anisotropy threshold used for fiber tracking", argstr="--trackingThreshold %f") - costStepSize = traits.Float(desc="Cost image sub-voxel sampling", argstr="--costStepSize %f") - maximumStepSize = traits.Float(desc="Maximum step size to move when tracking", argstr="--maximumStepSize %f") - minimumStepSize = traits.Float(desc="Minimum step size to move when tracking", argstr="--minimumStepSize %f") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputTensorVolume = File( + desc="Required: input tensor image file name", + exists=True, + argstr="--inputTensorVolume %s") + inputAnisotropyVolume = File( + desc="Required: input anisotropy image file name", + exists=True, + argstr="--inputAnisotropyVolume %s") + inputCostVolume = File( + desc="Required: input vcl_cost image file name", + exists=True, + argstr="--inputCostVolume %s") + inputStartingSeedsLabelMapVolume = File( + desc="Required: input starting seeds LabelMap image file name", + exists=True, + argstr="--inputStartingSeedsLabelMapVolume %s") + startingSeedsLabel = traits.Int( + desc="Label value for Starting Seeds", + argstr="--startingSeedsLabel %d") + outputTract = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", + argstr="--outputTract %s") + writeXMLPolyDataFile = traits.Bool( + desc="Flag to make use of the XML format for vtkPolyData fiber tracts.", + argstr="--writeXMLPolyDataFile ") + numberOfIterations = traits.Int( + desc="Number of iterations used for the optimization", + argstr="--numberOfIterations %d") + seedThreshold = traits.Float( + desc="Anisotropy threshold used for seed selection", + argstr="--seedThreshold %f") + trackingThreshold = traits.Float( + desc="Anisotropy threshold used for fiber tracking", + argstr="--trackingThreshold %f") + costStepSize = traits.Float( + desc="Cost image sub-voxel sampling", argstr="--costStepSize %f") + maximumStepSize = traits.Float( + desc="Maximum step size to move when tracking", + argstr="--maximumStepSize %f") + minimumStepSize = traits.Float( + desc="Minimum step size to move when tracking", + argstr="--minimumStepSize %f") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractFastMarchingTrackingOutputSpec(TraitedSpec): - outputTract = File(desc="Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", exists=True) + outputTract = File( + desc= + "Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", + exists=True) class gtractFastMarchingTracking(SEMLikeCommandLine): - """title: Fast Marching Tracking category: Diffusion.GTRACT @@ -658,11 +1018,27 @@ class gtractFastMarchingTracking(SEMLikeCommandLine): class gtractInvertDisplacementFieldInputSpec(CommandLineInputSpec): - baseImage = File(desc="Required: base image used to define the size of the inverse field", exists=True, argstr="--baseImage %s") - deformationImage = File(desc="Required: Displacement field image", exists=True, argstr="--deformationImage %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: Output deformation field", argstr="--outputVolume %s") - subsamplingFactor = traits.Int(desc="Subsampling factor for the deformation field", argstr="--subsamplingFactor %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + baseImage = File( + desc= + "Required: base image used to define the size of the inverse field", + exists=True, + argstr="--baseImage %s") + deformationImage = File( + desc="Required: Displacement field image", + exists=True, + argstr="--deformationImage %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: Output deformation field", + argstr="--outputVolume %s") + subsamplingFactor = traits.Int( + desc="Subsampling factor for the deformation field", + argstr="--subsamplingFactor %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractInvertDisplacementFieldOutputSpec(TraitedSpec): @@ -670,7 +1046,6 @@ class gtractInvertDisplacementFieldOutputSpec(TraitedSpec): class gtractInvertDisplacementField(SEMLikeCommandLine): - """title: Invert Displacement Field category: Diffusion.GTRACT @@ -697,44 +1072,105 @@ class gtractInvertDisplacementField(SEMLikeCommandLine): class gtractCoRegAnatomyInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input vector image file name. It is recommended that the input volume is the skull stripped baseline image of the DWI scan.", exists=True, argstr="--inputVolume %s") - inputAnatomicalVolume = File(desc="Required: input anatomical image file name. It is recommended that that the input anatomical image has been skull stripped and has the same orientation as the DWI scan.", exists=True, argstr="--inputAnatomicalVolume %s") - vectorIndex = traits.Int(desc="Vector image index in the moving image (within the DWI) to be used for registration.", argstr="--vectorIndex %d") - inputRigidTransform = File(desc="Required (for B-Spline type co-registration): input rigid transform file name. Used as a starting point for the anatomical B-Spline registration.", exists=True, argstr="--inputRigidTransform %s") - outputTransformName = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: filename for the fit transform.", argstr="--outputTransformName %s") - transformType = traits.Enum("Rigid", "Bspline", desc="Transform Type: Rigid|Bspline", argstr="--transformType %s") - numberOfIterations = traits.Int(desc="Number of iterations in the selected 3D fit", argstr="--numberOfIterations %d") - gridSize = InputMultiPath(traits.Int, desc="Number of grid subdivisions in all 3 directions", sep=",", argstr="--gridSize %s") + inputVolume = File( + desc= + "Required: input vector image file name. It is recommended that the input volume is the skull stripped baseline image of the DWI scan.", + exists=True, + argstr="--inputVolume %s") + inputAnatomicalVolume = File( + desc= + "Required: input anatomical image file name. It is recommended that that the input anatomical image has been skull stripped and has the same orientation as the DWI scan.", + exists=True, + argstr="--inputAnatomicalVolume %s") + vectorIndex = traits.Int( + desc= + "Vector image index in the moving image (within the DWI) to be used for registration.", + argstr="--vectorIndex %d") + inputRigidTransform = File( + desc= + "Required (for B-Spline type co-registration): input rigid transform file name. Used as a starting point for the anatomical B-Spline registration.", + exists=True, + argstr="--inputRigidTransform %s") + outputTransformName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: filename for the fit transform.", + argstr="--outputTransformName %s") + transformType = traits.Enum( + "Rigid", + "Bspline", + desc="Transform Type: Rigid|Bspline", + argstr="--transformType %s") + numberOfIterations = traits.Int( + desc="Number of iterations in the selected 3D fit", + argstr="--numberOfIterations %d") + gridSize = InputMultiPath( + traits.Int, + desc="Number of grid subdivisions in all 3 directions", + sep=",", + argstr="--gridSize %s") borderSize = traits.Int(desc="Size of border", argstr="--borderSize %d") - numberOfHistogramBins = traits.Int(desc="Number of histogram bins", argstr="--numberOfHistogramBins %d") - spatialScale = traits.Int(desc="Scales the number of voxels in the image by this value to specify the number of voxels used in the registration", argstr="--spatialScale %d") - convergence = traits.Float(desc="Convergence Factor", argstr="--convergence %f") - gradientTolerance = traits.Float(desc="Gradient Tolerance", argstr="--gradientTolerance %f") + numberOfHistogramBins = traits.Int( + desc="Number of histogram bins", argstr="--numberOfHistogramBins %d") + spatialScale = traits.Int( + desc= + "Scales the number of voxels in the image by this value to specify the number of voxels used in the registration", + argstr="--spatialScale %d") + convergence = traits.Float( + desc="Convergence Factor", argstr="--convergence %f") + gradientTolerance = traits.Float( + desc="Gradient Tolerance", argstr="--gradientTolerance %f") maxBSplineDisplacement = traits.Float( - desc=" Sets the maximum allowed displacements in image physical coordinates for BSpline control grid along each axis. A value of 0.0 indicates that the problem should be unbounded. NOTE: This only constrains the BSpline portion, and does not limit the displacement from the associated bulk transform. This can lead to a substantial reduction in computation time in the BSpline optimizer., ", argstr="--maxBSplineDisplacement %f") - maximumStepSize = traits.Float(desc="Maximum permitted step size to move in the selected 3D fit", argstr="--maximumStepSize %f") - minimumStepSize = traits.Float(desc="Minimum required step size to move in the selected 3D fit without converging -- decrease this to make the fit more exacting", argstr="--minimumStepSize %f") - translationScale = traits.Float(desc="How much to scale up changes in position compared to unit rotational changes in radians -- decrease this to put more translation in the fit", argstr="--translationScale %f") - relaxationFactor = traits.Float(desc="Fraction of gradient from Jacobian to attempt to move in the selected 3D fit", argstr="--relaxationFactor %f") + desc= + " Sets the maximum allowed displacements in image physical coordinates for BSpline control grid along each axis. A value of 0.0 indicates that the problem should be unbounded. NOTE: This only constrains the BSpline portion, and does not limit the displacement from the associated bulk transform. This can lead to a substantial reduction in computation time in the BSpline optimizer., ", + argstr="--maxBSplineDisplacement %f") + maximumStepSize = traits.Float( + desc="Maximum permitted step size to move in the selected 3D fit", + argstr="--maximumStepSize %f") + minimumStepSize = traits.Float( + desc= + "Minimum required step size to move in the selected 3D fit without converging -- decrease this to make the fit more exacting", + argstr="--minimumStepSize %f") + translationScale = traits.Float( + desc= + "How much to scale up changes in position compared to unit rotational changes in radians -- decrease this to put more translation in the fit", + argstr="--translationScale %f") + relaxationFactor = traits.Float( + desc= + "Fraction of gradient from Jacobian to attempt to move in the selected 3D fit", + argstr="--relaxationFactor %f") numberOfSamples = traits.Int( - desc="The number of voxels sampled for mutual information computation. Increase this for a slower, more careful fit. NOTE that it is suggested to use samplingPercentage instead of this option. However, if set, it overwrites the samplingPercentage option. ", argstr="--numberOfSamples %d") + desc= + "The number of voxels sampled for mutual information computation. Increase this for a slower, more careful fit. NOTE that it is suggested to use samplingPercentage instead of this option. However, if set, it overwrites the samplingPercentage option. ", + argstr="--numberOfSamples %d") samplingPercentage = traits.Float( - desc="This is a number in (0.0,1.0] interval that shows the percentage of the input fixed image voxels that are sampled for mutual information computation. Increase this for a slower, more careful fit. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation. The default is to use approximately 5% of voxels (for backwards compatibility 5% ~= 500000/(256*256*256)). Typical values range from 1% for low detail images to 20% for high detail images.", argstr="--samplingPercentage %f") + desc= + "This is a number in (0.0,1.0] interval that shows the percentage of the input fixed image voxels that are sampled for mutual information computation. Increase this for a slower, more careful fit. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation. The default is to use approximately 5% of voxels (for backwards compatibility 5% ~= 500000/(256*256*256)). Typical values range from 1% for low detail images to 20% for high detail images.", + argstr="--samplingPercentage %f") useMomentsAlign = traits.Bool( - desc="MomentsAlign assumes that the center of mass of the images represent similar structures. Perform a MomentsAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either CenterOfHeadLAlign, GeometryAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", argstr="--useMomentsAlign ") + desc= + "MomentsAlign assumes that the center of mass of the images represent similar structures. Perform a MomentsAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either CenterOfHeadLAlign, GeometryAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useMomentsAlign ") useGeometryAlign = traits.Bool( - desc="GeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. Perform a GeometryCenterAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, CenterOfHeadAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", argstr="--useGeometryAlign ") + desc= + "GeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. Perform a GeometryCenterAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, CenterOfHeadAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useGeometryAlign ") useCenterOfHeadAlign = traits.Bool( - desc="CenterOfHeadAlign attempts to find a hemisphere full of foreground voxels from the superior direction as an estimate of where the center of a head shape would be to drive a center of mass estimate. Perform a CenterOfHeadAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, GeometryAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", argstr="--useCenterOfHeadAlign ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + desc= + "CenterOfHeadAlign attempts to find a hemisphere full of foreground voxels from the superior direction as an estimate of where the center of a head shape would be to drive a center of mass estimate. Perform a CenterOfHeadAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, GeometryAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useCenterOfHeadAlign ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractCoRegAnatomyOutputSpec(TraitedSpec): - outputTransformName = File(desc="Required: filename for the fit transform.", exists=True) + outputTransformName = File( + desc="Required: filename for the fit transform.", exists=True) class gtractCoRegAnatomy(SEMLikeCommandLine): - """title: Coregister B0 to Anatomy B-Spline category: Diffusion.GTRACT @@ -761,24 +1197,65 @@ class gtractCoRegAnatomy(SEMLikeCommandLine): class gtractResampleDWIInPlaceInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image is a 4D NRRD image.", exists=True, argstr="--inputVolume %s") - referenceVolume = File(desc="If provided, resample to the final space of the referenceVolume 3D data set.", exists=True, argstr="--referenceVolume %s") - outputResampledB0 = traits.Either(traits.Bool, File(), hash_files=False, desc="Convenience function for extracting the first index location (assumed to be the B0)", argstr="--outputResampledB0 %s") - inputTransform = File(desc="Required: transform file derived from rigid registration of b0 image to reference structural image.", exists=True, argstr="--inputTransform %s") - warpDWITransform = File(desc="Optional: transform file to warp gradient volumes.", exists=True, argstr="--warpDWITransform %s") - debugLevel = traits.Int(desc="Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", argstr="--debugLevel %d") - imageOutputSize = InputMultiPath(traits.Int, desc="The voxel lattice for the output image, padding is added if necessary. NOTE: if 0,0,0, then the inputVolume size is used.", sep=",", argstr="--imageOutputSize %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image (NRRD file) that has been rigidly transformed into the space of the structural image and padded if image padding was changed from 0,0,0 default.", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="Required: input image is a 4D NRRD image.", + exists=True, + argstr="--inputVolume %s") + referenceVolume = File( + desc= + "If provided, resample to the final space of the referenceVolume 3D data set.", + exists=True, + argstr="--referenceVolume %s") + outputResampledB0 = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Convenience function for extracting the first index location (assumed to be the B0)", + argstr="--outputResampledB0 %s") + inputTransform = File( + desc= + "Required: transform file derived from rigid registration of b0 image to reference structural image.", + exists=True, + argstr="--inputTransform %s") + warpDWITransform = File( + desc="Optional: transform file to warp gradient volumes.", + exists=True, + argstr="--warpDWITransform %s") + debugLevel = traits.Int( + desc= + "Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", + argstr="--debugLevel %d") + imageOutputSize = InputMultiPath( + traits.Int, + desc= + "The voxel lattice for the output image, padding is added if necessary. NOTE: if 0,0,0, then the inputVolume size is used.", + sep=",", + argstr="--imageOutputSize %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: output image (NRRD file) that has been rigidly transformed into the space of the structural image and padded if image padding was changed from 0,0,0 default.", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractResampleDWIInPlaceOutputSpec(TraitedSpec): - outputResampledB0 = File(desc="Convenience function for extracting the first index location (assumed to be the B0)", exists=True) - outputVolume = File(desc="Required: output image (NRRD file) that has been rigidly transformed into the space of the structural image and padded if image padding was changed from 0,0,0 default.", exists=True) + outputResampledB0 = File( + desc= + "Convenience function for extracting the first index location (assumed to be the B0)", + exists=True) + outputVolume = File( + desc= + "Required: output image (NRRD file) that has been rigidly transformed into the space of the structural image and padded if image padding was changed from 0,0,0 default.", + exists=True) class gtractResampleDWIInPlace(SEMLikeCommandLine): - """title: Resample DWI In Place category: Diffusion.GTRACT @@ -800,21 +1277,53 @@ class gtractResampleDWIInPlace(SEMLikeCommandLine): input_spec = gtractResampleDWIInPlaceInputSpec output_spec = gtractResampleDWIInPlaceOutputSpec _cmd = " gtractResampleDWIInPlace " - _outputs_filenames = {'outputResampledB0': 'outputResampledB0.nii', 'outputVolume': 'outputVolume.nii'} + _outputs_filenames = { + 'outputResampledB0': 'outputResampledB0.nii', + 'outputVolume': 'outputVolume.nii' + } _redirect_x = False class gtractCostFastMarchingInputSpec(CommandLineInputSpec): - inputTensorVolume = File(desc="Required: input tensor image file name", exists=True, argstr="--inputTensorVolume %s") - inputAnisotropyVolume = File(desc="Required: input anisotropy image file name", exists=True, argstr="--inputAnisotropyVolume %s") - inputStartingSeedsLabelMapVolume = File(desc="Required: input starting seeds LabelMap image file name", exists=True, argstr="--inputStartingSeedsLabelMapVolume %s") - startingSeedsLabel = traits.Int(desc="Label value for Starting Seeds", argstr="--startingSeedsLabel %d") - outputCostVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output vcl_cost image", argstr="--outputCostVolume %s") - outputSpeedVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output speed image", argstr="--outputSpeedVolume %s") - anisotropyWeight = traits.Float(desc="Anisotropy weight used for vcl_cost function calculations", argstr="--anisotropyWeight %f") - stoppingValue = traits.Float(desc="Terminiating value for vcl_cost function estimation", argstr="--stoppingValue %f") - seedThreshold = traits.Float(desc="Anisotropy threshold used for seed selection", argstr="--seedThreshold %f") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputTensorVolume = File( + desc="Required: input tensor image file name", + exists=True, + argstr="--inputTensorVolume %s") + inputAnisotropyVolume = File( + desc="Required: input anisotropy image file name", + exists=True, + argstr="--inputAnisotropyVolume %s") + inputStartingSeedsLabelMapVolume = File( + desc="Required: input starting seeds LabelMap image file name", + exists=True, + argstr="--inputStartingSeedsLabelMapVolume %s") + startingSeedsLabel = traits.Int( + desc="Label value for Starting Seeds", + argstr="--startingSeedsLabel %d") + outputCostVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output vcl_cost image", + argstr="--outputCostVolume %s") + outputSpeedVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output speed image", + argstr="--outputSpeedVolume %s") + anisotropyWeight = traits.Float( + desc="Anisotropy weight used for vcl_cost function calculations", + argstr="--anisotropyWeight %f") + stoppingValue = traits.Float( + desc="Terminiating value for vcl_cost function estimation", + argstr="--stoppingValue %f") + seedThreshold = traits.Float( + desc="Anisotropy threshold used for seed selection", + argstr="--seedThreshold %f") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractCostFastMarchingOutputSpec(TraitedSpec): @@ -823,7 +1332,6 @@ class gtractCostFastMarchingOutputSpec(TraitedSpec): class gtractCostFastMarching(SEMLikeCommandLine): - """title: Cost Fast Marching category: Diffusion.GTRACT @@ -845,47 +1353,126 @@ class gtractCostFastMarching(SEMLikeCommandLine): input_spec = gtractCostFastMarchingInputSpec output_spec = gtractCostFastMarchingOutputSpec _cmd = " gtractCostFastMarching " - _outputs_filenames = {'outputCostVolume': 'outputCostVolume.nrrd', 'outputSpeedVolume': 'outputSpeedVolume.nrrd'} + _outputs_filenames = { + 'outputCostVolume': 'outputCostVolume.nrrd', + 'outputSpeedVolume': 'outputSpeedVolume.nrrd' + } _redirect_x = False class gtractFiberTrackingInputSpec(CommandLineInputSpec): - inputTensorVolume = File(desc="Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): input tensor image file name", exists=True, argstr="--inputTensorVolume %s") - inputAnisotropyVolume = File(desc="Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): input anisotropy image file name", exists=True, argstr="--inputAnisotropyVolume %s") - inputStartingSeedsLabelMapVolume = File(desc="Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): input starting seeds LabelMap image file name", exists=True, argstr="--inputStartingSeedsLabelMapVolume %s") - startingSeedsLabel = traits.Int(desc="Label value for Starting Seeds (required if Label number used to create seed point in Slicer was not 1)", argstr="--startingSeedsLabel %d") - inputEndingSeedsLabelMapVolume = File(desc="Required (for Streamline, GraphSearch, and Guided fiber tracking methods): input ending seeds LabelMap image file name", exists=True, argstr="--inputEndingSeedsLabelMapVolume %s") - endingSeedsLabel = traits.Int(desc="Label value for Ending Seeds (required if Label number used to create seed point in Slicer was not 1)", argstr="--endingSeedsLabel %d") - inputTract = File(desc="Required (for Guided fiber tracking method): guide fiber in vtkPolydata file containing one tract line.", exists=True, argstr="--inputTract %s") - outputTract = traits.Either(traits.Bool, File(), hash_files=False, desc="Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): name of output vtkPolydata file containing tract lines and the point data collected along them.", argstr="--outputTract %s") - writeXMLPolyDataFile = traits.Bool(desc="Flag to make use of the XML format for vtkPolyData fiber tracts.", argstr="--writeXMLPolyDataFile ") - trackingMethod = traits.Enum("Guided", "Free", "Streamline", "GraphSearch", desc="Fiber tracking Filter Type: Guided|Free|Streamline|GraphSearch", argstr="--trackingMethod %s") - guidedCurvatureThreshold = traits.Float(desc="Guided Curvature Threshold (Degrees)", argstr="--guidedCurvatureThreshold %f") - maximumGuideDistance = traits.Float(desc="Maximum distance for using the guide fiber direction", argstr="--maximumGuideDistance %f") - seedThreshold = traits.Float(desc="Anisotropy threshold for seed selection (recommended for Free fiber tracking)", argstr="--seedThreshold %f") - trackingThreshold = traits.Float(desc="Anisotropy threshold for fiber tracking (anisotropy values of the next point along the path)", argstr="--trackingThreshold %f") - curvatureThreshold = traits.Float(desc="Curvature threshold in degrees (recommended for Free fiber tracking)", argstr="--curvatureThreshold %f") - branchingThreshold = traits.Float(desc="Anisotropy Branching threshold (recommended for GraphSearch fiber tracking method)", argstr="--branchingThreshold %f") - maximumBranchPoints = traits.Int(desc="Maximum branch points (recommended for GraphSearch fiber tracking method)", argstr="--maximumBranchPoints %d") - useRandomWalk = traits.Bool(desc="Flag to use random walk.", argstr="--useRandomWalk ") - randomSeed = traits.Int(desc="Random number generator seed", argstr="--randomSeed %d") - branchingAngle = traits.Float(desc="Branching angle in degrees (recommended for GraphSearch fiber tracking method)", argstr="--branchingAngle %f") - minimumLength = traits.Float(desc="Minimum fiber length. Helpful for filtering invalid tracts.", argstr="--minimumLength %f") - maximumLength = traits.Float(desc="Maximum fiber length (voxels)", argstr="--maximumLength %f") - stepSize = traits.Float(desc="Fiber tracking step size", argstr="--stepSize %f") - useLoopDetection = traits.Bool(desc="Flag to make use of loop detection.", argstr="--useLoopDetection ") - useTend = traits.Bool(desc="Flag to make use of Tend F and Tend G parameters.", argstr="--useTend ") + inputTensorVolume = File( + desc= + "Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): input tensor image file name", + exists=True, + argstr="--inputTensorVolume %s") + inputAnisotropyVolume = File( + desc= + "Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): input anisotropy image file name", + exists=True, + argstr="--inputAnisotropyVolume %s") + inputStartingSeedsLabelMapVolume = File( + desc= + "Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): input starting seeds LabelMap image file name", + exists=True, + argstr="--inputStartingSeedsLabelMapVolume %s") + startingSeedsLabel = traits.Int( + desc= + "Label value for Starting Seeds (required if Label number used to create seed point in Slicer was not 1)", + argstr="--startingSeedsLabel %d") + inputEndingSeedsLabelMapVolume = File( + desc= + "Required (for Streamline, GraphSearch, and Guided fiber tracking methods): input ending seeds LabelMap image file name", + exists=True, + argstr="--inputEndingSeedsLabelMapVolume %s") + endingSeedsLabel = traits.Int( + desc= + "Label value for Ending Seeds (required if Label number used to create seed point in Slicer was not 1)", + argstr="--endingSeedsLabel %d") + inputTract = File( + desc= + "Required (for Guided fiber tracking method): guide fiber in vtkPolydata file containing one tract line.", + exists=True, + argstr="--inputTract %s") + outputTract = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): name of output vtkPolydata file containing tract lines and the point data collected along them.", + argstr="--outputTract %s") + writeXMLPolyDataFile = traits.Bool( + desc="Flag to make use of the XML format for vtkPolyData fiber tracts.", + argstr="--writeXMLPolyDataFile ") + trackingMethod = traits.Enum( + "Guided", + "Free", + "Streamline", + "GraphSearch", + desc="Fiber tracking Filter Type: Guided|Free|Streamline|GraphSearch", + argstr="--trackingMethod %s") + guidedCurvatureThreshold = traits.Float( + desc="Guided Curvature Threshold (Degrees)", + argstr="--guidedCurvatureThreshold %f") + maximumGuideDistance = traits.Float( + desc="Maximum distance for using the guide fiber direction", + argstr="--maximumGuideDistance %f") + seedThreshold = traits.Float( + desc= + "Anisotropy threshold for seed selection (recommended for Free fiber tracking)", + argstr="--seedThreshold %f") + trackingThreshold = traits.Float( + desc= + "Anisotropy threshold for fiber tracking (anisotropy values of the next point along the path)", + argstr="--trackingThreshold %f") + curvatureThreshold = traits.Float( + desc= + "Curvature threshold in degrees (recommended for Free fiber tracking)", + argstr="--curvatureThreshold %f") + branchingThreshold = traits.Float( + desc= + "Anisotropy Branching threshold (recommended for GraphSearch fiber tracking method)", + argstr="--branchingThreshold %f") + maximumBranchPoints = traits.Int( + desc= + "Maximum branch points (recommended for GraphSearch fiber tracking method)", + argstr="--maximumBranchPoints %d") + useRandomWalk = traits.Bool( + desc="Flag to use random walk.", argstr="--useRandomWalk ") + randomSeed = traits.Int( + desc="Random number generator seed", argstr="--randomSeed %d") + branchingAngle = traits.Float( + desc= + "Branching angle in degrees (recommended for GraphSearch fiber tracking method)", + argstr="--branchingAngle %f") + minimumLength = traits.Float( + desc="Minimum fiber length. Helpful for filtering invalid tracts.", + argstr="--minimumLength %f") + maximumLength = traits.Float( + desc="Maximum fiber length (voxels)", argstr="--maximumLength %f") + stepSize = traits.Float( + desc="Fiber tracking step size", argstr="--stepSize %f") + useLoopDetection = traits.Bool( + desc="Flag to make use of loop detection.", + argstr="--useLoopDetection ") + useTend = traits.Bool( + desc="Flag to make use of Tend F and Tend G parameters.", + argstr="--useTend ") tendF = traits.Float(desc="Tend F parameter", argstr="--tendF %f") tendG = traits.Float(desc="Tend G parameter", argstr="--tendG %f") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractFiberTrackingOutputSpec(TraitedSpec): - outputTract = File(desc="Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): name of output vtkPolydata file containing tract lines and the point data collected along them.", exists=True) + outputTract = File( + desc= + "Required (for Free, Streamline, GraphSearch, and Guided fiber tracking methods): name of output vtkPolydata file containing tract lines and the point data collected along them.", + exists=True) class gtractFiberTracking(SEMLikeCommandLine): - """title: Fiber Tracking category: Diffusion.GTRACT @@ -912,19 +1499,41 @@ class gtractFiberTracking(SEMLikeCommandLine): class extractNrrdVectorIndexInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input file containing the vector that will be extracted", exists=True, argstr="--inputVolume %s") - vectorIndex = traits.Int(desc="Index in the vector image to extract", argstr="--vectorIndex %d") - setImageOrientation = traits.Enum("AsAcquired", "Axial", "Coronal", "Sagittal", desc="Sets the image orientation of the extracted vector (Axial, Coronal, Sagittal)", argstr="--setImageOrientation %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the vector image at the given index", argstr="--outputVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc= + "Required: input file containing the vector that will be extracted", + exists=True, + argstr="--inputVolume %s") + vectorIndex = traits.Int( + desc="Index in the vector image to extract", argstr="--vectorIndex %d") + setImageOrientation = traits.Enum( + "AsAcquired", + "Axial", + "Coronal", + "Sagittal", + desc= + "Sets the image orientation of the extracted vector (Axial, Coronal, Sagittal)", + argstr="--setImageOrientation %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the vector image at the given index", + argstr="--outputVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class extractNrrdVectorIndexOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the vector image at the given index", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the vector image at the given index", + exists=True) class extractNrrdVectorIndex(SEMLikeCommandLine): - """title: Extract Nrrd Index category: Diffusion.GTRACT @@ -951,20 +1560,41 @@ class extractNrrdVectorIndex(SEMLikeCommandLine): class gtractResampleFibersInputSpec(CommandLineInputSpec): - inputForwardDeformationFieldVolume = File(desc="Required: input forward deformation field image file name", exists=True, argstr="--inputForwardDeformationFieldVolume %s") - inputReverseDeformationFieldVolume = File(desc="Required: input reverse deformation field image file name", exists=True, argstr="--inputReverseDeformationFieldVolume %s") - inputTract = File(desc="Required: name of input vtkPolydata file containing tract lines.", exists=True, argstr="--inputTract %s") - outputTract = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", argstr="--outputTract %s") - writeXMLPolyDataFile = traits.Bool(desc="Flag to make use of the XML format for vtkPolyData fiber tracts.", argstr="--writeXMLPolyDataFile ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputForwardDeformationFieldVolume = File( + desc="Required: input forward deformation field image file name", + exists=True, + argstr="--inputForwardDeformationFieldVolume %s") + inputReverseDeformationFieldVolume = File( + desc="Required: input reverse deformation field image file name", + exists=True, + argstr="--inputReverseDeformationFieldVolume %s") + inputTract = File( + desc="Required: name of input vtkPolydata file containing tract lines.", + exists=True, + argstr="--inputTract %s") + outputTract = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", + argstr="--outputTract %s") + writeXMLPolyDataFile = traits.Bool( + desc="Flag to make use of the XML format for vtkPolyData fiber tracts.", + argstr="--writeXMLPolyDataFile ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractResampleFibersOutputSpec(TraitedSpec): - outputTract = File(desc="Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", exists=True) + outputTract = File( + desc= + "Required: name of output vtkPolydata file containing tract lines and the point data collected along them.", + exists=True) class gtractResampleFibers(SEMLikeCommandLine): - """title: Resample Fibers category: Diffusion.GTRACT @@ -991,29 +1621,68 @@ class gtractResampleFibers(SEMLikeCommandLine): class gtractTensorInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image 4D NRRD image. Must contain data based on at least 6 distinct diffusion directions. The inputVolume is allowed to have multiple b0 and gradient direction images. Averaging of the b0 image is done internally in this step. Prior averaging of the DWIs is not required.", - exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: name of output NRRD file containing the Tensor vector image", argstr="--outputVolume %s") - medianFilterSize = InputMultiPath(traits.Int, desc="Median filter radius in all 3 directions", sep=",", argstr="--medianFilterSize %s") + inputVolume = File( + desc= + "Required: input image 4D NRRD image. Must contain data based on at least 6 distinct diffusion directions. The inputVolume is allowed to have multiple b0 and gradient direction images. Averaging of the b0 image is done internally in this step. Prior averaging of the DWIs is not required.", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: name of output NRRD file containing the Tensor vector image", + argstr="--outputVolume %s") + medianFilterSize = InputMultiPath( + traits.Int, + desc="Median filter radius in all 3 directions", + sep=",", + argstr="--medianFilterSize %s") maskProcessingMode = traits.Enum( - "NOMASK", "ROIAUTO", "ROI", desc="ROIAUTO: mask is implicitly defined using a otsu forground and hole filling algorithm. ROI: Uses the masks to define what parts of the image should be used for computing the transform. NOMASK: no mask used", argstr="--maskProcessingMode %s") - maskVolume = File(desc="Mask Image, if maskProcessingMode is ROI", exists=True, argstr="--maskVolume %s") + "NOMASK", + "ROIAUTO", + "ROI", + desc= + "ROIAUTO: mask is implicitly defined using a otsu forground and hole filling algorithm. ROI: Uses the masks to define what parts of the image should be used for computing the transform. NOMASK: no mask used", + argstr="--maskProcessingMode %s") + maskVolume = File( + desc="Mask Image, if maskProcessingMode is ROI", + exists=True, + argstr="--maskVolume %s") backgroundSuppressingThreshold = traits.Int( - desc="Image threshold to suppress background. This sets a threshold used on the b0 image to remove background voxels from processing. Typically, values of 100 and 500 work well for Siemens and GE DTI data, respectively. Check your data particularly in the globus pallidus to make sure the brain tissue is not being eliminated with this threshold.", argstr="--backgroundSuppressingThreshold %d") - resampleIsotropic = traits.Bool(desc="Flag to resample to isotropic voxels. Enabling this feature is recommended if fiber tracking will be performed.", argstr="--resampleIsotropic ") - size = traits.Float(desc="Isotropic voxel size to resample to", argstr="--size %f") - b0Index = traits.Int(desc="Index in input vector index to extract", argstr="--b0Index %d") - applyMeasurementFrame = traits.Bool(desc="Flag to apply the measurement frame to the gradient directions", argstr="--applyMeasurementFrame ") - ignoreIndex = InputMultiPath(traits.Int, desc="Ignore diffusion gradient index. Used to remove specific gradient directions with artifacts.", sep=",", argstr="--ignoreIndex %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + desc= + "Image threshold to suppress background. This sets a threshold used on the b0 image to remove background voxels from processing. Typically, values of 100 and 500 work well for Siemens and GE DTI data, respectively. Check your data particularly in the globus pallidus to make sure the brain tissue is not being eliminated with this threshold.", + argstr="--backgroundSuppressingThreshold %d") + resampleIsotropic = traits.Bool( + desc= + "Flag to resample to isotropic voxels. Enabling this feature is recommended if fiber tracking will be performed.", + argstr="--resampleIsotropic ") + size = traits.Float( + desc="Isotropic voxel size to resample to", argstr="--size %f") + b0Index = traits.Int( + desc="Index in input vector index to extract", argstr="--b0Index %d") + applyMeasurementFrame = traits.Bool( + desc="Flag to apply the measurement frame to the gradient directions", + argstr="--applyMeasurementFrame ") + ignoreIndex = InputMultiPath( + traits.Int, + desc= + "Ignore diffusion gradient index. Used to remove specific gradient directions with artifacts.", + sep=",", + argstr="--ignoreIndex %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class gtractTensorOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: name of output NRRD file containing the Tensor vector image", exists=True) + outputVolume = File( + desc= + "Required: name of output NRRD file containing the Tensor vector image", + exists=True) class gtractTensor(SEMLikeCommandLine): - """title: Tensor Estimation category: Diffusion.GTRACT diff --git a/nipype/interfaces/semtools/diffusion/maxcurvature.py b/nipype/interfaces/semtools/diffusion/maxcurvature.py index 6629a006c9..570109eb1b 100644 --- a/nipype/interfaces/semtools/diffusion/maxcurvature.py +++ b/nipype/interfaces/semtools/diffusion/maxcurvature.py @@ -12,7 +12,12 @@ class maxcurvatureInputSpec(CommandLineInputSpec): image = File(desc="FA Image", exists=True, argstr="--image %s") - output = traits.Either(traits.Bool, File(), hash_files=False, desc="Output File", argstr="--output %s") + output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output File", + argstr="--output %s") sigma = traits.Float(desc="Scale of Gradients", argstr="--sigma %f") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") @@ -22,7 +27,6 @@ class maxcurvatureOutputSpec(TraitedSpec): class maxcurvature(SEMLikeCommandLine): - """title: MaxCurvature-Hessian (DTIProcess) category: Diffusion diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py index 0a7e27fee1..e3c03641e5 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py @@ -4,73 +4,70 @@ def test_DWIConvert_inputs(): - input_map = dict(allowLossyConversion=dict(argstr='--allowLossyConversion ', - ), - args=dict(argstr='%s', - ), - conversionMode=dict(argstr='--conversionMode %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fMRI=dict(argstr='--fMRI ', - ), - fslNIFTIFile=dict(argstr='--fslNIFTIFile %s', - ), - gradientVectorFile=dict(argstr='--gradientVectorFile %s', - hash_files=False, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBValues=dict(argstr='--inputBValues %s', - ), - inputBVectors=dict(argstr='--inputBVectors %s', - ), - inputDicomDirectory=dict(argstr='--inputDicomDirectory %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputBValues=dict(argstr='--outputBValues %s', - hash_files=False, - ), - outputBVectors=dict(argstr='--outputBVectors %s', - hash_files=False, - ), - outputDirectory=dict(argstr='--outputDirectory %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - smallGradientThreshold=dict(argstr='--smallGradientThreshold %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transposeInputBVectors=dict(argstr='--transposeInputBVectors ', - ), - useBMatrixGradientDirections=dict(argstr='--useBMatrixGradientDirections ', - ), - useIdentityMeaseurementFrame=dict(argstr='--useIdentityMeaseurementFrame ', - ), - writeProtocolGradientsFile=dict(argstr='--writeProtocolGradientsFile ', - ), + input_map = dict( + allowLossyConversion=dict(argstr='--allowLossyConversion ', ), + args=dict(argstr='%s', ), + conversionMode=dict(argstr='--conversionMode %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fMRI=dict(argstr='--fMRI ', ), + fslNIFTIFile=dict(argstr='--fslNIFTIFile %s', ), + gradientVectorFile=dict( + argstr='--gradientVectorFile %s', + hash_files=False, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBValues=dict(argstr='--inputBValues %s', ), + inputBVectors=dict(argstr='--inputBVectors %s', ), + inputDicomDirectory=dict(argstr='--inputDicomDirectory %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputBValues=dict( + argstr='--outputBValues %s', + hash_files=False, + ), + outputBVectors=dict( + argstr='--outputBVectors %s', + hash_files=False, + ), + outputDirectory=dict( + argstr='--outputDirectory %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + smallGradientThreshold=dict(argstr='--smallGradientThreshold %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transposeInputBVectors=dict(argstr='--transposeInputBVectors ', ), + useBMatrixGradientDirections=dict( + argstr='--useBMatrixGradientDirections ', ), + useIdentityMeaseurementFrame=dict( + argstr='--useIdentityMeaseurementFrame ', ), + writeProtocolGradientsFile=dict( + argstr='--writeProtocolGradientsFile ', ), ) inputs = DWIConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWIConvert_outputs(): - output_map = dict(gradientVectorFile=dict(), - outputBValues=dict(), - outputBVectors=dict(), - outputDirectory=dict(), - outputVolume=dict(), + output_map = dict( + gradientVectorFile=dict(), + outputBValues=dict(), + outputBVectors=dict(), + outputDirectory=dict(), + outputVolume=dict(), ) outputs = DWIConvert.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py index 5b88f17a54..518cf63615 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py @@ -4,42 +4,35 @@ def test_compareTractInclusion_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - closeness=dict(argstr='--closeness %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - numberOfPoints=dict(argstr='--numberOfPoints %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - standardFiber=dict(argstr='--standardFiber %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - testFiber=dict(argstr='--testFiber %s', - ), - testForBijection=dict(argstr='--testForBijection ', - ), - testForFiberCardinality=dict(argstr='--testForFiberCardinality ', - ), - writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', - ), + input_map = dict( + args=dict(argstr='%s', ), + closeness=dict(argstr='--closeness %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + numberOfPoints=dict(argstr='--numberOfPoints %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + standardFiber=dict(argstr='--standardFiber %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + testFiber=dict(argstr='--testFiber %s', ), + testForBijection=dict(argstr='--testForBijection ', ), + testForFiberCardinality=dict(argstr='--testForFiberCardinality ', ), + writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', ), ) inputs = compareTractInclusion.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_compareTractInclusion_outputs(): output_map = dict() outputs = compareTractInclusion.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py index 4cbbf0e4ea..f1922d282b 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py @@ -4,38 +4,36 @@ def test_dtiaverage_inputs(): - input_map = dict(DTI_double=dict(argstr='--DTI_double ', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputs=dict(argstr='--inputs %s...', - ), - tensor_output=dict(argstr='--tensor_output %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), + input_map = dict( + DTI_double=dict(argstr='--DTI_double ', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputs=dict(argstr='--inputs %s...', ), + tensor_output=dict( + argstr='--tensor_output %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), ) inputs = dtiaverage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_dtiaverage_outputs(): - output_map = dict(tensor_output=dict(), - ) + output_map = dict(tensor_output=dict(), ) outputs = dtiaverage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py index 80a0f78fe0..8b96cb8951 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py @@ -4,72 +4,66 @@ def test_dtiestim_inputs(): - input_map = dict(B0=dict(argstr='--B0 %s', - hash_files=False, - ), - B0_mask_output=dict(argstr='--B0_mask_output %s', - hash_files=False, - ), - DTI_double=dict(argstr='--DTI_double ', - ), - args=dict(argstr='%s', - ), - bad_region_mask=dict(argstr='--bad_region_mask %s', - ), - brain_mask=dict(argstr='--brain_mask %s', - ), - correction=dict(argstr='--correction %s', - ), - defaultTensor=dict(argstr='--defaultTensor %s', - sep=',', - ), - dwi_image=dict(argstr='--dwi_image %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - idwi=dict(argstr='--idwi %s', - hash_files=False, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - method=dict(argstr='--method %s', - ), - shiftNeg=dict(argstr='--shiftNeg ', - ), - shiftNegCoeff=dict(argstr='--shiftNegCoeff %f', - ), - sigma=dict(argstr='--sigma %f', - ), - step=dict(argstr='--step %f', - ), - tensor_output=dict(argstr='--tensor_output %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--threshold %d', - ), - verbose=dict(argstr='--verbose ', - ), - weight_iterations=dict(argstr='--weight_iterations %d', - ), + input_map = dict( + B0=dict( + argstr='--B0 %s', + hash_files=False, + ), + B0_mask_output=dict( + argstr='--B0_mask_output %s', + hash_files=False, + ), + DTI_double=dict(argstr='--DTI_double ', ), + args=dict(argstr='%s', ), + bad_region_mask=dict(argstr='--bad_region_mask %s', ), + brain_mask=dict(argstr='--brain_mask %s', ), + correction=dict(argstr='--correction %s', ), + defaultTensor=dict( + argstr='--defaultTensor %s', + sep=',', + ), + dwi_image=dict(argstr='--dwi_image %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + idwi=dict( + argstr='--idwi %s', + hash_files=False, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + method=dict(argstr='--method %s', ), + shiftNeg=dict(argstr='--shiftNeg ', ), + shiftNegCoeff=dict(argstr='--shiftNegCoeff %f', ), + sigma=dict(argstr='--sigma %f', ), + step=dict(argstr='--step %f', ), + tensor_output=dict( + argstr='--tensor_output %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='--threshold %d', ), + verbose=dict(argstr='--verbose ', ), + weight_iterations=dict(argstr='--weight_iterations %d', ), ) inputs = dtiestim.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_dtiestim_outputs(): - output_map = dict(B0=dict(), - B0_mask_output=dict(), - idwi=dict(), - tensor_output=dict(), + output_map = dict( + B0=dict(), + B0_mask_output=dict(), + idwi=dict(), + tensor_output=dict(), ) outputs = dtiestim.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py index 6090c81526..b66a93f723 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py @@ -4,115 +4,118 @@ def test_dtiprocess_inputs(): - input_map = dict(DTI_double=dict(argstr='--DTI_double ', - ), - RD_output=dict(argstr='--RD_output %s', - hash_files=False, - ), - affineitk_file=dict(argstr='--affineitk_file %s', - ), - args=dict(argstr='%s', - ), - color_fa_output=dict(argstr='--color_fa_output %s', - hash_files=False, - ), - correction=dict(argstr='--correction %s', - ), - deformation_output=dict(argstr='--deformation_output %s', - hash_files=False, - ), - dof_file=dict(argstr='--dof_file %s', - ), - dti_image=dict(argstr='--dti_image %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fa_gradient_output=dict(argstr='--fa_gradient_output %s', - hash_files=False, - ), - fa_gradmag_output=dict(argstr='--fa_gradmag_output %s', - hash_files=False, - ), - fa_output=dict(argstr='--fa_output %s', - hash_files=False, - ), - forward=dict(argstr='--forward %s', - ), - frobenius_norm_output=dict(argstr='--frobenius_norm_output %s', - hash_files=False, - ), - hField=dict(argstr='--hField ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interpolation=dict(argstr='--interpolation %s', - ), - lambda1_output=dict(argstr='--lambda1_output %s', - hash_files=False, - ), - lambda2_output=dict(argstr='--lambda2_output %s', - hash_files=False, - ), - lambda3_output=dict(argstr='--lambda3_output %s', - hash_files=False, - ), - mask=dict(argstr='--mask %s', - ), - md_output=dict(argstr='--md_output %s', - hash_files=False, - ), - negative_eigenvector_output=dict(argstr='--negative_eigenvector_output %s', - hash_files=False, - ), - newdof_file=dict(argstr='--newdof_file %s', - ), - outmask=dict(argstr='--outmask %s', - hash_files=False, - ), - principal_eigenvector_output=dict(argstr='--principal_eigenvector_output %s', - hash_files=False, - ), - reorientation=dict(argstr='--reorientation %s', - ), - rot_output=dict(argstr='--rot_output %s', - hash_files=False, - ), - scalar_float=dict(argstr='--scalar_float ', - ), - sigma=dict(argstr='--sigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), + input_map = dict( + DTI_double=dict(argstr='--DTI_double ', ), + RD_output=dict( + argstr='--RD_output %s', + hash_files=False, + ), + affineitk_file=dict(argstr='--affineitk_file %s', ), + args=dict(argstr='%s', ), + color_fa_output=dict( + argstr='--color_fa_output %s', + hash_files=False, + ), + correction=dict(argstr='--correction %s', ), + deformation_output=dict( + argstr='--deformation_output %s', + hash_files=False, + ), + dof_file=dict(argstr='--dof_file %s', ), + dti_image=dict(argstr='--dti_image %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fa_gradient_output=dict( + argstr='--fa_gradient_output %s', + hash_files=False, + ), + fa_gradmag_output=dict( + argstr='--fa_gradmag_output %s', + hash_files=False, + ), + fa_output=dict( + argstr='--fa_output %s', + hash_files=False, + ), + forward=dict(argstr='--forward %s', ), + frobenius_norm_output=dict( + argstr='--frobenius_norm_output %s', + hash_files=False, + ), + hField=dict(argstr='--hField ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interpolation=dict(argstr='--interpolation %s', ), + lambda1_output=dict( + argstr='--lambda1_output %s', + hash_files=False, + ), + lambda2_output=dict( + argstr='--lambda2_output %s', + hash_files=False, + ), + lambda3_output=dict( + argstr='--lambda3_output %s', + hash_files=False, + ), + mask=dict(argstr='--mask %s', ), + md_output=dict( + argstr='--md_output %s', + hash_files=False, + ), + negative_eigenvector_output=dict( + argstr='--negative_eigenvector_output %s', + hash_files=False, + ), + newdof_file=dict(argstr='--newdof_file %s', ), + outmask=dict( + argstr='--outmask %s', + hash_files=False, + ), + principal_eigenvector_output=dict( + argstr='--principal_eigenvector_output %s', + hash_files=False, + ), + reorientation=dict(argstr='--reorientation %s', ), + rot_output=dict( + argstr='--rot_output %s', + hash_files=False, + ), + scalar_float=dict(argstr='--scalar_float ', ), + sigma=dict(argstr='--sigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), ) inputs = dtiprocess.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_dtiprocess_outputs(): - output_map = dict(RD_output=dict(), - color_fa_output=dict(), - deformation_output=dict(), - fa_gradient_output=dict(), - fa_gradmag_output=dict(), - fa_output=dict(), - frobenius_norm_output=dict(), - lambda1_output=dict(), - lambda2_output=dict(), - lambda3_output=dict(), - md_output=dict(), - negative_eigenvector_output=dict(), - outmask=dict(), - principal_eigenvector_output=dict(), - rot_output=dict(), + output_map = dict( + RD_output=dict(), + color_fa_output=dict(), + deformation_output=dict(), + fa_gradient_output=dict(), + fa_gradmag_output=dict(), + fa_output=dict(), + frobenius_norm_output=dict(), + lambda1_output=dict(), + lambda2_output=dict(), + lambda3_output=dict(), + md_output=dict(), + negative_eigenvector_output=dict(), + outmask=dict(), + principal_eigenvector_output=dict(), + rot_output=dict(), ) outputs = dtiprocess.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py index ca4ceaa0fa..8b9a65904f 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py @@ -4,40 +4,37 @@ def test_extractNrrdVectorIndex_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - setImageOrientation=dict(argstr='--setImageOrientation %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - vectorIndex=dict(argstr='--vectorIndex %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + setImageOrientation=dict(argstr='--setImageOrientation %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + vectorIndex=dict(argstr='--vectorIndex %d', ), ) inputs = extractNrrdVectorIndex.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_extractNrrdVectorIndex_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = extractNrrdVectorIndex.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py index 1caaeaac78..dbd4ed60de 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py @@ -4,38 +4,36 @@ def test_gtractAnisotropyMap_inputs(): - input_map = dict(anisotropyType=dict(argstr='--anisotropyType %s', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputTensorVolume=dict(argstr='--inputTensorVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + anisotropyType=dict(argstr='--anisotropyType %s', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputTensorVolume=dict(argstr='--inputTensorVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractAnisotropyMap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractAnisotropyMap_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractAnisotropyMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py index 574119212f..e8656a361f 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py @@ -4,40 +4,37 @@ def test_gtractAverageBvalues_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - averageB0only=dict(argstr='--averageB0only ', - ), - directionsTolerance=dict(argstr='--directionsTolerance %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + averageB0only=dict(argstr='--averageB0only ', ), + directionsTolerance=dict(argstr='--directionsTolerance %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractAverageBvalues.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractAverageBvalues_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractAverageBvalues.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py index e3c4f337b7..1b60024162 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py @@ -4,40 +4,37 @@ def test_gtractClipAnisotropy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - clipFirstSlice=dict(argstr='--clipFirstSlice ', - ), - clipLastSlice=dict(argstr='--clipLastSlice ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + clipFirstSlice=dict(argstr='--clipFirstSlice ', ), + clipLastSlice=dict(argstr='--clipLastSlice ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractClipAnisotropy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractClipAnisotropy_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractClipAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py index a8aab5aedf..da9f4d296b 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py @@ -4,79 +4,59 @@ def test_gtractCoRegAnatomy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - borderSize=dict(argstr='--borderSize %d', - ), - convergence=dict(argstr='--convergence %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gradientTolerance=dict(argstr='--gradientTolerance %f', - ), - gridSize=dict(argstr='--gridSize %s', - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputAnatomicalVolume=dict(argstr='--inputAnatomicalVolume %s', - ), - inputRigidTransform=dict(argstr='--inputRigidTransform %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - maxBSplineDisplacement=dict(argstr='--maxBSplineDisplacement %f', - ), - maximumStepSize=dict(argstr='--maximumStepSize %f', - ), - minimumStepSize=dict(argstr='--minimumStepSize %f', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfIterations=dict(argstr='--numberOfIterations %d', - ), - numberOfSamples=dict(argstr='--numberOfSamples %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputTransformName=dict(argstr='--outputTransformName %s', - hash_files=False, - ), - relaxationFactor=dict(argstr='--relaxationFactor %f', - ), - samplingPercentage=dict(argstr='--samplingPercentage %f', - ), - spatialScale=dict(argstr='--spatialScale %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - ), - translationScale=dict(argstr='--translationScale %f', - ), - useCenterOfHeadAlign=dict(argstr='--useCenterOfHeadAlign ', - ), - useGeometryAlign=dict(argstr='--useGeometryAlign ', - ), - useMomentsAlign=dict(argstr='--useMomentsAlign ', - ), - vectorIndex=dict(argstr='--vectorIndex %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + borderSize=dict(argstr='--borderSize %d', ), + convergence=dict(argstr='--convergence %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradientTolerance=dict(argstr='--gradientTolerance %f', ), + gridSize=dict( + argstr='--gridSize %s', + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputAnatomicalVolume=dict(argstr='--inputAnatomicalVolume %s', ), + inputRigidTransform=dict(argstr='--inputRigidTransform %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + maxBSplineDisplacement=dict(argstr='--maxBSplineDisplacement %f', ), + maximumStepSize=dict(argstr='--maximumStepSize %f', ), + minimumStepSize=dict(argstr='--minimumStepSize %f', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfIterations=dict(argstr='--numberOfIterations %d', ), + numberOfSamples=dict(argstr='--numberOfSamples %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputTransformName=dict( + argstr='--outputTransformName %s', + hash_files=False, + ), + relaxationFactor=dict(argstr='--relaxationFactor %f', ), + samplingPercentage=dict(argstr='--samplingPercentage %f', ), + spatialScale=dict(argstr='--spatialScale %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict(argstr='--transformType %s', ), + translationScale=dict(argstr='--translationScale %f', ), + useCenterOfHeadAlign=dict(argstr='--useCenterOfHeadAlign ', ), + useGeometryAlign=dict(argstr='--useGeometryAlign ', ), + useMomentsAlign=dict(argstr='--useMomentsAlign ', ), + vectorIndex=dict(argstr='--vectorIndex %d', ), ) inputs = gtractCoRegAnatomy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractCoRegAnatomy_outputs(): - output_map = dict(outputTransformName=dict(), - ) + output_map = dict(outputTransformName=dict(), ) outputs = gtractCoRegAnatomy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py index 276952f0f9..34c83788de 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py @@ -4,38 +4,36 @@ def test_gtractConcatDwi_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignoreOrigins=dict(argstr='--ignoreOrigins ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s...', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignoreOrigins=dict(argstr='--ignoreOrigins ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s...', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractConcatDwi.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractConcatDwi_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractConcatDwi.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py index dfb9a73889..84cb1d143f 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py @@ -4,38 +4,36 @@ def test_gtractCopyImageOrientation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractCopyImageOrientation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractCopyImageOrientation_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractCopyImageOrientation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py index c367284ef3..a2b49ed145 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py @@ -4,63 +4,53 @@ def test_gtractCoregBvalues_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debugLevel=dict(argstr='--debugLevel %d', - ), - eddyCurrentCorrection=dict(argstr='--eddyCurrentCorrection ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedVolume=dict(argstr='--fixedVolume %s', - ), - fixedVolumeIndex=dict(argstr='--fixedVolumeIndex %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - maximumStepSize=dict(argstr='--maximumStepSize %f', - ), - minimumStepSize=dict(argstr='--minimumStepSize %f', - ), - movingVolume=dict(argstr='--movingVolume %s', - ), - numberOfIterations=dict(argstr='--numberOfIterations %d', - ), - numberOfSpatialSamples=dict(argstr='--numberOfSpatialSamples %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - registerB0Only=dict(argstr='--registerB0Only ', - ), - relaxationFactor=dict(argstr='--relaxationFactor %f', - ), - samplingPercentage=dict(argstr='--samplingPercentage %f', - ), - spatialScale=dict(argstr='--spatialScale %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debugLevel=dict(argstr='--debugLevel %d', ), + eddyCurrentCorrection=dict(argstr='--eddyCurrentCorrection ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedVolume=dict(argstr='--fixedVolume %s', ), + fixedVolumeIndex=dict(argstr='--fixedVolumeIndex %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + maximumStepSize=dict(argstr='--maximumStepSize %f', ), + minimumStepSize=dict(argstr='--minimumStepSize %f', ), + movingVolume=dict(argstr='--movingVolume %s', ), + numberOfIterations=dict(argstr='--numberOfIterations %d', ), + numberOfSpatialSamples=dict(argstr='--numberOfSpatialSamples %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + registerB0Only=dict(argstr='--registerB0Only ', ), + relaxationFactor=dict(argstr='--relaxationFactor %f', ), + samplingPercentage=dict(argstr='--samplingPercentage %f', ), + spatialScale=dict(argstr='--spatialScale %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractCoregBvalues.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractCoregBvalues_outputs(): - output_map = dict(outputTransform=dict(), - outputVolume=dict(), + output_map = dict( + outputTransform=dict(), + outputVolume=dict(), ) outputs = gtractCoregBvalues.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py index f50f8c47aa..79eb0e35e5 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py @@ -4,51 +4,48 @@ def test_gtractCostFastMarching_inputs(): - input_map = dict(anisotropyWeight=dict(argstr='--anisotropyWeight %f', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', - ), - inputStartingSeedsLabelMapVolume=dict(argstr='--inputStartingSeedsLabelMapVolume %s', - ), - inputTensorVolume=dict(argstr='--inputTensorVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputCostVolume=dict(argstr='--outputCostVolume %s', - hash_files=False, - ), - outputSpeedVolume=dict(argstr='--outputSpeedVolume %s', - hash_files=False, - ), - seedThreshold=dict(argstr='--seedThreshold %f', - ), - startingSeedsLabel=dict(argstr='--startingSeedsLabel %d', - ), - stoppingValue=dict(argstr='--stoppingValue %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + anisotropyWeight=dict(argstr='--anisotropyWeight %f', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', ), + inputStartingSeedsLabelMapVolume=dict( + argstr='--inputStartingSeedsLabelMapVolume %s', ), + inputTensorVolume=dict(argstr='--inputTensorVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputCostVolume=dict( + argstr='--outputCostVolume %s', + hash_files=False, + ), + outputSpeedVolume=dict( + argstr='--outputSpeedVolume %s', + hash_files=False, + ), + seedThreshold=dict(argstr='--seedThreshold %f', ), + startingSeedsLabel=dict(argstr='--startingSeedsLabel %d', ), + stoppingValue=dict(argstr='--stoppingValue %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractCostFastMarching.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractCostFastMarching_outputs(): - output_map = dict(outputCostVolume=dict(), - outputSpeedVolume=dict(), + output_map = dict( + outputCostVolume=dict(), + outputSpeedVolume=dict(), ) outputs = gtractCostFastMarching.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py index bd461a549b..dd4df64d47 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py @@ -4,40 +4,37 @@ def test_gtractCreateGuideFiber_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputFiber=dict(argstr='--inputFiber %s', - ), - numberOfPoints=dict(argstr='--numberOfPoints %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputFiber=dict(argstr='--outputFiber %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputFiber=dict(argstr='--inputFiber %s', ), + numberOfPoints=dict(argstr='--numberOfPoints %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputFiber=dict( + argstr='--outputFiber %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', ), ) inputs = gtractCreateGuideFiber.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractCreateGuideFiber_outputs(): - output_map = dict(outputFiber=dict(), - ) + output_map = dict(outputFiber=dict(), ) outputs = gtractCreateGuideFiber.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py index 0e6676c0fc..384fb5fa32 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py @@ -4,58 +4,47 @@ def test_gtractFastMarchingTracking_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - costStepSize=dict(argstr='--costStepSize %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', - ), - inputCostVolume=dict(argstr='--inputCostVolume %s', - ), - inputStartingSeedsLabelMapVolume=dict(argstr='--inputStartingSeedsLabelMapVolume %s', - ), - inputTensorVolume=dict(argstr='--inputTensorVolume %s', - ), - maximumStepSize=dict(argstr='--maximumStepSize %f', - ), - minimumStepSize=dict(argstr='--minimumStepSize %f', - ), - numberOfIterations=dict(argstr='--numberOfIterations %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputTract=dict(argstr='--outputTract %s', - hash_files=False, - ), - seedThreshold=dict(argstr='--seedThreshold %f', - ), - startingSeedsLabel=dict(argstr='--startingSeedsLabel %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trackingThreshold=dict(argstr='--trackingThreshold %f', - ), - writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', - ), + input_map = dict( + args=dict(argstr='%s', ), + costStepSize=dict(argstr='--costStepSize %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', ), + inputCostVolume=dict(argstr='--inputCostVolume %s', ), + inputStartingSeedsLabelMapVolume=dict( + argstr='--inputStartingSeedsLabelMapVolume %s', ), + inputTensorVolume=dict(argstr='--inputTensorVolume %s', ), + maximumStepSize=dict(argstr='--maximumStepSize %f', ), + minimumStepSize=dict(argstr='--minimumStepSize %f', ), + numberOfIterations=dict(argstr='--numberOfIterations %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputTract=dict( + argstr='--outputTract %s', + hash_files=False, + ), + seedThreshold=dict(argstr='--seedThreshold %f', ), + startingSeedsLabel=dict(argstr='--startingSeedsLabel %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trackingThreshold=dict(argstr='--trackingThreshold %f', ), + writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', ), ) inputs = gtractFastMarchingTracking.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractFastMarchingTracking_outputs(): - output_map = dict(outputTract=dict(), - ) + output_map = dict(outputTract=dict(), ) outputs = gtractFastMarchingTracking.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py index 15b4876080..52edd05bd6 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py @@ -4,86 +4,63 @@ def test_gtractFiberTracking_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - branchingAngle=dict(argstr='--branchingAngle %f', - ), - branchingThreshold=dict(argstr='--branchingThreshold %f', - ), - curvatureThreshold=dict(argstr='--curvatureThreshold %f', - ), - endingSeedsLabel=dict(argstr='--endingSeedsLabel %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - guidedCurvatureThreshold=dict(argstr='--guidedCurvatureThreshold %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', - ), - inputEndingSeedsLabelMapVolume=dict(argstr='--inputEndingSeedsLabelMapVolume %s', - ), - inputStartingSeedsLabelMapVolume=dict(argstr='--inputStartingSeedsLabelMapVolume %s', - ), - inputTensorVolume=dict(argstr='--inputTensorVolume %s', - ), - inputTract=dict(argstr='--inputTract %s', - ), - maximumBranchPoints=dict(argstr='--maximumBranchPoints %d', - ), - maximumGuideDistance=dict(argstr='--maximumGuideDistance %f', - ), - maximumLength=dict(argstr='--maximumLength %f', - ), - minimumLength=dict(argstr='--minimumLength %f', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputTract=dict(argstr='--outputTract %s', - hash_files=False, - ), - randomSeed=dict(argstr='--randomSeed %d', - ), - seedThreshold=dict(argstr='--seedThreshold %f', - ), - startingSeedsLabel=dict(argstr='--startingSeedsLabel %d', - ), - stepSize=dict(argstr='--stepSize %f', - ), - tendF=dict(argstr='--tendF %f', - ), - tendG=dict(argstr='--tendG %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trackingMethod=dict(argstr='--trackingMethod %s', - ), - trackingThreshold=dict(argstr='--trackingThreshold %f', - ), - useLoopDetection=dict(argstr='--useLoopDetection ', - ), - useRandomWalk=dict(argstr='--useRandomWalk ', - ), - useTend=dict(argstr='--useTend ', - ), - writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', - ), + input_map = dict( + args=dict(argstr='%s', ), + branchingAngle=dict(argstr='--branchingAngle %f', ), + branchingThreshold=dict(argstr='--branchingThreshold %f', ), + curvatureThreshold=dict(argstr='--curvatureThreshold %f', ), + endingSeedsLabel=dict(argstr='--endingSeedsLabel %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + guidedCurvatureThreshold=dict( + argstr='--guidedCurvatureThreshold %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', ), + inputEndingSeedsLabelMapVolume=dict( + argstr='--inputEndingSeedsLabelMapVolume %s', ), + inputStartingSeedsLabelMapVolume=dict( + argstr='--inputStartingSeedsLabelMapVolume %s', ), + inputTensorVolume=dict(argstr='--inputTensorVolume %s', ), + inputTract=dict(argstr='--inputTract %s', ), + maximumBranchPoints=dict(argstr='--maximumBranchPoints %d', ), + maximumGuideDistance=dict(argstr='--maximumGuideDistance %f', ), + maximumLength=dict(argstr='--maximumLength %f', ), + minimumLength=dict(argstr='--minimumLength %f', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputTract=dict( + argstr='--outputTract %s', + hash_files=False, + ), + randomSeed=dict(argstr='--randomSeed %d', ), + seedThreshold=dict(argstr='--seedThreshold %f', ), + startingSeedsLabel=dict(argstr='--startingSeedsLabel %d', ), + stepSize=dict(argstr='--stepSize %f', ), + tendF=dict(argstr='--tendF %f', ), + tendG=dict(argstr='--tendG %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trackingMethod=dict(argstr='--trackingMethod %s', ), + trackingThreshold=dict(argstr='--trackingThreshold %f', ), + useLoopDetection=dict(argstr='--useLoopDetection ', ), + useRandomWalk=dict(argstr='--useRandomWalk ', ), + useTend=dict(argstr='--useTend ', ), + writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', ), ) inputs = gtractFiberTracking.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractFiberTracking_outputs(): - output_map = dict(outputTract=dict(), - ) + output_map = dict(outputTract=dict(), ) outputs = gtractFiberTracking.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py index 0ae9c227a8..bd4b6193d1 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py @@ -4,38 +4,36 @@ def test_gtractImageConformity_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractImageConformity.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractImageConformity_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractImageConformity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py index 36363523d0..4a942b2fed 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py @@ -4,41 +4,40 @@ def test_gtractInvertBSplineTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - landmarkDensity=dict(argstr='--landmarkDensity %s', - sep=',', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', ), + inputTransform=dict(argstr='--inputTransform %s', ), + landmarkDensity=dict( + argstr='--landmarkDensity %s', + sep=',', + ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractInvertBSplineTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractInvertBSplineTransform_outputs(): - output_map = dict(outputTransform=dict(), - ) + output_map = dict(outputTransform=dict(), ) outputs = gtractInvertBSplineTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py index 4e7cdebdd3..f3f62ba216 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py @@ -4,40 +4,37 @@ def test_gtractInvertDisplacementField_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - baseImage=dict(argstr='--baseImage %s', - ), - deformationImage=dict(argstr='--deformationImage %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - subsamplingFactor=dict(argstr='--subsamplingFactor %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + baseImage=dict(argstr='--baseImage %s', ), + deformationImage=dict(argstr='--deformationImage %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + subsamplingFactor=dict(argstr='--subsamplingFactor %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractInvertDisplacementField.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractInvertDisplacementField_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractInvertDisplacementField.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py index 8cc8cc1e4b..e3022d47d9 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py @@ -4,36 +4,35 @@ def test_gtractInvertRigidTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputTransform=dict(argstr='--inputTransform %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractInvertRigidTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractInvertRigidTransform_outputs(): - output_map = dict(outputTransform=dict(), - ) + output_map = dict(outputTransform=dict(), ) outputs = gtractInvertRigidTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py index 4cc895fb06..e7ff3d6f49 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py @@ -4,42 +4,38 @@ def test_gtractResampleAnisotropy_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputAnatomicalVolume=dict(argstr='--inputAnatomicalVolume %s', - ), - inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputAnatomicalVolume=dict(argstr='--inputAnatomicalVolume %s', ), + inputAnisotropyVolume=dict(argstr='--inputAnisotropyVolume %s', ), + inputTransform=dict(argstr='--inputTransform %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict(argstr='--transformType %s', ), ) inputs = gtractResampleAnisotropy.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractResampleAnisotropy_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractResampleAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py index c77c067c51..f579fbc08b 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py @@ -4,44 +4,39 @@ def test_gtractResampleB0_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputAnatomicalVolume=dict(argstr='--inputAnatomicalVolume %s', - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - ), - vectorIndex=dict(argstr='--vectorIndex %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputAnatomicalVolume=dict(argstr='--inputAnatomicalVolume %s', ), + inputTransform=dict(argstr='--inputTransform %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict(argstr='--transformType %s', ), + vectorIndex=dict(argstr='--vectorIndex %d', ), ) inputs = gtractResampleB0.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractResampleB0_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractResampleB0.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py index 5fd928f854..a693f89eb4 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py @@ -4,42 +4,38 @@ def test_gtractResampleCodeImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputCodeVolume=dict(argstr='--inputCodeVolume %s', - ), - inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputCodeVolume=dict(argstr='--inputCodeVolume %s', ), + inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', ), + inputTransform=dict(argstr='--inputTransform %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict(argstr='--transformType %s', ), ) inputs = gtractResampleCodeImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractResampleCodeImage_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractResampleCodeImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py index 569320ba6f..6157775575 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py @@ -4,50 +4,49 @@ def test_gtractResampleDWIInPlace_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debugLevel=dict(argstr='--debugLevel %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - imageOutputSize=dict(argstr='--imageOutputSize %s', - sep=',', - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputResampledB0=dict(argstr='--outputResampledB0 %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - referenceVolume=dict(argstr='--referenceVolume %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warpDWITransform=dict(argstr='--warpDWITransform %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + debugLevel=dict(argstr='--debugLevel %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + imageOutputSize=dict( + argstr='--imageOutputSize %s', + sep=',', + ), + inputTransform=dict(argstr='--inputTransform %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputResampledB0=dict( + argstr='--outputResampledB0 %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + referenceVolume=dict(argstr='--referenceVolume %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warpDWITransform=dict(argstr='--warpDWITransform %s', ), ) inputs = gtractResampleDWIInPlace.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractResampleDWIInPlace_outputs(): - output_map = dict(outputResampledB0=dict(), - outputVolume=dict(), + output_map = dict( + outputResampledB0=dict(), + outputVolume=dict(), ) outputs = gtractResampleDWIInPlace.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py index b3c4abc11a..cbdb701706 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py @@ -4,42 +4,40 @@ def test_gtractResampleFibers_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputForwardDeformationFieldVolume=dict(argstr='--inputForwardDeformationFieldVolume %s', - ), - inputReverseDeformationFieldVolume=dict(argstr='--inputReverseDeformationFieldVolume %s', - ), - inputTract=dict(argstr='--inputTract %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputTract=dict(argstr='--outputTract %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputForwardDeformationFieldVolume=dict( + argstr='--inputForwardDeformationFieldVolume %s', ), + inputReverseDeformationFieldVolume=dict( + argstr='--inputReverseDeformationFieldVolume %s', ), + inputTract=dict(argstr='--inputTract %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputTract=dict( + argstr='--outputTract %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + writeXMLPolyDataFile=dict(argstr='--writeXMLPolyDataFile ', ), ) inputs = gtractResampleFibers.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractResampleFibers_outputs(): - output_map = dict(outputTract=dict(), - ) + output_map = dict(outputTract=dict(), ) outputs = gtractResampleFibers.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py index af662c076c..ff5b5efde5 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py @@ -4,56 +4,51 @@ def test_gtractTensor_inputs(): - input_map = dict(applyMeasurementFrame=dict(argstr='--applyMeasurementFrame ', - ), - args=dict(argstr='%s', - ), - b0Index=dict(argstr='--b0Index %d', - ), - backgroundSuppressingThreshold=dict(argstr='--backgroundSuppressingThreshold %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignoreIndex=dict(argstr='--ignoreIndex %s', - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - maskProcessingMode=dict(argstr='--maskProcessingMode %s', - ), - maskVolume=dict(argstr='--maskVolume %s', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - resampleIsotropic=dict(argstr='--resampleIsotropic ', - ), - size=dict(argstr='--size %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + applyMeasurementFrame=dict(argstr='--applyMeasurementFrame ', ), + args=dict(argstr='%s', ), + b0Index=dict(argstr='--b0Index %d', ), + backgroundSuppressingThreshold=dict( + argstr='--backgroundSuppressingThreshold %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignoreIndex=dict( + argstr='--ignoreIndex %s', + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + maskProcessingMode=dict(argstr='--maskProcessingMode %s', ), + maskVolume=dict(argstr='--maskVolume %s', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + resampleIsotropic=dict(argstr='--resampleIsotropic ', ), + size=dict(argstr='--size %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractTensor.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractTensor_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = gtractTensor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py index 8f074267fe..c7888ede29 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py @@ -4,38 +4,36 @@ def test_gtractTransformToDisplacementField_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputDeformationFieldVolume=dict(argstr='--outputDeformationFieldVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', ), + inputTransform=dict(argstr='--inputTransform %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputDeformationFieldVolume=dict( + argstr='--outputDeformationFieldVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = gtractTransformToDisplacementField.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_gtractTransformToDisplacementField_outputs(): - output_map = dict(outputDeformationFieldVolume=dict(), - ) + output_map = dict(outputDeformationFieldVolume=dict(), ) outputs = gtractTransformToDisplacementField.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py index 8efcf5d131..057be11567 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py @@ -4,38 +4,36 @@ def test_maxcurvature_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image=dict(argstr='--image %s', - ), - output=dict(argstr='--output %s', - hash_files=False, - ), - sigma=dict(argstr='--sigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image=dict(argstr='--image %s', ), + output=dict( + argstr='--output %s', + hash_files=False, + ), + sigma=dict(argstr='--sigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), ) inputs = maxcurvature.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_maxcurvature_outputs(): - output_map = dict(output=dict(), - ) + output_map = dict(output=dict(), ) outputs = maxcurvature.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py b/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py index 918fa113d8..19adc2a817 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py +++ b/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py @@ -11,7 +11,8 @@ class fiberstatsInputSpec(CommandLineInputSpec): - fiber_file = File(desc="DTI Fiber File", exists=True, argstr="--fiber_file %s") + fiber_file = File( + desc="DTI Fiber File", exists=True, argstr="--fiber_file %s") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") @@ -20,7 +21,6 @@ class fiberstatsOutputSpec(TraitedSpec): class fiberstats(SEMLikeCommandLine): - """title: FiberStats (DTIProcess) category: Diffusion.Tractography.CommandLineOnly diff --git a/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py b/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py index bc003cebc4..c0e9dcbbaf 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py +++ b/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py @@ -11,30 +11,73 @@ class fiberprocessInputSpec(CommandLineInputSpec): - fiber_file = File(desc="DTI fiber file", exists=True, argstr="--fiber_file %s") - fiber_output = traits.Either(traits.Bool, File(), hash_files=False, desc="Output fiber file. May be warped or updated with new data depending on other options used.", argstr="--fiber_output %s") - tensor_volume = File(desc="Interpolate tensor values from the given field", exists=True, argstr="--tensor_volume %s") - h_field = File(desc="HField for warp and statistics lookup. If this option is used tensor-volume must also be specified.", exists=True, argstr="--h_field %s") - displacement_field = File(desc="Displacement Field for warp and statistics lookup. If this option is used tensor-volume must also be specified.", exists=True, argstr="--displacement_field %s") - saveProperties = traits.Bool(desc="save the tensor property as scalar data into the vtk (only works for vtk fiber files). ", argstr="--saveProperties ") - no_warp = traits.Bool(desc="Do not warp the geometry of the tensors only obtain the new statistics.", argstr="--no_warp ") - fiber_radius = traits.Float(desc="set radius of all fibers to this value", argstr="--fiber_radius %f") - index_space = traits.Bool(desc="Use index-space for fiber output coordinates, otherwise us world space for fiber output coordinates (from tensor file).", argstr="--index_space ") - voxelize = traits.Either(traits.Bool, File(), hash_files=False, - desc="Voxelize fiber into a label map (the labelmap filename is the argument of -V). The tensor file must be specified using -T for information about the size, origin, spacing of the image. The deformation is applied before the voxelization ", argstr="--voxelize %s") - voxelize_count_fibers = traits.Bool(desc="Count number of fibers per-voxel instead of just setting to 1", argstr="--voxelize_count_fibers ") - voxel_label = traits.Int(desc="Label for voxelized fiber", argstr="--voxel_label %d") + fiber_file = File( + desc="DTI fiber file", exists=True, argstr="--fiber_file %s") + fiber_output = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output fiber file. May be warped or updated with new data depending on other options used.", + argstr="--fiber_output %s") + tensor_volume = File( + desc="Interpolate tensor values from the given field", + exists=True, + argstr="--tensor_volume %s") + h_field = File( + desc= + "HField for warp and statistics lookup. If this option is used tensor-volume must also be specified.", + exists=True, + argstr="--h_field %s") + displacement_field = File( + desc= + "Displacement Field for warp and statistics lookup. If this option is used tensor-volume must also be specified.", + exists=True, + argstr="--displacement_field %s") + saveProperties = traits.Bool( + desc= + "save the tensor property as scalar data into the vtk (only works for vtk fiber files). ", + argstr="--saveProperties ") + no_warp = traits.Bool( + desc= + "Do not warp the geometry of the tensors only obtain the new statistics.", + argstr="--no_warp ") + fiber_radius = traits.Float( + desc="set radius of all fibers to this value", + argstr="--fiber_radius %f") + index_space = traits.Bool( + desc= + "Use index-space for fiber output coordinates, otherwise us world space for fiber output coordinates (from tensor file).", + argstr="--index_space ") + voxelize = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Voxelize fiber into a label map (the labelmap filename is the argument of -V). The tensor file must be specified using -T for information about the size, origin, spacing of the image. The deformation is applied before the voxelization ", + argstr="--voxelize %s") + voxelize_count_fibers = traits.Bool( + desc="Count number of fibers per-voxel instead of just setting to 1", + argstr="--voxelize_count_fibers ") + voxel_label = traits.Int( + desc="Label for voxelized fiber", argstr="--voxel_label %d") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") - noDataChange = traits.Bool(desc="Do not change data ??? ", argstr="--noDataChange ") + noDataChange = traits.Bool( + desc="Do not change data ??? ", argstr="--noDataChange ") class fiberprocessOutputSpec(TraitedSpec): - fiber_output = File(desc="Output fiber file. May be warped or updated with new data depending on other options used.", exists=True) - voxelize = File(desc="Voxelize fiber into a label map (the labelmap filename is the argument of -V). The tensor file must be specified using -T for information about the size, origin, spacing of the image. The deformation is applied before the voxelization ", exists=True) + fiber_output = File( + desc= + "Output fiber file. May be warped or updated with new data depending on other options used.", + exists=True) + voxelize = File( + desc= + "Voxelize fiber into a label map (the labelmap filename is the argument of -V). The tensor file must be specified using -T for information about the size, origin, spacing of the image. The deformation is applied before the voxelization ", + exists=True) class fiberprocess(SEMLikeCommandLine): - """title: FiberProcess (DTIProcess) category: Diffusion.Tractography @@ -60,5 +103,8 @@ class fiberprocess(SEMLikeCommandLine): input_spec = fiberprocessInputSpec output_spec = fiberprocessOutputSpec _cmd = " fiberprocess " - _outputs_filenames = {'fiber_output': 'fiber_output.vtk', 'voxelize': 'voxelize.nii'} + _outputs_filenames = { + 'fiber_output': 'fiber_output.vtk', + 'voxelize': 'voxelize.nii' + } _redirect_x = False diff --git a/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py b/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py index fb8532f87e..498cb2579d 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py +++ b/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py @@ -11,27 +11,57 @@ class fibertrackInputSpec(CommandLineInputSpec): - input_tensor_file = File(desc="Tensor Image", exists=True, argstr="--input_tensor_file %s") - input_roi_file = File(desc="The filename of the image which contains the labels used for seeding and constraining the algorithm.", exists=True, argstr="--input_roi_file %s") - output_fiber_file = traits.Either(traits.Bool, File(), hash_files=False, desc="The filename for the fiber file produced by the algorithm. This file must end in a .fib or .vtk extension for ITK spatial object and vtkPolyData formats respectively.", argstr="--output_fiber_file %s") - source_label = traits.Int(desc="The label of voxels in the labelfile to use for seeding tractography. One tract is seeded from the center of each voxel with this label", argstr="--source_label %d") - target_label = traits.Int(desc="The label of voxels in the labelfile used to constrain tractography. Tracts that do not pass through a voxel with this label are rejected. Set this keep all tracts.", argstr="--target_label %d") - forbidden_label = traits.Int(desc="Forbidden label", argstr="--forbidden_label %d") - whole_brain = traits.Bool(desc="If this option is enabled all voxels in the image are used to seed tractography. When this option is enabled both source and target labels function as target labels", argstr="--whole_brain ") - max_angle = traits.Float(desc="Maximum angle of change in radians", argstr="--max_angle %f") - step_size = traits.Float(desc="Step size in mm for the tracking algorithm", argstr="--step_size %f") - min_fa = traits.Float(desc="The minimum FA threshold to continue tractography", argstr="--min_fa %f") + input_tensor_file = File( + desc="Tensor Image", exists=True, argstr="--input_tensor_file %s") + input_roi_file = File( + desc= + "The filename of the image which contains the labels used for seeding and constraining the algorithm.", + exists=True, + argstr="--input_roi_file %s") + output_fiber_file = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The filename for the fiber file produced by the algorithm. This file must end in a .fib or .vtk extension for ITK spatial object and vtkPolyData formats respectively.", + argstr="--output_fiber_file %s") + source_label = traits.Int( + desc= + "The label of voxels in the labelfile to use for seeding tractography. One tract is seeded from the center of each voxel with this label", + argstr="--source_label %d") + target_label = traits.Int( + desc= + "The label of voxels in the labelfile used to constrain tractography. Tracts that do not pass through a voxel with this label are rejected. Set this keep all tracts.", + argstr="--target_label %d") + forbidden_label = traits.Int( + desc="Forbidden label", argstr="--forbidden_label %d") + whole_brain = traits.Bool( + desc= + "If this option is enabled all voxels in the image are used to seed tractography. When this option is enabled both source and target labels function as target labels", + argstr="--whole_brain ") + max_angle = traits.Float( + desc="Maximum angle of change in radians", argstr="--max_angle %f") + step_size = traits.Float( + desc="Step size in mm for the tracking algorithm", + argstr="--step_size %f") + min_fa = traits.Float( + desc="The minimum FA threshold to continue tractography", + argstr="--min_fa %f") force = traits.Bool(desc="Ignore sanity checks.", argstr="--force ") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") - really_verbose = traits.Bool(desc="Follow detail of fiber tracking algorithm", argstr="--really_verbose ") + really_verbose = traits.Bool( + desc="Follow detail of fiber tracking algorithm", + argstr="--really_verbose ") class fibertrackOutputSpec(TraitedSpec): - output_fiber_file = File(desc="The filename for the fiber file produced by the algorithm. This file must end in a .fib or .vtk extension for ITK spatial object and vtkPolyData formats respectively.", exists=True) + output_fiber_file = File( + desc= + "The filename for the fiber file produced by the algorithm. This file must end in a .fib or .vtk extension for ITK spatial object and vtkPolyData formats respectively.", + exists=True) class fibertrack(SEMLikeCommandLine): - """title: FiberTrack (DTIProcess) category: Diffusion.Tractography diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py index 0342389ba4..5592e86a09 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py @@ -4,98 +4,73 @@ def test_UKFTractography_inputs(): - input_map = dict(Ql=dict(argstr='--Ql %f', - ), - Qm=dict(argstr='--Qm %f', - ), - Qw=dict(argstr='--Qw %f', - ), - Rs=dict(argstr='--Rs %f', - ), - args=dict(argstr='%s', - ), - dwiFile=dict(argstr='--dwiFile %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - freeWater=dict(argstr='--freeWater ', - ), - fullTensorModel=dict(argstr='--fullTensorModel ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - labels=dict(argstr='--labels %s', - sep=',', - ), - maskFile=dict(argstr='--maskFile %s', - ), - maxBranchingAngle=dict(argstr='--maxBranchingAngle %f', - ), - maxHalfFiberLength=dict(argstr='--maxHalfFiberLength %f', - ), - minBranchingAngle=dict(argstr='--minBranchingAngle %f', - ), - minFA=dict(argstr='--minFA %f', - ), - minGA=dict(argstr='--minGA %f', - ), - numTensor=dict(argstr='--numTensor %s', - ), - numThreads=dict(argstr='--numThreads %d', - ), - recordCovariance=dict(argstr='--recordCovariance ', - ), - recordFA=dict(argstr='--recordFA ', - ), - recordFreeWater=dict(argstr='--recordFreeWater ', - ), - recordLength=dict(argstr='--recordLength %f', - ), - recordNMSE=dict(argstr='--recordNMSE ', - ), - recordState=dict(argstr='--recordState ', - ), - recordTensors=dict(argstr='--recordTensors ', - ), - recordTrace=dict(argstr='--recordTrace ', - ), - seedFALimit=dict(argstr='--seedFALimit %f', - ), - seedsFile=dict(argstr='--seedsFile %s', - ), - seedsPerVoxel=dict(argstr='--seedsPerVoxel %d', - ), - stepLength=dict(argstr='--stepLength %f', - ), - storeGlyphs=dict(argstr='--storeGlyphs ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tracts=dict(argstr='--tracts %s', - hash_files=False, - ), - tractsWithSecondTensor=dict(argstr='--tractsWithSecondTensor %s', - hash_files=False, - ), - writeAsciiTracts=dict(argstr='--writeAsciiTracts ', - ), - writeUncompressedTracts=dict(argstr='--writeUncompressedTracts ', - ), + input_map = dict( + Ql=dict(argstr='--Ql %f', ), + Qm=dict(argstr='--Qm %f', ), + Qw=dict(argstr='--Qw %f', ), + Rs=dict(argstr='--Rs %f', ), + args=dict(argstr='%s', ), + dwiFile=dict(argstr='--dwiFile %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + freeWater=dict(argstr='--freeWater ', ), + fullTensorModel=dict(argstr='--fullTensorModel ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + labels=dict( + argstr='--labels %s', + sep=',', + ), + maskFile=dict(argstr='--maskFile %s', ), + maxBranchingAngle=dict(argstr='--maxBranchingAngle %f', ), + maxHalfFiberLength=dict(argstr='--maxHalfFiberLength %f', ), + minBranchingAngle=dict(argstr='--minBranchingAngle %f', ), + minFA=dict(argstr='--minFA %f', ), + minGA=dict(argstr='--minGA %f', ), + numTensor=dict(argstr='--numTensor %s', ), + numThreads=dict(argstr='--numThreads %d', ), + recordCovariance=dict(argstr='--recordCovariance ', ), + recordFA=dict(argstr='--recordFA ', ), + recordFreeWater=dict(argstr='--recordFreeWater ', ), + recordLength=dict(argstr='--recordLength %f', ), + recordNMSE=dict(argstr='--recordNMSE ', ), + recordState=dict(argstr='--recordState ', ), + recordTensors=dict(argstr='--recordTensors ', ), + recordTrace=dict(argstr='--recordTrace ', ), + seedFALimit=dict(argstr='--seedFALimit %f', ), + seedsFile=dict(argstr='--seedsFile %s', ), + seedsPerVoxel=dict(argstr='--seedsPerVoxel %d', ), + stepLength=dict(argstr='--stepLength %f', ), + storeGlyphs=dict(argstr='--storeGlyphs ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tracts=dict( + argstr='--tracts %s', + hash_files=False, + ), + tractsWithSecondTensor=dict( + argstr='--tractsWithSecondTensor %s', + hash_files=False, + ), + writeAsciiTracts=dict(argstr='--writeAsciiTracts ', ), + writeUncompressedTracts=dict(argstr='--writeUncompressedTracts ', ), ) inputs = UKFTractography.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_UKFTractography_outputs(): - output_map = dict(tracts=dict(), - tractsWithSecondTensor=dict(), + output_map = dict( + tracts=dict(), + tractsWithSecondTensor=dict(), ) outputs = UKFTractography.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py index 8da03c52fc..b61399fbdd 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py @@ -4,59 +4,51 @@ def test_fiberprocess_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - displacement_field=dict(argstr='--displacement_field %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fiber_file=dict(argstr='--fiber_file %s', - ), - fiber_output=dict(argstr='--fiber_output %s', - hash_files=False, - ), - fiber_radius=dict(argstr='--fiber_radius %f', - ), - h_field=dict(argstr='--h_field %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - index_space=dict(argstr='--index_space ', - ), - noDataChange=dict(argstr='--noDataChange ', - ), - no_warp=dict(argstr='--no_warp ', - ), - saveProperties=dict(argstr='--saveProperties ', - ), - tensor_volume=dict(argstr='--tensor_volume %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), - voxel_label=dict(argstr='--voxel_label %d', - ), - voxelize=dict(argstr='--voxelize %s', - hash_files=False, - ), - voxelize_count_fibers=dict(argstr='--voxelize_count_fibers ', - ), + input_map = dict( + args=dict(argstr='%s', ), + displacement_field=dict(argstr='--displacement_field %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fiber_file=dict(argstr='--fiber_file %s', ), + fiber_output=dict( + argstr='--fiber_output %s', + hash_files=False, + ), + fiber_radius=dict(argstr='--fiber_radius %f', ), + h_field=dict(argstr='--h_field %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + index_space=dict(argstr='--index_space ', ), + noDataChange=dict(argstr='--noDataChange ', ), + no_warp=dict(argstr='--no_warp ', ), + saveProperties=dict(argstr='--saveProperties ', ), + tensor_volume=dict(argstr='--tensor_volume %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), + voxel_label=dict(argstr='--voxel_label %d', ), + voxelize=dict( + argstr='--voxelize %s', + hash_files=False, + ), + voxelize_count_fibers=dict(argstr='--voxelize_count_fibers ', ), ) inputs = fiberprocess.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_fiberprocess_outputs(): - output_map = dict(fiber_output=dict(), - voxelize=dict(), + output_map = dict( + fiber_output=dict(), + voxelize=dict(), ) outputs = fiberprocess.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py index 4d241dc205..dd0cd348e4 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py @@ -4,30 +4,29 @@ def test_fiberstats_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fiber_file=dict(argstr='--fiber_file %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fiber_file=dict(argstr='--fiber_file %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), ) inputs = fiberstats.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_fiberstats_outputs(): output_map = dict() outputs = fiberstats.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py index b1a503a711..83b5d20b68 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py @@ -4,56 +4,45 @@ def test_fibertrack_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - forbidden_label=dict(argstr='--forbidden_label %d', - ), - force=dict(argstr='--force ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_roi_file=dict(argstr='--input_roi_file %s', - ), - input_tensor_file=dict(argstr='--input_tensor_file %s', - ), - max_angle=dict(argstr='--max_angle %f', - ), - min_fa=dict(argstr='--min_fa %f', - ), - output_fiber_file=dict(argstr='--output_fiber_file %s', - hash_files=False, - ), - really_verbose=dict(argstr='--really_verbose ', - ), - source_label=dict(argstr='--source_label %d', - ), - step_size=dict(argstr='--step_size %f', - ), - target_label=dict(argstr='--target_label %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), - whole_brain=dict(argstr='--whole_brain ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + forbidden_label=dict(argstr='--forbidden_label %d', ), + force=dict(argstr='--force ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_roi_file=dict(argstr='--input_roi_file %s', ), + input_tensor_file=dict(argstr='--input_tensor_file %s', ), + max_angle=dict(argstr='--max_angle %f', ), + min_fa=dict(argstr='--min_fa %f', ), + output_fiber_file=dict( + argstr='--output_fiber_file %s', + hash_files=False, + ), + really_verbose=dict(argstr='--really_verbose ', ), + source_label=dict(argstr='--source_label %d', ), + step_size=dict(argstr='--step_size %f', ), + target_label=dict(argstr='--target_label %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), + whole_brain=dict(argstr='--whole_brain ', ), ) inputs = fibertrack.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_fibertrack_outputs(): - output_map = dict(output_fiber_file=dict(), - ) + output_map = dict(output_fiber_file=dict(), ) outputs = fibertrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py b/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py index dd29991b97..11971dbb6d 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py +++ b/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py @@ -12,48 +12,135 @@ class UKFTractographyInputSpec(CommandLineInputSpec): dwiFile = File(desc="Input DWI volume", exists=True, argstr="--dwiFile %s") - seedsFile = File(desc="Seeds for diffusion. If not specified, full brain tractography will be performed, and the algorithm will start from every voxel in the brain mask where the Generalized Anisotropy is bigger than 0.18", exists=True, argstr="--seedsFile %s") - labels = InputMultiPath(traits.Int, desc="A vector of the ROI labels to be used", sep=",", argstr="--labels %s") - maskFile = File(desc="Mask for diffusion tractography", exists=True, argstr="--maskFile %s") - tracts = traits.Either(traits.Bool, File(), hash_files=False, desc="Tracts generated, with first tensor output", argstr="--tracts %s") - writeAsciiTracts = traits.Bool(desc="Write tract file as a VTK binary data file", argstr="--writeAsciiTracts ") - writeUncompressedTracts = traits.Bool(desc="Write tract file as a VTK uncompressed data file", argstr="--writeUncompressedTracts ") - seedsPerVoxel = traits.Int(desc=" Each seed generates a fiber, thus using more seeds generates more fibers. In general use 1 or 2 seeds, and for a more thorough result use 5 or 10 (depending on your machine this may take up to 2 days to run)., ", argstr="--seedsPerVoxel %d") - numTensor = traits.Enum("1", "2", desc="Number of tensors used", argstr="--numTensor %s") - freeWater = traits.Bool(desc="Adds a term for free water difusion to the model. (Note for experts: if checked, the 1T simple model is forced) ", argstr="--freeWater ") - recordFA = traits.Bool(desc="Whether to store FA. Attaches field 'FA', and 'FA2' for 2-tensor case to fiber. ", argstr="--recordFA ") - recordFreeWater = traits.Bool(desc="Whether to store the fraction of free water. Attaches field 'FreeWater' to fiber.", argstr="--recordFreeWater ") - recordTrace = traits.Bool(desc="Whether to store Trace. Attaches field 'Trace', and 'Trace2' for 2-tensor case to fiber.", argstr="--recordTrace ") - recordTensors = traits.Bool(desc="Recording the tensors enables Slicer to color the fiber bundles by FA, orientation, and so on. The fields will be called 'TensorN', where N is the tensor number. ", argstr="--recordTensors ") - recordNMSE = traits.Bool(desc="Whether to store NMSE. Attaches field 'NMSE' to fiber. ", argstr="--recordNMSE ") - recordState = traits.Bool(desc="Whether to attach the states to the fiber. Will generate field 'state'.", argstr="--recordState ") - recordCovariance = traits.Bool(desc="Whether to store the covariance. Will generate field 'covariance' in fiber.", argstr="--recordCovariance ") - recordLength = traits.Float(desc="Record length of tractography, in millimeters", argstr="--recordLength %f") - minFA = traits.Float(desc="Abort the tractography when the Fractional Anisotropy is less than this value", argstr="--minFA %f") - minGA = traits.Float(desc="Abort the tractography when the Generalized Anisotropy is less than this value", argstr="--minGA %f") - fullTensorModel = traits.Bool(desc="Whether to use the full tensor model. If unchecked, use the default simple tensor model", argstr="--fullTensorModel ") - numThreads = traits.Int(desc="Number of threads used during computation. Set to the number of cores on your workstation for optimal speed. If left undefined the number of cores detected will be used. ", argstr="--numThreads %d") - stepLength = traits.Float(desc="Step length of tractography, in millimeters", argstr="--stepLength %f") - maxHalfFiberLength = traits.Float(desc="The max length limit of the half fibers generated during tractography. Here the fiber is \'half\' because the tractography goes in only one direction from one seed point at a time", argstr="--maxHalfFiberLength %f") - seedFALimit = traits.Float(desc="Seed points whose FA are below this value are excluded", argstr="--seedFALimit %f") - Qm = traits.Float(desc="Process noise for angles/direction", argstr="--Qm %f") + seedsFile = File( + desc= + "Seeds for diffusion. If not specified, full brain tractography will be performed, and the algorithm will start from every voxel in the brain mask where the Generalized Anisotropy is bigger than 0.18", + exists=True, + argstr="--seedsFile %s") + labels = InputMultiPath( + traits.Int, + desc="A vector of the ROI labels to be used", + sep=",", + argstr="--labels %s") + maskFile = File( + desc="Mask for diffusion tractography", + exists=True, + argstr="--maskFile %s") + tracts = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Tracts generated, with first tensor output", + argstr="--tracts %s") + writeAsciiTracts = traits.Bool( + desc="Write tract file as a VTK binary data file", + argstr="--writeAsciiTracts ") + writeUncompressedTracts = traits.Bool( + desc="Write tract file as a VTK uncompressed data file", + argstr="--writeUncompressedTracts ") + seedsPerVoxel = traits.Int( + desc= + " Each seed generates a fiber, thus using more seeds generates more fibers. In general use 1 or 2 seeds, and for a more thorough result use 5 or 10 (depending on your machine this may take up to 2 days to run)., ", + argstr="--seedsPerVoxel %d") + numTensor = traits.Enum( + "1", "2", desc="Number of tensors used", argstr="--numTensor %s") + freeWater = traits.Bool( + desc= + "Adds a term for free water difusion to the model. (Note for experts: if checked, the 1T simple model is forced) ", + argstr="--freeWater ") + recordFA = traits.Bool( + desc= + "Whether to store FA. Attaches field 'FA', and 'FA2' for 2-tensor case to fiber. ", + argstr="--recordFA ") + recordFreeWater = traits.Bool( + desc= + "Whether to store the fraction of free water. Attaches field 'FreeWater' to fiber.", + argstr="--recordFreeWater ") + recordTrace = traits.Bool( + desc= + "Whether to store Trace. Attaches field 'Trace', and 'Trace2' for 2-tensor case to fiber.", + argstr="--recordTrace ") + recordTensors = traits.Bool( + desc= + "Recording the tensors enables Slicer to color the fiber bundles by FA, orientation, and so on. The fields will be called 'TensorN', where N is the tensor number. ", + argstr="--recordTensors ") + recordNMSE = traits.Bool( + desc="Whether to store NMSE. Attaches field 'NMSE' to fiber. ", + argstr="--recordNMSE ") + recordState = traits.Bool( + desc= + "Whether to attach the states to the fiber. Will generate field 'state'.", + argstr="--recordState ") + recordCovariance = traits.Bool( + desc= + "Whether to store the covariance. Will generate field 'covariance' in fiber.", + argstr="--recordCovariance ") + recordLength = traits.Float( + desc="Record length of tractography, in millimeters", + argstr="--recordLength %f") + minFA = traits.Float( + desc= + "Abort the tractography when the Fractional Anisotropy is less than this value", + argstr="--minFA %f") + minGA = traits.Float( + desc= + "Abort the tractography when the Generalized Anisotropy is less than this value", + argstr="--minGA %f") + fullTensorModel = traits.Bool( + desc= + "Whether to use the full tensor model. If unchecked, use the default simple tensor model", + argstr="--fullTensorModel ") + numThreads = traits.Int( + desc= + "Number of threads used during computation. Set to the number of cores on your workstation for optimal speed. If left undefined the number of cores detected will be used. ", + argstr="--numThreads %d") + stepLength = traits.Float( + desc="Step length of tractography, in millimeters", + argstr="--stepLength %f") + maxHalfFiberLength = traits.Float( + desc= + "The max length limit of the half fibers generated during tractography. Here the fiber is \'half\' because the tractography goes in only one direction from one seed point at a time", + argstr="--maxHalfFiberLength %f") + seedFALimit = traits.Float( + desc="Seed points whose FA are below this value are excluded", + argstr="--seedFALimit %f") + Qm = traits.Float( + desc="Process noise for angles/direction", argstr="--Qm %f") Ql = traits.Float(desc="Process noise for eigenvalues", argstr="--Ql %f") - Qw = traits.Float(desc="Process noise for free water weights, ignored if no free water estimation", argstr="--Qw %f") + Qw = traits.Float( + desc= + "Process noise for free water weights, ignored if no free water estimation", + argstr="--Qw %f") Rs = traits.Float(desc="Measurement noise", argstr="--Rs %f") maxBranchingAngle = traits.Float( - desc="Maximum branching angle, in degrees. When using multiple tensors, a new branch will be created when the tensors' major directions form an angle between (minBranchingAngle, maxBranchingAngle). Branching is supressed when this maxBranchingAngle is set to 0.0", argstr="--maxBranchingAngle %f") - minBranchingAngle = traits.Float(desc="Minimum branching angle, in degrees. When using multiple tensors, a new branch will be created when the tensors' major directions form an angle between (minBranchingAngle, maxBranchingAngle)", argstr="--minBranchingAngle %f") - tractsWithSecondTensor = traits.Either(traits.Bool, File(), hash_files=False, desc="Tracts generated, with second tensor output (if there is one)", argstr="--tractsWithSecondTensor %s") - storeGlyphs = traits.Bool(desc="Store tensors' main directions as two-point lines in a separate file named glyphs_{tracts}. When using multiple tensors, only the major tensors' main directions are stored", argstr="--storeGlyphs ") + desc= + "Maximum branching angle, in degrees. When using multiple tensors, a new branch will be created when the tensors' major directions form an angle between (minBranchingAngle, maxBranchingAngle). Branching is supressed when this maxBranchingAngle is set to 0.0", + argstr="--maxBranchingAngle %f") + minBranchingAngle = traits.Float( + desc= + "Minimum branching angle, in degrees. When using multiple tensors, a new branch will be created when the tensors' major directions form an angle between (minBranchingAngle, maxBranchingAngle)", + argstr="--minBranchingAngle %f") + tractsWithSecondTensor = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Tracts generated, with second tensor output (if there is one)", + argstr="--tractsWithSecondTensor %s") + storeGlyphs = traits.Bool( + desc= + "Store tensors' main directions as two-point lines in a separate file named glyphs_{tracts}. When using multiple tensors, only the major tensors' main directions are stored", + argstr="--storeGlyphs ") class UKFTractographyOutputSpec(TraitedSpec): - tracts = File(desc="Tracts generated, with first tensor output", exists=True) - tractsWithSecondTensor = File(desc="Tracts generated, with second tensor output (if there is one)", exists=True) + tracts = File( + desc="Tracts generated, with first tensor output", exists=True) + tractsWithSecondTensor = File( + desc="Tracts generated, with second tensor output (if there is one)", + exists=True) class UKFTractography(SEMLikeCommandLine): - """title: UKF Tractography category: Diffusion.Tractography @@ -73,5 +160,8 @@ class UKFTractography(SEMLikeCommandLine): input_spec = UKFTractographyInputSpec output_spec = UKFTractographyOutputSpec _cmd = " UKFTractography " - _outputs_filenames = {'tracts': 'tracts.vtp', 'tractsWithSecondTensor': 'tractsWithSecondTensor.vtp'} + _outputs_filenames = { + 'tracts': 'tracts.vtp', + 'tractsWithSecondTensor': 'tractsWithSecondTensor.vtp' + } _redirect_x = False diff --git a/nipype/interfaces/semtools/featurecreator.py b/nipype/interfaces/semtools/featurecreator.py index d194e2b9c1..69ff2d675c 100644 --- a/nipype/interfaces/semtools/featurecreator.py +++ b/nipype/interfaces/semtools/featurecreator.py @@ -11,8 +11,16 @@ class GenerateCsfClippedFromClassifiedImageInputSpec(CommandLineInputSpec): - inputCassifiedVolume = File(desc="Required: input tissue label image", exists=True, argstr="--inputCassifiedVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputCassifiedVolume = File( + desc="Required: input tissue label image", + exists=True, + argstr="--inputCassifiedVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class GenerateCsfClippedFromClassifiedImageOutputSpec(TraitedSpec): @@ -20,7 +28,6 @@ class GenerateCsfClippedFromClassifiedImageOutputSpec(TraitedSpec): class GenerateCsfClippedFromClassifiedImage(SEMLikeCommandLine): - """title: GenerateCsfClippedFromClassifiedImage category: FeatureCreator diff --git a/nipype/interfaces/semtools/filtering/__init__.py b/nipype/interfaces/semtools/filtering/__init__.py index ac69328f10..1e69233303 100644 --- a/nipype/interfaces/semtools/filtering/__init__.py +++ b/nipype/interfaces/semtools/filtering/__init__.py @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import from .denoising import UnbiasedNonLocalMeans -from .featuredetection import GenerateSummedGradientImage, CannySegmentationLevelSetImageFilter, DilateImage, TextureFromNoiseImageFilter, FlippedDifference, ErodeImage, GenerateBrainClippedImage, NeighborhoodMedian, GenerateTestImage, NeighborhoodMean, HammerAttributeCreator, TextureMeasureFilter, DilateMask, DumpBinaryTrainingVectors, DistanceMaps, STAPLEAnalysis, GradientAnisotropicDiffusionImageFilter, CannyEdge +from .featuredetection import ( + GenerateSummedGradientImage, CannySegmentationLevelSetImageFilter, + DilateImage, TextureFromNoiseImageFilter, FlippedDifference, ErodeImage, + GenerateBrainClippedImage, NeighborhoodMedian, GenerateTestImage, + NeighborhoodMean, HammerAttributeCreator, TextureMeasureFilter, DilateMask, + DumpBinaryTrainingVectors, DistanceMaps, STAPLEAnalysis, + GradientAnisotropicDiffusionImageFilter, CannyEdge) diff --git a/nipype/interfaces/semtools/filtering/denoising.py b/nipype/interfaces/semtools/filtering/denoising.py index f98663df78..97d687c512 100644 --- a/nipype/interfaces/semtools/filtering/denoising.py +++ b/nipype/interfaces/semtools/filtering/denoising.py @@ -11,21 +11,47 @@ class UnbiasedNonLocalMeansInputSpec(CommandLineInputSpec): - sigma = traits.Float(desc="The root power of noise (sigma) in the complex Gaussian process the Rician comes from. If it is underestimated, the algorithm fails to remove the noise. If it is overestimated, over-blurring is likely to occur.", argstr="--sigma %f") - rs = InputMultiPath(traits.Int, desc="The algorithm search for similar voxels in a neighborhood of this radius (radii larger than 5,5,5 are very slow, and the results can be only marginally better. Small radii may fail to effectively remove the noise).", sep=",", argstr="--rs %s") - rc = InputMultiPath(traits.Int, desc="Similarity between blocks is computed as the difference between mean values and gradients. These parameters are computed fitting a hyperplane with LS inside a neighborhood of this size", sep=",", argstr="--rc %s") - hp = traits.Float(desc="This parameter is related to noise; the larger the parameter, the more aggressive the filtering. Should be near 1, and only values between 0.8 and 1.2 are allowed", argstr="--hp %f") - ps = traits.Float(desc="To accelerate computations, preselection is used: if the normalized difference is above this threshold, the voxel will be discarded (non used for average)", argstr="--ps %f") - inputVolume = File(position=-2, desc="Input MRI volume.", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output (filtered) MRI volume.", argstr="%s") + sigma = traits.Float( + desc= + "The root power of noise (sigma) in the complex Gaussian process the Rician comes from. If it is underestimated, the algorithm fails to remove the noise. If it is overestimated, over-blurring is likely to occur.", + argstr="--sigma %f") + rs = InputMultiPath( + traits.Int, + desc= + "The algorithm search for similar voxels in a neighborhood of this radius (radii larger than 5,5,5 are very slow, and the results can be only marginally better. Small radii may fail to effectively remove the noise).", + sep=",", + argstr="--rs %s") + rc = InputMultiPath( + traits.Int, + desc= + "Similarity between blocks is computed as the difference between mean values and gradients. These parameters are computed fitting a hyperplane with LS inside a neighborhood of this size", + sep=",", + argstr="--rc %s") + hp = traits.Float( + desc= + "This parameter is related to noise; the larger the parameter, the more aggressive the filtering. Should be near 1, and only values between 0.8 and 1.2 are allowed", + argstr="--hp %f") + ps = traits.Float( + desc= + "To accelerate computations, preselection is used: if the normalized difference is above this threshold, the voxel will be discarded (non used for average)", + argstr="--ps %f") + inputVolume = File( + position=-2, desc="Input MRI volume.", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output (filtered) MRI volume.", + argstr="%s") class UnbiasedNonLocalMeansOutputSpec(TraitedSpec): - outputVolume = File(position=-1, desc="Output (filtered) MRI volume.", exists=True) + outputVolume = File( + position=-1, desc="Output (filtered) MRI volume.", exists=True) class UnbiasedNonLocalMeans(SEMLikeCommandLine): - """title: Unbiased NLM for MRI category: Filtering.Denoising diff --git a/nipype/interfaces/semtools/filtering/featuredetection.py b/nipype/interfaces/semtools/filtering/featuredetection.py index 99c78d3993..ca4973ab43 100644 --- a/nipype/interfaces/semtools/filtering/featuredetection.py +++ b/nipype/interfaces/semtools/filtering/featuredetection.py @@ -11,11 +11,27 @@ class GenerateSummedGradientImageInputSpec(CommandLineInputSpec): - inputVolume1 = File(desc="input volume 1, usally t1 image", exists=True, argstr="--inputVolume1 %s") - inputVolume2 = File(desc="input volume 2, usally t2 image", exists=True, argstr="--inputVolume2 %s") - outputFileName = traits.Either(traits.Bool, File(), hash_files=False, desc="(required) output file name", argstr="--outputFileName %s") - MaximumGradient = traits.Bool(desc="If set this flag, it will compute maximum gradient between two input volumes instead of sum of it.", argstr="--MaximumGradient ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume1 = File( + desc="input volume 1, usally t1 image", + exists=True, + argstr="--inputVolume1 %s") + inputVolume2 = File( + desc="input volume 2, usally t2 image", + exists=True, + argstr="--inputVolume2 %s") + outputFileName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="(required) output file name", + argstr="--outputFileName %s") + MaximumGradient = traits.Bool( + desc= + "If set this flag, it will compute maximum gradient between two input volumes instead of sum of it.", + argstr="--MaximumGradient ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class GenerateSummedGradientImageOutputSpec(TraitedSpec): @@ -23,7 +39,6 @@ class GenerateSummedGradientImageOutputSpec(TraitedSpec): class GenerateSummedGradientImage(SEMLikeCommandLine): - """title: GenerateSummedGradient category: Filtering.FeatureDetection @@ -48,12 +63,22 @@ class GenerateSummedGradientImage(SEMLikeCommandLine): class CannySegmentationLevelSetImageFilterInputSpec(CommandLineInputSpec): inputVolume = File(exists=True, argstr="--inputVolume %s") initialModel = File(exists=True, argstr="--initialModel %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, argstr="--outputVolume %s") - outputSpeedVolume = traits.Either(traits.Bool, File(), hash_files=False, argstr="--outputSpeedVolume %s") - cannyThreshold = traits.Float(desc="Canny Threshold Value", argstr="--cannyThreshold %f") - cannyVariance = traits.Float(desc="Canny variance", argstr="--cannyVariance %f") - advectionWeight = traits.Float(desc="Controls the smoothness of the resulting mask, small number are more smooth, large numbers allow more sharp corners. ", argstr="--advectionWeight %f") - initialModelIsovalue = traits.Float(desc="The identification of the input model iso-surface. (for a binary image with 0s and 1s use 0.5) (for a binary image with 0s and 255's use 127.5).", argstr="--initialModelIsovalue %f") + outputVolume = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--outputVolume %s") + outputSpeedVolume = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--outputSpeedVolume %s") + cannyThreshold = traits.Float( + desc="Canny Threshold Value", argstr="--cannyThreshold %f") + cannyVariance = traits.Float( + desc="Canny variance", argstr="--cannyVariance %f") + advectionWeight = traits.Float( + desc= + "Controls the smoothness of the resulting mask, small number are more smooth, large numbers allow more sharp corners. ", + argstr="--advectionWeight %f") + initialModelIsovalue = traits.Float( + desc= + "The identification of the input model iso-surface. (for a binary image with 0s and 1s use 0.5) (for a binary image with 0s and 255's use 127.5).", + argstr="--initialModelIsovalue %f") maxIterations = traits.Int(desc="The", argstr="--maxIterations %d") @@ -63,7 +88,6 @@ class CannySegmentationLevelSetImageFilterOutputSpec(TraitedSpec): class CannySegmentationLevelSetImageFilter(SEMLikeCommandLine): - """title: Canny Level Set Image Filter category: Filtering.FeatureDetection @@ -83,15 +107,28 @@ class CannySegmentationLevelSetImageFilter(SEMLikeCommandLine): input_spec = CannySegmentationLevelSetImageFilterInputSpec output_spec = CannySegmentationLevelSetImageFilterOutputSpec _cmd = " CannySegmentationLevelSetImageFilter " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'outputSpeedVolume': 'outputSpeedVolume.nii'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'outputSpeedVolume': 'outputSpeedVolume.nii' + } _redirect_x = False class DilateImageInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - inputMaskVolume = File(desc="Required: input brain mask image", exists=True, argstr="--inputMaskVolume %s") - inputRadius = traits.Int(desc="Required: input neighborhood radius", argstr="--inputRadius %d") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + inputMaskVolume = File( + desc="Required: input brain mask image", + exists=True, + argstr="--inputMaskVolume %s") + inputRadius = traits.Int( + desc="Required: input neighborhood radius", argstr="--inputRadius %d") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class DilateImageOutputSpec(TraitedSpec): @@ -99,7 +136,6 @@ class DilateImageOutputSpec(TraitedSpec): class DilateImage(SEMLikeCommandLine): - """title: Dilate Image category: Filtering.FeatureDetection @@ -124,9 +160,16 @@ class DilateImage(SEMLikeCommandLine): class TextureFromNoiseImageFilterInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - inputRadius = traits.Int(desc="Required: input neighborhood radius", argstr="--inputRadius %d") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + inputRadius = traits.Int( + desc="Required: input neighborhood radius", argstr="--inputRadius %d") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class TextureFromNoiseImageFilterOutputSpec(TraitedSpec): @@ -134,7 +177,6 @@ class TextureFromNoiseImageFilterOutputSpec(TraitedSpec): class TextureFromNoiseImageFilter(SEMLikeCommandLine): - """title: TextureFromNoiseImageFilter category: Filtering.FeatureDetection @@ -159,9 +201,18 @@ class TextureFromNoiseImageFilter(SEMLikeCommandLine): class FlippedDifferenceInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - inputMaskVolume = File(desc="Required: input brain mask image", exists=True, argstr="--inputMaskVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + inputMaskVolume = File( + desc="Required: input brain mask image", + exists=True, + argstr="--inputMaskVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class FlippedDifferenceOutputSpec(TraitedSpec): @@ -169,7 +220,6 @@ class FlippedDifferenceOutputSpec(TraitedSpec): class FlippedDifference(SEMLikeCommandLine): - """title: Flip Image category: Filtering.FeatureDetection @@ -194,10 +244,20 @@ class FlippedDifference(SEMLikeCommandLine): class ErodeImageInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - inputMaskVolume = File(desc="Required: input brain mask image", exists=True, argstr="--inputMaskVolume %s") - inputRadius = traits.Int(desc="Required: input neighborhood radius", argstr="--inputRadius %d") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + inputMaskVolume = File( + desc="Required: input brain mask image", + exists=True, + argstr="--inputMaskVolume %s") + inputRadius = traits.Int( + desc="Required: input neighborhood radius", argstr="--inputRadius %d") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class ErodeImageOutputSpec(TraitedSpec): @@ -205,7 +265,6 @@ class ErodeImageOutputSpec(TraitedSpec): class ErodeImage(SEMLikeCommandLine): - """title: Erode Image category: Filtering.FeatureDetection @@ -230,10 +289,23 @@ class ErodeImage(SEMLikeCommandLine): class GenerateBrainClippedImageInputSpec(CommandLineInputSpec): - inputImg = File(desc="input volume 1, usally t1 image", exists=True, argstr="--inputImg %s") - inputMsk = File(desc="input volume 2, usally t2 image", exists=True, argstr="--inputMsk %s") - outputFileName = traits.Either(traits.Bool, File(), hash_files=False, desc="(required) output file name", argstr="--outputFileName %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputImg = File( + desc="input volume 1, usally t1 image", + exists=True, + argstr="--inputImg %s") + inputMsk = File( + desc="input volume 2, usally t2 image", + exists=True, + argstr="--inputMsk %s") + outputFileName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="(required) output file name", + argstr="--outputFileName %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class GenerateBrainClippedImageOutputSpec(TraitedSpec): @@ -241,7 +313,6 @@ class GenerateBrainClippedImageOutputSpec(TraitedSpec): class GenerateBrainClippedImage(SEMLikeCommandLine): - """title: GenerateBrainClippedImage category: Filtering.FeatureDetection @@ -264,10 +335,20 @@ class GenerateBrainClippedImage(SEMLikeCommandLine): class NeighborhoodMedianInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - inputMaskVolume = File(desc="Required: input brain mask image", exists=True, argstr="--inputMaskVolume %s") - inputRadius = traits.Int(desc="Required: input neighborhood radius", argstr="--inputRadius %d") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + inputMaskVolume = File( + desc="Required: input brain mask image", + exists=True, + argstr="--inputMaskVolume %s") + inputRadius = traits.Int( + desc="Required: input neighborhood radius", argstr="--inputRadius %d") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class NeighborhoodMedianOutputSpec(TraitedSpec): @@ -275,7 +356,6 @@ class NeighborhoodMedianOutputSpec(TraitedSpec): class NeighborhoodMedian(SEMLikeCommandLine): - """title: Neighborhood Median category: Filtering.FeatureDetection @@ -300,11 +380,22 @@ class NeighborhoodMedian(SEMLikeCommandLine): class GenerateTestImageInputSpec(CommandLineInputSpec): - inputVolume = File(desc="input volume 1, usally t1 image", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="(required) output file name", argstr="--outputVolume %s") - lowerBoundOfOutputVolume = traits.Float(argstr="--lowerBoundOfOutputVolume %f") - upperBoundOfOutputVolume = traits.Float(argstr="--upperBoundOfOutputVolume %f") - outputVolumeSize = traits.Float(desc="output Volume Size", argstr="--outputVolumeSize %f") + inputVolume = File( + desc="input volume 1, usally t1 image", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="(required) output file name", + argstr="--outputVolume %s") + lowerBoundOfOutputVolume = traits.Float( + argstr="--lowerBoundOfOutputVolume %f") + upperBoundOfOutputVolume = traits.Float( + argstr="--upperBoundOfOutputVolume %f") + outputVolumeSize = traits.Float( + desc="output Volume Size", argstr="--outputVolumeSize %f") class GenerateTestImageOutputSpec(TraitedSpec): @@ -312,7 +403,6 @@ class GenerateTestImageOutputSpec(TraitedSpec): class GenerateTestImage(SEMLikeCommandLine): - """title: DownSampleImage category: Filtering.FeatureDetection @@ -335,10 +425,20 @@ class GenerateTestImage(SEMLikeCommandLine): class NeighborhoodMeanInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - inputMaskVolume = File(desc="Required: input brain mask image", exists=True, argstr="--inputMaskVolume %s") - inputRadius = traits.Int(desc="Required: input neighborhood radius", argstr="--inputRadius %d") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + inputMaskVolume = File( + desc="Required: input brain mask image", + exists=True, + argstr="--inputMaskVolume %s") + inputRadius = traits.Int( + desc="Required: input neighborhood radius", argstr="--inputRadius %d") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class NeighborhoodMeanOutputSpec(TraitedSpec): @@ -346,7 +446,6 @@ class NeighborhoodMeanOutputSpec(TraitedSpec): class NeighborhoodMean(SEMLikeCommandLine): - """title: Neighborhood Mean category: Filtering.FeatureDetection @@ -372,11 +471,24 @@ class NeighborhoodMean(SEMLikeCommandLine): class HammerAttributeCreatorInputSpec(CommandLineInputSpec): Scale = traits.Int(desc="Determine Scale of Ball", argstr="--Scale %d") - Strength = traits.Float(desc="Determine Strength of Edges", argstr="--Strength %f") - inputGMVolume = File(desc="Required: input grey matter posterior image", exists=True, argstr="--inputGMVolume %s") - inputWMVolume = File(desc="Required: input white matter posterior image", exists=True, argstr="--inputWMVolume %s") - inputCSFVolume = File(desc="Required: input CSF posterior image", exists=True, argstr="--inputCSFVolume %s") - outputVolumeBase = traits.Str(desc="Required: output image base name to be appended for each feature vector.", argstr="--outputVolumeBase %s") + Strength = traits.Float( + desc="Determine Strength of Edges", argstr="--Strength %f") + inputGMVolume = File( + desc="Required: input grey matter posterior image", + exists=True, + argstr="--inputGMVolume %s") + inputWMVolume = File( + desc="Required: input white matter posterior image", + exists=True, + argstr="--inputWMVolume %s") + inputCSFVolume = File( + desc="Required: input CSF posterior image", + exists=True, + argstr="--inputCSFVolume %s") + outputVolumeBase = traits.Str( + desc= + "Required: output image base name to be appended for each feature vector.", + argstr="--outputVolumeBase %s") class HammerAttributeCreatorOutputSpec(TraitedSpec): @@ -384,7 +496,6 @@ class HammerAttributeCreatorOutputSpec(TraitedSpec): class HammerAttributeCreator(SEMLikeCommandLine): - """title: HAMMER Feature Vectors category: Filtering.FeatureDetection @@ -413,7 +524,8 @@ class TextureMeasureFilterInputSpec(CommandLineInputSpec): inputMaskVolume = File(exists=True, argstr="--inputMaskVolume %s") distance = traits.Int(argstr="--distance %d") insideROIValue = traits.Float(argstr="--insideROIValue %f") - outputFilename = traits.Either(traits.Bool, File(), hash_files=False, argstr="--outputFilename %s") + outputFilename = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--outputFilename %s") class TextureMeasureFilterOutputSpec(TraitedSpec): @@ -421,7 +533,6 @@ class TextureMeasureFilterOutputSpec(TraitedSpec): class TextureMeasureFilter(SEMLikeCommandLine): - """title: Canny Level Set Image Filter category: Filtering.FeatureDetection @@ -446,11 +557,24 @@ class TextureMeasureFilter(SEMLikeCommandLine): class DilateMaskInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - inputBinaryVolume = File(desc="Required: input brain mask image", exists=True, argstr="--inputBinaryVolume %s") - sizeStructuralElement = traits.Int(desc="size of structural element. sizeStructuralElement=1 means that 3x3x3 structuring element for 3D", argstr="--sizeStructuralElement %d") - lowerThreshold = traits.Float(desc="Required: lowerThreshold value", argstr="--lowerThreshold %f") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + inputBinaryVolume = File( + desc="Required: input brain mask image", + exists=True, + argstr="--inputBinaryVolume %s") + sizeStructuralElement = traits.Int( + desc= + "size of structural element. sizeStructuralElement=1 means that 3x3x3 structuring element for 3D", + argstr="--sizeStructuralElement %d") + lowerThreshold = traits.Float( + desc="Required: lowerThreshold value", argstr="--lowerThreshold %f") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class DilateMaskOutputSpec(TraitedSpec): @@ -458,7 +582,6 @@ class DilateMaskOutputSpec(TraitedSpec): class DilateMask(SEMLikeCommandLine): - """title: Dilate Image category: Filtering.FeatureDetection @@ -483,8 +606,14 @@ class DilateMask(SEMLikeCommandLine): class DumpBinaryTrainingVectorsInputSpec(CommandLineInputSpec): - inputHeaderFilename = File(desc="Required: input header file name", exists=True, argstr="--inputHeaderFilename %s") - inputVectorFilename = File(desc="Required: input vector filename", exists=True, argstr="--inputVectorFilename %s") + inputHeaderFilename = File( + desc="Required: input header file name", + exists=True, + argstr="--inputHeaderFilename %s") + inputVectorFilename = File( + desc="Required: input vector filename", + exists=True, + argstr="--inputVectorFilename %s") class DumpBinaryTrainingVectorsOutputSpec(TraitedSpec): @@ -492,7 +621,6 @@ class DumpBinaryTrainingVectorsOutputSpec(TraitedSpec): class DumpBinaryTrainingVectors(SEMLikeCommandLine): - """title: Erode Image category: Filtering.FeatureDetection @@ -517,10 +645,24 @@ class DumpBinaryTrainingVectors(SEMLikeCommandLine): class DistanceMapsInputSpec(CommandLineInputSpec): - inputLabelVolume = File(desc="Required: input tissue label image", exists=True, argstr="--inputLabelVolume %s") - inputMaskVolume = File(desc="Required: input brain mask image", exists=True, argstr="--inputMaskVolume %s") - inputTissueLabel = traits.Int(desc="Required: input integer value of tissue type used to calculate distance", argstr="--inputTissueLabel %d") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputLabelVolume = File( + desc="Required: input tissue label image", + exists=True, + argstr="--inputLabelVolume %s") + inputMaskVolume = File( + desc="Required: input brain mask image", + exists=True, + argstr="--inputMaskVolume %s") + inputTissueLabel = traits.Int( + desc= + "Required: input integer value of tissue type used to calculate distance", + argstr="--inputTissueLabel %d") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class DistanceMapsOutputSpec(TraitedSpec): @@ -528,7 +670,6 @@ class DistanceMapsOutputSpec(TraitedSpec): class DistanceMaps(SEMLikeCommandLine): - """title: Mauerer Distance category: Filtering.FeatureDetection @@ -553,9 +694,19 @@ class DistanceMaps(SEMLikeCommandLine): class STAPLEAnalysisInputSpec(CommandLineInputSpec): - inputDimension = traits.Int(desc="Required: input image Dimension 2 or 3", argstr="--inputDimension %d") - inputLabelVolume = InputMultiPath(File(exists=True), desc="Required: input label volume", argstr="--inputLabelVolume %s...") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputDimension = traits.Int( + desc="Required: input image Dimension 2 or 3", + argstr="--inputDimension %d") + inputLabelVolume = InputMultiPath( + File(exists=True), + desc="Required: input label volume", + argstr="--inputLabelVolume %s...") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class STAPLEAnalysisOutputSpec(TraitedSpec): @@ -563,7 +714,6 @@ class STAPLEAnalysisOutputSpec(TraitedSpec): class STAPLEAnalysis(SEMLikeCommandLine): - """title: Dilate Image category: Filtering.FeatureDetection @@ -588,11 +738,21 @@ class STAPLEAnalysis(SEMLikeCommandLine): class GradientAnisotropicDiffusionImageFilterInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input image", exists=True, argstr="--inputVolume %s") - numberOfIterations = traits.Int(desc="Optional value for number of Iterations", argstr="--numberOfIterations %d") - timeStep = traits.Float(desc="Time step for diffusion process", argstr="--timeStep %f") - conductance = traits.Float(desc="Conductance for diffusion process", argstr="--conductance %f") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + inputVolume = File( + desc="Required: input image", exists=True, argstr="--inputVolume %s") + numberOfIterations = traits.Int( + desc="Optional value for number of Iterations", + argstr="--numberOfIterations %d") + timeStep = traits.Float( + desc="Time step for diffusion process", argstr="--timeStep %f") + conductance = traits.Float( + desc="Conductance for diffusion process", argstr="--conductance %f") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class GradientAnisotropicDiffusionImageFilterOutputSpec(TraitedSpec): @@ -600,7 +760,6 @@ class GradientAnisotropicDiffusionImageFilterOutputSpec(TraitedSpec): class GradientAnisotropicDiffusionImageFilter(SEMLikeCommandLine): - """title: GradientAnisopropicDiffusionFilter category: Filtering.FeatureDetection @@ -619,13 +778,28 @@ class GradientAnisotropicDiffusionImageFilter(SEMLikeCommandLine): class CannyEdgeInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Required: input tissue label image", exists=True, argstr="--inputVolume %s") - variance = traits.Float(desc="Variance and Maximum error are used in the Gaussian smoothing of the input image. See itkDiscreteGaussianImageFilter for information on these parameters.", argstr="--variance %f") + inputVolume = File( + desc="Required: input tissue label image", + exists=True, + argstr="--inputVolume %s") + variance = traits.Float( + desc= + "Variance and Maximum error are used in the Gaussian smoothing of the input image. See itkDiscreteGaussianImageFilter for information on these parameters.", + argstr="--variance %f") upperThreshold = traits.Float( - desc="Threshold is the lowest allowed value in the output image. Its data type is the same as the data type of the output image. Any values below the Threshold level will be replaced with the OutsideValue parameter value, whose default is zero. ", argstr="--upperThreshold %f") + desc= + "Threshold is the lowest allowed value in the output image. Its data type is the same as the data type of the output image. Any values below the Threshold level will be replaced with the OutsideValue parameter value, whose default is zero. ", + argstr="--upperThreshold %f") lowerThreshold = traits.Float( - desc="Threshold is the lowest allowed value in the output image. Its data type is the same as the data type of the output image. Any values below the Threshold level will be replaced with the OutsideValue parameter value, whose default is zero. ", argstr="--lowerThreshold %f") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output image", argstr="--outputVolume %s") + desc= + "Threshold is the lowest allowed value in the output image. Its data type is the same as the data type of the output image. Any values below the Threshold level will be replaced with the OutsideValue parameter value, whose default is zero. ", + argstr="--lowerThreshold %f") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Required: output image", + argstr="--outputVolume %s") class CannyEdgeOutputSpec(TraitedSpec): @@ -633,7 +807,6 @@ class CannyEdgeOutputSpec(TraitedSpec): class CannyEdge(SEMLikeCommandLine): - """title: Canny Edge Detection category: Filtering.FeatureDetection diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py b/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py index ca3669e020..9abfd5d755 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py @@ -4,40 +4,37 @@ def test_CannyEdge_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - lowerThreshold=dict(argstr='--lowerThreshold %f', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upperThreshold=dict(argstr='--upperThreshold %f', - ), - variance=dict(argstr='--variance %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + lowerThreshold=dict(argstr='--lowerThreshold %f', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upperThreshold=dict(argstr='--upperThreshold %f', ), + variance=dict(argstr='--variance %f', ), ) inputs = CannyEdge.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CannyEdge_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = CannyEdge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py index 366fd626ab..cc8cd50417 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py @@ -4,49 +4,46 @@ def test_CannySegmentationLevelSetImageFilter_inputs(): - input_map = dict(advectionWeight=dict(argstr='--advectionWeight %f', - ), - args=dict(argstr='%s', - ), - cannyThreshold=dict(argstr='--cannyThreshold %f', - ), - cannyVariance=dict(argstr='--cannyVariance %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialModel=dict(argstr='--initialModel %s', - ), - initialModelIsovalue=dict(argstr='--initialModelIsovalue %f', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - maxIterations=dict(argstr='--maxIterations %d', - ), - outputSpeedVolume=dict(argstr='--outputSpeedVolume %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + advectionWeight=dict(argstr='--advectionWeight %f', ), + args=dict(argstr='%s', ), + cannyThreshold=dict(argstr='--cannyThreshold %f', ), + cannyVariance=dict(argstr='--cannyVariance %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialModel=dict(argstr='--initialModel %s', ), + initialModelIsovalue=dict(argstr='--initialModelIsovalue %f', ), + inputVolume=dict(argstr='--inputVolume %s', ), + maxIterations=dict(argstr='--maxIterations %d', ), + outputSpeedVolume=dict( + argstr='--outputSpeedVolume %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = CannySegmentationLevelSetImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CannySegmentationLevelSetImageFilter_outputs(): - output_map = dict(outputSpeedVolume=dict(), - outputVolume=dict(), + output_map = dict( + outputSpeedVolume=dict(), + outputVolume=dict(), ) outputs = CannySegmentationLevelSetImageFilter.output_spec() diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py index ce2c59dff9..ab559722bc 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py @@ -4,38 +4,36 @@ def test_DilateImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputRadius=dict(argstr='--inputRadius %d', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputRadius=dict(argstr='--inputRadius %d', ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DilateImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DilateImage_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = DilateImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py index 1e95808c9f..acfc4e0048 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py @@ -4,40 +4,37 @@ def test_DilateMask_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBinaryVolume=dict(argstr='--inputBinaryVolume %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - lowerThreshold=dict(argstr='--lowerThreshold %f', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - sizeStructuralElement=dict(argstr='--sizeStructuralElement %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBinaryVolume=dict(argstr='--inputBinaryVolume %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + lowerThreshold=dict(argstr='--lowerThreshold %f', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + sizeStructuralElement=dict(argstr='--sizeStructuralElement %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DilateMask.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DilateMask_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = DilateMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py index a9136fcbd5..9fe6cff9f0 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py @@ -4,38 +4,36 @@ def test_DistanceMaps_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputLabelVolume=dict(argstr='--inputLabelVolume %s', - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputTissueLabel=dict(argstr='--inputTissueLabel %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputLabelVolume=dict(argstr='--inputLabelVolume %s', ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputTissueLabel=dict(argstr='--inputTissueLabel %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DistanceMaps.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DistanceMaps_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = DistanceMaps.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py index 7504cc311e..f1fa2787ca 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py @@ -4,30 +4,29 @@ def test_DumpBinaryTrainingVectors_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputHeaderFilename=dict(argstr='--inputHeaderFilename %s', - ), - inputVectorFilename=dict(argstr='--inputVectorFilename %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputHeaderFilename=dict(argstr='--inputHeaderFilename %s', ), + inputVectorFilename=dict(argstr='--inputVectorFilename %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DumpBinaryTrainingVectors.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DumpBinaryTrainingVectors_outputs(): output_map = dict() outputs = DumpBinaryTrainingVectors.output_spec() diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py index 659c88471c..92452dd097 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py @@ -4,38 +4,36 @@ def test_ErodeImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputRadius=dict(argstr='--inputRadius %d', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputRadius=dict(argstr='--inputRadius %d', ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ErodeImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ErodeImage_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = ErodeImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py b/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py index e81e2cf9d9..379a87a8cd 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py @@ -4,36 +4,35 @@ def test_FlippedDifference_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FlippedDifference.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FlippedDifference_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = FlippedDifference.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py index 234494c3f4..d86f57feaa 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py @@ -4,38 +4,36 @@ def test_GenerateBrainClippedImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputImg=dict(argstr='--inputImg %s', - ), - inputMsk=dict(argstr='--inputMsk %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputFileName=dict(argstr='--outputFileName %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputImg=dict(argstr='--inputImg %s', ), + inputMsk=dict(argstr='--inputMsk %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputFileName=dict( + argstr='--outputFileName %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GenerateBrainClippedImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateBrainClippedImage_outputs(): - output_map = dict(outputFileName=dict(), - ) + output_map = dict(outputFileName=dict(), ) outputs = GenerateBrainClippedImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py index d073e15ab0..c340550313 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py @@ -4,40 +4,37 @@ def test_GenerateSummedGradientImage_inputs(): - input_map = dict(MaximumGradient=dict(argstr='--MaximumGradient ', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='--inputVolume1 %s', - ), - inputVolume2=dict(argstr='--inputVolume2 %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputFileName=dict(argstr='--outputFileName %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + MaximumGradient=dict(argstr='--MaximumGradient ', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict(argstr='--inputVolume1 %s', ), + inputVolume2=dict(argstr='--inputVolume2 %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputFileName=dict( + argstr='--outputFileName %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GenerateSummedGradientImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateSummedGradientImage_outputs(): - output_map = dict(outputFileName=dict(), - ) + output_map = dict(outputFileName=dict(), ) outputs = GenerateSummedGradientImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py index f9fb21b9da..c195dda481 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py @@ -4,40 +4,39 @@ def test_GenerateTestImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - lowerBoundOfOutputVolume=dict(argstr='--lowerBoundOfOutputVolume %f', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - outputVolumeSize=dict(argstr='--outputVolumeSize %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upperBoundOfOutputVolume=dict(argstr='--upperBoundOfOutputVolume %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + lowerBoundOfOutputVolume=dict( + argstr='--lowerBoundOfOutputVolume %f', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + outputVolumeSize=dict(argstr='--outputVolumeSize %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upperBoundOfOutputVolume=dict( + argstr='--upperBoundOfOutputVolume %f', ), ) inputs = GenerateTestImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateTestImage_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = GenerateTestImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py index 63215e0b8a..eb8529d541 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py @@ -4,40 +4,37 @@ def test_GradientAnisotropicDiffusionImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - conductance=dict(argstr='--conductance %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfIterations=dict(argstr='--numberOfIterations %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timeStep=dict(argstr='--timeStep %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + conductance=dict(argstr='--conductance %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfIterations=dict(argstr='--numberOfIterations %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timeStep=dict(argstr='--timeStep %f', ), ) inputs = GradientAnisotropicDiffusionImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GradientAnisotropicDiffusionImageFilter_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = GradientAnisotropicDiffusionImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py b/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py index 6920812aae..079cd20298 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py @@ -4,38 +4,33 @@ def test_HammerAttributeCreator_inputs(): - input_map = dict(Scale=dict(argstr='--Scale %d', - ), - Strength=dict(argstr='--Strength %f', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputCSFVolume=dict(argstr='--inputCSFVolume %s', - ), - inputGMVolume=dict(argstr='--inputGMVolume %s', - ), - inputWMVolume=dict(argstr='--inputWMVolume %s', - ), - outputVolumeBase=dict(argstr='--outputVolumeBase %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + Scale=dict(argstr='--Scale %d', ), + Strength=dict(argstr='--Strength %f', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputCSFVolume=dict(argstr='--inputCSFVolume %s', ), + inputGMVolume=dict(argstr='--inputGMVolume %s', ), + inputWMVolume=dict(argstr='--inputWMVolume %s', ), + outputVolumeBase=dict(argstr='--outputVolumeBase %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = HammerAttributeCreator.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_HammerAttributeCreator_outputs(): output_map = dict() outputs = HammerAttributeCreator.output_spec() diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py index c23362562c..bf35b6beed 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py @@ -4,38 +4,36 @@ def test_NeighborhoodMean_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputRadius=dict(argstr='--inputRadius %d', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputRadius=dict(argstr='--inputRadius %d', ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = NeighborhoodMean.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NeighborhoodMean_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = NeighborhoodMean.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py index ff2cdd38af..8f0da1f50b 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py @@ -4,38 +4,36 @@ def test_NeighborhoodMedian_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputRadius=dict(argstr='--inputRadius %d', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputRadius=dict(argstr='--inputRadius %d', ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = NeighborhoodMedian.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NeighborhoodMedian_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = NeighborhoodMedian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py b/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py index 45c55236d0..08f5615d97 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py @@ -4,36 +4,35 @@ def test_STAPLEAnalysis_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputDimension=dict(argstr='--inputDimension %d', - ), - inputLabelVolume=dict(argstr='--inputLabelVolume %s...', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputDimension=dict(argstr='--inputDimension %d', ), + inputLabelVolume=dict(argstr='--inputLabelVolume %s...', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = STAPLEAnalysis.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_STAPLEAnalysis_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = STAPLEAnalysis.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py index d351d8d56f..2964da9347 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py @@ -4,36 +4,35 @@ def test_TextureFromNoiseImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputRadius=dict(argstr='--inputRadius %d', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputRadius=dict(argstr='--inputRadius %d', ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TextureFromNoiseImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TextureFromNoiseImageFilter_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = TextureFromNoiseImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py index 771fa52f03..cf9c60b8b9 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py @@ -4,40 +4,37 @@ def test_TextureMeasureFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - distance=dict(argstr='--distance %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - insideROIValue=dict(argstr='--insideROIValue %f', - ), - outputFilename=dict(argstr='--outputFilename %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + distance=dict(argstr='--distance %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + insideROIValue=dict(argstr='--insideROIValue %f', ), + outputFilename=dict( + argstr='--outputFilename %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = TextureMeasureFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TextureMeasureFilter_outputs(): - output_map = dict(outputFilename=dict(), - ) + output_map = dict(outputFilename=dict(), ) outputs = TextureMeasureFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py b/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py index e237ca41db..a5784b72cf 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py @@ -4,49 +4,49 @@ def test_UnbiasedNonLocalMeans_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hp=dict(argstr='--hp %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - ps=dict(argstr='--ps %f', - ), - rc=dict(argstr='--rc %s', - sep=',', - ), - rs=dict(argstr='--rs %s', - sep=',', - ), - sigma=dict(argstr='--sigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + hp=dict(argstr='--hp %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + ps=dict(argstr='--ps %f', ), + rc=dict( + argstr='--rc %s', + sep=',', + ), + rs=dict( + argstr='--rs %s', + sep=',', + ), + sigma=dict(argstr='--sigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = UnbiasedNonLocalMeans.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_UnbiasedNonLocalMeans_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = UnbiasedNonLocalMeans.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/legacy/registration.py b/nipype/interfaces/semtools/legacy/registration.py index 7461fe067a..04bb425e3d 100644 --- a/nipype/interfaces/semtools/legacy/registration.py +++ b/nipype/interfaces/semtools/legacy/registration.py @@ -11,22 +11,41 @@ class scalartransformInputSpec(CommandLineInputSpec): - input_image = File(desc="Image to tranform", exists=True, argstr="--input_image %s") - output_image = traits.Either(traits.Bool, File(), hash_files=False, desc="The transformed image", argstr="--output_image %s") - transformation = traits.Either(traits.Bool, File(), hash_files=False, desc="Output file for transformation parameters", argstr="--transformation %s") - invert = traits.Bool(desc="Invert tranform before applying.", argstr="--invert ") - deformation = File(desc="Deformation field.", exists=True, argstr="--deformation %s") - h_field = traits.Bool(desc="The deformation is an h-field.", argstr="--h_field ") - interpolation = traits.Enum("nearestneighbor", "linear", "cubic", desc="Interpolation type (nearestneighbor, linear, cubic)", argstr="--interpolation %s") + input_image = File( + desc="Image to tranform", exists=True, argstr="--input_image %s") + output_image = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The transformed image", + argstr="--output_image %s") + transformation = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output file for transformation parameters", + argstr="--transformation %s") + invert = traits.Bool( + desc="Invert tranform before applying.", argstr="--invert ") + deformation = File( + desc="Deformation field.", exists=True, argstr="--deformation %s") + h_field = traits.Bool( + desc="The deformation is an h-field.", argstr="--h_field ") + interpolation = traits.Enum( + "nearestneighbor", + "linear", + "cubic", + desc="Interpolation type (nearestneighbor, linear, cubic)", + argstr="--interpolation %s") class scalartransformOutputSpec(TraitedSpec): output_image = File(desc="The transformed image", exists=True) - transformation = File(desc="Output file for transformation parameters", exists=True) + transformation = File( + desc="Output file for transformation parameters", exists=True) class scalartransform(SEMLikeCommandLine): - """title: ScalarTransform (DTIProcess) category: Legacy.Registration @@ -48,5 +67,8 @@ class scalartransform(SEMLikeCommandLine): input_spec = scalartransformInputSpec output_spec = scalartransformOutputSpec _cmd = " scalartransform " - _outputs_filenames = {'output_image': 'output_image.nii', 'transformation': 'transformation'} + _outputs_filenames = { + 'output_image': 'output_image.nii', + 'transformation': 'transformation' + } _redirect_x = False diff --git a/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py b/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py index ed643de764..b4ad7cc6f9 100644 --- a/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py +++ b/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py @@ -4,45 +4,44 @@ def test_scalartransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - deformation=dict(argstr='--deformation %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - h_field=dict(argstr='--h_field ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_image=dict(argstr='--input_image %s', - ), - interpolation=dict(argstr='--interpolation %s', - ), - invert=dict(argstr='--invert ', - ), - output_image=dict(argstr='--output_image %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformation=dict(argstr='--transformation %s', - hash_files=False, - ), + input_map = dict( + args=dict(argstr='%s', ), + deformation=dict(argstr='--deformation %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + h_field=dict(argstr='--h_field ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_image=dict(argstr='--input_image %s', ), + interpolation=dict(argstr='--interpolation %s', ), + invert=dict(argstr='--invert ', ), + output_image=dict( + argstr='--output_image %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformation=dict( + argstr='--transformation %s', + hash_files=False, + ), ) inputs = scalartransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_scalartransform_outputs(): - output_map = dict(output_image=dict(), - transformation=dict(), + output_map = dict( + output_image=dict(), + transformation=dict(), ) outputs = scalartransform.output_spec() diff --git a/nipype/interfaces/semtools/registration/__init__.py b/nipype/interfaces/semtools/registration/__init__.py index 3b9a8916d5..33bd60ad59 100644 --- a/nipype/interfaces/semtools/registration/__init__.py +++ b/nipype/interfaces/semtools/registration/__init__.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import -from .specialized import VBRAINSDemonWarp, BRAINSDemonWarp, BRAINSTransformFromFiducials +from .specialized import (VBRAINSDemonWarp, BRAINSDemonWarp, + BRAINSTransformFromFiducials) from .brainsresample import BRAINSResample from .brainsfit import BRAINSFit from .brainsresize import BRAINSResize diff --git a/nipype/interfaces/semtools/registration/brainsfit.py b/nipype/interfaces/semtools/registration/brainsfit.py index 9b6c0f5634..6142aac418 100644 --- a/nipype/interfaces/semtools/registration/brainsfit.py +++ b/nipype/interfaces/semtools/registration/brainsfit.py @@ -11,107 +11,372 @@ class BRAINSFitInputSpec(CommandLineInputSpec): - fixedVolume = File(desc="Input fixed image (the moving image will be transformed into this image space).", exists=True, argstr="--fixedVolume %s") - movingVolume = File(desc="Input moving image (this image will be transformed into the fixed image space).", exists=True, argstr="--movingVolume %s") + fixedVolume = File( + desc= + "Input fixed image (the moving image will be transformed into this image space).", + exists=True, + argstr="--fixedVolume %s") + movingVolume = File( + desc= + "Input moving image (this image will be transformed into the fixed image space).", + exists=True, + argstr="--movingVolume %s") samplingPercentage = traits.Float( - desc="Fraction of voxels of the fixed image that will be used for registration. The number has to be larger than zero and less or equal to one. Higher values increase the computation time but may give more accurate results. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation. The default is 0.002 (use approximately 0.2% of voxels, resulting in 100000 samples in a 512x512x192 volume) to provide a very fast registration in most cases. Typical values range from 0.01 (1%) for low detail images to 0.2 (20%) for high detail images.", argstr="--samplingPercentage %f") - splineGridSize = InputMultiPath(traits.Int, desc="Number of BSpline grid subdivisions along each axis of the fixed image, centered on the image space. Values must be 3 or higher for the BSpline to be correctly computed.", sep=",", argstr="--splineGridSize %s") - linearTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Output estimated transform - in case the computed transform is not BSpline. NOTE: You must set at least one output object (transform and/or output volume).", argstr="--linearTransform %s") - bsplineTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Output estimated transform - in case the computed transform is BSpline. NOTE: You must set at least one output object (transform and/or output volume).", argstr="--bsplineTransform %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Output image: the moving image warped to the fixed image space. NOTE: You must set at least one output object (transform and/or output volume).", argstr="--outputVolume %s") - initialTransform = File(desc="Transform to be applied to the moving image to initialize the registration. This can only be used if Initialize Transform Mode is Off.", exists=True, argstr="--initialTransform %s") - initializeTransformMode = traits.Enum("Off", "useMomentsAlign", "useCenterOfHeadAlign", "useGeometryAlign", "useCenterOfROIAlign", - desc="Determine how to initialize the transform center. useMomentsAlign assumes that the center of mass of the images represent similar structures. useCenterOfHeadAlign attempts to use the top of head and shape of neck to drive a center of mass estimate. useGeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. Off assumes that the physical space of the images are close. This flag is mutually exclusive with the Initialization transform.", argstr="--initializeTransformMode %s") - useRigid = traits.Bool(desc="Perform a rigid registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", argstr="--useRigid ") - useScaleVersor3D = traits.Bool(desc="Perform a ScaleVersor3D registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", argstr="--useScaleVersor3D ") - useScaleSkewVersor3D = traits.Bool(desc="Perform a ScaleSkewVersor3D registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", argstr="--useScaleSkewVersor3D ") - useAffine = traits.Bool(desc="Perform an Affine registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", argstr="--useAffine ") - useBSpline = traits.Bool(desc="Perform a BSpline registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", argstr="--useBSpline ") - useSyN = traits.Bool(desc="Perform a SyN registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", argstr="--useSyN ") - useComposite = traits.Bool(desc="Perform a Composite registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", argstr="--useComposite ") + desc= + "Fraction of voxels of the fixed image that will be used for registration. The number has to be larger than zero and less or equal to one. Higher values increase the computation time but may give more accurate results. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation. The default is 0.002 (use approximately 0.2% of voxels, resulting in 100000 samples in a 512x512x192 volume) to provide a very fast registration in most cases. Typical values range from 0.01 (1%) for low detail images to 0.2 (20%) for high detail images.", + argstr="--samplingPercentage %f") + splineGridSize = InputMultiPath( + traits.Int, + desc= + "Number of BSpline grid subdivisions along each axis of the fixed image, centered on the image space. Values must be 3 or higher for the BSpline to be correctly computed.", + sep=",", + argstr="--splineGridSize %s") + linearTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Output estimated transform - in case the computed transform is not BSpline. NOTE: You must set at least one output object (transform and/or output volume).", + argstr="--linearTransform %s") + bsplineTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Output estimated transform - in case the computed transform is BSpline. NOTE: You must set at least one output object (transform and/or output volume).", + argstr="--bsplineTransform %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Output image: the moving image warped to the fixed image space. NOTE: You must set at least one output object (transform and/or output volume).", + argstr="--outputVolume %s") + initialTransform = File( + desc= + "Transform to be applied to the moving image to initialize the registration. This can only be used if Initialize Transform Mode is Off.", + exists=True, + argstr="--initialTransform %s") + initializeTransformMode = traits.Enum( + "Off", + "useMomentsAlign", + "useCenterOfHeadAlign", + "useGeometryAlign", + "useCenterOfROIAlign", + desc= + "Determine how to initialize the transform center. useMomentsAlign assumes that the center of mass of the images represent similar structures. useCenterOfHeadAlign attempts to use the top of head and shape of neck to drive a center of mass estimate. useGeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. Off assumes that the physical space of the images are close. This flag is mutually exclusive with the Initialization transform.", + argstr="--initializeTransformMode %s") + useRigid = traits.Bool( + desc= + "Perform a rigid registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", + argstr="--useRigid ") + useScaleVersor3D = traits.Bool( + desc= + "Perform a ScaleVersor3D registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", + argstr="--useScaleVersor3D ") + useScaleSkewVersor3D = traits.Bool( + desc= + "Perform a ScaleSkewVersor3D registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", + argstr="--useScaleSkewVersor3D ") + useAffine = traits.Bool( + desc= + "Perform an Affine registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", + argstr="--useAffine ") + useBSpline = traits.Bool( + desc= + "Perform a BSpline registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", + argstr="--useBSpline ") + useSyN = traits.Bool( + desc= + "Perform a SyN registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", + argstr="--useSyN ") + useComposite = traits.Bool( + desc= + "Perform a Composite registration as part of the sequential registration steps. This family of options overrides the use of transformType if any of them are set.", + argstr="--useComposite ") maskProcessingMode = traits.Enum( - "NOMASK", "ROIAUTO", "ROI", desc="Specifies a mask to only consider a certain image region for the registration. If ROIAUTO is chosen, then the mask is computed using Otsu thresholding and hole filling. If ROI is chosen then the mask has to be specified as in input.", argstr="--maskProcessingMode %s") - fixedBinaryVolume = File(desc="Fixed Image binary mask volume, required if Masking Option is ROI. Image areas where the mask volume has zero value are ignored during the registration.", exists=True, argstr="--fixedBinaryVolume %s") - movingBinaryVolume = File(desc="Moving Image binary mask volume, required if Masking Option is ROI. Image areas where the mask volume has zero value are ignored during the registration.", exists=True, argstr="--movingBinaryVolume %s") + "NOMASK", + "ROIAUTO", + "ROI", + desc= + "Specifies a mask to only consider a certain image region for the registration. If ROIAUTO is chosen, then the mask is computed using Otsu thresholding and hole filling. If ROI is chosen then the mask has to be specified as in input.", + argstr="--maskProcessingMode %s") + fixedBinaryVolume = File( + desc= + "Fixed Image binary mask volume, required if Masking Option is ROI. Image areas where the mask volume has zero value are ignored during the registration.", + exists=True, + argstr="--fixedBinaryVolume %s") + movingBinaryVolume = File( + desc= + "Moving Image binary mask volume, required if Masking Option is ROI. Image areas where the mask volume has zero value are ignored during the registration.", + exists=True, + argstr="--movingBinaryVolume %s") outputFixedVolumeROI = traits.Either( - traits.Bool, File(), hash_files=False, desc="ROI that is automatically computed from the fixed image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", argstr="--outputFixedVolumeROI %s") + traits.Bool, + File(), + hash_files=False, + desc= + "ROI that is automatically computed from the fixed image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", + argstr="--outputFixedVolumeROI %s") outputMovingVolumeROI = traits.Either( - traits.Bool, File(), hash_files=False, desc="ROI that is automatically computed from the moving image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", argstr="--outputMovingVolumeROI %s") - useROIBSpline = traits.Bool(desc="If enabled then the bounding box of the input ROIs defines the BSpline grid support region. Otherwise the BSpline grid support region is the whole fixed image.", argstr="--useROIBSpline ") + traits.Bool, + File(), + hash_files=False, + desc= + "ROI that is automatically computed from the moving image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", + argstr="--outputMovingVolumeROI %s") + useROIBSpline = traits.Bool( + desc= + "If enabled then the bounding box of the input ROIs defines the BSpline grid support region. Otherwise the BSpline grid support region is the whole fixed image.", + argstr="--useROIBSpline ") histogramMatch = traits.Bool( - desc="Apply histogram matching operation for the input images to make them more similar. This is suitable for images of the same modality that may have different brightness or contrast, but the same overall intensity profile. Do NOT use if registering images from different modalities.", argstr="--histogramMatch ") - medianFilterSize = InputMultiPath(traits.Int, desc="Apply median filtering to reduce noise in the input volumes. The 3 values specify the radius for the optional MedianImageFilter preprocessing in all 3 directions (in voxels).", sep=",", argstr="--medianFilterSize %s") + desc= + "Apply histogram matching operation for the input images to make them more similar. This is suitable for images of the same modality that may have different brightness or contrast, but the same overall intensity profile. Do NOT use if registering images from different modalities.", + argstr="--histogramMatch ") + medianFilterSize = InputMultiPath( + traits.Int, + desc= + "Apply median filtering to reduce noise in the input volumes. The 3 values specify the radius for the optional MedianImageFilter preprocessing in all 3 directions (in voxels).", + sep=",", + argstr="--medianFilterSize %s") removeIntensityOutliers = traits.Float( - desc="Remove very high and very low intensity voxels from the input volumes. The parameter specifies the half percentage to decide outliers of image intensities. The default value is zero, which means no outlier removal. If the value of 0.005 is given, the 0.005% of both tails will be thrown away, so 0.01% of intensities in total would be ignored in the statistic calculation.", argstr="--removeIntensityOutliers %f") - fixedVolume2 = File(desc="Input fixed image that will be used for multimodal registration. (the moving image will be transformed into this image space).", exists=True, argstr="--fixedVolume2 %s") - movingVolume2 = File(desc="Input moving image that will be used for multimodal registration(this image will be transformed into the fixed image space).", exists=True, argstr="--movingVolume2 %s") - outputVolumePixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", desc="Data type for representing a voxel of the Output Volume.", argstr="--outputVolumePixelType %s") - backgroundFillValue = traits.Float(desc="This value will be used for filling those areas of the output image that have no corresponding voxels in the input moving image.", argstr="--backgroundFillValue %f") + desc= + "Remove very high and very low intensity voxels from the input volumes. The parameter specifies the half percentage to decide outliers of image intensities. The default value is zero, which means no outlier removal. If the value of 0.005 is given, the 0.005% of both tails will be thrown away, so 0.01% of intensities in total would be ignored in the statistic calculation.", + argstr="--removeIntensityOutliers %f") + fixedVolume2 = File( + desc= + "Input fixed image that will be used for multimodal registration. (the moving image will be transformed into this image space).", + exists=True, + argstr="--fixedVolume2 %s") + movingVolume2 = File( + desc= + "Input moving image that will be used for multimodal registration(this image will be transformed into the fixed image space).", + exists=True, + argstr="--movingVolume2 %s") + outputVolumePixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uint", + "uchar", + desc="Data type for representing a voxel of the Output Volume.", + argstr="--outputVolumePixelType %s") + backgroundFillValue = traits.Float( + desc= + "This value will be used for filling those areas of the output image that have no corresponding voxels in the input moving image.", + argstr="--backgroundFillValue %f") scaleOutputValues = traits.Bool( - desc="If true, and the voxel values do not fit within the minimum and maximum values of the desired outputVolumePixelType, then linearly scale the min/max output image voxel values to fit within the min/max range of the outputVolumePixelType.", argstr="--scaleOutputValues ") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", - desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, NearestNeighbor, BSpline, WindowedSinc, Hamming, Cosine, Welch, Lanczos, or ResampleInPlace. The ResampleInPlace option will create an image with the same discrete voxel values and will adjust the origin and direction of the physical space interpretation.", argstr="--interpolationMode %s") + desc= + "If true, and the voxel values do not fit within the minimum and maximum values of the desired outputVolumePixelType, then linearly scale the min/max output image voxel values to fit within the min/max range of the outputVolumePixelType.", + argstr="--scaleOutputValues ") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, NearestNeighbor, BSpline, WindowedSinc, Hamming, Cosine, Welch, Lanczos, or ResampleInPlace. The ResampleInPlace option will create an image with the same discrete voxel values and will adjust the origin and direction of the physical space interpretation.", + argstr="--interpolationMode %s") numberOfIterations = InputMultiPath( - traits.Int, desc="The maximum number of iterations to try before stopping the optimization. When using a lower value (500-1000) then the registration is forced to terminate earlier but there is a higher risk of stopping before an optimal solution is reached.", sep=",", argstr="--numberOfIterations %s") - maximumStepLength = traits.Float(desc="Starting step length of the optimizer. In general, higher values allow for recovering larger initial misalignments but there is an increased chance that the registration will not converge.", argstr="--maximumStepLength %f") + traits.Int, + desc= + "The maximum number of iterations to try before stopping the optimization. When using a lower value (500-1000) then the registration is forced to terminate earlier but there is a higher risk of stopping before an optimal solution is reached.", + sep=",", + argstr="--numberOfIterations %s") + maximumStepLength = traits.Float( + desc= + "Starting step length of the optimizer. In general, higher values allow for recovering larger initial misalignments but there is an increased chance that the registration will not converge.", + argstr="--maximumStepLength %f") minimumStepLength = InputMultiPath( - traits.Float, desc="Each step in the optimization takes steps at least this big. When none are possible, registration is complete. Smaller values allows the optimizer to make smaller adjustments, but the registration time may increase.", sep=",", argstr="--minimumStepLength %s") + traits.Float, + desc= + "Each step in the optimization takes steps at least this big. When none are possible, registration is complete. Smaller values allows the optimizer to make smaller adjustments, but the registration time may increase.", + sep=",", + argstr="--minimumStepLength %s") relaxationFactor = traits.Float( - desc="Specifies how quickly the optimization step length is decreased during registration. The value must be larger than 0 and smaller than 1. Larger values result in slower step size decrease, which allow for recovering larger initial misalignments but it increases the registration time and the chance that the registration will not converge.", argstr="--relaxationFactor %f") - translationScale = traits.Float(desc="How much to scale up changes in position (in mm) compared to unit rotational changes (in radians) -- decrease this to allow for more rotation in the search pattern.", argstr="--translationScale %f") - reproportionScale = traits.Float(desc="ScaleVersor3D 'Scale' compensation factor. Increase this to allow for more rescaling in a ScaleVersor3D or ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", argstr="--reproportionScale %f") - skewScale = traits.Float(desc="ScaleSkewVersor3D Skew compensation factor. Increase this to allow for more skew in a ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", argstr="--skewScale %f") + desc= + "Specifies how quickly the optimization step length is decreased during registration. The value must be larger than 0 and smaller than 1. Larger values result in slower step size decrease, which allow for recovering larger initial misalignments but it increases the registration time and the chance that the registration will not converge.", + argstr="--relaxationFactor %f") + translationScale = traits.Float( + desc= + "How much to scale up changes in position (in mm) compared to unit rotational changes (in radians) -- decrease this to allow for more rotation in the search pattern.", + argstr="--translationScale %f") + reproportionScale = traits.Float( + desc= + "ScaleVersor3D 'Scale' compensation factor. Increase this to allow for more rescaling in a ScaleVersor3D or ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", + argstr="--reproportionScale %f") + skewScale = traits.Float( + desc= + "ScaleSkewVersor3D Skew compensation factor. Increase this to allow for more skew in a ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", + argstr="--skewScale %f") maxBSplineDisplacement = traits.Float( - desc="Maximum allowed displacements in image physical coordinates (mm) for BSpline control grid along each axis. A value of 0.0 indicates that the problem should be unbounded. NOTE: This only constrains the BSpline portion, and does not limit the displacement from the associated bulk transform. This can lead to a substantial reduction in computation time in the BSpline optimizer., ", argstr="--maxBSplineDisplacement %f") - fixedVolumeTimeIndex = traits.Int(desc="The index in the time series for the 3D fixed image to fit. Only allowed if the fixed input volume is 4-dimensional.", argstr="--fixedVolumeTimeIndex %d") - movingVolumeTimeIndex = traits.Int(desc="The index in the time series for the 3D moving image to fit. Only allowed if the moving input volume is 4-dimensional", argstr="--movingVolumeTimeIndex %d") - numberOfHistogramBins = traits.Int(desc="The number of histogram levels used for mutual information metric estimation.", argstr="--numberOfHistogramBins %d") - numberOfMatchPoints = traits.Int(desc="Number of histogram match points used for mutual information metric estimation.", argstr="--numberOfMatchPoints %d") - costMetric = traits.Enum("MMI", "MSE", "NC", "MIH", desc="The cost metric to be used during fitting. Defaults to MMI. Options are MMI (Mattes Mutual Information), MSE (Mean Square Error), NC (Normalized Correlation), MC (Match Cardinality for binary images)", argstr="--costMetric %s") + desc= + "Maximum allowed displacements in image physical coordinates (mm) for BSpline control grid along each axis. A value of 0.0 indicates that the problem should be unbounded. NOTE: This only constrains the BSpline portion, and does not limit the displacement from the associated bulk transform. This can lead to a substantial reduction in computation time in the BSpline optimizer., ", + argstr="--maxBSplineDisplacement %f") + fixedVolumeTimeIndex = traits.Int( + desc= + "The index in the time series for the 3D fixed image to fit. Only allowed if the fixed input volume is 4-dimensional.", + argstr="--fixedVolumeTimeIndex %d") + movingVolumeTimeIndex = traits.Int( + desc= + "The index in the time series for the 3D moving image to fit. Only allowed if the moving input volume is 4-dimensional", + argstr="--movingVolumeTimeIndex %d") + numberOfHistogramBins = traits.Int( + desc= + "The number of histogram levels used for mutual information metric estimation.", + argstr="--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( + desc= + "Number of histogram match points used for mutual information metric estimation.", + argstr="--numberOfMatchPoints %d") + costMetric = traits.Enum( + "MMI", + "MSE", + "NC", + "MIH", + desc= + "The cost metric to be used during fitting. Defaults to MMI. Options are MMI (Mattes Mutual Information), MSE (Mean Square Error), NC (Normalized Correlation), MC (Match Cardinality for binary images)", + argstr="--costMetric %s") maskInferiorCutOffFromCenter = traits.Float( - desc="If Initialize Transform Mode is set to useCenterOfHeadAlign or Masking Option is ROIAUTO then this value defines the how much is cut of from the inferior part of the image. The cut-off distance is specified in millimeters, relative to the image center. If the value is 1000 or larger then no cut-off performed.", argstr="--maskInferiorCutOffFromCenter %f") + desc= + "If Initialize Transform Mode is set to useCenterOfHeadAlign or Masking Option is ROIAUTO then this value defines the how much is cut of from the inferior part of the image. The cut-off distance is specified in millimeters, relative to the image center. If the value is 1000 or larger then no cut-off performed.", + argstr="--maskInferiorCutOffFromCenter %f") ROIAutoDilateSize = traits.Float( - desc="This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. A setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f") + desc= + "This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. A setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", + argstr="--ROIAutoDilateSize %f") ROIAutoClosingSize = traits.Float( - desc="This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the hole closing size in mm. It is rounded up to the nearest whole pixel size in each direction. The default is to use a closing size of 9mm. For mouse data this value may need to be reset to 0.9 or smaller.", argstr="--ROIAutoClosingSize %f") + desc= + "This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the hole closing size in mm. It is rounded up to the nearest whole pixel size in each direction. The default is to use a closing size of 9mm. For mouse data this value may need to be reset to 0.9 or smaller.", + argstr="--ROIAutoClosingSize %f") numberOfSamples = traits.Int( - desc="The number of voxels sampled for mutual information computation. Increase this for higher accuracy, at the cost of longer computation time., NOTE that it is suggested to use samplingPercentage instead of this option. However, if set to non-zero, numberOfSamples overwrites the samplingPercentage option. ", argstr="--numberOfSamples %d") + desc= + "The number of voxels sampled for mutual information computation. Increase this for higher accuracy, at the cost of longer computation time., NOTE that it is suggested to use samplingPercentage instead of this option. However, if set to non-zero, numberOfSamples overwrites the samplingPercentage option. ", + argstr="--numberOfSamples %d") strippedOutputTransform = traits.Either( - traits.Bool, File(), hash_files=False, desc="Rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overridden if either bsplineTransform or linearTransform is set.", argstr="--strippedOutputTransform %s") + traits.Bool, + File(), + hash_files=False, + desc= + "Rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overridden if either bsplineTransform or linearTransform is set.", + argstr="--strippedOutputTransform %s") transformType = InputMultiPath( - traits.Str, desc="Specifies a list of registration types to be used. The valid types are, Rigid, ScaleVersor3D, ScaleSkewVersor3D, Affine, BSpline and SyN. Specifying more than one in a comma separated list will initialize the next stage with the previous results. If registrationClass flag is used, it overrides this parameter setting.", sep=",", argstr="--transformType %s") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", argstr="--outputTransform %s") + traits.Str, + desc= + "Specifies a list of registration types to be used. The valid types are, Rigid, ScaleVersor3D, ScaleSkewVersor3D, Affine, BSpline and SyN. Specifying more than one in a comma separated list will initialize the next stage with the previous results. If registrationClass flag is used, it overrides this parameter setting.", + sep=",", + argstr="--transformType %s") + outputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", + argstr="--outputTransform %s") initializeRegistrationByCurrentGenericTransform = traits.Bool( - desc="If this flag is ON, the current generic composite transform, resulted from the linear registration stages, is set to initialize the follow nonlinear registration process. However, by the default behaviour, the moving image is first warped based on the existant transform before it is passed to the BSpline registration filter. It is done to speed up the BSpline registration by reducing the computations of composite transform Jacobian.", argstr="--initializeRegistrationByCurrentGenericTransform ") - failureExitCode = traits.Int(desc="If the fit fails, exit with this status code. (It can be used to force a successfult exit status of (0) if the registration fails due to reaching the maximum number of iterations.", argstr="--failureExitCode %d") - writeTransformOnFailure = traits.Bool(desc="Flag to save the final transform even if the numberOfIterations are reached without convergence. (Intended for use when --failureExitCode 0 )", argstr="--writeTransformOnFailure ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use. (default is auto-detected)", argstr="--numberOfThreads %d") - debugLevel = traits.Int(desc="Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", argstr="--debugLevel %d") + desc= + "If this flag is ON, the current generic composite transform, resulted from the linear registration stages, is set to initialize the follow nonlinear registration process. However, by the default behaviour, the moving image is first warped based on the existant transform before it is passed to the BSpline registration filter. It is done to speed up the BSpline registration by reducing the computations of composite transform Jacobian.", + argstr="--initializeRegistrationByCurrentGenericTransform ") + failureExitCode = traits.Int( + desc= + "If the fit fails, exit with this status code. (It can be used to force a successfult exit status of (0) if the registration fails due to reaching the maximum number of iterations.", + argstr="--failureExitCode %d") + writeTransformOnFailure = traits.Bool( + desc= + "Flag to save the final transform even if the numberOfIterations are reached without convergence. (Intended for use when --failureExitCode 0 )", + argstr="--writeTransformOnFailure ") + numberOfThreads = traits.Int( + desc= + "Explicitly specify the maximum number of threads to use. (default is auto-detected)", + argstr="--numberOfThreads %d") + debugLevel = traits.Int( + desc= + "Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", + argstr="--debugLevel %d") costFunctionConvergenceFactor = traits.Float( - desc="From itkLBFGSBOptimizer.h: Set/Get the CostFunctionConvergenceFactor. Algorithm terminates when the reduction in cost function is less than (factor * epsmcj) where epsmch is the machine precision. Typical values for factor: 1e+12 for low accuracy; 1e+7 for moderate accuracy and 1e+1 for extremely high accuracy. 1e+9 seems to work well., ", argstr="--costFunctionConvergenceFactor %f") - projectedGradientTolerance = traits.Float(desc="From itkLBFGSBOptimizer.h: Set/Get the ProjectedGradientTolerance. Algorithm terminates when the project gradient is below the tolerance. Default lbfgsb value is 1e-5, but 1e-4 seems to work well., ", argstr="--projectedGradientTolerance %f") - maximumNumberOfEvaluations = traits.Int(desc="Maximum number of evaluations for line search in lbfgsb optimizer.", argstr="--maximumNumberOfEvaluations %d") - maximumNumberOfCorrections = traits.Int(desc="Maximum number of corrections in lbfgsb optimizer.", argstr="--maximumNumberOfCorrections %d") - gui = traits.Bool(desc="Display intermediate image volumes for debugging. NOTE: This is not part of the standard build sytem, and probably does nothing on your installation.", argstr="--gui ") - promptUser = traits.Bool(desc="Prompt the user to hit enter each time an image is sent to the DebugImageViewer", argstr="--promptUser ") - metricSamplingStrategy = traits.Enum("Random", desc="It defines the method that registration filter uses to sample the input fixed image. Only Random is supported for now.", argstr="--metricSamplingStrategy %s") - logFileReport = traits.Either(traits.Bool, File(), hash_files=False, desc="A file to write out final information report in CSV file: MetricName,MetricValue,FixedImageName,FixedMaskName,MovingImageName,MovingMaskName", argstr="--logFileReport %s") - writeOutputTransformInFloat = traits.Bool(desc="By default, the output registration transforms (either the output composite transform or each transform component) are written to the disk in double precision. If this flag is ON, the output transforms will be written in single (float) precision. It is especially important if the output transform is a displacement field transform, or it is a composite transform that includes several displacement fields.", argstr="--writeOutputTransformInFloat ") + desc= + "From itkLBFGSBOptimizer.h: Set/Get the CostFunctionConvergenceFactor. Algorithm terminates when the reduction in cost function is less than (factor * epsmcj) where epsmch is the machine precision. Typical values for factor: 1e+12 for low accuracy; 1e+7 for moderate accuracy and 1e+1 for extremely high accuracy. 1e+9 seems to work well., ", + argstr="--costFunctionConvergenceFactor %f") + projectedGradientTolerance = traits.Float( + desc= + "From itkLBFGSBOptimizer.h: Set/Get the ProjectedGradientTolerance. Algorithm terminates when the project gradient is below the tolerance. Default lbfgsb value is 1e-5, but 1e-4 seems to work well., ", + argstr="--projectedGradientTolerance %f") + maximumNumberOfEvaluations = traits.Int( + desc= + "Maximum number of evaluations for line search in lbfgsb optimizer.", + argstr="--maximumNumberOfEvaluations %d") + maximumNumberOfCorrections = traits.Int( + desc="Maximum number of corrections in lbfgsb optimizer.", + argstr="--maximumNumberOfCorrections %d") + gui = traits.Bool( + desc= + "Display intermediate image volumes for debugging. NOTE: This is not part of the standard build sytem, and probably does nothing on your installation.", + argstr="--gui ") + promptUser = traits.Bool( + desc= + "Prompt the user to hit enter each time an image is sent to the DebugImageViewer", + argstr="--promptUser ") + metricSamplingStrategy = traits.Enum( + "Random", + desc= + "It defines the method that registration filter uses to sample the input fixed image. Only Random is supported for now.", + argstr="--metricSamplingStrategy %s") + logFileReport = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "A file to write out final information report in CSV file: MetricName,MetricValue,FixedImageName,FixedMaskName,MovingImageName,MovingMaskName", + argstr="--logFileReport %s") + writeOutputTransformInFloat = traits.Bool( + desc= + "By default, the output registration transforms (either the output composite transform or each transform component) are written to the disk in double precision. If this flag is ON, the output transforms will be written in single (float) precision. It is especially important if the output transform is a displacement field transform, or it is a composite transform that includes several displacement fields.", + argstr="--writeOutputTransformInFloat ") class BRAINSFitOutputSpec(TraitedSpec): - linearTransform = File(desc="(optional) Output estimated transform - in case the computed transform is not BSpline. NOTE: You must set at least one output object (transform and/or output volume).", exists=True) - bsplineTransform = File(desc="(optional) Output estimated transform - in case the computed transform is BSpline. NOTE: You must set at least one output object (transform and/or output volume).", exists=True) - outputVolume = File(desc="(optional) Output image: the moving image warped to the fixed image space. NOTE: You must set at least one output object (transform and/or output volume).", exists=True) - outputFixedVolumeROI = File(desc="ROI that is automatically computed from the fixed image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", exists=True) - outputMovingVolumeROI = File(desc="ROI that is automatically computed from the moving image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", exists=True) - strippedOutputTransform = File(desc="Rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overridden if either bsplineTransform or linearTransform is set.", exists=True) - outputTransform = File(desc="(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", exists=True) - logFileReport = File(desc="A file to write out final information report in CSV file: MetricName,MetricValue,FixedImageName,FixedMaskName,MovingImageName,MovingMaskName", exists=True) + linearTransform = File( + desc= + "(optional) Output estimated transform - in case the computed transform is not BSpline. NOTE: You must set at least one output object (transform and/or output volume).", + exists=True) + bsplineTransform = File( + desc= + "(optional) Output estimated transform - in case the computed transform is BSpline. NOTE: You must set at least one output object (transform and/or output volume).", + exists=True) + outputVolume = File( + desc= + "(optional) Output image: the moving image warped to the fixed image space. NOTE: You must set at least one output object (transform and/or output volume).", + exists=True) + outputFixedVolumeROI = File( + desc= + "ROI that is automatically computed from the fixed image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", + exists=True) + outputMovingVolumeROI = File( + desc= + "ROI that is automatically computed from the moving image. Only available if Masking Option is ROIAUTO. Image areas where the mask volume has zero value are ignored during the registration.", + exists=True) + strippedOutputTransform = File( + desc= + "Rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overridden if either bsplineTransform or linearTransform is set.", + exists=True) + outputTransform = File( + desc= + "(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", + exists=True) + logFileReport = File( + desc= + "A file to write out final information report in CSV file: MetricName,MetricValue,FixedImageName,FixedMaskName,MovingImageName,MovingMaskName", + exists=True) class BRAINSFit(SEMLikeCommandLine): - """title: General Registration (BRAINS) category: Registration @@ -133,6 +398,14 @@ class BRAINSFit(SEMLikeCommandLine): input_spec = BRAINSFitInputSpec output_spec = BRAINSFitOutputSpec _cmd = " BRAINSFit " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'bsplineTransform': 'bsplineTransform.h5', 'outputTransform': 'outputTransform.h5', 'outputFixedVolumeROI': 'outputFixedVolumeROI.nii', - 'strippedOutputTransform': 'strippedOutputTransform.h5', 'outputMovingVolumeROI': 'outputMovingVolumeROI.nii', 'linearTransform': 'linearTransform.h5', 'logFileReport': 'logFileReport'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'bsplineTransform': 'bsplineTransform.h5', + 'outputTransform': 'outputTransform.h5', + 'outputFixedVolumeROI': 'outputFixedVolumeROI.nii', + 'strippedOutputTransform': 'strippedOutputTransform.h5', + 'outputMovingVolumeROI': 'outputMovingVolumeROI.nii', + 'linearTransform': 'linearTransform.h5', + 'logFileReport': 'logFileReport' + } _redirect_x = False diff --git a/nipype/interfaces/semtools/registration/brainsresample.py b/nipype/interfaces/semtools/registration/brainsresample.py index 988b83a56e..f9ea80acbd 100644 --- a/nipype/interfaces/semtools/registration/brainsresample.py +++ b/nipype/interfaces/semtools/registration/brainsresample.py @@ -11,20 +11,69 @@ class BRAINSResampleInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Image To Warp", exists=True, argstr="--inputVolume %s") - referenceVolume = File(desc="Reference image used only to define the output space. If not specified, the warping is done in the same space as the image to warp.", exists=True, argstr="--referenceVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Resulting deformed image", argstr="--outputVolume %s") - pixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", "binary", - desc="Specifies the pixel type for the input/output images. The \'binary\' pixel type uses a modified algorithm whereby the image is read in as unsigned char, a signed distance map is created, signed distance map is resampled, and then a thresholded image of type unsigned char is written to disk.", argstr="--pixelType %s") - deformationVolume = File(desc="Displacement Field to be used to warp the image (ITKv3 or earlier)", exists=True, argstr="--deformationVolume %s") - warpTransform = File(desc="Filename for the BRAINSFit transform (ITKv3 or earlier) or composite transform file (ITKv4)", exists=True, argstr="--warpTransform %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", - desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - inverseTransform = traits.Bool(desc="True/False is to compute inverse of given transformation. Default is false", argstr="--inverseTransform ") - defaultValue = traits.Float(desc="Default voxel value", argstr="--defaultValue %f") + inputVolume = File( + desc="Image To Warp", exists=True, argstr="--inputVolume %s") + referenceVolume = File( + desc= + "Reference image used only to define the output space. If not specified, the warping is done in the same space as the image to warp.", + exists=True, + argstr="--referenceVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Resulting deformed image", + argstr="--outputVolume %s") + pixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uint", + "uchar", + "binary", + desc= + "Specifies the pixel type for the input/output images. The \'binary\' pixel type uses a modified algorithm whereby the image is read in as unsigned char, a signed distance map is created, signed distance map is resampled, and then a thresholded image of type unsigned char is written to disk.", + argstr="--pixelType %s") + deformationVolume = File( + desc= + "Displacement Field to be used to warp the image (ITKv3 or earlier)", + exists=True, + argstr="--deformationVolume %s") + warpTransform = File( + desc= + "Filename for the BRAINSFit transform (ITKv3 or earlier) or composite transform file (ITKv4)", + exists=True, + argstr="--warpTransform %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + inverseTransform = traits.Bool( + desc= + "True/False is to compute inverse of given transformation. Default is false", + argstr="--inverseTransform ") + defaultValue = traits.Float( + desc="Default voxel value", argstr="--defaultValue %f") gridSpacing = InputMultiPath( - traits.Int, desc="Add warped grid to output image to help show the deformation that occured with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for makeing a 2D image of grid lines from the 3D space", sep=",", argstr="--gridSpacing %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + traits.Int, + desc= + "Add warped grid to output image to help show the deformation that occured with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for makeing a 2D image of grid lines from the 3D space", + sep=",", + argstr="--gridSpacing %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSResampleOutputSpec(TraitedSpec): @@ -32,7 +81,6 @@ class BRAINSResampleOutputSpec(TraitedSpec): class BRAINSResample(SEMLikeCommandLine): - """title: Resample Image (BRAINS) category: Registration diff --git a/nipype/interfaces/semtools/registration/brainsresize.py b/nipype/interfaces/semtools/registration/brainsresize.py index 3c05047109..11238dd914 100644 --- a/nipype/interfaces/semtools/registration/brainsresize.py +++ b/nipype/interfaces/semtools/registration/brainsresize.py @@ -11,11 +11,28 @@ class BRAINSResizeInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Image To Scale", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Resulting scaled image", argstr="--outputVolume %s") - pixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", "binary", - desc="Specifies the pixel type for the input/output images. The \'binary\' pixel type uses a modified algorithm whereby the image is read in as unsigned char, a signed distance map is created, signed distance map is resampled, and then a thresholded image of type unsigned char is written to disk.", argstr="--pixelType %s") - scaleFactor = traits.Float(desc="The scale factor for the image spacing.", argstr="--scaleFactor %f") + inputVolume = File( + desc="Image To Scale", exists=True, argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Resulting scaled image", + argstr="--outputVolume %s") + pixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uint", + "uchar", + "binary", + desc= + "Specifies the pixel type for the input/output images. The \'binary\' pixel type uses a modified algorithm whereby the image is read in as unsigned char, a signed distance map is created, signed distance map is resampled, and then a thresholded image of type unsigned char is written to disk.", + argstr="--pixelType %s") + scaleFactor = traits.Float( + desc="The scale factor for the image spacing.", + argstr="--scaleFactor %f") class BRAINSResizeOutputSpec(TraitedSpec): @@ -23,7 +40,6 @@ class BRAINSResizeOutputSpec(TraitedSpec): class BRAINSResize(SEMLikeCommandLine): - """title: Resize Image (BRAINS) category: Registration diff --git a/nipype/interfaces/semtools/registration/specialized.py b/nipype/interfaces/semtools/registration/specialized.py index 91cfa66a8e..2cc08e3ec7 100644 --- a/nipype/interfaces/semtools/registration/specialized.py +++ b/nipype/interfaces/semtools/registration/specialized.py @@ -11,58 +11,225 @@ class VBRAINSDemonWarpInputSpec(CommandLineInputSpec): - movingVolume = InputMultiPath(File(exists=True), desc="Required: input moving image", argstr="--movingVolume %s...") - fixedVolume = InputMultiPath(File(exists=True), desc="Required: input fixed (target) image", argstr="--fixedVolume %s...") - inputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="Input volumes will be typecast to this format: float|short|ushort|int|uchar", argstr="--inputPixelType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", argstr="--outputVolume %s") - outputDisplacementFieldVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", argstr="--outputDisplacementFieldVolume %s") - outputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="outputVolume will be typecast to this format: float|short|ushort|int|uchar", argstr="--outputPixelType %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", - desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - registrationFilterType = traits.Enum("Demons", "FastSymmetricForces", "Diffeomorphic", "LogDemons", "SymmetricLogDemons", desc="Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic|LogDemons|SymmetricLogDemons", argstr="--registrationFilterType %s") - smoothDisplacementFieldSigma = traits.Float(desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", argstr="--smoothDisplacementFieldSigma %f") - numberOfPyramidLevels = traits.Int(desc="Number of image pyramid levels to use in the multi-resolution registration.", argstr="--numberOfPyramidLevels %d") - minimumFixedPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumFixedPyramid %s") - minimumMovingPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumMovingPyramid %s") - arrayOfPyramidLevelIterations = InputMultiPath(traits.Int, desc="The number of iterations for each pyramid level", sep=",", argstr="--arrayOfPyramidLevelIterations %s") - histogramMatch = traits.Bool(desc="Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", argstr="--histogramMatch ") - numberOfHistogramBins = traits.Int(desc="The number of histogram levels", argstr="--numberOfHistogramBins %d") - numberOfMatchPoints = traits.Int(desc="The number of match points for histrogramMatch", argstr="--numberOfMatchPoints %d") - medianFilterSize = InputMultiPath(traits.Int, desc="Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", sep=",", argstr="--medianFilterSize %s") - initializeWithDisplacementField = File(desc="Initial deformation field vector image file name", exists=True, argstr="--initializeWithDisplacementField %s") - initializeWithTransform = File(desc="Initial Transform filename", exists=True, argstr="--initializeWithTransform %s") - makeBOBF = traits.Bool(desc="Flag to make Brain-Only Background-Filled versions of the input and target volumes.", argstr="--makeBOBF ") - fixedBinaryVolume = File(desc="Mask filename for desired region of interest in the Fixed image.", exists=True, argstr="--fixedBinaryVolume %s") - movingBinaryVolume = File(desc="Mask filename for desired region of interest in the Moving image.", exists=True, argstr="--movingBinaryVolume %s") - lowerThresholdForBOBF = traits.Int(desc="Lower threshold for performing BOBF", argstr="--lowerThresholdForBOBF %d") - upperThresholdForBOBF = traits.Int(desc="Upper threshold for performing BOBF", argstr="--upperThresholdForBOBF %d") - backgroundFillValue = traits.Int(desc="Replacement value to overwrite background when performing BOBF", argstr="--backgroundFillValue %d") - seedForBOBF = InputMultiPath(traits.Int, desc="coordinates in all 3 directions for Seed when performing BOBF", sep=",", argstr="--seedForBOBF %s") - neighborhoodForBOBF = InputMultiPath(traits.Int, desc="neighborhood in all 3 directions to be included when performing BOBF", sep=",", argstr="--neighborhoodForBOBF %s") - outputDisplacementFieldPrefix = traits.Str(desc="Displacement field filename prefix for writing separate x, y, and z component images", argstr="--outputDisplacementFieldPrefix %s") - outputCheckerboardVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", argstr="--outputCheckerboardVolume %s") - checkerboardPatternSubdivisions = InputMultiPath(traits.Int, desc="Number of Checkerboard subdivisions in all 3 directions", sep=",", argstr="--checkerboardPatternSubdivisions %s") - outputNormalized = traits.Bool(desc="Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", argstr="--outputNormalized ") - outputDebug = traits.Bool(desc="Flag to write debugging images after each step.", argstr="--outputDebug ") - weightFactors = InputMultiPath(traits.Float, desc="Weight fatctors for each input images", sep=",", argstr="--weightFactors %s") - gradient_type = traits.Enum("0", "1", "2", desc="Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", argstr="--gradient_type %s") - upFieldSmoothing = traits.Float(desc="Smoothing sigma for the update field at each iteration", argstr="--upFieldSmoothing %f") - max_step_length = traits.Float(desc="Maximum length of an update vector (0: no restriction)", argstr="--max_step_length %f") - use_vanilla_dem = traits.Bool(desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") - gui = traits.Bool(desc="Display intermediate image volumes for debugging", argstr="--gui ") - promptUser = traits.Bool(desc="Prompt the user to hit enter each time an image is sent to the DebugImageViewer", argstr="--promptUser ") - numberOfBCHApproximationTerms = traits.Int(desc="Number of terms in the BCH expansion", argstr="--numberOfBCHApproximationTerms %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + movingVolume = InputMultiPath( + File(exists=True), + desc="Required: input moving image", + argstr="--movingVolume %s...") + fixedVolume = InputMultiPath( + File(exists=True), + desc="Required: input fixed (target) image", + argstr="--fixedVolume %s...") + inputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "Input volumes will be typecast to this format: float|short|ushort|int|uchar", + argstr="--inputPixelType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + argstr="--outputVolume %s") + outputDisplacementFieldVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + argstr="--outputDisplacementFieldVolume %s") + outputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "outputVolume will be typecast to this format: float|short|ushort|int|uchar", + argstr="--outputPixelType %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + registrationFilterType = traits.Enum( + "Demons", + "FastSymmetricForces", + "Diffeomorphic", + "LogDemons", + "SymmetricLogDemons", + desc= + "Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic|LogDemons|SymmetricLogDemons", + argstr="--registrationFilterType %s") + smoothDisplacementFieldSigma = traits.Float( + desc= + "A gaussian smoothing value to be applied to the deformation feild at each iteration.", + argstr="--smoothDisplacementFieldSigma %f") + numberOfPyramidLevels = traits.Int( + desc= + "Number of image pyramid levels to use in the multi-resolution registration.", + argstr="--numberOfPyramidLevels %d") + minimumFixedPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumFixedPyramid %s") + minimumMovingPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumMovingPyramid %s") + arrayOfPyramidLevelIterations = InputMultiPath( + traits.Int, + desc="The number of iterations for each pyramid level", + sep=",", + argstr="--arrayOfPyramidLevelIterations %s") + histogramMatch = traits.Bool( + desc= + "Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", + argstr="--histogramMatch ") + numberOfHistogramBins = traits.Int( + desc="The number of histogram levels", + argstr="--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( + desc="The number of match points for histrogramMatch", + argstr="--numberOfMatchPoints %d") + medianFilterSize = InputMultiPath( + traits.Int, + desc= + "Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", + sep=",", + argstr="--medianFilterSize %s") + initializeWithDisplacementField = File( + desc="Initial deformation field vector image file name", + exists=True, + argstr="--initializeWithDisplacementField %s") + initializeWithTransform = File( + desc="Initial Transform filename", + exists=True, + argstr="--initializeWithTransform %s") + makeBOBF = traits.Bool( + desc= + "Flag to make Brain-Only Background-Filled versions of the input and target volumes.", + argstr="--makeBOBF ") + fixedBinaryVolume = File( + desc="Mask filename for desired region of interest in the Fixed image.", + exists=True, + argstr="--fixedBinaryVolume %s") + movingBinaryVolume = File( + desc= + "Mask filename for desired region of interest in the Moving image.", + exists=True, + argstr="--movingBinaryVolume %s") + lowerThresholdForBOBF = traits.Int( + desc="Lower threshold for performing BOBF", + argstr="--lowerThresholdForBOBF %d") + upperThresholdForBOBF = traits.Int( + desc="Upper threshold for performing BOBF", + argstr="--upperThresholdForBOBF %d") + backgroundFillValue = traits.Int( + desc="Replacement value to overwrite background when performing BOBF", + argstr="--backgroundFillValue %d") + seedForBOBF = InputMultiPath( + traits.Int, + desc="coordinates in all 3 directions for Seed when performing BOBF", + sep=",", + argstr="--seedForBOBF %s") + neighborhoodForBOBF = InputMultiPath( + traits.Int, + desc= + "neighborhood in all 3 directions to be included when performing BOBF", + sep=",", + argstr="--neighborhoodForBOBF %s") + outputDisplacementFieldPrefix = traits.Str( + desc= + "Displacement field filename prefix for writing separate x, y, and z component images", + argstr="--outputDisplacementFieldPrefix %s") + outputCheckerboardVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + argstr="--outputCheckerboardVolume %s") + checkerboardPatternSubdivisions = InputMultiPath( + traits.Int, + desc="Number of Checkerboard subdivisions in all 3 directions", + sep=",", + argstr="--checkerboardPatternSubdivisions %s") + outputNormalized = traits.Bool( + desc= + "Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", + argstr="--outputNormalized ") + outputDebug = traits.Bool( + desc="Flag to write debugging images after each step.", + argstr="--outputDebug ") + weightFactors = InputMultiPath( + traits.Float, + desc="Weight fatctors for each input images", + sep=",", + argstr="--weightFactors %s") + gradient_type = traits.Enum( + "0", + "1", + "2", + desc= + "Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", + argstr="--gradient_type %s") + upFieldSmoothing = traits.Float( + desc="Smoothing sigma for the update field at each iteration", + argstr="--upFieldSmoothing %f") + max_step_length = traits.Float( + desc="Maximum length of an update vector (0: no restriction)", + argstr="--max_step_length %f") + use_vanilla_dem = traits.Bool( + desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") + gui = traits.Bool( + desc="Display intermediate image volumes for debugging", + argstr="--gui ") + promptUser = traits.Bool( + desc= + "Prompt the user to hit enter each time an image is sent to the DebugImageViewer", + argstr="--promptUser ") + numberOfBCHApproximationTerms = traits.Int( + desc="Number of terms in the BCH expansion", + argstr="--numberOfBCHApproximationTerms %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class VBRAINSDemonWarpOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", exists=True) - outputDisplacementFieldVolume = File(desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", exists=True) - outputCheckerboardVolume = File(desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", exists=True) + outputVolume = File( + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + exists=True) + outputDisplacementFieldVolume = File( + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + exists=True) + outputCheckerboardVolume = File( + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + exists=True) class VBRAINSDemonWarp(SEMLikeCommandLine): - """title: Vector Demon Registration (BRAINS) category: Registration.Specialized @@ -84,63 +251,231 @@ class VBRAINSDemonWarp(SEMLikeCommandLine): input_spec = VBRAINSDemonWarpInputSpec output_spec = VBRAINSDemonWarpOutputSpec _cmd = " VBRAINSDemonWarp " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', + 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd' + } _redirect_x = False class BRAINSDemonWarpInputSpec(CommandLineInputSpec): - movingVolume = File(desc="Required: input moving image", exists=True, argstr="--movingVolume %s") - fixedVolume = File(desc="Required: input fixed (target) image", exists=True, argstr="--fixedVolume %s") - inputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="Input volumes will be typecast to this format: float|short|ushort|int|uchar", argstr="--inputPixelType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", argstr="--outputVolume %s") - outputDisplacementFieldVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", argstr="--outputDisplacementFieldVolume %s") - outputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="outputVolume will be typecast to this format: float|short|ushort|int|uchar", argstr="--outputPixelType %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", - desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - registrationFilterType = traits.Enum("Demons", "FastSymmetricForces", "Diffeomorphic", desc="Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic", argstr="--registrationFilterType %s") - smoothDisplacementFieldSigma = traits.Float(desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", argstr="--smoothDisplacementFieldSigma %f") - numberOfPyramidLevels = traits.Int(desc="Number of image pyramid levels to use in the multi-resolution registration.", argstr="--numberOfPyramidLevels %d") - minimumFixedPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumFixedPyramid %s") - minimumMovingPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumMovingPyramid %s") - arrayOfPyramidLevelIterations = InputMultiPath(traits.Int, desc="The number of iterations for each pyramid level", sep=",", argstr="--arrayOfPyramidLevelIterations %s") - histogramMatch = traits.Bool(desc="Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", argstr="--histogramMatch ") - numberOfHistogramBins = traits.Int(desc="The number of histogram levels", argstr="--numberOfHistogramBins %d") - numberOfMatchPoints = traits.Int(desc="The number of match points for histrogramMatch", argstr="--numberOfMatchPoints %d") - medianFilterSize = InputMultiPath(traits.Int, desc="Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", sep=",", argstr="--medianFilterSize %s") - initializeWithDisplacementField = File(desc="Initial deformation field vector image file name", exists=True, argstr="--initializeWithDisplacementField %s") - initializeWithTransform = File(desc="Initial Transform filename", exists=True, argstr="--initializeWithTransform %s") + movingVolume = File( + desc="Required: input moving image", + exists=True, + argstr="--movingVolume %s") + fixedVolume = File( + desc="Required: input fixed (target) image", + exists=True, + argstr="--fixedVolume %s") + inputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "Input volumes will be typecast to this format: float|short|ushort|int|uchar", + argstr="--inputPixelType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + argstr="--outputVolume %s") + outputDisplacementFieldVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + argstr="--outputDisplacementFieldVolume %s") + outputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "outputVolume will be typecast to this format: float|short|ushort|int|uchar", + argstr="--outputPixelType %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + registrationFilterType = traits.Enum( + "Demons", + "FastSymmetricForces", + "Diffeomorphic", + desc= + "Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic", + argstr="--registrationFilterType %s") + smoothDisplacementFieldSigma = traits.Float( + desc= + "A gaussian smoothing value to be applied to the deformation feild at each iteration.", + argstr="--smoothDisplacementFieldSigma %f") + numberOfPyramidLevels = traits.Int( + desc= + "Number of image pyramid levels to use in the multi-resolution registration.", + argstr="--numberOfPyramidLevels %d") + minimumFixedPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumFixedPyramid %s") + minimumMovingPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumMovingPyramid %s") + arrayOfPyramidLevelIterations = InputMultiPath( + traits.Int, + desc="The number of iterations for each pyramid level", + sep=",", + argstr="--arrayOfPyramidLevelIterations %s") + histogramMatch = traits.Bool( + desc= + "Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", + argstr="--histogramMatch ") + numberOfHistogramBins = traits.Int( + desc="The number of histogram levels", + argstr="--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( + desc="The number of match points for histrogramMatch", + argstr="--numberOfMatchPoints %d") + medianFilterSize = InputMultiPath( + traits.Int, + desc= + "Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", + sep=",", + argstr="--medianFilterSize %s") + initializeWithDisplacementField = File( + desc="Initial deformation field vector image file name", + exists=True, + argstr="--initializeWithDisplacementField %s") + initializeWithTransform = File( + desc="Initial Transform filename", + exists=True, + argstr="--initializeWithTransform %s") maskProcessingMode = traits.Enum( - "NOMASK", "ROIAUTO", "ROI", "BOBF", desc="What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", argstr="--maskProcessingMode %s") - fixedBinaryVolume = File(desc="Mask filename for desired region of interest in the Fixed image.", exists=True, argstr="--fixedBinaryVolume %s") - movingBinaryVolume = File(desc="Mask filename for desired region of interest in the Moving image.", exists=True, argstr="--movingBinaryVolume %s") - lowerThresholdForBOBF = traits.Int(desc="Lower threshold for performing BOBF", argstr="--lowerThresholdForBOBF %d") - upperThresholdForBOBF = traits.Int(desc="Upper threshold for performing BOBF", argstr="--upperThresholdForBOBF %d") - backgroundFillValue = traits.Int(desc="Replacement value to overwrite background when performing BOBF", argstr="--backgroundFillValue %d") - seedForBOBF = InputMultiPath(traits.Int, desc="coordinates in all 3 directions for Seed when performing BOBF", sep=",", argstr="--seedForBOBF %s") - neighborhoodForBOBF = InputMultiPath(traits.Int, desc="neighborhood in all 3 directions to be included when performing BOBF", sep=",", argstr="--neighborhoodForBOBF %s") - outputDisplacementFieldPrefix = traits.Str(desc="Displacement field filename prefix for writing separate x, y, and z component images", argstr="--outputDisplacementFieldPrefix %s") - outputCheckerboardVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", argstr="--outputCheckerboardVolume %s") - checkerboardPatternSubdivisions = InputMultiPath(traits.Int, desc="Number of Checkerboard subdivisions in all 3 directions", sep=",", argstr="--checkerboardPatternSubdivisions %s") - outputNormalized = traits.Bool(desc="Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", argstr="--outputNormalized ") - outputDebug = traits.Bool(desc="Flag to write debugging images after each step.", argstr="--outputDebug ") - gradient_type = traits.Enum("0", "1", "2", desc="Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", argstr="--gradient_type %s") - upFieldSmoothing = traits.Float(desc="Smoothing sigma for the update field at each iteration", argstr="--upFieldSmoothing %f") - max_step_length = traits.Float(desc="Maximum length of an update vector (0: no restriction)", argstr="--max_step_length %f") - use_vanilla_dem = traits.Bool(desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") - gui = traits.Bool(desc="Display intermediate image volumes for debugging", argstr="--gui ") - promptUser = traits.Bool(desc="Prompt the user to hit enter each time an image is sent to the DebugImageViewer", argstr="--promptUser ") - numberOfBCHApproximationTerms = traits.Int(desc="Number of terms in the BCH expansion", argstr="--numberOfBCHApproximationTerms %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + "NOMASK", + "ROIAUTO", + "ROI", + "BOBF", + desc= + "What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", + argstr="--maskProcessingMode %s") + fixedBinaryVolume = File( + desc="Mask filename for desired region of interest in the Fixed image.", + exists=True, + argstr="--fixedBinaryVolume %s") + movingBinaryVolume = File( + desc= + "Mask filename for desired region of interest in the Moving image.", + exists=True, + argstr="--movingBinaryVolume %s") + lowerThresholdForBOBF = traits.Int( + desc="Lower threshold for performing BOBF", + argstr="--lowerThresholdForBOBF %d") + upperThresholdForBOBF = traits.Int( + desc="Upper threshold for performing BOBF", + argstr="--upperThresholdForBOBF %d") + backgroundFillValue = traits.Int( + desc="Replacement value to overwrite background when performing BOBF", + argstr="--backgroundFillValue %d") + seedForBOBF = InputMultiPath( + traits.Int, + desc="coordinates in all 3 directions for Seed when performing BOBF", + sep=",", + argstr="--seedForBOBF %s") + neighborhoodForBOBF = InputMultiPath( + traits.Int, + desc= + "neighborhood in all 3 directions to be included when performing BOBF", + sep=",", + argstr="--neighborhoodForBOBF %s") + outputDisplacementFieldPrefix = traits.Str( + desc= + "Displacement field filename prefix for writing separate x, y, and z component images", + argstr="--outputDisplacementFieldPrefix %s") + outputCheckerboardVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + argstr="--outputCheckerboardVolume %s") + checkerboardPatternSubdivisions = InputMultiPath( + traits.Int, + desc="Number of Checkerboard subdivisions in all 3 directions", + sep=",", + argstr="--checkerboardPatternSubdivisions %s") + outputNormalized = traits.Bool( + desc= + "Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", + argstr="--outputNormalized ") + outputDebug = traits.Bool( + desc="Flag to write debugging images after each step.", + argstr="--outputDebug ") + gradient_type = traits.Enum( + "0", + "1", + "2", + desc= + "Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", + argstr="--gradient_type %s") + upFieldSmoothing = traits.Float( + desc="Smoothing sigma for the update field at each iteration", + argstr="--upFieldSmoothing %f") + max_step_length = traits.Float( + desc="Maximum length of an update vector (0: no restriction)", + argstr="--max_step_length %f") + use_vanilla_dem = traits.Bool( + desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") + gui = traits.Bool( + desc="Display intermediate image volumes for debugging", + argstr="--gui ") + promptUser = traits.Bool( + desc= + "Prompt the user to hit enter each time an image is sent to the DebugImageViewer", + argstr="--promptUser ") + numberOfBCHApproximationTerms = traits.Int( + desc="Number of terms in the BCH expansion", + argstr="--numberOfBCHApproximationTerms %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSDemonWarpOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", exists=True) - outputDisplacementFieldVolume = File(desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", exists=True) - outputCheckerboardVolume = File(desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", exists=True) + outputVolume = File( + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + exists=True) + outputDisplacementFieldVolume = File( + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + exists=True) + outputCheckerboardVolume = File( + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + exists=True) class BRAINSDemonWarp(SEMLikeCommandLine): - """title: Demon Registration (BRAINS) category: Registration.Specialized @@ -162,26 +497,54 @@ class BRAINSDemonWarp(SEMLikeCommandLine): input_spec = BRAINSDemonWarpInputSpec output_spec = BRAINSDemonWarpOutputSpec _cmd = " BRAINSDemonWarp " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', + 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd' + } _redirect_x = False class BRAINSTransformFromFiducialsInputSpec(CommandLineInputSpec): - fixedLandmarks = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="Ordered list of landmarks in the fixed image", argstr="--fixedLandmarks %s...") - movingLandmarks = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="Ordered list of landmarks in the moving image", argstr="--movingLandmarks %s...") - saveTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Save the transform that results from registration", argstr="--saveTransform %s") - transformType = traits.Enum("Translation", "Rigid", "Similarity", desc="Type of transform to produce", argstr="--transformType %s") - fixedLandmarksFile = File(desc="An fcsv formatted file with a list of landmark points.", exists=True, argstr="--fixedLandmarksFile %s") - movingLandmarksFile = File(desc="An fcsv formatted file with a list of landmark points.", exists=True, argstr="--movingLandmarksFile %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + fixedLandmarks = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc="Ordered list of landmarks in the fixed image", + argstr="--fixedLandmarks %s...") + movingLandmarks = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc="Ordered list of landmarks in the moving image", + argstr="--movingLandmarks %s...") + saveTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Save the transform that results from registration", + argstr="--saveTransform %s") + transformType = traits.Enum( + "Translation", + "Rigid", + "Similarity", + desc="Type of transform to produce", + argstr="--transformType %s") + fixedLandmarksFile = File( + desc="An fcsv formatted file with a list of landmark points.", + exists=True, + argstr="--fixedLandmarksFile %s") + movingLandmarksFile = File( + desc="An fcsv formatted file with a list of landmark points.", + exists=True, + argstr="--movingLandmarksFile %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSTransformFromFiducialsOutputSpec(TraitedSpec): - saveTransform = File(desc="Save the transform that results from registration", exists=True) + saveTransform = File( + desc="Save the transform that results from registration", exists=True) class BRAINSTransformFromFiducials(SEMLikeCommandLine): - """title: Fiducial Registration (BRAINS) category: Registration.Specialized diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py index 3df134093f..535122ef38 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py @@ -4,120 +4,106 @@ def test_BRAINSDemonWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - arrayOfPyramidLevelIterations=dict(argstr='--arrayOfPyramidLevelIterations %s', - sep=',', - ), - backgroundFillValue=dict(argstr='--backgroundFillValue %d', - ), - checkerboardPatternSubdivisions=dict(argstr='--checkerboardPatternSubdivisions %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', - ), - fixedVolume=dict(argstr='--fixedVolume %s', - ), - gradient_type=dict(argstr='--gradient_type %s', - ), - gui=dict(argstr='--gui ', - ), - histogramMatch=dict(argstr='--histogramMatch ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initializeWithDisplacementField=dict(argstr='--initializeWithDisplacementField %s', - ), - initializeWithTransform=dict(argstr='--initializeWithTransform %s', - ), - inputPixelType=dict(argstr='--inputPixelType %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', - ), - maskProcessingMode=dict(argstr='--maskProcessingMode %s', - ), - max_step_length=dict(argstr='--max_step_length %f', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - minimumFixedPyramid=dict(argstr='--minimumFixedPyramid %s', - sep=',', - ), - minimumMovingPyramid=dict(argstr='--minimumMovingPyramid %s', - sep=',', - ), - movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', - ), - movingVolume=dict(argstr='--movingVolume %s', - ), - neighborhoodForBOBF=dict(argstr='--neighborhoodForBOBF %s', - sep=',', - ), - numberOfBCHApproximationTerms=dict(argstr='--numberOfBCHApproximationTerms %d', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputCheckerboardVolume=dict(argstr='--outputCheckerboardVolume %s', - hash_files=False, - ), - outputDebug=dict(argstr='--outputDebug ', - ), - outputDisplacementFieldPrefix=dict(argstr='--outputDisplacementFieldPrefix %s', - ), - outputDisplacementFieldVolume=dict(argstr='--outputDisplacementFieldVolume %s', - hash_files=False, - ), - outputNormalized=dict(argstr='--outputNormalized ', - ), - outputPixelType=dict(argstr='--outputPixelType %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - promptUser=dict(argstr='--promptUser ', - ), - registrationFilterType=dict(argstr='--registrationFilterType %s', - ), - seedForBOBF=dict(argstr='--seedForBOBF %s', - sep=',', - ), - smoothDisplacementFieldSigma=dict(argstr='--smoothDisplacementFieldSigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', - ), - upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', - ), - use_vanilla_dem=dict(argstr='--use_vanilla_dem ', - ), + input_map = dict( + args=dict(argstr='%s', ), + arrayOfPyramidLevelIterations=dict( + argstr='--arrayOfPyramidLevelIterations %s', + sep=',', + ), + backgroundFillValue=dict(argstr='--backgroundFillValue %d', ), + checkerboardPatternSubdivisions=dict( + argstr='--checkerboardPatternSubdivisions %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', ), + fixedVolume=dict(argstr='--fixedVolume %s', ), + gradient_type=dict(argstr='--gradient_type %s', ), + gui=dict(argstr='--gui ', ), + histogramMatch=dict(argstr='--histogramMatch ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initializeWithDisplacementField=dict( + argstr='--initializeWithDisplacementField %s', ), + initializeWithTransform=dict(argstr='--initializeWithTransform %s', ), + inputPixelType=dict(argstr='--inputPixelType %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', ), + maskProcessingMode=dict(argstr='--maskProcessingMode %s', ), + max_step_length=dict(argstr='--max_step_length %f', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + minimumFixedPyramid=dict( + argstr='--minimumFixedPyramid %s', + sep=',', + ), + minimumMovingPyramid=dict( + argstr='--minimumMovingPyramid %s', + sep=',', + ), + movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', ), + movingVolume=dict(argstr='--movingVolume %s', ), + neighborhoodForBOBF=dict( + argstr='--neighborhoodForBOBF %s', + sep=',', + ), + numberOfBCHApproximationTerms=dict( + argstr='--numberOfBCHApproximationTerms %d', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputCheckerboardVolume=dict( + argstr='--outputCheckerboardVolume %s', + hash_files=False, + ), + outputDebug=dict(argstr='--outputDebug ', ), + outputDisplacementFieldPrefix=dict( + argstr='--outputDisplacementFieldPrefix %s', ), + outputDisplacementFieldVolume=dict( + argstr='--outputDisplacementFieldVolume %s', + hash_files=False, + ), + outputNormalized=dict(argstr='--outputNormalized ', ), + outputPixelType=dict(argstr='--outputPixelType %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + promptUser=dict(argstr='--promptUser ', ), + registrationFilterType=dict(argstr='--registrationFilterType %s', ), + seedForBOBF=dict( + argstr='--seedForBOBF %s', + sep=',', + ), + smoothDisplacementFieldSigma=dict( + argstr='--smoothDisplacementFieldSigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', ), + upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', ), + use_vanilla_dem=dict(argstr='--use_vanilla_dem ', ), ) inputs = BRAINSDemonWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSDemonWarp_outputs(): - output_map = dict(outputCheckerboardVolume=dict(), - outputDisplacementFieldVolume=dict(), - outputVolume=dict(), + output_map = dict( + outputCheckerboardVolume=dict(), + outputDisplacementFieldVolume=dict(), + outputVolume=dict(), ) outputs = BRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py index 00248d9093..e9dd62c406 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py @@ -4,178 +4,148 @@ def test_BRAINSFit_inputs(): - input_map = dict(ROIAutoClosingSize=dict(argstr='--ROIAutoClosingSize %f', - ), - ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', - ), - args=dict(argstr='%s', - ), - backgroundFillValue=dict(argstr='--backgroundFillValue %f', - ), - bsplineTransform=dict(argstr='--bsplineTransform %s', - hash_files=False, - ), - costFunctionConvergenceFactor=dict(argstr='--costFunctionConvergenceFactor %f', - ), - costMetric=dict(argstr='--costMetric %s', - ), - debugLevel=dict(argstr='--debugLevel %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - failureExitCode=dict(argstr='--failureExitCode %d', - ), - fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', - ), - fixedVolume=dict(argstr='--fixedVolume %s', - ), - fixedVolume2=dict(argstr='--fixedVolume2 %s', - ), - fixedVolumeTimeIndex=dict(argstr='--fixedVolumeTimeIndex %d', - ), - gui=dict(argstr='--gui ', - ), - histogramMatch=dict(argstr='--histogramMatch ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialTransform=dict(argstr='--initialTransform %s', - ), - initializeRegistrationByCurrentGenericTransform=dict(argstr='--initializeRegistrationByCurrentGenericTransform ', - ), - initializeTransformMode=dict(argstr='--initializeTransformMode %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - linearTransform=dict(argstr='--linearTransform %s', - hash_files=False, - ), - logFileReport=dict(argstr='--logFileReport %s', - hash_files=False, - ), - maskInferiorCutOffFromCenter=dict(argstr='--maskInferiorCutOffFromCenter %f', - ), - maskProcessingMode=dict(argstr='--maskProcessingMode %s', - ), - maxBSplineDisplacement=dict(argstr='--maxBSplineDisplacement %f', - ), - maximumNumberOfCorrections=dict(argstr='--maximumNumberOfCorrections %d', - ), - maximumNumberOfEvaluations=dict(argstr='--maximumNumberOfEvaluations %d', - ), - maximumStepLength=dict(argstr='--maximumStepLength %f', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - metricSamplingStrategy=dict(argstr='--metricSamplingStrategy %s', - ), - minimumStepLength=dict(argstr='--minimumStepLength %s', - sep=',', - ), - movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', - ), - movingVolume=dict(argstr='--movingVolume %s', - ), - movingVolume2=dict(argstr='--movingVolume2 %s', - ), - movingVolumeTimeIndex=dict(argstr='--movingVolumeTimeIndex %d', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfIterations=dict(argstr='--numberOfIterations %s', - sep=',', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - numberOfSamples=dict(argstr='--numberOfSamples %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputFixedVolumeROI=dict(argstr='--outputFixedVolumeROI %s', - hash_files=False, - ), - outputMovingVolumeROI=dict(argstr='--outputMovingVolumeROI %s', - hash_files=False, - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', - ), - projectedGradientTolerance=dict(argstr='--projectedGradientTolerance %f', - ), - promptUser=dict(argstr='--promptUser ', - ), - relaxationFactor=dict(argstr='--relaxationFactor %f', - ), - removeIntensityOutliers=dict(argstr='--removeIntensityOutliers %f', - ), - reproportionScale=dict(argstr='--reproportionScale %f', - ), - samplingPercentage=dict(argstr='--samplingPercentage %f', - ), - scaleOutputValues=dict(argstr='--scaleOutputValues ', - ), - skewScale=dict(argstr='--skewScale %f', - ), - splineGridSize=dict(argstr='--splineGridSize %s', - sep=',', - ), - strippedOutputTransform=dict(argstr='--strippedOutputTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - sep=',', - ), - translationScale=dict(argstr='--translationScale %f', - ), - useAffine=dict(argstr='--useAffine ', - ), - useBSpline=dict(argstr='--useBSpline ', - ), - useComposite=dict(argstr='--useComposite ', - ), - useROIBSpline=dict(argstr='--useROIBSpline ', - ), - useRigid=dict(argstr='--useRigid ', - ), - useScaleSkewVersor3D=dict(argstr='--useScaleSkewVersor3D ', - ), - useScaleVersor3D=dict(argstr='--useScaleVersor3D ', - ), - useSyN=dict(argstr='--useSyN ', - ), - writeOutputTransformInFloat=dict(argstr='--writeOutputTransformInFloat ', - ), - writeTransformOnFailure=dict(argstr='--writeTransformOnFailure ', - ), + input_map = dict( + ROIAutoClosingSize=dict(argstr='--ROIAutoClosingSize %f', ), + ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', ), + args=dict(argstr='%s', ), + backgroundFillValue=dict(argstr='--backgroundFillValue %f', ), + bsplineTransform=dict( + argstr='--bsplineTransform %s', + hash_files=False, + ), + costFunctionConvergenceFactor=dict( + argstr='--costFunctionConvergenceFactor %f', ), + costMetric=dict(argstr='--costMetric %s', ), + debugLevel=dict(argstr='--debugLevel %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + failureExitCode=dict(argstr='--failureExitCode %d', ), + fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', ), + fixedVolume=dict(argstr='--fixedVolume %s', ), + fixedVolume2=dict(argstr='--fixedVolume2 %s', ), + fixedVolumeTimeIndex=dict(argstr='--fixedVolumeTimeIndex %d', ), + gui=dict(argstr='--gui ', ), + histogramMatch=dict(argstr='--histogramMatch ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialTransform=dict(argstr='--initialTransform %s', ), + initializeRegistrationByCurrentGenericTransform=dict( + argstr='--initializeRegistrationByCurrentGenericTransform ', ), + initializeTransformMode=dict(argstr='--initializeTransformMode %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + linearTransform=dict( + argstr='--linearTransform %s', + hash_files=False, + ), + logFileReport=dict( + argstr='--logFileReport %s', + hash_files=False, + ), + maskInferiorCutOffFromCenter=dict( + argstr='--maskInferiorCutOffFromCenter %f', ), + maskProcessingMode=dict(argstr='--maskProcessingMode %s', ), + maxBSplineDisplacement=dict(argstr='--maxBSplineDisplacement %f', ), + maximumNumberOfCorrections=dict( + argstr='--maximumNumberOfCorrections %d', ), + maximumNumberOfEvaluations=dict( + argstr='--maximumNumberOfEvaluations %d', ), + maximumStepLength=dict(argstr='--maximumStepLength %f', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + metricSamplingStrategy=dict(argstr='--metricSamplingStrategy %s', ), + minimumStepLength=dict( + argstr='--minimumStepLength %s', + sep=',', + ), + movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', ), + movingVolume=dict(argstr='--movingVolume %s', ), + movingVolume2=dict(argstr='--movingVolume2 %s', ), + movingVolumeTimeIndex=dict(argstr='--movingVolumeTimeIndex %d', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfIterations=dict( + argstr='--numberOfIterations %s', + sep=',', + ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + numberOfSamples=dict(argstr='--numberOfSamples %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputFixedVolumeROI=dict( + argstr='--outputFixedVolumeROI %s', + hash_files=False, + ), + outputMovingVolumeROI=dict( + argstr='--outputMovingVolumeROI %s', + hash_files=False, + ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', ), + projectedGradientTolerance=dict( + argstr='--projectedGradientTolerance %f', ), + promptUser=dict(argstr='--promptUser ', ), + relaxationFactor=dict(argstr='--relaxationFactor %f', ), + removeIntensityOutliers=dict(argstr='--removeIntensityOutliers %f', ), + reproportionScale=dict(argstr='--reproportionScale %f', ), + samplingPercentage=dict(argstr='--samplingPercentage %f', ), + scaleOutputValues=dict(argstr='--scaleOutputValues ', ), + skewScale=dict(argstr='--skewScale %f', ), + splineGridSize=dict( + argstr='--splineGridSize %s', + sep=',', + ), + strippedOutputTransform=dict( + argstr='--strippedOutputTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict( + argstr='--transformType %s', + sep=',', + ), + translationScale=dict(argstr='--translationScale %f', ), + useAffine=dict(argstr='--useAffine ', ), + useBSpline=dict(argstr='--useBSpline ', ), + useComposite=dict(argstr='--useComposite ', ), + useROIBSpline=dict(argstr='--useROIBSpline ', ), + useRigid=dict(argstr='--useRigid ', ), + useScaleSkewVersor3D=dict(argstr='--useScaleSkewVersor3D ', ), + useScaleVersor3D=dict(argstr='--useScaleVersor3D ', ), + useSyN=dict(argstr='--useSyN ', ), + writeOutputTransformInFloat=dict( + argstr='--writeOutputTransformInFloat ', ), + writeTransformOnFailure=dict(argstr='--writeTransformOnFailure ', ), ) inputs = BRAINSFit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSFit_outputs(): - output_map = dict(bsplineTransform=dict(), - linearTransform=dict(), - logFileReport=dict(), - outputFixedVolumeROI=dict(), - outputMovingVolumeROI=dict(), - outputTransform=dict(), - outputVolume=dict(), - strippedOutputTransform=dict(), + output_map = dict( + bsplineTransform=dict(), + linearTransform=dict(), + logFileReport=dict(), + outputFixedVolumeROI=dict(), + outputMovingVolumeROI=dict(), + outputTransform=dict(), + outputVolume=dict(), + strippedOutputTransform=dict(), ) outputs = BRAINSFit.output_spec() diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py index a2444018e2..5a6e0beefe 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py @@ -4,53 +4,46 @@ def test_BRAINSResample_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - defaultValue=dict(argstr='--defaultValue %f', - ), - deformationVolume=dict(argstr='--deformationVolume %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gridSpacing=dict(argstr='--gridSpacing %s', - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - inverseTransform=dict(argstr='--inverseTransform ', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - pixelType=dict(argstr='--pixelType %s', - ), - referenceVolume=dict(argstr='--referenceVolume %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warpTransform=dict(argstr='--warpTransform %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + defaultValue=dict(argstr='--defaultValue %f', ), + deformationVolume=dict(argstr='--deformationVolume %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridSpacing=dict( + argstr='--gridSpacing %s', + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + inverseTransform=dict(argstr='--inverseTransform ', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + pixelType=dict(argstr='--pixelType %s', ), + referenceVolume=dict(argstr='--referenceVolume %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warpTransform=dict(argstr='--warpTransform %s', ), ) inputs = BRAINSResample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSResample_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py index c394a6cee1..7587bf648c 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py @@ -4,38 +4,36 @@ def test_BRAINSResize_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - pixelType=dict(argstr='--pixelType %s', - ), - scaleFactor=dict(argstr='--scaleFactor %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + pixelType=dict(argstr='--pixelType %s', ), + scaleFactor=dict(argstr='--scaleFactor %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSResize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSResize_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSResize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py index 928fa49e61..c7e25825b9 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py @@ -4,44 +4,39 @@ def test_BRAINSTransformFromFiducials_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedLandmarks=dict(argstr='--fixedLandmarks %s...', - ), - fixedLandmarksFile=dict(argstr='--fixedLandmarksFile %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - movingLandmarks=dict(argstr='--movingLandmarks %s...', - ), - movingLandmarksFile=dict(argstr='--movingLandmarksFile %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - saveTransform=dict(argstr='--saveTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedLandmarks=dict(argstr='--fixedLandmarks %s...', ), + fixedLandmarksFile=dict(argstr='--fixedLandmarksFile %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + movingLandmarks=dict(argstr='--movingLandmarks %s...', ), + movingLandmarksFile=dict(argstr='--movingLandmarksFile %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + saveTransform=dict( + argstr='--saveTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict(argstr='--transformType %s', ), ) inputs = BRAINSTransformFromFiducials.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSTransformFromFiducials_outputs(): - output_map = dict(saveTransform=dict(), - ) + output_map = dict(saveTransform=dict(), ) outputs = BRAINSTransformFromFiducials.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py b/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py index 1fd9c45b34..d4e7c12a7f 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py @@ -4,123 +4,110 @@ def test_VBRAINSDemonWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - arrayOfPyramidLevelIterations=dict(argstr='--arrayOfPyramidLevelIterations %s', - sep=',', - ), - backgroundFillValue=dict(argstr='--backgroundFillValue %d', - ), - checkerboardPatternSubdivisions=dict(argstr='--checkerboardPatternSubdivisions %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', - ), - fixedVolume=dict(argstr='--fixedVolume %s...', - ), - gradient_type=dict(argstr='--gradient_type %s', - ), - gui=dict(argstr='--gui ', - ), - histogramMatch=dict(argstr='--histogramMatch ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initializeWithDisplacementField=dict(argstr='--initializeWithDisplacementField %s', - ), - initializeWithTransform=dict(argstr='--initializeWithTransform %s', - ), - inputPixelType=dict(argstr='--inputPixelType %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', - ), - makeBOBF=dict(argstr='--makeBOBF ', - ), - max_step_length=dict(argstr='--max_step_length %f', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - minimumFixedPyramid=dict(argstr='--minimumFixedPyramid %s', - sep=',', - ), - minimumMovingPyramid=dict(argstr='--minimumMovingPyramid %s', - sep=',', - ), - movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', - ), - movingVolume=dict(argstr='--movingVolume %s...', - ), - neighborhoodForBOBF=dict(argstr='--neighborhoodForBOBF %s', - sep=',', - ), - numberOfBCHApproximationTerms=dict(argstr='--numberOfBCHApproximationTerms %d', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputCheckerboardVolume=dict(argstr='--outputCheckerboardVolume %s', - hash_files=False, - ), - outputDebug=dict(argstr='--outputDebug ', - ), - outputDisplacementFieldPrefix=dict(argstr='--outputDisplacementFieldPrefix %s', - ), - outputDisplacementFieldVolume=dict(argstr='--outputDisplacementFieldVolume %s', - hash_files=False, - ), - outputNormalized=dict(argstr='--outputNormalized ', - ), - outputPixelType=dict(argstr='--outputPixelType %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - promptUser=dict(argstr='--promptUser ', - ), - registrationFilterType=dict(argstr='--registrationFilterType %s', - ), - seedForBOBF=dict(argstr='--seedForBOBF %s', - sep=',', - ), - smoothDisplacementFieldSigma=dict(argstr='--smoothDisplacementFieldSigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', - ), - upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', - ), - use_vanilla_dem=dict(argstr='--use_vanilla_dem ', - ), - weightFactors=dict(argstr='--weightFactors %s', - sep=',', - ), + input_map = dict( + args=dict(argstr='%s', ), + arrayOfPyramidLevelIterations=dict( + argstr='--arrayOfPyramidLevelIterations %s', + sep=',', + ), + backgroundFillValue=dict(argstr='--backgroundFillValue %d', ), + checkerboardPatternSubdivisions=dict( + argstr='--checkerboardPatternSubdivisions %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', ), + fixedVolume=dict(argstr='--fixedVolume %s...', ), + gradient_type=dict(argstr='--gradient_type %s', ), + gui=dict(argstr='--gui ', ), + histogramMatch=dict(argstr='--histogramMatch ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initializeWithDisplacementField=dict( + argstr='--initializeWithDisplacementField %s', ), + initializeWithTransform=dict(argstr='--initializeWithTransform %s', ), + inputPixelType=dict(argstr='--inputPixelType %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', ), + makeBOBF=dict(argstr='--makeBOBF ', ), + max_step_length=dict(argstr='--max_step_length %f', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + minimumFixedPyramid=dict( + argstr='--minimumFixedPyramid %s', + sep=',', + ), + minimumMovingPyramid=dict( + argstr='--minimumMovingPyramid %s', + sep=',', + ), + movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', ), + movingVolume=dict(argstr='--movingVolume %s...', ), + neighborhoodForBOBF=dict( + argstr='--neighborhoodForBOBF %s', + sep=',', + ), + numberOfBCHApproximationTerms=dict( + argstr='--numberOfBCHApproximationTerms %d', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputCheckerboardVolume=dict( + argstr='--outputCheckerboardVolume %s', + hash_files=False, + ), + outputDebug=dict(argstr='--outputDebug ', ), + outputDisplacementFieldPrefix=dict( + argstr='--outputDisplacementFieldPrefix %s', ), + outputDisplacementFieldVolume=dict( + argstr='--outputDisplacementFieldVolume %s', + hash_files=False, + ), + outputNormalized=dict(argstr='--outputNormalized ', ), + outputPixelType=dict(argstr='--outputPixelType %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + promptUser=dict(argstr='--promptUser ', ), + registrationFilterType=dict(argstr='--registrationFilterType %s', ), + seedForBOBF=dict( + argstr='--seedForBOBF %s', + sep=',', + ), + smoothDisplacementFieldSigma=dict( + argstr='--smoothDisplacementFieldSigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', ), + upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', ), + use_vanilla_dem=dict(argstr='--use_vanilla_dem ', ), + weightFactors=dict( + argstr='--weightFactors %s', + sep=',', + ), ) inputs = VBRAINSDemonWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VBRAINSDemonWarp_outputs(): - output_map = dict(outputCheckerboardVolume=dict(), - outputDisplacementFieldVolume=dict(), - outputVolume=dict(), + output_map = dict( + outputCheckerboardVolume=dict(), + outputDisplacementFieldVolume=dict(), + outputVolume=dict(), ) outputs = VBRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/__init__.py b/nipype/interfaces/semtools/segmentation/__init__.py index 9fbf33be3c..d0cd69e0c9 100644 --- a/nipype/interfaces/semtools/segmentation/__init__.py +++ b/nipype/interfaces/semtools/segmentation/__init__.py @@ -1,3 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import -from .specialized import BRAINSCut, BRAINSROIAuto, BRAINSConstellationDetector, BRAINSCreateLabelMapFromProbabilityMaps, BinaryMaskEditorBasedOnLandmarks, BRAINSMultiSTAPLE, BRAINSABC, ESLR +from .specialized import ( + BRAINSCut, BRAINSROIAuto, BRAINSConstellationDetector, + BRAINSCreateLabelMapFromProbabilityMaps, BinaryMaskEditorBasedOnLandmarks, + BRAINSMultiSTAPLE, BRAINSABC, ESLR) diff --git a/nipype/interfaces/semtools/segmentation/specialized.py b/nipype/interfaces/semtools/segmentation/specialized.py index 2e4e73fccc..fa08b8e260 100644 --- a/nipype/interfaces/semtools/segmentation/specialized.py +++ b/nipype/interfaces/semtools/segmentation/specialized.py @@ -11,23 +11,60 @@ class BRAINSCutInputSpec(CommandLineInputSpec): - netConfiguration = File(desc="XML File defining BRAINSCut parameters. OLD NAME. PLEASE USE modelConfigurationFilename instead.", exists=True, argstr="--netConfiguration %s") - modelConfigurationFilename = File(desc="XML File defining BRAINSCut parameters", exists=True, argstr="--modelConfigurationFilename %s") - trainModelStartIndex = traits.Int(desc="Starting iteration for training", argstr="--trainModelStartIndex %d") - verbose = traits.Int(desc="print out some debugging information", argstr="--verbose %d") - multiStructureThreshold = traits.Bool(desc="multiStructureThreshold module to deal with overlaping area", argstr="--multiStructureThreshold ") - histogramEqualization = traits.Bool(desc="A Histogram Equalization process could be added to the creating/applying process from Subject To Atlas. Default is false, which genreate input vectors without Histogram Equalization. ", argstr="--histogramEqualization ") - computeSSEOn = traits.Bool(desc="compute Sum of Square Error (SSE) along the trained model until the number of iteration given in the modelConfigurationFilename file", argstr="--computeSSEOn ") - generateProbability = traits.Bool(desc="Generate probability map", argstr="--generateProbability ") - createVectors = traits.Bool(desc="create vectors for training neural net", argstr="--createVectors ") - trainModel = traits.Bool(desc="train the neural net", argstr="--trainModel ") - NoTrainingVectorShuffling = traits.Bool(desc="If this flag is on, there will be no shuffling.", argstr="--NoTrainingVectorShuffling ") - applyModel = traits.Bool(desc="apply the neural net", argstr="--applyModel ") - validate = traits.Bool(desc="validate data set.Just need for the first time run ( This is for validation of xml file and not working yet )", argstr="--validate ") + netConfiguration = File( + desc= + "XML File defining BRAINSCut parameters. OLD NAME. PLEASE USE modelConfigurationFilename instead.", + exists=True, + argstr="--netConfiguration %s") + modelConfigurationFilename = File( + desc="XML File defining BRAINSCut parameters", + exists=True, + argstr="--modelConfigurationFilename %s") + trainModelStartIndex = traits.Int( + desc="Starting iteration for training", + argstr="--trainModelStartIndex %d") + verbose = traits.Int( + desc="print out some debugging information", argstr="--verbose %d") + multiStructureThreshold = traits.Bool( + desc="multiStructureThreshold module to deal with overlaping area", + argstr="--multiStructureThreshold ") + histogramEqualization = traits.Bool( + desc= + "A Histogram Equalization process could be added to the creating/applying process from Subject To Atlas. Default is false, which genreate input vectors without Histogram Equalization. ", + argstr="--histogramEqualization ") + computeSSEOn = traits.Bool( + desc= + "compute Sum of Square Error (SSE) along the trained model until the number of iteration given in the modelConfigurationFilename file", + argstr="--computeSSEOn ") + generateProbability = traits.Bool( + desc="Generate probability map", argstr="--generateProbability ") + createVectors = traits.Bool( + desc="create vectors for training neural net", + argstr="--createVectors ") + trainModel = traits.Bool( + desc="train the neural net", argstr="--trainModel ") + NoTrainingVectorShuffling = traits.Bool( + desc="If this flag is on, there will be no shuffling.", + argstr="--NoTrainingVectorShuffling ") + applyModel = traits.Bool( + desc="apply the neural net", argstr="--applyModel ") + validate = traits.Bool( + desc= + "validate data set.Just need for the first time run ( This is for validation of xml file and not working yet )", + argstr="--validate ") method = traits.Enum("RandomForest", "ANN", argstr="--method %s") - numberOfTrees = traits.Int(desc=" Random tree: number of trees. This is to be used when only one model with specified depth wish to be created. ", argstr="--numberOfTrees %d") - randomTreeDepth = traits.Int(desc=" Random tree depth. This is to be used when only one model with specified depth wish to be created. ", argstr="--randomTreeDepth %d") - modelFilename = traits.Str(desc=" model file name given from user (not by xml configuration file) ", argstr="--modelFilename %s") + numberOfTrees = traits.Int( + desc= + " Random tree: number of trees. This is to be used when only one model with specified depth wish to be created. ", + argstr="--numberOfTrees %d") + randomTreeDepth = traits.Int( + desc= + " Random tree depth. This is to be used when only one model with specified depth wish to be created. ", + argstr="--randomTreeDepth %d") + modelFilename = traits.Str( + desc= + " model file name given from user (not by xml configuration file) ", + argstr="--modelFilename %s") class BRAINSCutOutputSpec(TraitedSpec): @@ -35,7 +72,6 @@ class BRAINSCutOutputSpec(TraitedSpec): class BRAINSCut(SEMLikeCommandLine): - """title: BRAINSCut (BRAINS) category: Segmentation.Specialized @@ -58,27 +94,69 @@ class BRAINSCut(SEMLikeCommandLine): class BRAINSROIAutoInputSpec(CommandLineInputSpec): - inputVolume = File(desc="The input image for finding the largest region filled mask.", exists=True, argstr="--inputVolume %s") - outputROIMaskVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="The ROI automatically found from the input image.", argstr="--outputROIMaskVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="The inputVolume with optional [maskOutput|cropOutput] to the region of the brain mask.", argstr="--outputVolume %s") - maskOutput = traits.Bool(desc="The inputVolume multiplied by the ROI mask.", argstr="--maskOutput ") - cropOutput = traits.Bool(desc="The inputVolume cropped to the region of the ROI mask.", argstr="--cropOutput ") - otsuPercentileThreshold = traits.Float(desc="Parameter to the Otsu threshold algorithm.", argstr="--otsuPercentileThreshold %f") - thresholdCorrectionFactor = traits.Float(desc="A factor to scale the Otsu algorithm's result threshold, in case clipping mangles the image.", argstr="--thresholdCorrectionFactor %f") - closingSize = traits.Float(desc="The Closing Size (in millimeters) for largest connected filled mask. This value is divided by image spacing and rounded to the next largest voxel number.", argstr="--closingSize %f") + inputVolume = File( + desc="The input image for finding the largest region filled mask.", + exists=True, + argstr="--inputVolume %s") + outputROIMaskVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The ROI automatically found from the input image.", + argstr="--outputROIMaskVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The inputVolume with optional [maskOutput|cropOutput] to the region of the brain mask.", + argstr="--outputVolume %s") + maskOutput = traits.Bool( + desc="The inputVolume multiplied by the ROI mask.", + argstr="--maskOutput ") + cropOutput = traits.Bool( + desc="The inputVolume cropped to the region of the ROI mask.", + argstr="--cropOutput ") + otsuPercentileThreshold = traits.Float( + desc="Parameter to the Otsu threshold algorithm.", + argstr="--otsuPercentileThreshold %f") + thresholdCorrectionFactor = traits.Float( + desc= + "A factor to scale the Otsu algorithm's result threshold, in case clipping mangles the image.", + argstr="--thresholdCorrectionFactor %f") + closingSize = traits.Float( + desc= + "The Closing Size (in millimeters) for largest connected filled mask. This value is divided by image spacing and rounded to the next largest voxel number.", + argstr="--closingSize %f") ROIAutoDilateSize = traits.Float( - desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f") - outputVolumePixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", desc="The output image Pixel Type is the scalar datatype for representation of the Output Volume.", argstr="--outputVolumePixelType %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + desc= + "This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", + argstr="--ROIAutoDilateSize %f") + outputVolumePixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uint", + "uchar", + desc= + "The output image Pixel Type is the scalar datatype for representation of the Output Volume.", + argstr="--outputVolumePixelType %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSROIAutoOutputSpec(TraitedSpec): - outputROIMaskVolume = File(desc="The ROI automatically found from the input image.", exists=True) - outputVolume = File(desc="The inputVolume with optional [maskOutput|cropOutput] to the region of the brain mask.", exists=True) + outputROIMaskVolume = File( + desc="The ROI automatically found from the input image.", exists=True) + outputVolume = File( + desc= + "The inputVolume with optional [maskOutput|cropOutput] to the region of the brain mask.", + exists=True) class BRAINSROIAuto(SEMLikeCommandLine): - """title: Foreground masking (BRAINS) category: Segmentation.Specialized @@ -98,82 +176,269 @@ class BRAINSROIAuto(SEMLikeCommandLine): input_spec = BRAINSROIAutoInputSpec output_spec = BRAINSROIAutoOutputSpec _cmd = " BRAINSROIAuto " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'outputROIMaskVolume': 'outputROIMaskVolume.nii'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'outputROIMaskVolume': 'outputROIMaskVolume.nii' + } _redirect_x = False class BRAINSConstellationDetectorInputSpec(CommandLineInputSpec): - houghEyeDetectorMode = traits.Int(desc=", This flag controls the mode of Hough eye detector. By default, value of 1 is for T1W images, while the value of 0 is for T2W and PD images., ", argstr="--houghEyeDetectorMode %d") - inputTemplateModel = File(desc="User-specified template model., ", exists=True, argstr="--inputTemplateModel %s") - LLSModel = File(desc="Linear least squares model filename in HD5 format", exists=True, argstr="--LLSModel %s") - inputVolume = File(desc="Input image in which to find ACPC points", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File( - ), hash_files=False, desc="ACPC-aligned output image with the same voxels, but updated origin, and direction cosign so that the AC point would fall at the physical location (0.0,0.0,0.0), and the mid-sagital plane is the plane where physical L/R coordinate is 0.0.", argstr="--outputVolume %s") - outputResampledVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="ACPC-aligned output image in a resampled unifor space. Currently this is a 1mm, 256^3, Identity direction image.", argstr="--outputResampledVolume %s") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="The filename for the original space to ACPC alignment to be written (in .h5 format)., ", argstr="--outputTransform %s") - outputLandmarksInInputSpace = traits.Either(traits.Bool, File( - ), hash_files=False, desc=", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the original image space (the detected RP, AC, PC, and VN4) in it to be written., ", argstr="--outputLandmarksInInputSpace %s") - outputLandmarksInACPCAlignedSpace = traits.Either(traits.Bool, File( - ), hash_files=False, desc=", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the output image space (the detected RP, AC, PC, and VN4) in it to be written., ", argstr="--outputLandmarksInACPCAlignedSpace %s") - outputMRML = traits.Either(traits.Bool, File( - ), hash_files=False, desc=", The filename for the new subject-specific scene definition file in the same format produced by Slicer3 (in .mrml format). Only the components that were specified by the user on command line would be generated. Compatible components include inputVolume, outputVolume, outputLandmarksInInputSpace, outputLandmarksInACPCAlignedSpace, and outputTransform., ", argstr="--outputMRML %s") + houghEyeDetectorMode = traits.Int( + desc= + ", This flag controls the mode of Hough eye detector. By default, value of 1 is for T1W images, while the value of 0 is for T2W and PD images., ", + argstr="--houghEyeDetectorMode %d") + inputTemplateModel = File( + desc="User-specified template model., ", + exists=True, + argstr="--inputTemplateModel %s") + LLSModel = File( + desc="Linear least squares model filename in HD5 format", + exists=True, + argstr="--LLSModel %s") + inputVolume = File( + desc="Input image in which to find ACPC points", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "ACPC-aligned output image with the same voxels, but updated origin, and direction cosign so that the AC point would fall at the physical location (0.0,0.0,0.0), and the mid-sagital plane is the plane where physical L/R coordinate is 0.0.", + argstr="--outputVolume %s") + outputResampledVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "ACPC-aligned output image in a resampled unifor space. Currently this is a 1mm, 256^3, Identity direction image.", + argstr="--outputResampledVolume %s") + outputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The filename for the original space to ACPC alignment to be written (in .h5 format)., ", + argstr="--outputTransform %s") + outputLandmarksInInputSpace = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + ", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the original image space (the detected RP, AC, PC, and VN4) in it to be written., ", + argstr="--outputLandmarksInInputSpace %s") + outputLandmarksInACPCAlignedSpace = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + ", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the output image space (the detected RP, AC, PC, and VN4) in it to be written., ", + argstr="--outputLandmarksInACPCAlignedSpace %s") + outputMRML = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + ", The filename for the new subject-specific scene definition file in the same format produced by Slicer3 (in .mrml format). Only the components that were specified by the user on command line would be generated. Compatible components include inputVolume, outputVolume, outputLandmarksInInputSpace, outputLandmarksInACPCAlignedSpace, and outputTransform., ", + argstr="--outputMRML %s") outputVerificationScript = traits.Either( - traits.Bool, File(), hash_files=False, desc=", The filename for the Slicer3 script that verifies the aligned landmarks against the aligned image file. This will happen only in conjunction with saveOutputLandmarks and an outputVolume., ", argstr="--outputVerificationScript %s") + traits.Bool, + File(), + hash_files=False, + desc= + ", The filename for the Slicer3 script that verifies the aligned landmarks against the aligned image file. This will happen only in conjunction with saveOutputLandmarks and an outputVolume., ", + argstr="--outputVerificationScript %s") mspQualityLevel = traits.Int( - desc=", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds), NOTE: -1= Prealigned so no estimate!., ", argstr="--mspQualityLevel %d") - otsuPercentileThreshold = traits.Float(desc=", This is a parameter to FindLargestForegroundFilledMask, which is employed when acLowerBound is set and an outputUntransformedClippedVolume is requested., ", argstr="--otsuPercentileThreshold %f") + desc= + ", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds), NOTE: -1= Prealigned so no estimate!., ", + argstr="--mspQualityLevel %d") + otsuPercentileThreshold = traits.Float( + desc= + ", This is a parameter to FindLargestForegroundFilledMask, which is employed when acLowerBound is set and an outputUntransformedClippedVolume is requested., ", + argstr="--otsuPercentileThreshold %f") acLowerBound = traits.Float( - desc=", When generating a resampled output image, replace the image with the BackgroundFillValue everywhere below the plane This Far in physical units (millimeters) below (inferior to) the AC point (as found by the model.) The oversize default was chosen to have no effect. Based on visualizing a thousand masks in the IPIG study, we recommend a limit no smaller than 80.0 mm., ", argstr="--acLowerBound %f") - cutOutHeadInOutputVolume = traits.Bool(desc=", Flag to cut out just the head tissue when producing an (un)transformed clipped volume., ", argstr="--cutOutHeadInOutputVolume ") - outputUntransformedClippedVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output image in which to store neck-clipped input image, with the use of --acLowerBound and maybe --cutOutHeadInUntransformedVolume.", argstr="--outputUntransformedClippedVolume %s") - rescaleIntensities = traits.Bool(desc=", Flag to turn on rescaling image intensities on input., ", argstr="--rescaleIntensities ") + desc= + ", When generating a resampled output image, replace the image with the BackgroundFillValue everywhere below the plane This Far in physical units (millimeters) below (inferior to) the AC point (as found by the model.) The oversize default was chosen to have no effect. Based on visualizing a thousand masks in the IPIG study, we recommend a limit no smaller than 80.0 mm., ", + argstr="--acLowerBound %f") + cutOutHeadInOutputVolume = traits.Bool( + desc= + ", Flag to cut out just the head tissue when producing an (un)transformed clipped volume., ", + argstr="--cutOutHeadInOutputVolume ") + outputUntransformedClippedVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output image in which to store neck-clipped input image, with the use of --acLowerBound and maybe --cutOutHeadInUntransformedVolume.", + argstr="--outputUntransformedClippedVolume %s") + rescaleIntensities = traits.Bool( + desc= + ", Flag to turn on rescaling image intensities on input., ", + argstr="--rescaleIntensities ") trimRescaledIntensities = traits.Float( - desc=", Turn on clipping the rescaled image one-tailed on input. Units of standard deviations above the mean. Very large values are very permissive. Non-positive value turns clipping off. Defaults to removing 0.00001 of a normal tail above the mean., ", argstr="--trimRescaledIntensities %f") + desc= + ", Turn on clipping the rescaled image one-tailed on input. Units of standard deviations above the mean. Very large values are very permissive. Non-positive value turns clipping off. Defaults to removing 0.00001 of a normal tail above the mean., ", + argstr="--trimRescaledIntensities %f") rescaleIntensitiesOutputRange = InputMultiPath( - traits.Int, desc=", This pair of integers gives the lower and upper bounds on the signal portion of the output image. Out-of-field voxels are taken from BackgroundFillValue., ", sep=",", argstr="--rescaleIntensitiesOutputRange %s") - BackgroundFillValue = traits.Str(desc="Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", argstr="--BackgroundFillValue %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", - desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - forceACPoint = InputMultiPath(traits.Float, desc=", Use this flag to manually specify the AC point from the original image on the command line., ", sep=",", argstr="--forceACPoint %s") - forcePCPoint = InputMultiPath(traits.Float, desc=", Use this flag to manually specify the PC point from the original image on the command line., ", sep=",", argstr="--forcePCPoint %s") - forceVN4Point = InputMultiPath(traits.Float, desc=", Use this flag to manually specify the VN4 point from the original image on the command line., ", sep=",", argstr="--forceVN4Point %s") - forceRPPoint = InputMultiPath(traits.Float, desc=", Use this flag to manually specify the RP point from the original image on the command line., ", sep=",", argstr="--forceRPPoint %s") + traits.Int, + desc= + ", This pair of integers gives the lower and upper bounds on the signal portion of the output image. Out-of-field voxels are taken from BackgroundFillValue., ", + sep=",", + argstr="--rescaleIntensitiesOutputRange %s") + BackgroundFillValue = traits.Str( + desc= + "Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", + argstr="--BackgroundFillValue %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + forceACPoint = InputMultiPath( + traits.Float, + desc= + ", Use this flag to manually specify the AC point from the original image on the command line., ", + sep=",", + argstr="--forceACPoint %s") + forcePCPoint = InputMultiPath( + traits.Float, + desc= + ", Use this flag to manually specify the PC point from the original image on the command line., ", + sep=",", + argstr="--forcePCPoint %s") + forceVN4Point = InputMultiPath( + traits.Float, + desc= + ", Use this flag to manually specify the VN4 point from the original image on the command line., ", + sep=",", + argstr="--forceVN4Point %s") + forceRPPoint = InputMultiPath( + traits.Float, + desc= + ", Use this flag to manually specify the RP point from the original image on the command line., ", + sep=",", + argstr="--forceRPPoint %s") inputLandmarksEMSP = File( - desc=", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (in .fcsv) with the landmarks in the estimated MSP aligned space to be loaded. The detector will only process landmarks not enlisted on the file., ", exists=True, argstr="--inputLandmarksEMSP %s") - forceHoughEyeDetectorReportFailure = traits.Bool(desc=", Flag indicates whether the Hough eye detector should report failure, ", argstr="--forceHoughEyeDetectorReportFailure ") - rmpj = traits.Float(desc=", Search radius for MPJ in unit of mm, ", argstr="--rmpj %f") - rac = traits.Float(desc=", Search radius for AC in unit of mm, ", argstr="--rac %f") - rpc = traits.Float(desc=", Search radius for PC in unit of mm, ", argstr="--rpc %f") - rVN4 = traits.Float(desc=", Search radius for VN4 in unit of mm, ", argstr="--rVN4 %f") - debug = traits.Bool(desc=", Show internal debugging information., ", argstr="--debug ") - verbose = traits.Bool(desc=", Show more verbose output, ", argstr="--verbose ") - writeBranded2DImage = traits.Either(traits.Bool, File(), hash_files=False, desc=", The filename for the 2D .png branded midline debugging image. This will happen only in conjunction with requesting an outputVolume., ", argstr="--writeBranded2DImage %s") - resultsDir = traits.Either(traits.Bool, Directory(), hash_files=False, desc=", The directory for the debuging images to be written., ", argstr="--resultsDir %s") - writedebuggingImagesLevel = traits.Int(desc=", This flag controls if debugging images are produced. By default value of 0 is no images. Anything greater than zero will be increasing level of debugging images., ", argstr="--writedebuggingImagesLevel %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") - atlasVolume = File(desc="Atlas volume image to be used for BRAINSFit registration", exists=True, argstr="--atlasVolume %s") - atlasLandmarks = File(desc="Atlas landmarks to be used for BRAINSFit registration initialization, ", exists=True, argstr="--atlasLandmarks %s") - atlasLandmarkWeights = File(desc="Weights associated with atlas landmarks to be used for BRAINSFit registration initialization, ", exists=True, argstr="--atlasLandmarkWeights %s") + desc= + ", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (in .fcsv) with the landmarks in the estimated MSP aligned space to be loaded. The detector will only process landmarks not enlisted on the file., ", + exists=True, + argstr="--inputLandmarksEMSP %s") + forceHoughEyeDetectorReportFailure = traits.Bool( + desc= + ", Flag indicates whether the Hough eye detector should report failure, ", + argstr="--forceHoughEyeDetectorReportFailure ") + rmpj = traits.Float( + desc= + ", Search radius for MPJ in unit of mm, ", + argstr="--rmpj %f") + rac = traits.Float( + desc=", Search radius for AC in unit of mm, ", + argstr="--rac %f") + rpc = traits.Float( + desc=", Search radius for PC in unit of mm, ", + argstr="--rpc %f") + rVN4 = traits.Float( + desc= + ", Search radius for VN4 in unit of mm, ", + argstr="--rVN4 %f") + debug = traits.Bool( + desc= + ", Show internal debugging information., ", + argstr="--debug ") + verbose = traits.Bool( + desc=", Show more verbose output, ", + argstr="--verbose ") + writeBranded2DImage = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + ", The filename for the 2D .png branded midline debugging image. This will happen only in conjunction with requesting an outputVolume., ", + argstr="--writeBranded2DImage %s") + resultsDir = traits.Either( + traits.Bool, + Directory(), + hash_files=False, + desc= + ", The directory for the debuging images to be written., ", + argstr="--resultsDir %s") + writedebuggingImagesLevel = traits.Int( + desc= + ", This flag controls if debugging images are produced. By default value of 0 is no images. Anything greater than zero will be increasing level of debugging images., ", + argstr="--writedebuggingImagesLevel %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") + atlasVolume = File( + desc="Atlas volume image to be used for BRAINSFit registration", + exists=True, + argstr="--atlasVolume %s") + atlasLandmarks = File( + desc= + "Atlas landmarks to be used for BRAINSFit registration initialization, ", + exists=True, + argstr="--atlasLandmarks %s") + atlasLandmarkWeights = File( + desc= + "Weights associated with atlas landmarks to be used for BRAINSFit registration initialization, ", + exists=True, + argstr="--atlasLandmarkWeights %s") class BRAINSConstellationDetectorOutputSpec(TraitedSpec): - outputVolume = File(desc="ACPC-aligned output image with the same voxels, but updated origin, and direction cosign so that the AC point would fall at the physical location (0.0,0.0,0.0), and the mid-sagital plane is the plane where physical L/R coordinate is 0.0.", exists=True) - outputResampledVolume = File(desc="ACPC-aligned output image in a resampled unifor space. Currently this is a 1mm, 256^3, Identity direction image.", exists=True) - outputTransform = File(desc="The filename for the original space to ACPC alignment to be written (in .h5 format)., ", exists=True) + outputVolume = File( + desc= + "ACPC-aligned output image with the same voxels, but updated origin, and direction cosign so that the AC point would fall at the physical location (0.0,0.0,0.0), and the mid-sagital plane is the plane where physical L/R coordinate is 0.0.", + exists=True) + outputResampledVolume = File( + desc= + "ACPC-aligned output image in a resampled unifor space. Currently this is a 1mm, 256^3, Identity direction image.", + exists=True) + outputTransform = File( + desc= + "The filename for the original space to ACPC alignment to be written (in .h5 format)., ", + exists=True) outputLandmarksInInputSpace = File( - desc=", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the original image space (the detected RP, AC, PC, and VN4) in it to be written., ", exists=True) + desc= + ", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the original image space (the detected RP, AC, PC, and VN4) in it to be written., ", + exists=True) outputLandmarksInACPCAlignedSpace = File( - desc=", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the output image space (the detected RP, AC, PC, and VN4) in it to be written., ", exists=True) + desc= + ", The filename for the new subject-specific landmark definition file in the same format produced by Slicer3 (.fcsv) with the landmarks in the output image space (the detected RP, AC, PC, and VN4) in it to be written., ", + exists=True) outputMRML = File( - desc=", The filename for the new subject-specific scene definition file in the same format produced by Slicer3 (in .mrml format). Only the components that were specified by the user on command line would be generated. Compatible components include inputVolume, outputVolume, outputLandmarksInInputSpace, outputLandmarksInACPCAlignedSpace, and outputTransform., ", exists=True) - outputVerificationScript = File(desc=", The filename for the Slicer3 script that verifies the aligned landmarks against the aligned image file. This will happen only in conjunction with saveOutputLandmarks and an outputVolume., ", exists=True) - outputUntransformedClippedVolume = File(desc="Output image in which to store neck-clipped input image, with the use of --acLowerBound and maybe --cutOutHeadInUntransformedVolume.", exists=True) - writeBranded2DImage = File(desc=", The filename for the 2D .png branded midline debugging image. This will happen only in conjunction with requesting an outputVolume., ", exists=True) - resultsDir = Directory(desc=", The directory for the debuging images to be written., ", exists=True) + desc= + ", The filename for the new subject-specific scene definition file in the same format produced by Slicer3 (in .mrml format). Only the components that were specified by the user on command line would be generated. Compatible components include inputVolume, outputVolume, outputLandmarksInInputSpace, outputLandmarksInACPCAlignedSpace, and outputTransform., ", + exists=True) + outputVerificationScript = File( + desc= + ", The filename for the Slicer3 script that verifies the aligned landmarks against the aligned image file. This will happen only in conjunction with saveOutputLandmarks and an outputVolume., ", + exists=True) + outputUntransformedClippedVolume = File( + desc= + "Output image in which to store neck-clipped input image, with the use of --acLowerBound and maybe --cutOutHeadInUntransformedVolume.", + exists=True) + writeBranded2DImage = File( + desc= + ", The filename for the 2D .png branded midline debugging image. This will happen only in conjunction with requesting an outputVolume., ", + exists=True) + resultsDir = Directory( + desc= + ", The directory for the debuging images to be written., ", + exists=True) class BRAINSConstellationDetector(SEMLikeCommandLine): - """title: Brain Landmark Constellation Detector (BRAINS) category: Segmentation.Specialized @@ -189,19 +454,66 @@ class BRAINSConstellationDetector(SEMLikeCommandLine): input_spec = BRAINSConstellationDetectorInputSpec output_spec = BRAINSConstellationDetectorOutputSpec _cmd = " BRAINSConstellationDetector " - _outputs_filenames = {'outputVolume': 'outputVolume.nii.gz', 'outputMRML': 'outputMRML.mrml', 'resultsDir': 'resultsDir', 'outputResampledVolume': 'outputResampledVolume.nii.gz', 'outputTransform': 'outputTransform.h5', 'writeBranded2DImage': 'writeBranded2DImage.png', - 'outputLandmarksInACPCAlignedSpace': 'outputLandmarksInACPCAlignedSpace.fcsv', 'outputLandmarksInInputSpace': 'outputLandmarksInInputSpace.fcsv', 'outputUntransformedClippedVolume': 'outputUntransformedClippedVolume.nii.gz', 'outputVerificationScript': 'outputVerificationScript.sh'} + _outputs_filenames = { + 'outputVolume': + 'outputVolume.nii.gz', + 'outputMRML': + 'outputMRML.mrml', + 'resultsDir': + 'resultsDir', + 'outputResampledVolume': + 'outputResampledVolume.nii.gz', + 'outputTransform': + 'outputTransform.h5', + 'writeBranded2DImage': + 'writeBranded2DImage.png', + 'outputLandmarksInACPCAlignedSpace': + 'outputLandmarksInACPCAlignedSpace.fcsv', + 'outputLandmarksInInputSpace': + 'outputLandmarksInInputSpace.fcsv', + 'outputUntransformedClippedVolume': + 'outputUntransformedClippedVolume.nii.gz', + 'outputVerificationScript': + 'outputVerificationScript.sh' + } _redirect_x = False class BRAINSCreateLabelMapFromProbabilityMapsInputSpec(CommandLineInputSpec): - inputProbabilityVolume = InputMultiPath(File(exists=True), desc="The list of proobabilityimages.", argstr="--inputProbabilityVolume %s...") - priorLabelCodes = InputMultiPath(traits.Int, desc="A list of PriorLabelCode values used for coding the output label images", sep=",", argstr="--priorLabelCodes %s") - foregroundPriors = InputMultiPath(traits.Int, desc="A list: For each Prior Label, 1 if foreground, 0 if background", sep=",", argstr="--foregroundPriors %s") - nonAirRegionMask = File(desc="a mask representing the \'NonAirRegion\' -- Just force pixels in this region to zero", exists=True, argstr="--nonAirRegionMask %s") - inclusionThreshold = traits.Float(desc="tolerance for inclusion", argstr="--inclusionThreshold %f") - dirtyLabelVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="the labels prior to cleaning", argstr="--dirtyLabelVolume %s") - cleanLabelVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="the foreground labels volume", argstr="--cleanLabelVolume %s") + inputProbabilityVolume = InputMultiPath( + File(exists=True), + desc="The list of proobabilityimages.", + argstr="--inputProbabilityVolume %s...") + priorLabelCodes = InputMultiPath( + traits.Int, + desc= + "A list of PriorLabelCode values used for coding the output label images", + sep=",", + argstr="--priorLabelCodes %s") + foregroundPriors = InputMultiPath( + traits.Int, + desc="A list: For each Prior Label, 1 if foreground, 0 if background", + sep=",", + argstr="--foregroundPriors %s") + nonAirRegionMask = File( + desc= + "a mask representing the \'NonAirRegion\' -- Just force pixels in this region to zero", + exists=True, + argstr="--nonAirRegionMask %s") + inclusionThreshold = traits.Float( + desc="tolerance for inclusion", argstr="--inclusionThreshold %f") + dirtyLabelVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="the labels prior to cleaning", + argstr="--dirtyLabelVolume %s") + cleanLabelVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="the foreground labels volume", + argstr="--cleanLabelVolume %s") class BRAINSCreateLabelMapFromProbabilityMapsOutputSpec(TraitedSpec): @@ -210,7 +522,6 @@ class BRAINSCreateLabelMapFromProbabilityMapsOutputSpec(TraitedSpec): class BRAINSCreateLabelMapFromProbabilityMaps(SEMLikeCommandLine): - """title: Create Label Map From Probability Maps (BRAINS) category: Segmentation.Specialized @@ -222,28 +533,61 @@ class BRAINSCreateLabelMapFromProbabilityMaps(SEMLikeCommandLine): input_spec = BRAINSCreateLabelMapFromProbabilityMapsInputSpec output_spec = BRAINSCreateLabelMapFromProbabilityMapsOutputSpec _cmd = " BRAINSCreateLabelMapFromProbabilityMaps " - _outputs_filenames = {'dirtyLabelVolume': 'dirtyLabelVolume.nii', 'cleanLabelVolume': 'cleanLabelVolume.nii'} + _outputs_filenames = { + 'dirtyLabelVolume': 'dirtyLabelVolume.nii', + 'cleanLabelVolume': 'cleanLabelVolume.nii' + } _redirect_x = False class BinaryMaskEditorBasedOnLandmarksInputSpec(CommandLineInputSpec): - inputBinaryVolume = File(desc="Input binary image in which to be edited", exists=True, argstr="--inputBinaryVolume %s") - outputBinaryVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output binary image in which to be edited", argstr="--outputBinaryVolume %s") - inputLandmarksFilename = File(desc=" The filename for the landmark definition file in the same format produced by Slicer3 (.fcsv). ", exists=True, argstr="--inputLandmarksFilename %s") - inputLandmarkNames = InputMultiPath(traits.Str, desc=" A target input landmark name to be edited. This should be listed in the inputLandmakrFilename Given. ", sep=",", argstr="--inputLandmarkNames %s") + inputBinaryVolume = File( + desc="Input binary image in which to be edited", + exists=True, + argstr="--inputBinaryVolume %s") + outputBinaryVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output binary image in which to be edited", + argstr="--outputBinaryVolume %s") + inputLandmarksFilename = File( + desc= + " The filename for the landmark definition file in the same format produced by Slicer3 (.fcsv). ", + exists=True, + argstr="--inputLandmarksFilename %s") + inputLandmarkNames = InputMultiPath( + traits.Str, + desc= + " A target input landmark name to be edited. This should be listed in the inputLandmakrFilename Given. ", + sep=",", + argstr="--inputLandmarkNames %s") setCutDirectionForLandmark = InputMultiPath( - traits.Str, desc="Setting the cutting out direction of the input binary image to the one of anterior, posterior, left, right, superior or posterior. (ENUMERATION: ANTERIOR, POSTERIOR, LEFT, RIGHT, SUPERIOR, POSTERIOR) ", sep=",", argstr="--setCutDirectionForLandmark %s") + traits.Str, + desc= + "Setting the cutting out direction of the input binary image to the one of anterior, posterior, left, right, superior or posterior. (ENUMERATION: ANTERIOR, POSTERIOR, LEFT, RIGHT, SUPERIOR, POSTERIOR) ", + sep=",", + argstr="--setCutDirectionForLandmark %s") setCutDirectionForObliquePlane = InputMultiPath( - traits.Str, desc="If this is true, the mask will be thresholded out to the direction of inferior, posterior, and/or left. Default behavrior is that cutting out to the direction of superior, anterior and/or right. ", sep=",", argstr="--setCutDirectionForObliquePlane %s") - inputLandmarkNamesForObliquePlane = InputMultiPath(traits.Str, desc=" Three subset landmark names of inputLandmarksFilename for a oblique plane computation. The plane computed for binary volume editing. ", sep=",", argstr="--inputLandmarkNamesForObliquePlane %s") + traits.Str, + desc= + "If this is true, the mask will be thresholded out to the direction of inferior, posterior, and/or left. Default behavrior is that cutting out to the direction of superior, anterior and/or right. ", + sep=",", + argstr="--setCutDirectionForObliquePlane %s") + inputLandmarkNamesForObliquePlane = InputMultiPath( + traits.Str, + desc= + " Three subset landmark names of inputLandmarksFilename for a oblique plane computation. The plane computed for binary volume editing. ", + sep=",", + argstr="--inputLandmarkNamesForObliquePlane %s") class BinaryMaskEditorBasedOnLandmarksOutputSpec(TraitedSpec): - outputBinaryVolume = File(desc="Output binary image in which to be edited", exists=True) + outputBinaryVolume = File( + desc="Output binary image in which to be edited", exists=True) class BinaryMaskEditorBasedOnLandmarks(SEMLikeCommandLine): - """title: BRAINS Binary Mask Editor Based On Landmarks(BRAINS) category: Segmentation.Specialized @@ -262,23 +606,49 @@ class BinaryMaskEditorBasedOnLandmarks(SEMLikeCommandLine): class BRAINSMultiSTAPLEInputSpec(CommandLineInputSpec): - inputCompositeT1Volume = File(desc="Composite T1, all label maps transofrmed into the space for this image.", exists=True, argstr="--inputCompositeT1Volume %s") - inputLabelVolume = InputMultiPath(File(exists=True), desc="The list of proobabilityimages.", argstr="--inputLabelVolume %s...") - inputTransform = InputMultiPath(File(exists=True), desc="transforms to apply to label volumes", argstr="--inputTransform %s...") - labelForUndecidedPixels = traits.Int(desc="Label for undecided pixels", argstr="--labelForUndecidedPixels %d") - resampledVolumePrefix = traits.Str(desc="if given, write out resampled volumes with this prefix", argstr="--resampledVolumePrefix %s") - skipResampling = traits.Bool(desc="Omit resampling images into reference space", argstr="--skipResampling ") - outputMultiSTAPLE = traits.Either(traits.Bool, File(), hash_files=False, desc="the MultiSTAPLE average of input label volumes", argstr="--outputMultiSTAPLE %s") - outputConfusionMatrix = traits.Either(traits.Bool, File(), hash_files=False, desc="Confusion Matrix", argstr="--outputConfusionMatrix %s") + inputCompositeT1Volume = File( + desc= + "Composite T1, all label maps transofrmed into the space for this image.", + exists=True, + argstr="--inputCompositeT1Volume %s") + inputLabelVolume = InputMultiPath( + File(exists=True), + desc="The list of proobabilityimages.", + argstr="--inputLabelVolume %s...") + inputTransform = InputMultiPath( + File(exists=True), + desc="transforms to apply to label volumes", + argstr="--inputTransform %s...") + labelForUndecidedPixels = traits.Int( + desc="Label for undecided pixels", + argstr="--labelForUndecidedPixels %d") + resampledVolumePrefix = traits.Str( + desc="if given, write out resampled volumes with this prefix", + argstr="--resampledVolumePrefix %s") + skipResampling = traits.Bool( + desc="Omit resampling images into reference space", + argstr="--skipResampling ") + outputMultiSTAPLE = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="the MultiSTAPLE average of input label volumes", + argstr="--outputMultiSTAPLE %s") + outputConfusionMatrix = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Confusion Matrix", + argstr="--outputConfusionMatrix %s") class BRAINSMultiSTAPLEOutputSpec(TraitedSpec): - outputMultiSTAPLE = File(desc="the MultiSTAPLE average of input label volumes", exists=True) + outputMultiSTAPLE = File( + desc="the MultiSTAPLE average of input label volumes", exists=True) outputConfusionMatrix = File(desc="Confusion Matrix", exists=True) class BRAINSMultiSTAPLE(SEMLikeCommandLine): - """title: Create best representative label map) category: Segmentation.Specialized @@ -290,61 +660,203 @@ class BRAINSMultiSTAPLE(SEMLikeCommandLine): input_spec = BRAINSMultiSTAPLEInputSpec output_spec = BRAINSMultiSTAPLEOutputSpec _cmd = " BRAINSMultiSTAPLE " - _outputs_filenames = {'outputMultiSTAPLE': 'outputMultiSTAPLE.nii', 'outputConfusionMatrix': 'outputConfusionMatrixh5|mat|txt'} + _outputs_filenames = { + 'outputMultiSTAPLE': 'outputMultiSTAPLE.nii', + 'outputConfusionMatrix': 'outputConfusionMatrixh5|mat|txt' + } _redirect_x = False class BRAINSABCInputSpec(CommandLineInputSpec): - inputVolumes = InputMultiPath(File(exists=True), desc="The list of input image files to be segmented.", argstr="--inputVolumes %s...") - atlasDefinition = File(desc="Contains all parameters for Atlas", exists=True, argstr="--atlasDefinition %s") - restoreState = File(desc="The initial state for the registration process", exists=True, argstr="--restoreState %s") - saveState = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Filename to which save the final state of the registration", argstr="--saveState %s") - inputVolumeTypes = InputMultiPath(traits.Str, desc="The list of input image types corresponding to the inputVolumes.", sep=",", argstr="--inputVolumeTypes %s") - outputDir = traits.Either(traits.Bool, Directory(), hash_files=False, desc="Ouput directory", argstr="--outputDir %s") - atlasToSubjectTransformType = traits.Enum("Identity", "Rigid", "Affine", "BSpline", "SyN", desc=" What type of linear transform type do you want to use to register the atlas to the reference subject image.", argstr="--atlasToSubjectTransformType %s") - atlasToSubjectTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="The transform from atlas to the subject", argstr="--atlasToSubjectTransform %s") - atlasToSubjectInitialTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="The initial transform from atlas to the subject", argstr="--atlasToSubjectInitialTransform %s") - subjectIntermodeTransformType = traits.Enum("Identity", "Rigid", "Affine", "BSpline", desc=" What type of linear transform type do you want to use to register the atlas to the reference subject image.", argstr="--subjectIntermodeTransformType %s") - outputVolumes = traits.Either(traits.Bool, InputMultiPath(File(), ), hash_files=False, - desc="Corrected Output Images: should specify the same number of images as inputVolume, if only one element is given, then it is used as a file pattern where %s is replaced by the imageVolumeType, and %d by the index list location.", argstr="--outputVolumes %s...") - outputLabels = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Label Image", argstr="--outputLabels %s") - outputDirtyLabels = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Dirty Label Image", argstr="--outputDirtyLabels %s") - posteriorTemplate = traits.Str(desc="filename template for Posterior output files", argstr="--posteriorTemplate %s") - outputFormat = traits.Enum("NIFTI", "Meta", "Nrrd", desc="Output format", argstr="--outputFormat %s") - interpolationMode = traits.Enum("BSpline", "NearestNeighbor", "WindowedSinc", "Linear", "ResampleInPlace", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", - desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, NearestNeighbor, BSpline, WindowedSinc, or ResampleInPlace. The ResampleInPlace option will create an image with the same discrete voxel values and will adjust the origin and direction of the physical space interpretation.", argstr="--interpolationMode %s") - maxIterations = traits.Int(desc="Filter iterations", argstr="--maxIterations %d") - medianFilterSize = InputMultiPath(traits.Int, desc="The radius for the optional MedianImageFilter preprocessing in all 3 directions.", sep=",", argstr="--medianFilterSize %s") - filterIteration = traits.Int(desc="Filter iterations", argstr="--filterIteration %d") - filterTimeStep = traits.Float(desc="Filter time step should be less than (PixelSpacing/(1^(DIM+1)), value is set to negative, then allow automatic setting of this value. ", argstr="--filterTimeStep %f") - filterMethod = traits.Enum("None", "CurvatureFlow", "GradientAnisotropicDiffusion", "Median", desc="Filter method for preprocessing of registration", argstr="--filterMethod %s") - maxBiasDegree = traits.Int(desc="Maximum bias degree", argstr="--maxBiasDegree %d") - useKNN = traits.Bool(desc="Use the KNN stage of estimating posteriors.", argstr="--useKNN ") - purePlugsThreshold = traits.Float(desc="If this threshold value is greater than zero, only pure samples are used to compute the distributions in EM classification, and only pure samples are used for KNN training. The default value is set to 0, that means not using pure plugs. However, a value of 0.2 is suggested if you want to activate using pure plugs option.", argstr="--purePlugsThreshold %f") - numberOfSubSamplesInEachPlugArea = InputMultiPath(traits.Int, desc="Number of continous index samples taken at each direction of lattice space for each plug volume.", sep=",", argstr="--numberOfSubSamplesInEachPlugArea %s") - atlasWarpingOff = traits.Bool(desc="Deformable registration of atlas to subject", argstr="--atlasWarpingOff ") - gridSize = InputMultiPath(traits.Int, desc="Grid size for atlas warping with BSplines", sep=",", argstr="--gridSize %s") + inputVolumes = InputMultiPath( + File(exists=True), + desc="The list of input image files to be segmented.", + argstr="--inputVolumes %s...") + atlasDefinition = File( + desc="Contains all parameters for Atlas", + exists=True, + argstr="--atlasDefinition %s") + restoreState = File( + desc="The initial state for the registration process", + exists=True, + argstr="--restoreState %s") + saveState = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Filename to which save the final state of the registration", + argstr="--saveState %s") + inputVolumeTypes = InputMultiPath( + traits.Str, + desc="The list of input image types corresponding to the inputVolumes.", + sep=",", + argstr="--inputVolumeTypes %s") + outputDir = traits.Either( + traits.Bool, + Directory(), + hash_files=False, + desc="Ouput directory", + argstr="--outputDir %s") + atlasToSubjectTransformType = traits.Enum( + "Identity", + "Rigid", + "Affine", + "BSpline", + "SyN", + desc= + " What type of linear transform type do you want to use to register the atlas to the reference subject image.", + argstr="--atlasToSubjectTransformType %s") + atlasToSubjectTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The transform from atlas to the subject", + argstr="--atlasToSubjectTransform %s") + atlasToSubjectInitialTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The initial transform from atlas to the subject", + argstr="--atlasToSubjectInitialTransform %s") + subjectIntermodeTransformType = traits.Enum( + "Identity", + "Rigid", + "Affine", + "BSpline", + desc= + " What type of linear transform type do you want to use to register the atlas to the reference subject image.", + argstr="--subjectIntermodeTransformType %s") + outputVolumes = traits.Either( + traits.Bool, + InputMultiPath(File(), ), + hash_files=False, + desc= + "Corrected Output Images: should specify the same number of images as inputVolume, if only one element is given, then it is used as a file pattern where %s is replaced by the imageVolumeType, and %d by the index list location.", + argstr="--outputVolumes %s...") + outputLabels = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output Label Image", + argstr="--outputLabels %s") + outputDirtyLabels = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output Dirty Label Image", + argstr="--outputDirtyLabels %s") + posteriorTemplate = traits.Str( + desc="filename template for Posterior output files", + argstr="--posteriorTemplate %s") + outputFormat = traits.Enum( + "NIFTI", + "Meta", + "Nrrd", + desc="Output format", + argstr="--outputFormat %s") + interpolationMode = traits.Enum( + "BSpline", + "NearestNeighbor", + "WindowedSinc", + "Linear", + "ResampleInPlace", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, NearestNeighbor, BSpline, WindowedSinc, or ResampleInPlace. The ResampleInPlace option will create an image with the same discrete voxel values and will adjust the origin and direction of the physical space interpretation.", + argstr="--interpolationMode %s") + maxIterations = traits.Int( + desc="Filter iterations", argstr="--maxIterations %d") + medianFilterSize = InputMultiPath( + traits.Int, + desc= + "The radius for the optional MedianImageFilter preprocessing in all 3 directions.", + sep=",", + argstr="--medianFilterSize %s") + filterIteration = traits.Int( + desc="Filter iterations", argstr="--filterIteration %d") + filterTimeStep = traits.Float( + desc= + "Filter time step should be less than (PixelSpacing/(1^(DIM+1)), value is set to negative, then allow automatic setting of this value. ", + argstr="--filterTimeStep %f") + filterMethod = traits.Enum( + "None", + "CurvatureFlow", + "GradientAnisotropicDiffusion", + "Median", + desc="Filter method for preprocessing of registration", + argstr="--filterMethod %s") + maxBiasDegree = traits.Int( + desc="Maximum bias degree", argstr="--maxBiasDegree %d") + useKNN = traits.Bool( + desc="Use the KNN stage of estimating posteriors.", argstr="--useKNN ") + purePlugsThreshold = traits.Float( + desc= + "If this threshold value is greater than zero, only pure samples are used to compute the distributions in EM classification, and only pure samples are used for KNN training. The default value is set to 0, that means not using pure plugs. However, a value of 0.2 is suggested if you want to activate using pure plugs option.", + argstr="--purePlugsThreshold %f") + numberOfSubSamplesInEachPlugArea = InputMultiPath( + traits.Int, + desc= + "Number of continous index samples taken at each direction of lattice space for each plug volume.", + sep=",", + argstr="--numberOfSubSamplesInEachPlugArea %s") + atlasWarpingOff = traits.Bool( + desc="Deformable registration of atlas to subject", + argstr="--atlasWarpingOff ") + gridSize = InputMultiPath( + traits.Int, + desc="Grid size for atlas warping with BSplines", + sep=",", + argstr="--gridSize %s") defaultSuffix = traits.Str(argstr="--defaultSuffix %s") - implicitOutputs = traits.Either(traits.Bool, InputMultiPath(File(), ), hash_files=False, desc="Outputs to be made available to NiPype. Needed because not all BRAINSABC outputs have command line arguments.", argstr="--implicitOutputs %s...") - debuglevel = traits.Int(desc="Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", argstr="--debuglevel %d") - writeLess = traits.Bool(desc="Does not write posteriors and filtered, bias corrected images", argstr="--writeLess ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + implicitOutputs = traits.Either( + traits.Bool, + InputMultiPath(File(), ), + hash_files=False, + desc= + "Outputs to be made available to NiPype. Needed because not all BRAINSABC outputs have command line arguments.", + argstr="--implicitOutputs %s...") + debuglevel = traits.Int( + desc= + "Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", + argstr="--debuglevel %d") + writeLess = traits.Bool( + desc="Does not write posteriors and filtered, bias corrected images", + argstr="--writeLess ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSABCOutputSpec(TraitedSpec): - saveState = File(desc="(optional) Filename to which save the final state of the registration", exists=True) + saveState = File( + desc= + "(optional) Filename to which save the final state of the registration", + exists=True) outputDir = Directory(desc="Ouput directory", exists=True) - atlasToSubjectTransform = File(desc="The transform from atlas to the subject", exists=True) - atlasToSubjectInitialTransform = File(desc="The initial transform from atlas to the subject", exists=True) + atlasToSubjectTransform = File( + desc="The transform from atlas to the subject", exists=True) + atlasToSubjectInitialTransform = File( + desc="The initial transform from atlas to the subject", exists=True) outputVolumes = OutputMultiPath( - File(exists=True), desc="Corrected Output Images: should specify the same number of images as inputVolume, if only one element is given, then it is used as a file pattern where %s is replaced by the imageVolumeType, and %d by the index list location.") + File(exists=True), + desc= + "Corrected Output Images: should specify the same number of images as inputVolume, if only one element is given, then it is used as a file pattern where %s is replaced by the imageVolumeType, and %d by the index list location." + ) outputLabels = File(desc="Output Label Image", exists=True) outputDirtyLabels = File(desc="Output Dirty Label Image", exists=True) - implicitOutputs = OutputMultiPath(File(exists=True), desc="Outputs to be made available to NiPype. Needed because not all BRAINSABC outputs have command line arguments.") + implicitOutputs = OutputMultiPath( + File(exists=True), + desc= + "Outputs to be made available to NiPype. Needed because not all BRAINSABC outputs have command line arguments." + ) class BRAINSABC(SEMLikeCommandLine): - """title: Intra-subject registration, bias Correction, and tissue classification (BRAINS) category: Segmentation.Specialized @@ -356,21 +868,45 @@ class BRAINSABC(SEMLikeCommandLine): input_spec = BRAINSABCInputSpec output_spec = BRAINSABCOutputSpec _cmd = " BRAINSABC " - _outputs_filenames = {'saveState': 'saveState.h5', 'outputLabels': 'outputLabels.nii.gz', 'atlasToSubjectTransform': 'atlasToSubjectTransform.h5', 'atlasToSubjectInitialTransform': 'atlasToSubjectInitialTransform.h5', - 'outputDirtyLabels': 'outputDirtyLabels.nii.gz', 'outputVolumes': 'outputVolumes.nii.gz', 'outputDir': 'outputDir', 'implicitOutputs': 'implicitOutputs.nii.gz'} + _outputs_filenames = { + 'saveState': 'saveState.h5', + 'outputLabels': 'outputLabels.nii.gz', + 'atlasToSubjectTransform': 'atlasToSubjectTransform.h5', + 'atlasToSubjectInitialTransform': 'atlasToSubjectInitialTransform.h5', + 'outputDirtyLabels': 'outputDirtyLabels.nii.gz', + 'outputVolumes': 'outputVolumes.nii.gz', + 'outputDir': 'outputDir', + 'implicitOutputs': 'implicitOutputs.nii.gz' + } _redirect_x = False class ESLRInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Input Label Volume", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Label Volume", argstr="--outputVolume %s") - low = traits.Int(desc="The lower bound of the labels to be used.", argstr="--low %d") - high = traits.Int(desc="The higher bound of the labels to be used.", argstr="--high %d") - closingSize = traits.Int(desc="The closing size for hole filling.", argstr="--closingSize %d") - openingSize = traits.Int(desc="The opening size for hole filling.", argstr="--openingSize %d") - safetySize = traits.Int(desc="The safetySize size for the clipping region.", argstr="--safetySize %d") - preserveOutside = traits.Bool(desc="For values outside the specified range, preserve those values.", argstr="--preserveOutside ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="Input Label Volume", exists=True, argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output Label Volume", + argstr="--outputVolume %s") + low = traits.Int( + desc="The lower bound of the labels to be used.", argstr="--low %d") + high = traits.Int( + desc="The higher bound of the labels to be used.", argstr="--high %d") + closingSize = traits.Int( + desc="The closing size for hole filling.", argstr="--closingSize %d") + openingSize = traits.Int( + desc="The opening size for hole filling.", argstr="--openingSize %d") + safetySize = traits.Int( + desc="The safetySize size for the clipping region.", + argstr="--safetySize %d") + preserveOutside = traits.Bool( + desc="For values outside the specified range, preserve those values.", + argstr="--preserveOutside ") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class ESLROutputSpec(TraitedSpec): @@ -378,7 +914,6 @@ class ESLROutputSpec(TraitedSpec): class ESLR(SEMLikeCommandLine): - """title: Clean Contiguous Label Map (BRAINS) category: Segmentation.Specialized diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py index d07166b086..da9565dfca 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py @@ -4,111 +4,107 @@ def test_BRAINSABC_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - atlasDefinition=dict(argstr='--atlasDefinition %s', - ), - atlasToSubjectInitialTransform=dict(argstr='--atlasToSubjectInitialTransform %s', - hash_files=False, - ), - atlasToSubjectTransform=dict(argstr='--atlasToSubjectTransform %s', - hash_files=False, - ), - atlasToSubjectTransformType=dict(argstr='--atlasToSubjectTransformType %s', - ), - atlasWarpingOff=dict(argstr='--atlasWarpingOff ', - ), - debuglevel=dict(argstr='--debuglevel %d', - ), - defaultSuffix=dict(argstr='--defaultSuffix %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - filterIteration=dict(argstr='--filterIteration %d', - ), - filterMethod=dict(argstr='--filterMethod %s', - ), - filterTimeStep=dict(argstr='--filterTimeStep %f', - ), - gridSize=dict(argstr='--gridSize %s', - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - implicitOutputs=dict(argstr='--implicitOutputs %s...', - hash_files=False, - ), - inputVolumeTypes=dict(argstr='--inputVolumeTypes %s', - sep=',', - ), - inputVolumes=dict(argstr='--inputVolumes %s...', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - maxBiasDegree=dict(argstr='--maxBiasDegree %d', - ), - maxIterations=dict(argstr='--maxIterations %d', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - numberOfSubSamplesInEachPlugArea=dict(argstr='--numberOfSubSamplesInEachPlugArea %s', - sep=',', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputDir=dict(argstr='--outputDir %s', - hash_files=False, - ), - outputDirtyLabels=dict(argstr='--outputDirtyLabels %s', - hash_files=False, - ), - outputFormat=dict(argstr='--outputFormat %s', - ), - outputLabels=dict(argstr='--outputLabels %s', - hash_files=False, - ), - outputVolumes=dict(argstr='--outputVolumes %s...', - hash_files=False, - ), - posteriorTemplate=dict(argstr='--posteriorTemplate %s', - ), - purePlugsThreshold=dict(argstr='--purePlugsThreshold %f', - ), - restoreState=dict(argstr='--restoreState %s', - ), - saveState=dict(argstr='--saveState %s', - hash_files=False, - ), - subjectIntermodeTransformType=dict(argstr='--subjectIntermodeTransformType %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - useKNN=dict(argstr='--useKNN ', - ), - writeLess=dict(argstr='--writeLess ', - ), + input_map = dict( + args=dict(argstr='%s', ), + atlasDefinition=dict(argstr='--atlasDefinition %s', ), + atlasToSubjectInitialTransform=dict( + argstr='--atlasToSubjectInitialTransform %s', + hash_files=False, + ), + atlasToSubjectTransform=dict( + argstr='--atlasToSubjectTransform %s', + hash_files=False, + ), + atlasToSubjectTransformType=dict( + argstr='--atlasToSubjectTransformType %s', ), + atlasWarpingOff=dict(argstr='--atlasWarpingOff ', ), + debuglevel=dict(argstr='--debuglevel %d', ), + defaultSuffix=dict(argstr='--defaultSuffix %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + filterIteration=dict(argstr='--filterIteration %d', ), + filterMethod=dict(argstr='--filterMethod %s', ), + filterTimeStep=dict(argstr='--filterTimeStep %f', ), + gridSize=dict( + argstr='--gridSize %s', + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + implicitOutputs=dict( + argstr='--implicitOutputs %s...', + hash_files=False, + ), + inputVolumeTypes=dict( + argstr='--inputVolumeTypes %s', + sep=',', + ), + inputVolumes=dict(argstr='--inputVolumes %s...', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + maxBiasDegree=dict(argstr='--maxBiasDegree %d', ), + maxIterations=dict(argstr='--maxIterations %d', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + numberOfSubSamplesInEachPlugArea=dict( + argstr='--numberOfSubSamplesInEachPlugArea %s', + sep=',', + ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputDir=dict( + argstr='--outputDir %s', + hash_files=False, + ), + outputDirtyLabels=dict( + argstr='--outputDirtyLabels %s', + hash_files=False, + ), + outputFormat=dict(argstr='--outputFormat %s', ), + outputLabels=dict( + argstr='--outputLabels %s', + hash_files=False, + ), + outputVolumes=dict( + argstr='--outputVolumes %s...', + hash_files=False, + ), + posteriorTemplate=dict(argstr='--posteriorTemplate %s', ), + purePlugsThreshold=dict(argstr='--purePlugsThreshold %f', ), + restoreState=dict(argstr='--restoreState %s', ), + saveState=dict( + argstr='--saveState %s', + hash_files=False, + ), + subjectIntermodeTransformType=dict( + argstr='--subjectIntermodeTransformType %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + useKNN=dict(argstr='--useKNN ', ), + writeLess=dict(argstr='--writeLess ', ), ) inputs = BRAINSABC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSABC_outputs(): - output_map = dict(atlasToSubjectInitialTransform=dict(), - atlasToSubjectTransform=dict(), - implicitOutputs=dict(), - outputDir=dict(), - outputDirtyLabels=dict(), - outputLabels=dict(), - outputVolumes=dict(), - saveState=dict(), + output_map = dict( + atlasToSubjectInitialTransform=dict(), + atlasToSubjectTransform=dict(), + implicitOutputs=dict(), + outputDir=dict(), + outputDirtyLabels=dict(), + outputLabels=dict(), + outputVolumes=dict(), + saveState=dict(), ) outputs = BRAINSABC.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py index 865ce1fe93..31fbccd144 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py @@ -4,132 +4,126 @@ def test_BRAINSConstellationDetector_inputs(): - input_map = dict(BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', - ), - LLSModel=dict(argstr='--LLSModel %s', - ), - acLowerBound=dict(argstr='--acLowerBound %f', - ), - args=dict(argstr='%s', - ), - atlasLandmarkWeights=dict(argstr='--atlasLandmarkWeights %s', - ), - atlasLandmarks=dict(argstr='--atlasLandmarks %s', - ), - atlasVolume=dict(argstr='--atlasVolume %s', - ), - cutOutHeadInOutputVolume=dict(argstr='--cutOutHeadInOutputVolume ', - ), - debug=dict(argstr='--debug ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - forceACPoint=dict(argstr='--forceACPoint %s', - sep=',', - ), - forceHoughEyeDetectorReportFailure=dict(argstr='--forceHoughEyeDetectorReportFailure ', - ), - forcePCPoint=dict(argstr='--forcePCPoint %s', - sep=',', - ), - forceRPPoint=dict(argstr='--forceRPPoint %s', - sep=',', - ), - forceVN4Point=dict(argstr='--forceVN4Point %s', - sep=',', - ), - houghEyeDetectorMode=dict(argstr='--houghEyeDetectorMode %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputLandmarksEMSP=dict(argstr='--inputLandmarksEMSP %s', - ), - inputTemplateModel=dict(argstr='--inputTemplateModel %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - mspQualityLevel=dict(argstr='--mspQualityLevel %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', - ), - outputLandmarksInACPCAlignedSpace=dict(argstr='--outputLandmarksInACPCAlignedSpace %s', - hash_files=False, - ), - outputLandmarksInInputSpace=dict(argstr='--outputLandmarksInInputSpace %s', - hash_files=False, - ), - outputMRML=dict(argstr='--outputMRML %s', - hash_files=False, - ), - outputResampledVolume=dict(argstr='--outputResampledVolume %s', - hash_files=False, - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - outputUntransformedClippedVolume=dict(argstr='--outputUntransformedClippedVolume %s', - hash_files=False, - ), - outputVerificationScript=dict(argstr='--outputVerificationScript %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - rVN4=dict(argstr='--rVN4 %f', - ), - rac=dict(argstr='--rac %f', - ), - rescaleIntensities=dict(argstr='--rescaleIntensities ', - ), - rescaleIntensitiesOutputRange=dict(argstr='--rescaleIntensitiesOutputRange %s', - sep=',', - ), - resultsDir=dict(argstr='--resultsDir %s', - hash_files=False, - ), - rmpj=dict(argstr='--rmpj %f', - ), - rpc=dict(argstr='--rpc %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trimRescaledIntensities=dict(argstr='--trimRescaledIntensities %f', - ), - verbose=dict(argstr='--verbose ', - ), - writeBranded2DImage=dict(argstr='--writeBranded2DImage %s', - hash_files=False, - ), - writedebuggingImagesLevel=dict(argstr='--writedebuggingImagesLevel %d', - ), + input_map = dict( + BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', ), + LLSModel=dict(argstr='--LLSModel %s', ), + acLowerBound=dict(argstr='--acLowerBound %f', ), + args=dict(argstr='%s', ), + atlasLandmarkWeights=dict(argstr='--atlasLandmarkWeights %s', ), + atlasLandmarks=dict(argstr='--atlasLandmarks %s', ), + atlasVolume=dict(argstr='--atlasVolume %s', ), + cutOutHeadInOutputVolume=dict(argstr='--cutOutHeadInOutputVolume ', ), + debug=dict(argstr='--debug ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + forceACPoint=dict( + argstr='--forceACPoint %s', + sep=',', + ), + forceHoughEyeDetectorReportFailure=dict( + argstr='--forceHoughEyeDetectorReportFailure ', ), + forcePCPoint=dict( + argstr='--forcePCPoint %s', + sep=',', + ), + forceRPPoint=dict( + argstr='--forceRPPoint %s', + sep=',', + ), + forceVN4Point=dict( + argstr='--forceVN4Point %s', + sep=',', + ), + houghEyeDetectorMode=dict(argstr='--houghEyeDetectorMode %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputLandmarksEMSP=dict(argstr='--inputLandmarksEMSP %s', ), + inputTemplateModel=dict(argstr='--inputTemplateModel %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + mspQualityLevel=dict(argstr='--mspQualityLevel %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', ), + outputLandmarksInACPCAlignedSpace=dict( + argstr='--outputLandmarksInACPCAlignedSpace %s', + hash_files=False, + ), + outputLandmarksInInputSpace=dict( + argstr='--outputLandmarksInInputSpace %s', + hash_files=False, + ), + outputMRML=dict( + argstr='--outputMRML %s', + hash_files=False, + ), + outputResampledVolume=dict( + argstr='--outputResampledVolume %s', + hash_files=False, + ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + outputUntransformedClippedVolume=dict( + argstr='--outputUntransformedClippedVolume %s', + hash_files=False, + ), + outputVerificationScript=dict( + argstr='--outputVerificationScript %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + rVN4=dict(argstr='--rVN4 %f', ), + rac=dict(argstr='--rac %f', ), + rescaleIntensities=dict(argstr='--rescaleIntensities ', ), + rescaleIntensitiesOutputRange=dict( + argstr='--rescaleIntensitiesOutputRange %s', + sep=',', + ), + resultsDir=dict( + argstr='--resultsDir %s', + hash_files=False, + ), + rmpj=dict(argstr='--rmpj %f', ), + rpc=dict(argstr='--rpc %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trimRescaledIntensities=dict(argstr='--trimRescaledIntensities %f', ), + verbose=dict(argstr='--verbose ', ), + writeBranded2DImage=dict( + argstr='--writeBranded2DImage %s', + hash_files=False, + ), + writedebuggingImagesLevel=dict( + argstr='--writedebuggingImagesLevel %d', ), ) inputs = BRAINSConstellationDetector.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSConstellationDetector_outputs(): - output_map = dict(outputLandmarksInACPCAlignedSpace=dict(), - outputLandmarksInInputSpace=dict(), - outputMRML=dict(), - outputResampledVolume=dict(), - outputTransform=dict(), - outputUntransformedClippedVolume=dict(), - outputVerificationScript=dict(), - outputVolume=dict(), - resultsDir=dict(), - writeBranded2DImage=dict(), + output_map = dict( + outputLandmarksInACPCAlignedSpace=dict(), + outputLandmarksInInputSpace=dict(), + outputMRML=dict(), + outputResampledVolume=dict(), + outputTransform=dict(), + outputUntransformedClippedVolume=dict(), + outputVerificationScript=dict(), + outputVolume=dict(), + resultsDir=dict(), + writeBranded2DImage=dict(), ) outputs = BRAINSConstellationDetector.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py index b3962fd835..1e9f7bfeda 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py @@ -4,47 +4,50 @@ def test_BRAINSCreateLabelMapFromProbabilityMaps_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cleanLabelVolume=dict(argstr='--cleanLabelVolume %s', - hash_files=False, - ), - dirtyLabelVolume=dict(argstr='--dirtyLabelVolume %s', - hash_files=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - foregroundPriors=dict(argstr='--foregroundPriors %s', - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inclusionThreshold=dict(argstr='--inclusionThreshold %f', - ), - inputProbabilityVolume=dict(argstr='--inputProbabilityVolume %s...', - ), - nonAirRegionMask=dict(argstr='--nonAirRegionMask %s', - ), - priorLabelCodes=dict(argstr='--priorLabelCodes %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + cleanLabelVolume=dict( + argstr='--cleanLabelVolume %s', + hash_files=False, + ), + dirtyLabelVolume=dict( + argstr='--dirtyLabelVolume %s', + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + foregroundPriors=dict( + argstr='--foregroundPriors %s', + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inclusionThreshold=dict(argstr='--inclusionThreshold %f', ), + inputProbabilityVolume=dict(argstr='--inputProbabilityVolume %s...', ), + nonAirRegionMask=dict(argstr='--nonAirRegionMask %s', ), + priorLabelCodes=dict( + argstr='--priorLabelCodes %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSCreateLabelMapFromProbabilityMaps.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSCreateLabelMapFromProbabilityMaps_outputs(): - output_map = dict(cleanLabelVolume=dict(), - dirtyLabelVolume=dict(), + output_map = dict( + cleanLabelVolume=dict(), + dirtyLabelVolume=dict(), ) outputs = BRAINSCreateLabelMapFromProbabilityMaps.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py index 5e8a6f99bd..8d4e8a018e 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py @@ -4,60 +4,46 @@ def test_BRAINSCut_inputs(): - input_map = dict(NoTrainingVectorShuffling=dict(argstr='--NoTrainingVectorShuffling ', - ), - applyModel=dict(argstr='--applyModel ', - ), - args=dict(argstr='%s', - ), - computeSSEOn=dict(argstr='--computeSSEOn ', - ), - createVectors=dict(argstr='--createVectors ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - generateProbability=dict(argstr='--generateProbability ', - ), - histogramEqualization=dict(argstr='--histogramEqualization ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - method=dict(argstr='--method %s', - ), - modelConfigurationFilename=dict(argstr='--modelConfigurationFilename %s', - ), - modelFilename=dict(argstr='--modelFilename %s', - ), - multiStructureThreshold=dict(argstr='--multiStructureThreshold ', - ), - netConfiguration=dict(argstr='--netConfiguration %s', - ), - numberOfTrees=dict(argstr='--numberOfTrees %d', - ), - randomTreeDepth=dict(argstr='--randomTreeDepth %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trainModel=dict(argstr='--trainModel ', - ), - trainModelStartIndex=dict(argstr='--trainModelStartIndex %d', - ), - validate=dict(argstr='--validate ', - ), - verbose=dict(argstr='--verbose %d', - ), + input_map = dict( + NoTrainingVectorShuffling=dict( + argstr='--NoTrainingVectorShuffling ', ), + applyModel=dict(argstr='--applyModel ', ), + args=dict(argstr='%s', ), + computeSSEOn=dict(argstr='--computeSSEOn ', ), + createVectors=dict(argstr='--createVectors ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + generateProbability=dict(argstr='--generateProbability ', ), + histogramEqualization=dict(argstr='--histogramEqualization ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + method=dict(argstr='--method %s', ), + modelConfigurationFilename=dict( + argstr='--modelConfigurationFilename %s', ), + modelFilename=dict(argstr='--modelFilename %s', ), + multiStructureThreshold=dict(argstr='--multiStructureThreshold ', ), + netConfiguration=dict(argstr='--netConfiguration %s', ), + numberOfTrees=dict(argstr='--numberOfTrees %d', ), + randomTreeDepth=dict(argstr='--randomTreeDepth %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trainModel=dict(argstr='--trainModel ', ), + trainModelStartIndex=dict(argstr='--trainModelStartIndex %d', ), + validate=dict(argstr='--validate ', ), + verbose=dict(argstr='--verbose %d', ), ) inputs = BRAINSCut.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSCut_outputs(): output_map = dict() outputs = BRAINSCut.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py index 38035b7903..b879ea9442 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py @@ -4,47 +4,45 @@ def test_BRAINSMultiSTAPLE_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputCompositeT1Volume=dict(argstr='--inputCompositeT1Volume %s', - ), - inputLabelVolume=dict(argstr='--inputLabelVolume %s...', - ), - inputTransform=dict(argstr='--inputTransform %s...', - ), - labelForUndecidedPixels=dict(argstr='--labelForUndecidedPixels %d', - ), - outputConfusionMatrix=dict(argstr='--outputConfusionMatrix %s', - hash_files=False, - ), - outputMultiSTAPLE=dict(argstr='--outputMultiSTAPLE %s', - hash_files=False, - ), - resampledVolumePrefix=dict(argstr='--resampledVolumePrefix %s', - ), - skipResampling=dict(argstr='--skipResampling ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputCompositeT1Volume=dict(argstr='--inputCompositeT1Volume %s', ), + inputLabelVolume=dict(argstr='--inputLabelVolume %s...', ), + inputTransform=dict(argstr='--inputTransform %s...', ), + labelForUndecidedPixels=dict(argstr='--labelForUndecidedPixels %d', ), + outputConfusionMatrix=dict( + argstr='--outputConfusionMatrix %s', + hash_files=False, + ), + outputMultiSTAPLE=dict( + argstr='--outputMultiSTAPLE %s', + hash_files=False, + ), + resampledVolumePrefix=dict(argstr='--resampledVolumePrefix %s', ), + skipResampling=dict(argstr='--skipResampling ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSMultiSTAPLE.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSMultiSTAPLE_outputs(): - output_map = dict(outputConfusionMatrix=dict(), - outputMultiSTAPLE=dict(), + output_map = dict( + outputConfusionMatrix=dict(), + outputMultiSTAPLE=dict(), ) outputs = BRAINSMultiSTAPLE.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py index 577f01aba6..e3414b7320 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py @@ -4,53 +4,49 @@ def test_BRAINSROIAuto_inputs(): - input_map = dict(ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', - ), - args=dict(argstr='%s', - ), - closingSize=dict(argstr='--closingSize %f', - ), - cropOutput=dict(argstr='--cropOutput ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - maskOutput=dict(argstr='--maskOutput ', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', - ), - outputROIMaskVolume=dict(argstr='--outputROIMaskVolume %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresholdCorrectionFactor=dict(argstr='--thresholdCorrectionFactor %f', - ), + input_map = dict( + ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', ), + args=dict(argstr='%s', ), + closingSize=dict(argstr='--closingSize %f', ), + cropOutput=dict(argstr='--cropOutput ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + maskOutput=dict(argstr='--maskOutput ', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', ), + outputROIMaskVolume=dict( + argstr='--outputROIMaskVolume %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresholdCorrectionFactor=dict( + argstr='--thresholdCorrectionFactor %f', ), ) inputs = BRAINSROIAuto.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSROIAuto_outputs(): - output_map = dict(outputROIMaskVolume=dict(), - outputVolume=dict(), + output_map = dict( + outputROIMaskVolume=dict(), + outputVolume=dict(), ) outputs = BRAINSROIAuto.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py index f9c7d4a191..a6569264a3 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py @@ -4,48 +4,51 @@ def test_BinaryMaskEditorBasedOnLandmarks_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBinaryVolume=dict(argstr='--inputBinaryVolume %s', - ), - inputLandmarkNames=dict(argstr='--inputLandmarkNames %s', - sep=',', - ), - inputLandmarkNamesForObliquePlane=dict(argstr='--inputLandmarkNamesForObliquePlane %s', - sep=',', - ), - inputLandmarksFilename=dict(argstr='--inputLandmarksFilename %s', - ), - outputBinaryVolume=dict(argstr='--outputBinaryVolume %s', - hash_files=False, - ), - setCutDirectionForLandmark=dict(argstr='--setCutDirectionForLandmark %s', - sep=',', - ), - setCutDirectionForObliquePlane=dict(argstr='--setCutDirectionForObliquePlane %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBinaryVolume=dict(argstr='--inputBinaryVolume %s', ), + inputLandmarkNames=dict( + argstr='--inputLandmarkNames %s', + sep=',', + ), + inputLandmarkNamesForObliquePlane=dict( + argstr='--inputLandmarkNamesForObliquePlane %s', + sep=',', + ), + inputLandmarksFilename=dict(argstr='--inputLandmarksFilename %s', ), + outputBinaryVolume=dict( + argstr='--outputBinaryVolume %s', + hash_files=False, + ), + setCutDirectionForLandmark=dict( + argstr='--setCutDirectionForLandmark %s', + sep=',', + ), + setCutDirectionForObliquePlane=dict( + argstr='--setCutDirectionForObliquePlane %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BinaryMaskEditorBasedOnLandmarks.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BinaryMaskEditorBasedOnLandmarks_outputs(): - output_map = dict(outputBinaryVolume=dict(), - ) + output_map = dict(outputBinaryVolume=dict(), ) outputs = BinaryMaskEditorBasedOnLandmarks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py index cd29a7fd82..cc14b572af 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py @@ -4,48 +4,41 @@ def test_ESLR_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - closingSize=dict(argstr='--closingSize %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - high=dict(argstr='--high %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - low=dict(argstr='--low %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - openingSize=dict(argstr='--openingSize %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - preserveOutside=dict(argstr='--preserveOutside ', - ), - safetySize=dict(argstr='--safetySize %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + closingSize=dict(argstr='--closingSize %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + high=dict(argstr='--high %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + low=dict(argstr='--low %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + openingSize=dict(argstr='--openingSize %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + preserveOutside=dict(argstr='--preserveOutside ', ), + safetySize=dict(argstr='--safetySize %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ESLR.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ESLR_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = ESLR.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/testing/featuredetection.py b/nipype/interfaces/semtools/testing/featuredetection.py index ec684d5907..e8f332c0a6 100644 --- a/nipype/interfaces/semtools/testing/featuredetection.py +++ b/nipype/interfaces/semtools/testing/featuredetection.py @@ -8,8 +8,11 @@ class SphericalCoordinateGenerationInputSpec(CommandLineInputSpec): - inputAtlasImage = File(desc="Input atlas image", exists=True, argstr="--inputAtlasImage %s") - outputPath = traits.Str(desc="Output path for rho, phi and theta images", argstr="--outputPath %s") + inputAtlasImage = File( + desc="Input atlas image", exists=True, argstr="--inputAtlasImage %s") + outputPath = traits.Str( + desc="Output path for rho, phi and theta images", + argstr="--outputPath %s") class SphericalCoordinateGenerationOutputSpec(TraitedSpec): @@ -17,7 +20,6 @@ class SphericalCoordinateGenerationOutputSpec(TraitedSpec): class SphericalCoordinateGeneration(SEMLikeCommandLine): - """title: Spherical Coordinate Generation category: Testing.FeatureDetection diff --git a/nipype/interfaces/semtools/testing/generateaveragelmkfile.py b/nipype/interfaces/semtools/testing/generateaveragelmkfile.py index a308778415..bbb414c366 100644 --- a/nipype/interfaces/semtools/testing/generateaveragelmkfile.py +++ b/nipype/interfaces/semtools/testing/generateaveragelmkfile.py @@ -8,16 +8,28 @@ class GenerateAverageLmkFileInputSpec(CommandLineInputSpec): - inputLandmarkFiles = InputMultiPath(traits.Str, desc="Input landmark files names (.fcsv or .wts)", sep=",", argstr="--inputLandmarkFiles %s") - outputLandmarkFile = traits.Either(traits.Bool, File(), hash_files=False, desc="Ouput landmark file name that includes average values for landmarks (.fcsv or .wts)", argstr="--outputLandmarkFile %s") + inputLandmarkFiles = InputMultiPath( + traits.Str, + desc="Input landmark files names (.fcsv or .wts)", + sep=",", + argstr="--inputLandmarkFiles %s") + outputLandmarkFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Ouput landmark file name that includes average values for landmarks (.fcsv or .wts)", + argstr="--outputLandmarkFile %s") class GenerateAverageLmkFileOutputSpec(TraitedSpec): - outputLandmarkFile = File(desc="Ouput landmark file name that includes average values for landmarks (.fcsv or .wts)", exists=True) + outputLandmarkFile = File( + desc= + "Ouput landmark file name that includes average values for landmarks (.fcsv or .wts)", + exists=True) class GenerateAverageLmkFile(SEMLikeCommandLine): - """title: Average Fiducials category: Testing diff --git a/nipype/interfaces/semtools/testing/landmarkscompare.py b/nipype/interfaces/semtools/testing/landmarkscompare.py index 6d15778e76..872d6d0df0 100644 --- a/nipype/interfaces/semtools/testing/landmarkscompare.py +++ b/nipype/interfaces/semtools/testing/landmarkscompare.py @@ -8,9 +8,18 @@ class LandmarksCompareInputSpec(CommandLineInputSpec): - inputLandmarkFile1 = File(desc="First input landmark file (.fcsv or .wts)", exists=True, argstr="--inputLandmarkFile1 %s") - inputLandmarkFile2 = File(desc="Second input landmark file (.fcsv or .wts)", exists=True, argstr="--inputLandmarkFile2 %s") - tolerance = traits.Float(desc="The maximum error (in mm) allowed in each direction of a landmark", argstr="--tolerance %f") + inputLandmarkFile1 = File( + desc="First input landmark file (.fcsv or .wts)", + exists=True, + argstr="--inputLandmarkFile1 %s") + inputLandmarkFile2 = File( + desc="Second input landmark file (.fcsv or .wts)", + exists=True, + argstr="--inputLandmarkFile2 %s") + tolerance = traits.Float( + desc= + "The maximum error (in mm) allowed in each direction of a landmark", + argstr="--tolerance %f") class LandmarksCompareOutputSpec(TraitedSpec): @@ -18,7 +27,6 @@ class LandmarksCompareOutputSpec(TraitedSpec): class LandmarksCompare(SEMLikeCommandLine): - """title: Compare Fiducials category: Testing diff --git a/nipype/interfaces/semtools/tests/test_auto_DWICompare.py b/nipype/interfaces/semtools/tests/test_auto_DWICompare.py index a9c60b1229..d6e193264d 100644 --- a/nipype/interfaces/semtools/tests/test_auto_DWICompare.py +++ b/nipype/interfaces/semtools/tests/test_auto_DWICompare.py @@ -4,30 +4,29 @@ def test_DWICompare_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='--inputVolume1 %s', - ), - inputVolume2=dict(argstr='--inputVolume2 %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict(argstr='--inputVolume1 %s', ), + inputVolume2=dict(argstr='--inputVolume2 %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWICompare.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWICompare_outputs(): output_map = dict() outputs = DWICompare.output_spec() diff --git a/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py b/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py index 271085be8c..5a274eedab 100644 --- a/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py +++ b/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py @@ -4,32 +4,30 @@ def test_DWISimpleCompare_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - checkDWIData=dict(argstr='--checkDWIData ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='--inputVolume1 %s', - ), - inputVolume2=dict(argstr='--inputVolume2 %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + checkDWIData=dict(argstr='--checkDWIData ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict(argstr='--inputVolume1 %s', ), + inputVolume2=dict(argstr='--inputVolume2 %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWISimpleCompare.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWISimpleCompare_outputs(): output_map = dict() outputs = DWISimpleCompare.output_spec() diff --git a/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py b/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py index 83d0194964..e5fd94f7c0 100644 --- a/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py +++ b/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py @@ -4,34 +4,34 @@ def test_GenerateCsfClippedFromClassifiedImage_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputCassifiedVolume=dict(argstr='--inputCassifiedVolume %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputCassifiedVolume=dict(argstr='--inputCassifiedVolume %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GenerateCsfClippedFromClassifiedImage.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateCsfClippedFromClassifiedImage_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = GenerateCsfClippedFromClassifiedImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/__init__.py b/nipype/interfaces/semtools/utilities/__init__.py index f647492fcc..698b76a534 100644 --- a/nipype/interfaces/semtools/utilities/__init__.py +++ b/nipype/interfaces/semtools/utilities/__init__.py @@ -1,3 +1,11 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import -from .brains import BRAINSConstellationModeler, landmarksConstellationWeights, BRAINSTrimForegroundInDirection, BRAINSLmkTransform, BRAINSMush, BRAINSTransformConvert, landmarksConstellationAligner, BRAINSEyeDetector, BRAINSLinearModelerEPCA, BRAINSInitializedControlPoints, CleanUpOverlapLabels, BRAINSClipInferior, GenerateLabelMapFromProbabilityMap, BRAINSAlignMSP, BRAINSLandmarkInitializer, insertMidACPCpoint, BRAINSSnapShotWriter, JointHistogram, ShuffleVectorsModule, ImageRegionPlotter +from .brains import ( + BRAINSConstellationModeler, landmarksConstellationWeights, + BRAINSTrimForegroundInDirection, BRAINSLmkTransform, BRAINSMush, + BRAINSTransformConvert, landmarksConstellationAligner, BRAINSEyeDetector, + BRAINSLinearModelerEPCA, BRAINSInitializedControlPoints, + CleanUpOverlapLabels, BRAINSClipInferior, + GenerateLabelMapFromProbabilityMap, BRAINSAlignMSP, + BRAINSLandmarkInitializer, insertMidACPCpoint, BRAINSSnapShotWriter, + JointHistogram, ShuffleVectorsModule, ImageRegionPlotter) diff --git a/nipype/interfaces/semtools/utilities/brains.py b/nipype/interfaces/semtools/utilities/brains.py index 4e64db7bd4..abc696b5d9 100644 --- a/nipype/interfaces/semtools/utilities/brains.py +++ b/nipype/interfaces/semtools/utilities/brains.py @@ -11,32 +11,79 @@ class BRAINSConstellationModelerInputSpec(CommandLineInputSpec): - verbose = traits.Bool(desc=", Show more verbose output, ", argstr="--verbose ") - inputTrainingList = File(desc=", Setup file, giving all parameters for training up a template model for each landmark., ", exists=True, argstr="--inputTrainingList %s") - outputModel = traits.Either(traits.Bool, File(), hash_files=False, desc=", The full filename of the output model file., ", argstr="--outputModel %s") + verbose = traits.Bool( + desc=", Show more verbose output, ", + argstr="--verbose ") + inputTrainingList = File( + desc= + ", Setup file, giving all parameters for training up a template model for each landmark., ", + exists=True, + argstr="--inputTrainingList %s") + outputModel = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + ", The full filename of the output model file., ", + argstr="--outputModel %s") saveOptimizedLandmarks = traits.Bool( - desc=", Flag to make a new subject-specific landmark definition file in the same format produced by Slicer3 with the optimized landmark (the detected RP, AC, and PC) in it. Useful to tighten the variances in the ConstellationModeler., ", argstr="--saveOptimizedLandmarks ") + desc= + ", Flag to make a new subject-specific landmark definition file in the same format produced by Slicer3 with the optimized landmark (the detected RP, AC, and PC) in it. Useful to tighten the variances in the ConstellationModeler., ", + argstr="--saveOptimizedLandmarks ") optimizedLandmarksFilenameExtender = traits.Str( - desc=", If the trainingList is (indexFullPathName) and contains landmark data filenames [path]/[filename].fcsv , make the optimized landmarks filenames out of [path]/[filename](thisExtender) and the optimized version of the input trainingList out of (indexFullPathName)(thisExtender) , when you rewrite all the landmarks according to the saveOptimizedLandmarks flag., ", argstr="--optimizedLandmarksFilenameExtender %s") - resultsDir = traits.Either(traits.Bool, Directory(), hash_files=False, desc=", The directory for the results to be written., ", argstr="--resultsDir %s") - mspQualityLevel = traits.Int(desc=", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", argstr="--mspQualityLevel %d") - rescaleIntensities = traits.Bool(desc=", Flag to turn on rescaling image intensities on input., ", argstr="--rescaleIntensities ") + desc= + ", If the trainingList is (indexFullPathName) and contains landmark data filenames [path]/[filename].fcsv , make the optimized landmarks filenames out of [path]/[filename](thisExtender) and the optimized version of the input trainingList out of (indexFullPathName)(thisExtender) , when you rewrite all the landmarks according to the saveOptimizedLandmarks flag., ", + argstr="--optimizedLandmarksFilenameExtender %s") + resultsDir = traits.Either( + traits.Bool, + Directory(), + hash_files=False, + desc= + ", The directory for the results to be written., ", + argstr="--resultsDir %s") + mspQualityLevel = traits.Int( + desc= + ", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", + argstr="--mspQualityLevel %d") + rescaleIntensities = traits.Bool( + desc= + ", Flag to turn on rescaling image intensities on input., ", + argstr="--rescaleIntensities ") trimRescaledIntensities = traits.Float( - desc=", Turn on clipping the rescaled image one-tailed on input. Units of standard deviations above the mean. Very large values are very permissive. Non-positive value turns clipping off. Defaults to removing 0.00001 of a normal tail above the mean., ", argstr="--trimRescaledIntensities %f") + desc= + ", Turn on clipping the rescaled image one-tailed on input. Units of standard deviations above the mean. Very large values are very permissive. Non-positive value turns clipping off. Defaults to removing 0.00001 of a normal tail above the mean., ", + argstr="--trimRescaledIntensities %f") rescaleIntensitiesOutputRange = InputMultiPath( - traits.Int, desc=", This pair of integers gives the lower and upper bounds on the signal portion of the output image. Out-of-field voxels are taken from BackgroundFillValue., ", sep=",", argstr="--rescaleIntensitiesOutputRange %s") - BackgroundFillValue = traits.Str(desc="Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", argstr="--BackgroundFillValue %s") - writedebuggingImagesLevel = traits.Int(desc=", This flag controls if debugging images are produced. By default value of 0 is no images. Anything greater than zero will be increasing level of debugging images., ", argstr="--writedebuggingImagesLevel %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + traits.Int, + desc= + ", This pair of integers gives the lower and upper bounds on the signal portion of the output image. Out-of-field voxels are taken from BackgroundFillValue., ", + sep=",", + argstr="--rescaleIntensitiesOutputRange %s") + BackgroundFillValue = traits.Str( + desc= + "Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", + argstr="--BackgroundFillValue %s") + writedebuggingImagesLevel = traits.Int( + desc= + ", This flag controls if debugging images are produced. By default value of 0 is no images. Anything greater than zero will be increasing level of debugging images., ", + argstr="--writedebuggingImagesLevel %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSConstellationModelerOutputSpec(TraitedSpec): - outputModel = File(desc=", The full filename of the output model file., ", exists=True) - resultsDir = Directory(desc=", The directory for the results to be written., ", exists=True) + outputModel = File( + desc= + ", The full filename of the output model file., ", + exists=True) + resultsDir = Directory( + desc= + ", The directory for the results to be written., ", + exists=True) class BRAINSConstellationModeler(SEMLikeCommandLine): - """title: Generate Landmarks Model (BRAINS) category: Utilities.BRAINS @@ -48,23 +95,44 @@ class BRAINSConstellationModeler(SEMLikeCommandLine): input_spec = BRAINSConstellationModelerInputSpec output_spec = BRAINSConstellationModelerOutputSpec _cmd = " BRAINSConstellationModeler " - _outputs_filenames = {'outputModel': 'outputModel.mdl', 'resultsDir': 'resultsDir'} + _outputs_filenames = { + 'outputModel': 'outputModel.mdl', + 'resultsDir': 'resultsDir' + } _redirect_x = False class landmarksConstellationWeightsInputSpec(CommandLineInputSpec): - inputTrainingList = File(desc=", Setup file, giving all parameters for training up a Weight list for landmark., ", exists=True, argstr="--inputTrainingList %s") - inputTemplateModel = File(desc="User-specified template model., ", exists=True, argstr="--inputTemplateModel %s") - LLSModel = File(desc="Linear least squares model filename in HD5 format", exists=True, argstr="--LLSModel %s") - outputWeightsList = traits.Either(traits.Bool, File(), hash_files=False, desc=", The filename of a csv file which is a list of landmarks and their corresponding weights., ", argstr="--outputWeightsList %s") + inputTrainingList = File( + desc= + ", Setup file, giving all parameters for training up a Weight list for landmark., ", + exists=True, + argstr="--inputTrainingList %s") + inputTemplateModel = File( + desc="User-specified template model., ", + exists=True, + argstr="--inputTemplateModel %s") + LLSModel = File( + desc="Linear least squares model filename in HD5 format", + exists=True, + argstr="--LLSModel %s") + outputWeightsList = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + ", The filename of a csv file which is a list of landmarks and their corresponding weights., ", + argstr="--outputWeightsList %s") class landmarksConstellationWeightsOutputSpec(TraitedSpec): - outputWeightsList = File(desc=", The filename of a csv file which is a list of landmarks and their corresponding weights., ", exists=True) + outputWeightsList = File( + desc= + ", The filename of a csv file which is a list of landmarks and their corresponding weights., ", + exists=True) class landmarksConstellationWeights(SEMLikeCommandLine): - """title: Generate Landmarks Weights (BRAINS) category: Utilities.BRAINS @@ -81,22 +149,50 @@ class landmarksConstellationWeights(SEMLikeCommandLine): class BRAINSTrimForegroundInDirectionInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Input image to trim off the neck (and also air-filling noise.)", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output image with neck and air-filling noise trimmed isotropic image with AC at center of image.", argstr="--outputVolume %s") - directionCode = traits.Int(desc=", This flag chooses which dimension to compare. The sign lets you flip direction., ", argstr="--directionCode %d") - otsuPercentileThreshold = traits.Float(desc=", This is a parameter to FindLargestForegroundFilledMask, which is employed to trim off air-filling noise., ", argstr="--otsuPercentileThreshold %f") - closingSize = traits.Int(desc=", This is a parameter to FindLargestForegroundFilledMask, ", argstr="--closingSize %d") - headSizeLimit = traits.Float(desc=", Use this to vary from the command line our search for how much upper tissue is head for the center-of-mass calculation. Units are CCs, not cubic millimeters., ", argstr="--headSizeLimit %f") - BackgroundFillValue = traits.Str(desc="Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", argstr="--BackgroundFillValue %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="Input image to trim off the neck (and also air-filling noise.)", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output image with neck and air-filling noise trimmed isotropic image with AC at center of image.", + argstr="--outputVolume %s") + directionCode = traits.Int( + desc= + ", This flag chooses which dimension to compare. The sign lets you flip direction., ", + argstr="--directionCode %d") + otsuPercentileThreshold = traits.Float( + desc= + ", This is a parameter to FindLargestForegroundFilledMask, which is employed to trim off air-filling noise., ", + argstr="--otsuPercentileThreshold %f") + closingSize = traits.Int( + desc= + ", This is a parameter to FindLargestForegroundFilledMask, ", + argstr="--closingSize %d") + headSizeLimit = traits.Float( + desc= + ", Use this to vary from the command line our search for how much upper tissue is head for the center-of-mass calculation. Units are CCs, not cubic millimeters., ", + argstr="--headSizeLimit %f") + BackgroundFillValue = traits.Str( + desc= + "Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", + argstr="--BackgroundFillValue %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSTrimForegroundInDirectionOutputSpec(TraitedSpec): - outputVolume = File(desc="Output image with neck and air-filling noise trimmed isotropic image with AC at center of image.", exists=True) + outputVolume = File( + desc= + "Output image with neck and air-filling noise trimmed isotropic image with AC at center of image.", + exists=True) class BRAINSTrimForegroundInDirection(SEMLikeCommandLine): - """title: Trim Foreground In Direction (BRAINS) category: Utilities.BRAINS @@ -117,22 +213,48 @@ class BRAINSTrimForegroundInDirection(SEMLikeCommandLine): class BRAINSLmkTransformInputSpec(CommandLineInputSpec): - inputMovingLandmarks = File(desc="Input Moving Landmark list file in fcsv, ", exists=True, argstr="--inputMovingLandmarks %s") - inputFixedLandmarks = File(desc="Input Fixed Landmark list file in fcsv, ", exists=True, argstr="--inputFixedLandmarks %s") - outputAffineTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="The filename for the estimated affine transform, ", argstr="--outputAffineTransform %s") - inputMovingVolume = File(desc="The filename of input moving volume", exists=True, argstr="--inputMovingVolume %s") - inputReferenceVolume = File(desc="The filename of the reference volume", exists=True, argstr="--inputReferenceVolume %s") - outputResampledVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="The filename of the output resampled volume", argstr="--outputResampledVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputMovingLandmarks = File( + desc="Input Moving Landmark list file in fcsv, ", + exists=True, + argstr="--inputMovingLandmarks %s") + inputFixedLandmarks = File( + desc="Input Fixed Landmark list file in fcsv, ", + exists=True, + argstr="--inputFixedLandmarks %s") + outputAffineTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The filename for the estimated affine transform, ", + argstr="--outputAffineTransform %s") + inputMovingVolume = File( + desc="The filename of input moving volume", + exists=True, + argstr="--inputMovingVolume %s") + inputReferenceVolume = File( + desc="The filename of the reference volume", + exists=True, + argstr="--inputReferenceVolume %s") + outputResampledVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The filename of the output resampled volume", + argstr="--outputResampledVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSLmkTransformOutputSpec(TraitedSpec): - outputAffineTransform = File(desc="The filename for the estimated affine transform, ", exists=True) - outputResampledVolume = File(desc="The filename of the output resampled volume", exists=True) + outputAffineTransform = File( + desc="The filename for the estimated affine transform, ", + exists=True) + outputResampledVolume = File( + desc="The filename of the output resampled volume", exists=True) class BRAINSLmkTransform(SEMLikeCommandLine): - """title: Landmark Transform (BRAINS) category: Utilities.BRAINS @@ -148,37 +270,96 @@ class BRAINSLmkTransform(SEMLikeCommandLine): input_spec = BRAINSLmkTransformInputSpec output_spec = BRAINSLmkTransformOutputSpec _cmd = " BRAINSLmkTransform " - _outputs_filenames = {'outputResampledVolume': 'outputResampledVolume.nii', 'outputAffineTransform': 'outputAffineTransform.h5'} + _outputs_filenames = { + 'outputResampledVolume': 'outputResampledVolume.nii', + 'outputAffineTransform': 'outputAffineTransform.h5' + } _redirect_x = False class BRAINSMushInputSpec(CommandLineInputSpec): - inputFirstVolume = File(desc="Input image (1) for mixture optimization", exists=True, argstr="--inputFirstVolume %s") - inputSecondVolume = File(desc="Input image (2) for mixture optimization", exists=True, argstr="--inputSecondVolume %s") - inputMaskVolume = File(desc="Input label image for mixture optimization", exists=True, argstr="--inputMaskVolume %s") - outputWeightsFile = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Weights File", argstr="--outputWeightsFile %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="The MUSH image produced from the T1 and T2 weighted images", argstr="--outputVolume %s") - outputMask = traits.Either(traits.Bool, File(), hash_files=False, desc="The brain volume mask generated from the MUSH image", argstr="--outputMask %s") - seed = InputMultiPath(traits.Int, desc="Seed Point for Brain Region Filling", sep=",", argstr="--seed %s") - desiredMean = traits.Float(desc="Desired mean within the mask for weighted sum of both images.", argstr="--desiredMean %f") - desiredVariance = traits.Float(desc="Desired variance within the mask for weighted sum of both images.", argstr="--desiredVariance %f") - lowerThresholdFactorPre = traits.Float(desc="Lower threshold factor for finding an initial brain mask", argstr="--lowerThresholdFactorPre %f") - upperThresholdFactorPre = traits.Float(desc="Upper threshold factor for finding an initial brain mask", argstr="--upperThresholdFactorPre %f") - lowerThresholdFactor = traits.Float(desc="Lower threshold factor for defining the brain mask", argstr="--lowerThresholdFactor %f") - upperThresholdFactor = traits.Float(desc="Upper threshold factor for defining the brain mask", argstr="--upperThresholdFactor %f") - boundingBoxSize = InputMultiPath(traits.Int, desc="Size of the cubic bounding box mask used when no brain mask is present", sep=",", argstr="--boundingBoxSize %s") - boundingBoxStart = InputMultiPath(traits.Int, desc="XYZ point-coordinate for the start of the cubic bounding box mask used when no brain mask is present", sep=",", argstr="--boundingBoxStart %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputFirstVolume = File( + desc="Input image (1) for mixture optimization", + exists=True, + argstr="--inputFirstVolume %s") + inputSecondVolume = File( + desc="Input image (2) for mixture optimization", + exists=True, + argstr="--inputSecondVolume %s") + inputMaskVolume = File( + desc="Input label image for mixture optimization", + exists=True, + argstr="--inputMaskVolume %s") + outputWeightsFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output Weights File", + argstr="--outputWeightsFile %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The MUSH image produced from the T1 and T2 weighted images", + argstr="--outputVolume %s") + outputMask = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The brain volume mask generated from the MUSH image", + argstr="--outputMask %s") + seed = InputMultiPath( + traits.Int, + desc="Seed Point for Brain Region Filling", + sep=",", + argstr="--seed %s") + desiredMean = traits.Float( + desc="Desired mean within the mask for weighted sum of both images.", + argstr="--desiredMean %f") + desiredVariance = traits.Float( + desc= + "Desired variance within the mask for weighted sum of both images.", + argstr="--desiredVariance %f") + lowerThresholdFactorPre = traits.Float( + desc="Lower threshold factor for finding an initial brain mask", + argstr="--lowerThresholdFactorPre %f") + upperThresholdFactorPre = traits.Float( + desc="Upper threshold factor for finding an initial brain mask", + argstr="--upperThresholdFactorPre %f") + lowerThresholdFactor = traits.Float( + desc="Lower threshold factor for defining the brain mask", + argstr="--lowerThresholdFactor %f") + upperThresholdFactor = traits.Float( + desc="Upper threshold factor for defining the brain mask", + argstr="--upperThresholdFactor %f") + boundingBoxSize = InputMultiPath( + traits.Int, + desc= + "Size of the cubic bounding box mask used when no brain mask is present", + sep=",", + argstr="--boundingBoxSize %s") + boundingBoxStart = InputMultiPath( + traits.Int, + desc= + "XYZ point-coordinate for the start of the cubic bounding box mask used when no brain mask is present", + sep=",", + argstr="--boundingBoxStart %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSMushOutputSpec(TraitedSpec): outputWeightsFile = File(desc="Output Weights File", exists=True) - outputVolume = File(desc="The MUSH image produced from the T1 and T2 weighted images", exists=True) - outputMask = File(desc="The brain volume mask generated from the MUSH image", exists=True) + outputVolume = File( + desc="The MUSH image produced from the T1 and T2 weighted images", + exists=True) + outputMask = File( + desc="The brain volume mask generated from the MUSH image", + exists=True) class BRAINSMush(SEMLikeCommandLine): - """title: Brain Extraction from T1/T2 image (BRAINS) category: Utilities.BRAINS @@ -200,17 +381,40 @@ class BRAINSMush(SEMLikeCommandLine): input_spec = BRAINSMushInputSpec output_spec = BRAINSMushOutputSpec _cmd = " BRAINSMush " - _outputs_filenames = {'outputMask': 'outputMask.nii.gz', 'outputWeightsFile': 'outputWeightsFile.txt', 'outputVolume': 'outputVolume.nii.gz'} + _outputs_filenames = { + 'outputMask': 'outputMask.nii.gz', + 'outputWeightsFile': 'outputWeightsFile.txt', + 'outputVolume': 'outputVolume.nii.gz' + } _redirect_x = False class BRAINSTransformConvertInputSpec(CommandLineInputSpec): inputTransform = File(exists=True, argstr="--inputTransform %s") referenceVolume = File(exists=True, argstr="--referenceVolume %s") - outputTransformType = traits.Enum("Affine", "VersorRigid", "ScaleVersor", "ScaleSkewVersor", "DisplacementField", "Same", desc="The target transformation type. Must be conversion-compatible with the input transform type", argstr="--outputTransformType %s") - outputPrecisionType = traits.Enum("double", "float", desc="Precision type of the output transform. It can be either single precision or double precision", argstr="--outputPrecisionType %s") - displacementVolume = traits.Either(traits.Bool, File(), hash_files=False, argstr="--displacementVolume %s") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, argstr="--outputTransform %s") + outputTransformType = traits.Enum( + "Affine", + "VersorRigid", + "ScaleVersor", + "ScaleSkewVersor", + "DisplacementField", + "Same", + desc= + "The target transformation type. Must be conversion-compatible with the input transform type", + argstr="--outputTransformType %s") + outputPrecisionType = traits.Enum( + "double", + "float", + desc= + "Precision type of the output transform. It can be either single precision or double precision", + argstr="--outputPrecisionType %s") + displacementVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + argstr="--displacementVolume %s") + outputTransform = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--outputTransform %s") class BRAINSTransformConvertOutputSpec(TraitedSpec): @@ -219,7 +423,6 @@ class BRAINSTransformConvertOutputSpec(TraitedSpec): class BRAINSTransformConvert(SEMLikeCommandLine): - """title: BRAINS Transform Convert category: Utilities.BRAINS @@ -239,21 +442,32 @@ class BRAINSTransformConvert(SEMLikeCommandLine): input_spec = BRAINSTransformConvertInputSpec output_spec = BRAINSTransformConvertOutputSpec _cmd = " BRAINSTransformConvert " - _outputs_filenames = {'displacementVolume': 'displacementVolume.nii', 'outputTransform': 'outputTransform.mat'} + _outputs_filenames = { + 'displacementVolume': 'displacementVolume.nii', + 'outputTransform': 'outputTransform.mat' + } _redirect_x = False class landmarksConstellationAlignerInputSpec(CommandLineInputSpec): - inputLandmarksPaired = File(desc="Input landmark file (.fcsv)", exists=True, argstr="--inputLandmarksPaired %s") - outputLandmarksPaired = traits.Either(traits.Bool, File(), hash_files=False, desc="Output landmark file (.fcsv)", argstr="--outputLandmarksPaired %s") + inputLandmarksPaired = File( + desc="Input landmark file (.fcsv)", + exists=True, + argstr="--inputLandmarksPaired %s") + outputLandmarksPaired = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output landmark file (.fcsv)", + argstr="--outputLandmarksPaired %s") class landmarksConstellationAlignerOutputSpec(TraitedSpec): - outputLandmarksPaired = File(desc="Output landmark file (.fcsv)", exists=True) + outputLandmarksPaired = File( + desc="Output landmark file (.fcsv)", exists=True) class landmarksConstellationAligner(SEMLikeCommandLine): - """title: MidACPC Landmark Insertion category: Utilities.BRAINS @@ -272,10 +486,19 @@ class landmarksConstellationAligner(SEMLikeCommandLine): class BRAINSEyeDetectorInputSpec(CommandLineInputSpec): - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") - inputVolume = File(desc="The input volume", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="The output volume", argstr="--outputVolume %s") - debugDir = traits.Str(desc="A place for debug information", argstr="--debugDir %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") + inputVolume = File( + desc="The input volume", exists=True, argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The output volume", + argstr="--outputVolume %s") + debugDir = traits.Str( + desc="A place for debug information", argstr="--debugDir %s") class BRAINSEyeDetectorOutputSpec(TraitedSpec): @@ -283,7 +506,6 @@ class BRAINSEyeDetectorOutputSpec(TraitedSpec): class BRAINSEyeDetector(SEMLikeCommandLine): - """title: Eye Detector (BRAINS) category: Utilities.BRAINS @@ -302,8 +524,13 @@ class BRAINSEyeDetector(SEMLikeCommandLine): class BRAINSLinearModelerEPCAInputSpec(CommandLineInputSpec): - inputTrainingList = File(desc="Input Training Landmark List Filename, ", exists=True, argstr="--inputTrainingList %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputTrainingList = File( + desc="Input Training Landmark List Filename, ", + exists=True, + argstr="--inputTrainingList %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSLinearModelerEPCAOutputSpec(TraitedSpec): @@ -311,7 +538,6 @@ class BRAINSLinearModelerEPCAOutputSpec(TraitedSpec): class BRAINSLinearModelerEPCA(SEMLikeCommandLine): - """title: Landmark Linear Modeler (BRAINS) category: Utilities.BRAINS @@ -332,12 +558,31 @@ class BRAINSLinearModelerEPCA(SEMLikeCommandLine): class BRAINSInitializedControlPointsInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Input Volume", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Volume", argstr="--outputVolume %s") - splineGridSize = InputMultiPath(traits.Int, desc="The number of subdivisions of the BSpline Grid to be centered on the image space. Each dimension must have at least 3 subdivisions for the BSpline to be correctly computed. ", sep=",", argstr="--splineGridSize %s") - permuteOrder = InputMultiPath(traits.Int, desc="The permutation order for the images. The default is 0,1,2 (i.e. no permutation)", sep=",", argstr="--permuteOrder %s") - outputLandmarksFile = traits.Str(desc="Output filename", argstr="--outputLandmarksFile %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="Input Volume", exists=True, argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output Volume", + argstr="--outputVolume %s") + splineGridSize = InputMultiPath( + traits.Int, + desc= + "The number of subdivisions of the BSpline Grid to be centered on the image space. Each dimension must have at least 3 subdivisions for the BSpline to be correctly computed. ", + sep=",", + argstr="--splineGridSize %s") + permuteOrder = InputMultiPath( + traits.Int, + desc= + "The permutation order for the images. The default is 0,1,2 (i.e. no permutation)", + sep=",", + argstr="--permuteOrder %s") + outputLandmarksFile = traits.Str( + desc="Output filename", argstr="--outputLandmarksFile %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSInitializedControlPointsOutputSpec(TraitedSpec): @@ -345,7 +590,6 @@ class BRAINSInitializedControlPointsOutputSpec(TraitedSpec): class BRAINSInitializedControlPoints(SEMLikeCommandLine): - """title: Initialized Control Points (BRAINS) category: Utilities.BRAINS @@ -370,16 +614,29 @@ class BRAINSInitializedControlPoints(SEMLikeCommandLine): class CleanUpOverlapLabelsInputSpec(CommandLineInputSpec): - inputBinaryVolumes = InputMultiPath(File(exists=True), desc="The list of binary images to be checked and cleaned up. Order is important. Binary volume given first always wins out. ", argstr="--inputBinaryVolumes %s...") - outputBinaryVolumes = traits.Either(traits.Bool, InputMultiPath(File(), ), hash_files=False, desc="The output label map images, with integer values in it. Each label value specified in the inputLabels is combined into this output label map volume", argstr="--outputBinaryVolumes %s...") + inputBinaryVolumes = InputMultiPath( + File(exists=True), + desc= + "The list of binary images to be checked and cleaned up. Order is important. Binary volume given first always wins out. ", + argstr="--inputBinaryVolumes %s...") + outputBinaryVolumes = traits.Either( + traits.Bool, + InputMultiPath(File(), ), + hash_files=False, + desc= + "The output label map images, with integer values in it. Each label value specified in the inputLabels is combined into this output label map volume", + argstr="--outputBinaryVolumes %s...") class CleanUpOverlapLabelsOutputSpec(TraitedSpec): - outputBinaryVolumes = OutputMultiPath(File(exists=True), desc="The output label map images, with integer values in it. Each label value specified in the inputLabels is combined into this output label map volume") + outputBinaryVolumes = OutputMultiPath( + File(exists=True), + desc= + "The output label map images, with integer values in it. Each label value specified in the inputLabels is combined into this output label map volume" + ) class CleanUpOverlapLabels(SEMLikeCommandLine): - """title: Clean Up Overla Labels category: Utilities.BRAINS @@ -400,20 +657,38 @@ class CleanUpOverlapLabels(SEMLikeCommandLine): class BRAINSClipInferiorInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Input image to make a clipped short int copy from.", exists=True, argstr="--inputVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output image, a short int copy of the upper portion of the input image, filled with BackgroundFillValue.", argstr="--outputVolume %s") + inputVolume = File( + desc="Input image to make a clipped short int copy from.", + exists=True, + argstr="--inputVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output image, a short int copy of the upper portion of the input image, filled with BackgroundFillValue.", + argstr="--outputVolume %s") acLowerBound = traits.Float( - desc=", When the input image to the output image, replace the image with the BackgroundFillValue everywhere below the plane This Far in physical units (millimeters) below (inferior to) the AC point (assumed to be the voxel field middle.) The oversize default was chosen to have no effect. Based on visualizing a thousand masks in the IPIG study, we recommend a limit no smaller than 80.0 mm., ", argstr="--acLowerBound %f") - BackgroundFillValue = traits.Str(desc="Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", argstr="--BackgroundFillValue %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + desc= + ", When the input image to the output image, replace the image with the BackgroundFillValue everywhere below the plane This Far in physical units (millimeters) below (inferior to) the AC point (assumed to be the voxel field middle.) The oversize default was chosen to have no effect. Based on visualizing a thousand masks in the IPIG study, we recommend a limit no smaller than 80.0 mm., ", + argstr="--acLowerBound %f") + BackgroundFillValue = traits.Str( + desc= + "Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", + argstr="--BackgroundFillValue %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSClipInferiorOutputSpec(TraitedSpec): - outputVolume = File(desc="Output image, a short int copy of the upper portion of the input image, filled with BackgroundFillValue.", exists=True) + outputVolume = File( + desc= + "Output image, a short int copy of the upper portion of the input image, filled with BackgroundFillValue.", + exists=True) class BRAINSClipInferior(SEMLikeCommandLine): - """title: Clip Inferior of Center of Brain (BRAINS) category: Utilities.BRAINS @@ -432,17 +707,27 @@ class BRAINSClipInferior(SEMLikeCommandLine): class GenerateLabelMapFromProbabilityMapInputSpec(CommandLineInputSpec): - inputVolumes = InputMultiPath(File(exists=True), desc="The Input probaiblity images to be computed for lable maps", argstr="--inputVolumes %s...") - outputLabelVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="The Input binary image for region of interest", argstr="--outputLabelVolume %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolumes = InputMultiPath( + File(exists=True), + desc="The Input probaiblity images to be computed for lable maps", + argstr="--inputVolumes %s...") + outputLabelVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The Input binary image for region of interest", + argstr="--outputLabelVolume %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class GenerateLabelMapFromProbabilityMapOutputSpec(TraitedSpec): - outputLabelVolume = File(desc="The Input binary image for region of interest", exists=True) + outputLabelVolume = File( + desc="The Input binary image for region of interest", exists=True) class GenerateLabelMapFromProbabilityMap(SEMLikeCommandLine): - """title: Label Map from Probability Images category: Utilities.BRAINS @@ -463,29 +748,78 @@ class GenerateLabelMapFromProbabilityMap(SEMLikeCommandLine): class BRAINSAlignMSPInputSpec(CommandLineInputSpec): - inputVolume = File(desc=", The Image to be resampled, ", exists=True, argstr="--inputVolume %s") - OutputresampleMSP = traits.Either(traits.Bool, File(), hash_files=False, desc=", The image to be output., ", argstr="--OutputresampleMSP %s") - verbose = traits.Bool(desc=", Show more verbose output, ", argstr="--verbose ") - resultsDir = traits.Either(traits.Bool, Directory(), hash_files=False, desc=", The directory for the results to be written., ", argstr="--resultsDir %s") - writedebuggingImagesLevel = traits.Int(desc=", This flag controls if debugging images are produced. By default value of 0 is no images. Anything greater than zero will be increasing level of debugging images., ", argstr="--writedebuggingImagesLevel %d") - mspQualityLevel = traits.Int(desc=", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", argstr="--mspQualityLevel %d") - rescaleIntensities = traits.Bool(desc=", Flag to turn on rescaling image intensities on input., ", argstr="--rescaleIntensities ") + inputVolume = File( + desc=", The Image to be resampled, ", + exists=True, + argstr="--inputVolume %s") + OutputresampleMSP = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc=", The image to be output., ", + argstr="--OutputresampleMSP %s") + verbose = traits.Bool( + desc=", Show more verbose output, ", argstr="--verbose ") + resultsDir = traits.Either( + traits.Bool, + Directory(), + hash_files=False, + desc=", The directory for the results to be written., ", + argstr="--resultsDir %s") + writedebuggingImagesLevel = traits.Int( + desc= + ", This flag controls if debugging images are produced. By default value of 0 is no images. Anything greater than zero will be increasing level of debugging images., ", + argstr="--writedebuggingImagesLevel %d") + mspQualityLevel = traits.Int( + desc= + ", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", + argstr="--mspQualityLevel %d") + rescaleIntensities = traits.Bool( + desc= + ", Flag to turn on rescaling image intensities on input., ", + argstr="--rescaleIntensities ") trimRescaledIntensities = traits.Float( - desc=", Turn on clipping the rescaled image one-tailed on input. Units of standard deviations above the mean. Very large values are very permissive. Non-positive value turns clipping off. Defaults to removing 0.00001 of a normal tail above the mean., ", argstr="--trimRescaledIntensities %f") - rescaleIntensitiesOutputRange = InputMultiPath(traits.Int, desc=", This pair of integers gives the lower and upper bounds on the signal portion of the output image. Out-of-field voxels are taken from BackgroundFillValue., ", sep=",", argstr="--rescaleIntensitiesOutputRange %s") - BackgroundFillValue = traits.Str(desc="Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", argstr="--BackgroundFillValue %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", - desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + desc= + ", Turn on clipping the rescaled image one-tailed on input. Units of standard deviations above the mean. Very large values are very permissive. Non-positive value turns clipping off. Defaults to removing 0.00001 of a normal tail above the mean., ", + argstr="--trimRescaledIntensities %f") + rescaleIntensitiesOutputRange = InputMultiPath( + traits.Int, + desc= + ", This pair of integers gives the lower and upper bounds on the signal portion of the output image. Out-of-field voxels are taken from BackgroundFillValue., ", + sep=",", + argstr="--rescaleIntensitiesOutputRange %s") + BackgroundFillValue = traits.Str( + desc= + "Fill the background of image with specified short int value. Enter number or use BIGNEG for a large negative number.", + argstr="--BackgroundFillValue %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSAlignMSPOutputSpec(TraitedSpec): - OutputresampleMSP = File(desc=", The image to be output., ", exists=True) - resultsDir = Directory(desc=", The directory for the results to be written., ", exists=True) + OutputresampleMSP = File( + desc=", The image to be output., ", exists=True) + resultsDir = Directory( + desc=", The directory for the results to be written., ", + exists=True) class BRAINSAlignMSP(SEMLikeCommandLine): - """title: Align Mid Saggital Brain (BRAINS) category: Utilities.BRAINS @@ -497,23 +831,42 @@ class BRAINSAlignMSP(SEMLikeCommandLine): input_spec = BRAINSAlignMSPInputSpec output_spec = BRAINSAlignMSPOutputSpec _cmd = " BRAINSAlignMSP " - _outputs_filenames = {'OutputresampleMSP': 'OutputresampleMSP.nii', 'resultsDir': 'resultsDir'} + _outputs_filenames = { + 'OutputresampleMSP': 'OutputresampleMSP.nii', + 'resultsDir': 'resultsDir' + } _redirect_x = False class BRAINSLandmarkInitializerInputSpec(CommandLineInputSpec): - inputFixedLandmarkFilename = File(desc="input fixed landmark. *.fcsv", exists=True, argstr="--inputFixedLandmarkFilename %s") - inputMovingLandmarkFilename = File(desc="input moving landmark. *.fcsv", exists=True, argstr="--inputMovingLandmarkFilename %s") - inputWeightFilename = File(desc="Input weight file name for landmarks. Higher weighted landmark will be considered more heavily. Weights are propotional, that is the magnitude of weights will be normalized by its minimum and maximum value. ", exists=True, argstr="--inputWeightFilename %s") - outputTransformFilename = traits.Either(traits.Bool, File(), hash_files=False, desc="output transform file name (ex: ./outputTransform.mat) ", argstr="--outputTransformFilename %s") + inputFixedLandmarkFilename = File( + desc="input fixed landmark. *.fcsv", + exists=True, + argstr="--inputFixedLandmarkFilename %s") + inputMovingLandmarkFilename = File( + desc="input moving landmark. *.fcsv", + exists=True, + argstr="--inputMovingLandmarkFilename %s") + inputWeightFilename = File( + desc= + "Input weight file name for landmarks. Higher weighted landmark will be considered more heavily. Weights are propotional, that is the magnitude of weights will be normalized by its minimum and maximum value. ", + exists=True, + argstr="--inputWeightFilename %s") + outputTransformFilename = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="output transform file name (ex: ./outputTransform.mat) ", + argstr="--outputTransformFilename %s") class BRAINSLandmarkInitializerOutputSpec(TraitedSpec): - outputTransformFilename = File(desc="output transform file name (ex: ./outputTransform.mat) ", exists=True) + outputTransformFilename = File( + desc="output transform file name (ex: ./outputTransform.mat) ", + exists=True) class BRAINSLandmarkInitializer(SEMLikeCommandLine): - """title: BRAINSLandmarkInitializer category: Utilities.BRAINS @@ -536,8 +889,16 @@ class BRAINSLandmarkInitializer(SEMLikeCommandLine): class insertMidACPCpointInputSpec(CommandLineInputSpec): - inputLandmarkFile = File(desc="Input landmark file (.fcsv)", exists=True, argstr="--inputLandmarkFile %s") - outputLandmarkFile = traits.Either(traits.Bool, File(), hash_files=False, desc="Output landmark file (.fcsv)", argstr="--outputLandmarkFile %s") + inputLandmarkFile = File( + desc="Input landmark file (.fcsv)", + exists=True, + argstr="--inputLandmarkFile %s") + outputLandmarkFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Output landmark file (.fcsv)", + argstr="--outputLandmarkFile %s") class insertMidACPCpointOutputSpec(TraitedSpec): @@ -545,7 +906,6 @@ class insertMidACPCpointOutputSpec(TraitedSpec): class insertMidACPCpoint(SEMLikeCommandLine): - """title: MidACPC Landmark Insertion category: Utilities.BRAINS @@ -564,21 +924,54 @@ class insertMidACPCpoint(SEMLikeCommandLine): class BRAINSSnapShotWriterInputSpec(CommandLineInputSpec): - inputVolumes = InputMultiPath(File(exists=True), desc="Input image volume list to be extracted as 2D image. Multiple input is possible. At least one input is required.", argstr="--inputVolumes %s...") - inputBinaryVolumes = InputMultiPath(File(exists=True), desc="Input mask (binary) volume list to be extracted as 2D image. Multiple input is possible.", argstr="--inputBinaryVolumes %s...") - inputSliceToExtractInPhysicalPoint = InputMultiPath(traits.Float, desc="2D slice number of input images. For autoWorkUp output, which AC-PC aligned, 0,0,0 will be the center.", sep=",", argstr="--inputSliceToExtractInPhysicalPoint %s") - inputSliceToExtractInIndex = InputMultiPath(traits.Int, desc="2D slice number of input images. For size of 256*256*256 image, 128 is usually used.", sep=",", argstr="--inputSliceToExtractInIndex %s") - inputSliceToExtractInPercent = InputMultiPath(traits.Int, desc="2D slice number of input images. Percentage input from 0%-100%. (ex. --inputSliceToExtractInPercent 50,50,50", sep=",", argstr="--inputSliceToExtractInPercent %s") - inputPlaneDirection = InputMultiPath(traits.Int, desc="Plane to display. In general, 0=saggital, 1=coronal, and 2=axial plane.", sep=",", argstr="--inputPlaneDirection %s") - outputFilename = traits.Either(traits.Bool, File(), hash_files=False, desc="2D file name of input images. Required.", argstr="--outputFilename %s") + inputVolumes = InputMultiPath( + File(exists=True), + desc= + "Input image volume list to be extracted as 2D image. Multiple input is possible. At least one input is required.", + argstr="--inputVolumes %s...") + inputBinaryVolumes = InputMultiPath( + File(exists=True), + desc= + "Input mask (binary) volume list to be extracted as 2D image. Multiple input is possible.", + argstr="--inputBinaryVolumes %s...") + inputSliceToExtractInPhysicalPoint = InputMultiPath( + traits.Float, + desc= + "2D slice number of input images. For autoWorkUp output, which AC-PC aligned, 0,0,0 will be the center.", + sep=",", + argstr="--inputSliceToExtractInPhysicalPoint %s") + inputSliceToExtractInIndex = InputMultiPath( + traits.Int, + desc= + "2D slice number of input images. For size of 256*256*256 image, 128 is usually used.", + sep=",", + argstr="--inputSliceToExtractInIndex %s") + inputSliceToExtractInPercent = InputMultiPath( + traits.Int, + desc= + "2D slice number of input images. Percentage input from 0%-100%. (ex. --inputSliceToExtractInPercent 50,50,50", + sep=",", + argstr="--inputSliceToExtractInPercent %s") + inputPlaneDirection = InputMultiPath( + traits.Int, + desc= + "Plane to display. In general, 0=saggital, 1=coronal, and 2=axial plane.", + sep=",", + argstr="--inputPlaneDirection %s") + outputFilename = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="2D file name of input images. Required.", + argstr="--outputFilename %s") class BRAINSSnapShotWriterOutputSpec(TraitedSpec): - outputFilename = File(desc="2D file name of input images. Required.", exists=True) + outputFilename = File( + desc="2D file name of input images. Required.", exists=True) class BRAINSSnapShotWriter(SEMLikeCommandLine): - """title: BRAINSSnapShotWriter category: Utilities.BRAINS @@ -601,12 +994,30 @@ class BRAINSSnapShotWriter(SEMLikeCommandLine): class JointHistogramInputSpec(CommandLineInputSpec): - inputVolumeInXAxis = File(desc="The Input image to be computed for statistics", exists=True, argstr="--inputVolumeInXAxis %s") - inputVolumeInYAxis = File(desc="The Input image to be computed for statistics", exists=True, argstr="--inputVolumeInYAxis %s") - inputMaskVolumeInXAxis = File(desc="Input mask volume for inputVolumeInXAxis. Histogram will be computed just for the masked region", exists=True, argstr="--inputMaskVolumeInXAxis %s") - inputMaskVolumeInYAxis = File(desc="Input mask volume for inputVolumeInYAxis. Histogram will be computed just for the masked region", exists=True, argstr="--inputMaskVolumeInYAxis %s") - outputJointHistogramImage = traits.Str(desc=" output joint histogram image file name. Histogram is usually 2D image. ", argstr="--outputJointHistogramImage %s") - verbose = traits.Bool(desc=" print debugging information, ", argstr="--verbose ") + inputVolumeInXAxis = File( + desc="The Input image to be computed for statistics", + exists=True, + argstr="--inputVolumeInXAxis %s") + inputVolumeInYAxis = File( + desc="The Input image to be computed for statistics", + exists=True, + argstr="--inputVolumeInYAxis %s") + inputMaskVolumeInXAxis = File( + desc= + "Input mask volume for inputVolumeInXAxis. Histogram will be computed just for the masked region", + exists=True, + argstr="--inputMaskVolumeInXAxis %s") + inputMaskVolumeInYAxis = File( + desc= + "Input mask volume for inputVolumeInYAxis. Histogram will be computed just for the masked region", + exists=True, + argstr="--inputMaskVolumeInYAxis %s") + outputJointHistogramImage = traits.Str( + desc= + " output joint histogram image file name. Histogram is usually 2D image. ", + argstr="--outputJointHistogramImage %s") + verbose = traits.Bool( + desc=" print debugging information, ", argstr="--verbose ") class JointHistogramOutputSpec(TraitedSpec): @@ -614,7 +1025,6 @@ class JointHistogramOutputSpec(TraitedSpec): class JointHistogram(SEMLikeCommandLine): - """title: Write Out Image Intensities category: Utilities.BRAINS @@ -635,17 +1045,32 @@ class JointHistogram(SEMLikeCommandLine): class ShuffleVectorsModuleInputSpec(CommandLineInputSpec): - inputVectorFileBaseName = File(desc="input vector file name prefix. Usually end with .txt and header file has prost fix of .txt.hdr", exists=True, argstr="--inputVectorFileBaseName %s") - outputVectorFileBaseName = traits.Either(traits.Bool, File(), hash_files=False, desc="output vector file name prefix. Usually end with .txt and header file has prost fix of .txt.hdr", argstr="--outputVectorFileBaseName %s") - resampleProportion = traits.Float(desc="downsample size of 1 will be the same size as the input images, downsample size of 3 will throw 2/3 the vectors away.", argstr="--resampleProportion %f") + inputVectorFileBaseName = File( + desc= + "input vector file name prefix. Usually end with .txt and header file has prost fix of .txt.hdr", + exists=True, + argstr="--inputVectorFileBaseName %s") + outputVectorFileBaseName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "output vector file name prefix. Usually end with .txt and header file has prost fix of .txt.hdr", + argstr="--outputVectorFileBaseName %s") + resampleProportion = traits.Float( + desc= + "downsample size of 1 will be the same size as the input images, downsample size of 3 will throw 2/3 the vectors away.", + argstr="--resampleProportion %f") class ShuffleVectorsModuleOutputSpec(TraitedSpec): - outputVectorFileBaseName = File(desc="output vector file name prefix. Usually end with .txt and header file has prost fix of .txt.hdr", exists=True) + outputVectorFileBaseName = File( + desc= + "output vector file name prefix. Usually end with .txt and header file has prost fix of .txt.hdr", + exists=True) class ShuffleVectorsModule(SEMLikeCommandLine): - """title: ShuffleVectors category: Utilities.BRAINS @@ -663,20 +1088,42 @@ class ShuffleVectorsModule(SEMLikeCommandLine): input_spec = ShuffleVectorsModuleInputSpec output_spec = ShuffleVectorsModuleOutputSpec _cmd = " ShuffleVectorsModule " - _outputs_filenames = {'outputVectorFileBaseName': 'outputVectorFileBaseName'} + _outputs_filenames = { + 'outputVectorFileBaseName': 'outputVectorFileBaseName' + } _redirect_x = False class ImageRegionPlotterInputSpec(CommandLineInputSpec): - inputVolume1 = File(desc="The Input image to be computed for statistics", exists=True, argstr="--inputVolume1 %s") - inputVolume2 = File(desc="The Input image to be computed for statistics", exists=True, argstr="--inputVolume2 %s") - inputBinaryROIVolume = File(desc="The Input binary image for region of interest", exists=True, argstr="--inputBinaryROIVolume %s") - inputLabelVolume = File(desc="The Label Image", exists=True, argstr="--inputLabelVolume %s") - numberOfHistogramBins = traits.Int(desc=" the number of histogram levels", argstr="--numberOfHistogramBins %d") - outputJointHistogramData = traits.Str(desc=" output data file name", argstr="--outputJointHistogramData %s") - useROIAUTO = traits.Bool(desc=" Use ROIAUTO to compute region of interest. This cannot be used with inputLabelVolume", argstr="--useROIAUTO ") - useIntensityForHistogram = traits.Bool(desc=" Create Intensity Joint Histogram instead of Quantile Joint Histogram", argstr="--useIntensityForHistogram ") - verbose = traits.Bool(desc=" print debugging information, ", argstr="--verbose ") + inputVolume1 = File( + desc="The Input image to be computed for statistics", + exists=True, + argstr="--inputVolume1 %s") + inputVolume2 = File( + desc="The Input image to be computed for statistics", + exists=True, + argstr="--inputVolume2 %s") + inputBinaryROIVolume = File( + desc="The Input binary image for region of interest", + exists=True, + argstr="--inputBinaryROIVolume %s") + inputLabelVolume = File( + desc="The Label Image", exists=True, argstr="--inputLabelVolume %s") + numberOfHistogramBins = traits.Int( + desc=" the number of histogram levels", + argstr="--numberOfHistogramBins %d") + outputJointHistogramData = traits.Str( + desc=" output data file name", argstr="--outputJointHistogramData %s") + useROIAUTO = traits.Bool( + desc= + " Use ROIAUTO to compute region of interest. This cannot be used with inputLabelVolume", + argstr="--useROIAUTO ") + useIntensityForHistogram = traits.Bool( + desc= + " Create Intensity Joint Histogram instead of Quantile Joint Histogram", + argstr="--useIntensityForHistogram ") + verbose = traits.Bool( + desc=" print debugging information, ", argstr="--verbose ") class ImageRegionPlotterOutputSpec(TraitedSpec): @@ -684,7 +1131,6 @@ class ImageRegionPlotterOutputSpec(TraitedSpec): class ImageRegionPlotter(SEMLikeCommandLine): - """title: Write Out Image Intensities category: Utilities.BRAINS @@ -705,21 +1151,46 @@ class ImageRegionPlotter(SEMLikeCommandLine): class fcsv_to_hdf5InputSpec(CommandLineInputSpec): - versionID = traits.Str(desc=", Current version ID. It should be match with the version of BCD that will be using the output model file, ", argstr="--versionID %s") - landmarksInformationFile = traits.Either(traits.Bool, File(), hash_files=False, desc=", name of HDF5 file to write matrices into, ", argstr="--landmarksInformationFile %s") - landmarkTypesList = File(desc=", file containing list of landmark types, ", exists=True, argstr="--landmarkTypesList %s") - modelFile = traits.Either(traits.Bool, File(), hash_files=False, desc=", name of HDF5 file containing BRAINSConstellationDetector Model file (LLSMatrices, LLSMeans and LLSSearchRadii), ", argstr="--modelFile %s") - landmarkGlobPattern = traits.Str(desc="Glob pattern to select fcsv files", argstr="--landmarkGlobPattern %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + versionID = traits.Str( + desc= + ", Current version ID. It should be match with the version of BCD that will be using the output model file, ", + argstr="--versionID %s") + landmarksInformationFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc=", name of HDF5 file to write matrices into, ", + argstr="--landmarksInformationFile %s") + landmarkTypesList = File( + desc=", file containing list of landmark types, ", + exists=True, + argstr="--landmarkTypesList %s") + modelFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + ", name of HDF5 file containing BRAINSConstellationDetector Model file (LLSMatrices, LLSMeans and LLSSearchRadii), ", + argstr="--modelFile %s") + landmarkGlobPattern = traits.Str( + desc="Glob pattern to select fcsv files", + argstr="--landmarkGlobPattern %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class fcsv_to_hdf5OutputSpec(TraitedSpec): - landmarksInformationFile = File(desc=", name of HDF5 file to write matrices into, ", exists=True) - modelFile = File(desc=", name of HDF5 file containing BRAINSConstellationDetector Model file (LLSMatrices, LLSMeans and LLSSearchRadii), ", exists=True) + landmarksInformationFile = File( + desc=", name of HDF5 file to write matrices into, ", + exists=True) + modelFile = File( + desc= + ", name of HDF5 file containing BRAINSConstellationDetector Model file (LLSMatrices, LLSMeans and LLSSearchRadii), ", + exists=True) class fcsv_to_hdf5(SEMLikeCommandLine): - """title: fcsv_to_hdf5 (BRAINS) category: Utilities.BRAINS @@ -731,27 +1202,49 @@ class fcsv_to_hdf5(SEMLikeCommandLine): input_spec = fcsv_to_hdf5InputSpec output_spec = fcsv_to_hdf5OutputSpec _cmd = " fcsv_to_hdf5 " - _outputs_filenames = {'modelFile': 'modelFile', 'landmarksInformationFile': 'landmarksInformationFile.h5'} + _outputs_filenames = { + 'modelFile': 'modelFile', + 'landmarksInformationFile': 'landmarksInformationFile.h5' + } _redirect_x = False class FindCenterOfBrainInputSpec(CommandLineInputSpec): - inputVolume = File(desc="The image in which to find the center.", exists=True, argstr="--inputVolume %s") + inputVolume = File( + desc="The image in which to find the center.", + exists=True, + argstr="--inputVolume %s") imageMask = File(exists=True, argstr="--imageMask %s") - clippedImageMask = traits.Either(traits.Bool, File(), hash_files=False, argstr="--clippedImageMask %s") + clippedImageMask = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--clippedImageMask %s") maximize = traits.Bool(argstr="--maximize ") axis = traits.Int(argstr="--axis %d") - otsuPercentileThreshold = traits.Float(argstr="--otsuPercentileThreshold %f") + otsuPercentileThreshold = traits.Float( + argstr="--otsuPercentileThreshold %f") closingSize = traits.Int(argstr="--closingSize %d") headSizeLimit = traits.Float(argstr="--headSizeLimit %f") headSizeEstimate = traits.Float(argstr="--headSizeEstimate %f") backgroundValue = traits.Int(argstr="--backgroundValue %d") generateDebugImages = traits.Bool(argstr="--generateDebugImages ") - debugDistanceImage = traits.Either(traits.Bool, File(), hash_files=False, argstr="--debugDistanceImage %s") - debugGridImage = traits.Either(traits.Bool, File(), hash_files=False, argstr="--debugGridImage %s") - debugAfterGridComputationsForegroundImage = traits.Either(traits.Bool, File(), hash_files=False, argstr="--debugAfterGridComputationsForegroundImage %s") - debugClippedImageMask = traits.Either(traits.Bool, File(), hash_files=False, argstr="--debugClippedImageMask %s") - debugTrimmedImage = traits.Either(traits.Bool, File(), hash_files=False, argstr="--debugTrimmedImage %s") + debugDistanceImage = traits.Either( + traits.Bool, + File(), + hash_files=False, + argstr="--debugDistanceImage %s") + debugGridImage = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--debugGridImage %s") + debugAfterGridComputationsForegroundImage = traits.Either( + traits.Bool, + File(), + hash_files=False, + argstr="--debugAfterGridComputationsForegroundImage %s") + debugClippedImageMask = traits.Either( + traits.Bool, + File(), + hash_files=False, + argstr="--debugClippedImageMask %s") + debugTrimmedImage = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--debugTrimmedImage %s") class FindCenterOfBrainOutputSpec(TraitedSpec): @@ -764,7 +1257,6 @@ class FindCenterOfBrainOutputSpec(TraitedSpec): class FindCenterOfBrain(SEMLikeCommandLine): - """title: Center Of Brain (BRAINS) category: Utilities.BRAINS @@ -784,6 +1276,18 @@ class FindCenterOfBrain(SEMLikeCommandLine): input_spec = FindCenterOfBrainInputSpec output_spec = FindCenterOfBrainOutputSpec _cmd = " FindCenterOfBrain " - _outputs_filenames = {'debugClippedImageMask': 'debugClippedImageMask.nii', 'debugTrimmedImage': 'debugTrimmedImage.nii', 'debugDistanceImage': 'debugDistanceImage.nii', - 'debugGridImage': 'debugGridImage.nii', 'clippedImageMask': 'clippedImageMask.nii', 'debugAfterGridComputationsForegroundImage': 'debugAfterGridComputationsForegroundImage.nii'} + _outputs_filenames = { + 'debugClippedImageMask': + 'debugClippedImageMask.nii', + 'debugTrimmedImage': + 'debugTrimmedImage.nii', + 'debugDistanceImage': + 'debugDistanceImage.nii', + 'debugGridImage': + 'debugGridImage.nii', + 'clippedImageMask': + 'clippedImageMask.nii', + 'debugAfterGridComputationsForegroundImage': + 'debugAfterGridComputationsForegroundImage.nii' + } _redirect_x = False diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py index 5c5db3a206..a2fe2a0a06 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py @@ -4,56 +4,53 @@ def test_BRAINSAlignMSP_inputs(): - input_map = dict(BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', - ), - OutputresampleMSP=dict(argstr='--OutputresampleMSP %s', - hash_files=False, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - mspQualityLevel=dict(argstr='--mspQualityLevel %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - rescaleIntensities=dict(argstr='--rescaleIntensities ', - ), - rescaleIntensitiesOutputRange=dict(argstr='--rescaleIntensitiesOutputRange %s', - sep=',', - ), - resultsDir=dict(argstr='--resultsDir %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trimRescaledIntensities=dict(argstr='--trimRescaledIntensities %f', - ), - verbose=dict(argstr='--verbose ', - ), - writedebuggingImagesLevel=dict(argstr='--writedebuggingImagesLevel %d', - ), + input_map = dict( + BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', ), + OutputresampleMSP=dict( + argstr='--OutputresampleMSP %s', + hash_files=False, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + mspQualityLevel=dict(argstr='--mspQualityLevel %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + rescaleIntensities=dict(argstr='--rescaleIntensities ', ), + rescaleIntensitiesOutputRange=dict( + argstr='--rescaleIntensitiesOutputRange %s', + sep=',', + ), + resultsDir=dict( + argstr='--resultsDir %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trimRescaledIntensities=dict(argstr='--trimRescaledIntensities %f', ), + verbose=dict(argstr='--verbose ', ), + writedebuggingImagesLevel=dict( + argstr='--writedebuggingImagesLevel %d', ), ) inputs = BRAINSAlignMSP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSAlignMSP_outputs(): - output_map = dict(OutputresampleMSP=dict(), - resultsDir=dict(), + output_map = dict( + OutputresampleMSP=dict(), + resultsDir=dict(), ) outputs = BRAINSAlignMSP.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py index a6868c4e61..b1d3fca432 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py @@ -4,40 +4,37 @@ def test_BRAINSClipInferior_inputs(): - input_map = dict(BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', - ), - acLowerBound=dict(argstr='--acLowerBound %f', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', ), + acLowerBound=dict(argstr='--acLowerBound %f', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSClipInferior.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSClipInferior_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSClipInferior.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py index 80d8158e5e..70cb6ab7be 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py @@ -4,58 +4,55 @@ def test_BRAINSConstellationModeler_inputs(): - input_map = dict(BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputTrainingList=dict(argstr='--inputTrainingList %s', - ), - mspQualityLevel=dict(argstr='--mspQualityLevel %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - optimizedLandmarksFilenameExtender=dict(argstr='--optimizedLandmarksFilenameExtender %s', - ), - outputModel=dict(argstr='--outputModel %s', - hash_files=False, - ), - rescaleIntensities=dict(argstr='--rescaleIntensities ', - ), - rescaleIntensitiesOutputRange=dict(argstr='--rescaleIntensitiesOutputRange %s', - sep=',', - ), - resultsDir=dict(argstr='--resultsDir %s', - hash_files=False, - ), - saveOptimizedLandmarks=dict(argstr='--saveOptimizedLandmarks ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - trimRescaledIntensities=dict(argstr='--trimRescaledIntensities %f', - ), - verbose=dict(argstr='--verbose ', - ), - writedebuggingImagesLevel=dict(argstr='--writedebuggingImagesLevel %d', - ), + input_map = dict( + BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputTrainingList=dict(argstr='--inputTrainingList %s', ), + mspQualityLevel=dict(argstr='--mspQualityLevel %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + optimizedLandmarksFilenameExtender=dict( + argstr='--optimizedLandmarksFilenameExtender %s', ), + outputModel=dict( + argstr='--outputModel %s', + hash_files=False, + ), + rescaleIntensities=dict(argstr='--rescaleIntensities ', ), + rescaleIntensitiesOutputRange=dict( + argstr='--rescaleIntensitiesOutputRange %s', + sep=',', + ), + resultsDir=dict( + argstr='--resultsDir %s', + hash_files=False, + ), + saveOptimizedLandmarks=dict(argstr='--saveOptimizedLandmarks ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + trimRescaledIntensities=dict(argstr='--trimRescaledIntensities %f', ), + verbose=dict(argstr='--verbose ', ), + writedebuggingImagesLevel=dict( + argstr='--writedebuggingImagesLevel %d', ), ) inputs = BRAINSConstellationModeler.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSConstellationModeler_outputs(): - output_map = dict(outputModel=dict(), - resultsDir=dict(), + output_map = dict( + outputModel=dict(), + resultsDir=dict(), ) outputs = BRAINSConstellationModeler.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py index 59f4b66f60..991d4415f0 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py @@ -4,38 +4,36 @@ def test_BRAINSEyeDetector_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - debugDir=dict(argstr='--debugDir %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + debugDir=dict(argstr='--debugDir %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSEyeDetector.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSEyeDetector_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSEyeDetector.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py index b1f25c5be1..db438c9b57 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py @@ -4,44 +4,44 @@ def test_BRAINSInitializedControlPoints_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputLandmarksFile=dict(argstr='--outputLandmarksFile %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - permuteOrder=dict(argstr='--permuteOrder %s', - sep=',', - ), - splineGridSize=dict(argstr='--splineGridSize %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputLandmarksFile=dict(argstr='--outputLandmarksFile %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + permuteOrder=dict( + argstr='--permuteOrder %s', + sep=',', + ), + splineGridSize=dict( + argstr='--splineGridSize %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSInitializedControlPoints.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSInitializedControlPoints_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSInitializedControlPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py index edb4119b52..8a2173c292 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py @@ -4,38 +4,38 @@ def test_BRAINSLandmarkInitializer_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputFixedLandmarkFilename=dict(argstr='--inputFixedLandmarkFilename %s', - ), - inputMovingLandmarkFilename=dict(argstr='--inputMovingLandmarkFilename %s', - ), - inputWeightFilename=dict(argstr='--inputWeightFilename %s', - ), - outputTransformFilename=dict(argstr='--outputTransformFilename %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputFixedLandmarkFilename=dict( + argstr='--inputFixedLandmarkFilename %s', ), + inputMovingLandmarkFilename=dict( + argstr='--inputMovingLandmarkFilename %s', ), + inputWeightFilename=dict(argstr='--inputWeightFilename %s', ), + outputTransformFilename=dict( + argstr='--outputTransformFilename %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSLandmarkInitializer.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSLandmarkInitializer_outputs(): - output_map = dict(outputTransformFilename=dict(), - ) + output_map = dict(outputTransformFilename=dict(), ) outputs = BRAINSLandmarkInitializer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py index 8d8bfdab55..7d7d8301f1 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py @@ -4,30 +4,29 @@ def test_BRAINSLinearModelerEPCA_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputTrainingList=dict(argstr='--inputTrainingList %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputTrainingList=dict(argstr='--inputTrainingList %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSLinearModelerEPCA.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSLinearModelerEPCA_outputs(): output_map = dict() outputs = BRAINSLinearModelerEPCA.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py index 0210db6299..ad7f9f99db 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py @@ -4,45 +4,44 @@ def test_BRAINSLmkTransform_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputFixedLandmarks=dict(argstr='--inputFixedLandmarks %s', - ), - inputMovingLandmarks=dict(argstr='--inputMovingLandmarks %s', - ), - inputMovingVolume=dict(argstr='--inputMovingVolume %s', - ), - inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputAffineTransform=dict(argstr='--outputAffineTransform %s', - hash_files=False, - ), - outputResampledVolume=dict(argstr='--outputResampledVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputFixedLandmarks=dict(argstr='--inputFixedLandmarks %s', ), + inputMovingLandmarks=dict(argstr='--inputMovingLandmarks %s', ), + inputMovingVolume=dict(argstr='--inputMovingVolume %s', ), + inputReferenceVolume=dict(argstr='--inputReferenceVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputAffineTransform=dict( + argstr='--outputAffineTransform %s', + hash_files=False, + ), + outputResampledVolume=dict( + argstr='--outputResampledVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSLmkTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSLmkTransform_outputs(): - output_map = dict(outputAffineTransform=dict(), - outputResampledVolume=dict(), + output_map = dict( + outputAffineTransform=dict(), + outputResampledVolume=dict(), ) outputs = BRAINSLmkTransform.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py index 20b0a4467e..3b77fac8a5 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py @@ -4,68 +4,66 @@ def test_BRAINSMush_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - boundingBoxSize=dict(argstr='--boundingBoxSize %s', - sep=',', - ), - boundingBoxStart=dict(argstr='--boundingBoxStart %s', - sep=',', - ), - desiredMean=dict(argstr='--desiredMean %f', - ), - desiredVariance=dict(argstr='--desiredVariance %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputFirstVolume=dict(argstr='--inputFirstVolume %s', - ), - inputMaskVolume=dict(argstr='--inputMaskVolume %s', - ), - inputSecondVolume=dict(argstr='--inputSecondVolume %s', - ), - lowerThresholdFactor=dict(argstr='--lowerThresholdFactor %f', - ), - lowerThresholdFactorPre=dict(argstr='--lowerThresholdFactorPre %f', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputMask=dict(argstr='--outputMask %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - outputWeightsFile=dict(argstr='--outputWeightsFile %s', - hash_files=False, - ), - seed=dict(argstr='--seed %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upperThresholdFactor=dict(argstr='--upperThresholdFactor %f', - ), - upperThresholdFactorPre=dict(argstr='--upperThresholdFactorPre %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + boundingBoxSize=dict( + argstr='--boundingBoxSize %s', + sep=',', + ), + boundingBoxStart=dict( + argstr='--boundingBoxStart %s', + sep=',', + ), + desiredMean=dict(argstr='--desiredMean %f', ), + desiredVariance=dict(argstr='--desiredVariance %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputFirstVolume=dict(argstr='--inputFirstVolume %s', ), + inputMaskVolume=dict(argstr='--inputMaskVolume %s', ), + inputSecondVolume=dict(argstr='--inputSecondVolume %s', ), + lowerThresholdFactor=dict(argstr='--lowerThresholdFactor %f', ), + lowerThresholdFactorPre=dict(argstr='--lowerThresholdFactorPre %f', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputMask=dict( + argstr='--outputMask %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + outputWeightsFile=dict( + argstr='--outputWeightsFile %s', + hash_files=False, + ), + seed=dict( + argstr='--seed %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upperThresholdFactor=dict(argstr='--upperThresholdFactor %f', ), + upperThresholdFactorPre=dict(argstr='--upperThresholdFactorPre %f', ), ) inputs = BRAINSMush.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSMush_outputs(): - output_map = dict(outputMask=dict(), - outputVolume=dict(), - outputWeightsFile=dict(), + output_map = dict( + outputMask=dict(), + outputVolume=dict(), + outputWeightsFile=dict(), ) outputs = BRAINSMush.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py index 81d0f89d08..c99d85d0d0 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py @@ -4,48 +4,51 @@ def test_BRAINSSnapShotWriter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBinaryVolumes=dict(argstr='--inputBinaryVolumes %s...', - ), - inputPlaneDirection=dict(argstr='--inputPlaneDirection %s', - sep=',', - ), - inputSliceToExtractInIndex=dict(argstr='--inputSliceToExtractInIndex %s', - sep=',', - ), - inputSliceToExtractInPercent=dict(argstr='--inputSliceToExtractInPercent %s', - sep=',', - ), - inputSliceToExtractInPhysicalPoint=dict(argstr='--inputSliceToExtractInPhysicalPoint %s', - sep=',', - ), - inputVolumes=dict(argstr='--inputVolumes %s...', - ), - outputFilename=dict(argstr='--outputFilename %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBinaryVolumes=dict(argstr='--inputBinaryVolumes %s...', ), + inputPlaneDirection=dict( + argstr='--inputPlaneDirection %s', + sep=',', + ), + inputSliceToExtractInIndex=dict( + argstr='--inputSliceToExtractInIndex %s', + sep=',', + ), + inputSliceToExtractInPercent=dict( + argstr='--inputSliceToExtractInPercent %s', + sep=',', + ), + inputSliceToExtractInPhysicalPoint=dict( + argstr='--inputSliceToExtractInPhysicalPoint %s', + sep=',', + ), + inputVolumes=dict(argstr='--inputVolumes %s...', ), + outputFilename=dict( + argstr='--outputFilename %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSSnapShotWriter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSSnapShotWriter_outputs(): - output_map = dict(outputFilename=dict(), - ) + output_map = dict(outputFilename=dict(), ) outputs = BRAINSSnapShotWriter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py index 789b1f4a42..fd6e6f4925 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py @@ -4,43 +4,43 @@ def test_BRAINSTransformConvert_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - displacementVolume=dict(argstr='--displacementVolume %s', - hash_files=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputTransform=dict(argstr='--inputTransform %s', - ), - outputPrecisionType=dict(argstr='--outputPrecisionType %s', - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - outputTransformType=dict(argstr='--outputTransformType %s', - ), - referenceVolume=dict(argstr='--referenceVolume %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + displacementVolume=dict( + argstr='--displacementVolume %s', + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputTransform=dict(argstr='--inputTransform %s', ), + outputPrecisionType=dict(argstr='--outputPrecisionType %s', ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + outputTransformType=dict(argstr='--outputTransformType %s', ), + referenceVolume=dict(argstr='--referenceVolume %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSTransformConvert.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSTransformConvert_outputs(): - output_map = dict(displacementVolume=dict(), - outputTransform=dict(), + output_map = dict( + displacementVolume=dict(), + outputTransform=dict(), ) outputs = BRAINSTransformConvert.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py index 212b60c3d5..88e7c01a51 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py @@ -4,46 +4,40 @@ def test_BRAINSTrimForegroundInDirection_inputs(): - input_map = dict(BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', - ), - args=dict(argstr='%s', - ), - closingSize=dict(argstr='--closingSize %d', - ), - directionCode=dict(argstr='--directionCode %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - headSizeLimit=dict(argstr='--headSizeLimit %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + BackgroundFillValue=dict(argstr='--BackgroundFillValue %s', ), + args=dict(argstr='%s', ), + closingSize=dict(argstr='--closingSize %d', ), + directionCode=dict(argstr='--directionCode %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + headSizeLimit=dict(argstr='--headSizeLimit %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BRAINSTrimForegroundInDirection.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSTrimForegroundInDirection_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSTrimForegroundInDirection.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py b/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py index 42064ce399..5d1d684be6 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py @@ -4,34 +4,34 @@ def test_CleanUpOverlapLabels_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBinaryVolumes=dict(argstr='--inputBinaryVolumes %s...', - ), - outputBinaryVolumes=dict(argstr='--outputBinaryVolumes %s...', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBinaryVolumes=dict(argstr='--inputBinaryVolumes %s...', ), + outputBinaryVolumes=dict( + argstr='--outputBinaryVolumes %s...', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = CleanUpOverlapLabels.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CleanUpOverlapLabels_outputs(): - output_map = dict(outputBinaryVolumes=dict(), - ) + output_map = dict(outputBinaryVolumes=dict(), ) outputs = CleanUpOverlapLabels.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py b/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py index 9c0d44ea96..1fce32d337 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py @@ -4,71 +4,69 @@ def test_FindCenterOfBrain_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - axis=dict(argstr='--axis %d', - ), - backgroundValue=dict(argstr='--backgroundValue %d', - ), - clippedImageMask=dict(argstr='--clippedImageMask %s', - hash_files=False, - ), - closingSize=dict(argstr='--closingSize %d', - ), - debugAfterGridComputationsForegroundImage=dict(argstr='--debugAfterGridComputationsForegroundImage %s', - hash_files=False, - ), - debugClippedImageMask=dict(argstr='--debugClippedImageMask %s', - hash_files=False, - ), - debugDistanceImage=dict(argstr='--debugDistanceImage %s', - hash_files=False, - ), - debugGridImage=dict(argstr='--debugGridImage %s', - hash_files=False, - ), - debugTrimmedImage=dict(argstr='--debugTrimmedImage %s', - hash_files=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - generateDebugImages=dict(argstr='--generateDebugImages ', - ), - headSizeEstimate=dict(argstr='--headSizeEstimate %f', - ), - headSizeLimit=dict(argstr='--headSizeLimit %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - imageMask=dict(argstr='--imageMask %s', - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - maximize=dict(argstr='--maximize ', - ), - otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + axis=dict(argstr='--axis %d', ), + backgroundValue=dict(argstr='--backgroundValue %d', ), + clippedImageMask=dict( + argstr='--clippedImageMask %s', + hash_files=False, + ), + closingSize=dict(argstr='--closingSize %d', ), + debugAfterGridComputationsForegroundImage=dict( + argstr='--debugAfterGridComputationsForegroundImage %s', + hash_files=False, + ), + debugClippedImageMask=dict( + argstr='--debugClippedImageMask %s', + hash_files=False, + ), + debugDistanceImage=dict( + argstr='--debugDistanceImage %s', + hash_files=False, + ), + debugGridImage=dict( + argstr='--debugGridImage %s', + hash_files=False, + ), + debugTrimmedImage=dict( + argstr='--debugTrimmedImage %s', + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + generateDebugImages=dict(argstr='--generateDebugImages ', ), + headSizeEstimate=dict(argstr='--headSizeEstimate %f', ), + headSizeLimit=dict(argstr='--headSizeLimit %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + imageMask=dict(argstr='--imageMask %s', ), + inputVolume=dict(argstr='--inputVolume %s', ), + maximize=dict(argstr='--maximize ', ), + otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = FindCenterOfBrain.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FindCenterOfBrain_outputs(): - output_map = dict(clippedImageMask=dict(), - debugAfterGridComputationsForegroundImage=dict(), - debugClippedImageMask=dict(), - debugDistanceImage=dict(), - debugGridImage=dict(), - debugTrimmedImage=dict(), + output_map = dict( + clippedImageMask=dict(), + debugAfterGridComputationsForegroundImage=dict(), + debugClippedImageMask=dict(), + debugDistanceImage=dict(), + debugGridImage=dict(), + debugTrimmedImage=dict(), ) outputs = FindCenterOfBrain.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py b/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py index 2b0a376b28..f89675e964 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py @@ -4,36 +4,35 @@ def test_GenerateLabelMapFromProbabilityMap_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolumes=dict(argstr='--inputVolumes %s...', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputLabelVolume=dict(argstr='--outputLabelVolume %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolumes=dict(argstr='--inputVolumes %s...', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputLabelVolume=dict( + argstr='--outputLabelVolume %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GenerateLabelMapFromProbabilityMap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GenerateLabelMapFromProbabilityMap_outputs(): - output_map = dict(outputLabelVolume=dict(), - ) + output_map = dict(outputLabelVolume=dict(), ) outputs = GenerateLabelMapFromProbabilityMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py b/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py index 7e0f0c7b7c..e4e1e3fba1 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py @@ -4,44 +4,37 @@ def test_ImageRegionPlotter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputBinaryROIVolume=dict(argstr='--inputBinaryROIVolume %s', - ), - inputLabelVolume=dict(argstr='--inputLabelVolume %s', - ), - inputVolume1=dict(argstr='--inputVolume1 %s', - ), - inputVolume2=dict(argstr='--inputVolume2 %s', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - outputJointHistogramData=dict(argstr='--outputJointHistogramData %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - useIntensityForHistogram=dict(argstr='--useIntensityForHistogram ', - ), - useROIAUTO=dict(argstr='--useROIAUTO ', - ), - verbose=dict(argstr='--verbose ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputBinaryROIVolume=dict(argstr='--inputBinaryROIVolume %s', ), + inputLabelVolume=dict(argstr='--inputLabelVolume %s', ), + inputVolume1=dict(argstr='--inputVolume1 %s', ), + inputVolume2=dict(argstr='--inputVolume2 %s', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + outputJointHistogramData=dict( + argstr='--outputJointHistogramData %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + useIntensityForHistogram=dict(argstr='--useIntensityForHistogram ', ), + useROIAUTO=dict(argstr='--useROIAUTO ', ), + verbose=dict(argstr='--verbose ', ), ) inputs = ImageRegionPlotter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ImageRegionPlotter_outputs(): output_map = dict() outputs = ImageRegionPlotter.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py b/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py index ee2f544417..c332928bf9 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py @@ -4,38 +4,34 @@ def test_JointHistogram_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMaskVolumeInXAxis=dict(argstr='--inputMaskVolumeInXAxis %s', - ), - inputMaskVolumeInYAxis=dict(argstr='--inputMaskVolumeInYAxis %s', - ), - inputVolumeInXAxis=dict(argstr='--inputVolumeInXAxis %s', - ), - inputVolumeInYAxis=dict(argstr='--inputVolumeInYAxis %s', - ), - outputJointHistogramImage=dict(argstr='--outputJointHistogramImage %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMaskVolumeInXAxis=dict(argstr='--inputMaskVolumeInXAxis %s', ), + inputMaskVolumeInYAxis=dict(argstr='--inputMaskVolumeInYAxis %s', ), + inputVolumeInXAxis=dict(argstr='--inputVolumeInXAxis %s', ), + inputVolumeInYAxis=dict(argstr='--inputVolumeInYAxis %s', ), + outputJointHistogramImage=dict( + argstr='--outputJointHistogramImage %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), ) inputs = JointHistogram.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JointHistogram_outputs(): output_map = dict() outputs = JointHistogram.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py b/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py index 228dfe4234..3861388d43 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py @@ -4,36 +4,35 @@ def test_ShuffleVectorsModule_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVectorFileBaseName=dict(argstr='--inputVectorFileBaseName %s', - ), - outputVectorFileBaseName=dict(argstr='--outputVectorFileBaseName %s', - hash_files=False, - ), - resampleProportion=dict(argstr='--resampleProportion %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVectorFileBaseName=dict(argstr='--inputVectorFileBaseName %s', ), + outputVectorFileBaseName=dict( + argstr='--outputVectorFileBaseName %s', + hash_files=False, + ), + resampleProportion=dict(argstr='--resampleProportion %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ShuffleVectorsModule.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ShuffleVectorsModule_outputs(): - output_map = dict(outputVectorFileBaseName=dict(), - ) + output_map = dict(outputVectorFileBaseName=dict(), ) outputs = ShuffleVectorsModule.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py b/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py index 3885c5ac5e..208c5b155c 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py @@ -4,43 +4,43 @@ def test_fcsv_to_hdf5_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - landmarkGlobPattern=dict(argstr='--landmarkGlobPattern %s', - ), - landmarkTypesList=dict(argstr='--landmarkTypesList %s', - ), - landmarksInformationFile=dict(argstr='--landmarksInformationFile %s', - hash_files=False, - ), - modelFile=dict(argstr='--modelFile %s', - hash_files=False, - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - versionID=dict(argstr='--versionID %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + landmarkGlobPattern=dict(argstr='--landmarkGlobPattern %s', ), + landmarkTypesList=dict(argstr='--landmarkTypesList %s', ), + landmarksInformationFile=dict( + argstr='--landmarksInformationFile %s', + hash_files=False, + ), + modelFile=dict( + argstr='--modelFile %s', + hash_files=False, + ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + versionID=dict(argstr='--versionID %s', ), ) inputs = fcsv_to_hdf5.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_fcsv_to_hdf5_outputs(): - output_map = dict(landmarksInformationFile=dict(), - modelFile=dict(), + output_map = dict( + landmarksInformationFile=dict(), + modelFile=dict(), ) outputs = fcsv_to_hdf5.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py b/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py index aedcbb3e63..b81339cca7 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py @@ -4,34 +4,34 @@ def test_insertMidACPCpoint_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputLandmarkFile=dict(argstr='--inputLandmarkFile %s', - ), - outputLandmarkFile=dict(argstr='--outputLandmarkFile %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputLandmarkFile=dict(argstr='--inputLandmarkFile %s', ), + outputLandmarkFile=dict( + argstr='--outputLandmarkFile %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = insertMidACPCpoint.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_insertMidACPCpoint_outputs(): - output_map = dict(outputLandmarkFile=dict(), - ) + output_map = dict(outputLandmarkFile=dict(), ) outputs = insertMidACPCpoint.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py index ef1668861f..3f6fe802a4 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py @@ -4,34 +4,34 @@ def test_landmarksConstellationAligner_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputLandmarksPaired=dict(argstr='--inputLandmarksPaired %s', - ), - outputLandmarksPaired=dict(argstr='--outputLandmarksPaired %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputLandmarksPaired=dict(argstr='--inputLandmarksPaired %s', ), + outputLandmarksPaired=dict( + argstr='--outputLandmarksPaired %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = landmarksConstellationAligner.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_landmarksConstellationAligner_outputs(): - output_map = dict(outputLandmarksPaired=dict(), - ) + output_map = dict(outputLandmarksPaired=dict(), ) outputs = landmarksConstellationAligner.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py index 4bf7c61ab7..feb04c13a5 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py @@ -4,38 +4,36 @@ def test_landmarksConstellationWeights_inputs(): - input_map = dict(LLSModel=dict(argstr='--LLSModel %s', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputTemplateModel=dict(argstr='--inputTemplateModel %s', - ), - inputTrainingList=dict(argstr='--inputTrainingList %s', - ), - outputWeightsList=dict(argstr='--outputWeightsList %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + LLSModel=dict(argstr='--LLSModel %s', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputTemplateModel=dict(argstr='--inputTemplateModel %s', ), + inputTrainingList=dict(argstr='--inputTrainingList %s', ), + outputWeightsList=dict( + argstr='--outputWeightsList %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = landmarksConstellationWeights.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_landmarksConstellationWeights_outputs(): - output_map = dict(outputWeightsList=dict(), - ) + output_map = dict(outputWeightsList=dict(), ) outputs = landmarksConstellationWeights.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/__init__.py b/nipype/interfaces/slicer/__init__.py index c6b929c41e..c7ffc42259 100644 --- a/nipype/interfaces/slicer/__init__.py +++ b/nipype/interfaces/slicer/__init__.py @@ -4,7 +4,8 @@ from .segmentation import * from .filtering import * from .utilities import EMSegmentTransformToNewFormat -from .surface import MergeModels, ModelToLabelMap, GrayscaleModelMaker, ProbeVolumeWithModel, LabelMapSmoothing, ModelMaker +from .surface import (MergeModels, ModelToLabelMap, GrayscaleModelMaker, + ProbeVolumeWithModel, LabelMapSmoothing, ModelMaker) from .quantification import * from .legacy import * from .registration import * diff --git a/nipype/interfaces/slicer/converters.py b/nipype/interfaces/slicer/converters.py index cc110d9ceb..e93b994110 100644 --- a/nipype/interfaces/slicer/converters.py +++ b/nipype/interfaces/slicer/converters.py @@ -8,17 +8,39 @@ class DicomToNrrdConverterInputSpec(CommandLineInputSpec): - inputDicomDirectory = Directory(desc="Directory holding Dicom series", exists=True, argstr="--inputDicomDirectory %s") - outputDirectory = traits.Either(traits.Bool, Directory(), hash_files=False, desc="Directory holding the output NRRD format", argstr="--outputDirectory %s") - outputVolume = traits.Str(desc="Output filename (.nhdr or .nrrd)", argstr="--outputVolume %s") - smallGradientThreshold = traits.Float(desc="If a gradient magnitude is greater than 0 and less than smallGradientThreshold, then DicomToNrrdConverter will display an error message and quit, unless the useBMatrixGradientDirections option is set.", argstr="--smallGradientThreshold %f") - writeProtocolGradientsFile = traits.Bool(desc="Write the protocol gradients to a file suffixed by \'.txt\' as they were specified in the procol by multiplying each diffusion gradient direction by the measurement frame. This file is for debugging purposes only, the format is not fixed, and will likely change as debugging of new dicom formats is necessary.", argstr="--writeProtocolGradientsFile ") - useIdentityMeaseurementFrame = traits.Bool(desc="Adjust all the gradients so that the measurement frame is an identity matrix.", argstr="--useIdentityMeaseurementFrame ") - useBMatrixGradientDirections = traits.Bool(desc="Fill the nhdr header with the gradient directions and bvalues computed out of the BMatrix. Only changes behavior for Siemens data.", argstr="--useBMatrixGradientDirections ") + inputDicomDirectory = Directory( + desc="Directory holding Dicom series", + exists=True, + argstr="--inputDicomDirectory %s") + outputDirectory = traits.Either( + traits.Bool, + Directory(), + hash_files=False, + desc="Directory holding the output NRRD format", + argstr="--outputDirectory %s") + outputVolume = traits.Str( + desc="Output filename (.nhdr or .nrrd)", argstr="--outputVolume %s") + smallGradientThreshold = traits.Float( + desc= + "If a gradient magnitude is greater than 0 and less than smallGradientThreshold, then DicomToNrrdConverter will display an error message and quit, unless the useBMatrixGradientDirections option is set.", + argstr="--smallGradientThreshold %f") + writeProtocolGradientsFile = traits.Bool( + desc= + "Write the protocol gradients to a file suffixed by \'.txt\' as they were specified in the procol by multiplying each diffusion gradient direction by the measurement frame. This file is for debugging purposes only, the format is not fixed, and will likely change as debugging of new dicom formats is necessary.", + argstr="--writeProtocolGradientsFile ") + useIdentityMeaseurementFrame = traits.Bool( + desc= + "Adjust all the gradients so that the measurement frame is an identity matrix.", + argstr="--useIdentityMeaseurementFrame ") + useBMatrixGradientDirections = traits.Bool( + desc= + "Fill the nhdr header with the gradient directions and bvalues computed out of the BMatrix. Only changes behavior for Siemens data.", + argstr="--useBMatrixGradientDirections ") class DicomToNrrdConverterOutputSpec(TraitedSpec): - outputDirectory = Directory(desc="Directory holding the output NRRD format", exists=True) + outputDirectory = Directory( + desc="Directory holding the output NRRD format", exists=True) class DicomToNrrdConverter(SEMLikeCommandLine): @@ -47,9 +69,69 @@ class DicomToNrrdConverter(SEMLikeCommandLine): class OrientScalarVolumeInputSpec(CommandLineInputSpec): - inputVolume1 = File(position=-2, desc="Input volume 1", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="The oriented volume", argstr="%s") - orientation = traits.Enum("Axial", "Coronal", "Sagittal", "RIP", "LIP", "RSP", "LSP", "RIA", "LIA", "RSA", "LSA", "IRP", "ILP", "SRP", "SLP", "IRA", "ILA", "SRA", "SLA", "RPI", "LPI", "RAI", "LAI", "RPS", "LPS", "RAS", "LAS", "PRI", "PLI", "ARI", "ALI", "PRS", "PLS", "ARS", "ALS", "IPR", "SPR", "IAR", "SAR", "IPL", "SPL", "IAL", "SAL", "PIR", "PSR", "AIR", "ASR", "PIL", "PSL", "AIL", "ASL", desc="Orientation choices", argstr="--orientation %s") + inputVolume1 = File( + position=-2, desc="Input volume 1", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="The oriented volume", + argstr="%s") + orientation = traits.Enum( + "Axial", + "Coronal", + "Sagittal", + "RIP", + "LIP", + "RSP", + "LSP", + "RIA", + "LIA", + "RSA", + "LSA", + "IRP", + "ILP", + "SRP", + "SLP", + "IRA", + "ILA", + "SRA", + "SLA", + "RPI", + "LPI", + "RAI", + "LAI", + "RPS", + "LPS", + "RAS", + "LAS", + "PRI", + "PLI", + "ARI", + "ALI", + "PRS", + "PLS", + "ARS", + "ALS", + "IPR", + "SPR", + "IAR", + "SAR", + "IPL", + "SPL", + "IAL", + "SAL", + "PIR", + "PSR", + "AIR", + "ASR", + "PIL", + "PSL", + "AIL", + "ASL", + desc="Orientation choices", + argstr="--orientation %s") class OrientScalarVolumeOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/diffusion/__init__.py b/nipype/interfaces/slicer/diffusion/__init__.py index 85544b6594..fd7231cefe 100644 --- a/nipype/interfaces/slicer/diffusion/__init__.py +++ b/nipype/interfaces/slicer/diffusion/__init__.py @@ -1,3 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import -from .diffusion import ResampleDTIVolume, DWIRicianLMMSEFilter, TractographyLabelMapSeeding, DWIJointRicianLMMSEFilter, DiffusionWeightedVolumeMasking, DTIimport, DWIToDTIEstimation, DiffusionTensorScalarMeasurements, DTIexport +from .diffusion import ( + ResampleDTIVolume, DWIRicianLMMSEFilter, TractographyLabelMapSeeding, + DWIJointRicianLMMSEFilter, DiffusionWeightedVolumeMasking, DTIimport, + DWIToDTIEstimation, DiffusionTensorScalarMeasurements, DTIexport) diff --git a/nipype/interfaces/slicer/diffusion/diffusion.py b/nipype/interfaces/slicer/diffusion/diffusion.py index 1f669ac8d6..a088d25f8a 100644 --- a/nipype/interfaces/slicer/diffusion/diffusion.py +++ b/nipype/interfaces/slicer/diffusion/diffusion.py @@ -8,32 +8,133 @@ class ResampleDTIVolumeInputSpec(CommandLineInputSpec): - inputVolume = File(position=-2, desc="Input volume to be resampled", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Resampled Volume", argstr="%s") - Reference = File(desc="Reference Volume (spacing,size,orientation,origin)", exists=True, argstr="--Reference %s") + inputVolume = File( + position=-2, + desc="Input volume to be resampled", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Resampled Volume", + argstr="%s") + Reference = File( + desc="Reference Volume (spacing,size,orientation,origin)", + exists=True, + argstr="--Reference %s") transformationFile = File(exists=True, argstr="--transformationFile %s") - defField = File(desc="File containing the deformation field (3D vector image containing vectors with 3 components)", exists=True, argstr="--defField %s") - hfieldtype = traits.Enum("displacement", "h-Field", desc="Set if the deformation field is an -Field", argstr="--hfieldtype %s") - interpolation = traits.Enum("linear", "nn", "ws", "bs", desc="Sampling algorithm (linear , nn (nearest neighborhoor), ws (WindowedSinc), bs (BSpline) )", argstr="--interpolation %s") - correction = traits.Enum("zero", "none", "abs", "nearest", desc="Correct the tensors if computed tensor is not semi-definite positive", argstr="--correction %s") - transform_tensor_method = traits.Enum("PPD", "FS", desc="Chooses between 2 methods to transform the tensors: Finite Strain (FS), faster but less accurate, or Preservation of the Principal Direction (PPD)", argstr="--transform_tensor_method %s") - transform_order = traits.Enum("input-to-output", "output-to-input", desc="Select in what order the transforms are read", argstr="--transform_order %s") - notbulk = traits.Bool(desc="The transform following the BSpline transform is not set as a bulk transform for the BSpline transform", argstr="--notbulk ") - spaceChange = traits.Bool(desc="Space Orientation between transform and image is different (RAS/LPS) (warning: if the transform is a Transform Node in Slicer3, do not select)", argstr="--spaceChange ") - rotation_point = traits.List(desc="Center of rotation (only for rigid and affine transforms)", argstr="--rotation_point %s") - centered_transform = traits.Bool(desc="Set the center of the transformation to the center of the input image (only for rigid and affine transforms)", argstr="--centered_transform ") - image_center = traits.Enum("input", "output", desc="Image to use to center the transform (used only if \'Centered Transform\' is selected)", argstr="--image_center %s") - Inverse_ITK_Transformation = traits.Bool(desc="Inverse the transformation before applying it from output image to input image (only for rigid and affine transforms)", argstr="--Inverse_ITK_Transformation ") - spacing = InputMultiPath(traits.Float, desc="Spacing along each dimension (0 means use input spacing)", sep=",", argstr="--spacing %s") - size = InputMultiPath(traits.Float, desc="Size along each dimension (0 means use input size)", sep=",", argstr="--size %s") - origin = traits.List(desc="Origin of the output Image", argstr="--origin %s") - direction_matrix = InputMultiPath(traits.Float, desc="9 parameters of the direction matrix by rows (ijk to LPS if LPS transform, ijk to RAS if RAS transform)", sep=",", argstr="--direction_matrix %s") - number_of_thread = traits.Int(desc="Number of thread used to compute the output image", argstr="--number_of_thread %d") - default_pixel_value = traits.Float(desc="Default pixel value for samples falling outside of the input region", argstr="--default_pixel_value %f") - window_function = traits.Enum("h", "c", "w", "l", "b", desc="Window Function , h = Hamming , c = Cosine , w = Welch , l = Lanczos , b = Blackman", argstr="--window_function %s") - spline_order = traits.Int(desc="Spline Order (Spline order may be from 0 to 5)", argstr="--spline_order %d") - transform_matrix = InputMultiPath(traits.Float, desc="12 parameters of the transform matrix by rows ( --last 3 being translation-- )", sep=",", argstr="--transform_matrix %s") - transform = traits.Enum("rt", "a", desc="Transform algorithm, rt = Rigid Transform, a = Affine Transform", argstr="--transform %s") + defField = File( + desc= + "File containing the deformation field (3D vector image containing vectors with 3 components)", + exists=True, + argstr="--defField %s") + hfieldtype = traits.Enum( + "displacement", + "h-Field", + desc="Set if the deformation field is an -Field", + argstr="--hfieldtype %s") + interpolation = traits.Enum( + "linear", + "nn", + "ws", + "bs", + desc= + "Sampling algorithm (linear , nn (nearest neighborhoor), ws (WindowedSinc), bs (BSpline) )", + argstr="--interpolation %s") + correction = traits.Enum( + "zero", + "none", + "abs", + "nearest", + desc= + "Correct the tensors if computed tensor is not semi-definite positive", + argstr="--correction %s") + transform_tensor_method = traits.Enum( + "PPD", + "FS", + desc= + "Chooses between 2 methods to transform the tensors: Finite Strain (FS), faster but less accurate, or Preservation of the Principal Direction (PPD)", + argstr="--transform_tensor_method %s") + transform_order = traits.Enum( + "input-to-output", + "output-to-input", + desc="Select in what order the transforms are read", + argstr="--transform_order %s") + notbulk = traits.Bool( + desc= + "The transform following the BSpline transform is not set as a bulk transform for the BSpline transform", + argstr="--notbulk ") + spaceChange = traits.Bool( + desc= + "Space Orientation between transform and image is different (RAS/LPS) (warning: if the transform is a Transform Node in Slicer3, do not select)", + argstr="--spaceChange ") + rotation_point = traits.List( + desc="Center of rotation (only for rigid and affine transforms)", + argstr="--rotation_point %s") + centered_transform = traits.Bool( + desc= + "Set the center of the transformation to the center of the input image (only for rigid and affine transforms)", + argstr="--centered_transform ") + image_center = traits.Enum( + "input", + "output", + desc= + "Image to use to center the transform (used only if \'Centered Transform\' is selected)", + argstr="--image_center %s") + Inverse_ITK_Transformation = traits.Bool( + desc= + "Inverse the transformation before applying it from output image to input image (only for rigid and affine transforms)", + argstr="--Inverse_ITK_Transformation ") + spacing = InputMultiPath( + traits.Float, + desc="Spacing along each dimension (0 means use input spacing)", + sep=",", + argstr="--spacing %s") + size = InputMultiPath( + traits.Float, + desc="Size along each dimension (0 means use input size)", + sep=",", + argstr="--size %s") + origin = traits.List( + desc="Origin of the output Image", argstr="--origin %s") + direction_matrix = InputMultiPath( + traits.Float, + desc= + "9 parameters of the direction matrix by rows (ijk to LPS if LPS transform, ijk to RAS if RAS transform)", + sep=",", + argstr="--direction_matrix %s") + number_of_thread = traits.Int( + desc="Number of thread used to compute the output image", + argstr="--number_of_thread %d") + default_pixel_value = traits.Float( + desc= + "Default pixel value for samples falling outside of the input region", + argstr="--default_pixel_value %f") + window_function = traits.Enum( + "h", + "c", + "w", + "l", + "b", + desc= + "Window Function , h = Hamming , c = Cosine , w = Welch , l = Lanczos , b = Blackman", + argstr="--window_function %s") + spline_order = traits.Int( + desc="Spline Order (Spline order may be from 0 to 5)", + argstr="--spline_order %d") + transform_matrix = InputMultiPath( + traits.Float, + desc= + "12 parameters of the transform matrix by rows ( --last 3 being translation-- )", + sep=",", + argstr="--transform_matrix %s") + transform = traits.Enum( + "rt", + "a", + desc="Transform algorithm, rt = Rigid Transform, a = Affine Transform", + argstr="--transform %s") class ResampleDTIVolumeOutputSpec(TraitedSpec): @@ -64,18 +165,41 @@ class ResampleDTIVolume(SEMLikeCommandLine): class DWIRicianLMMSEFilterInputSpec(CommandLineInputSpec): - iter = traits.Int(desc="Number of iterations for the noise removal filter.", argstr="--iter %d") - re = InputMultiPath(traits.Int, desc="Estimation radius.", sep=",", argstr="--re %s") - rf = InputMultiPath(traits.Int, desc="Filtering radius.", sep=",", argstr="--rf %s") - mnvf = traits.Int(desc="Minimum number of voxels in kernel used for filtering.", argstr="--mnvf %d") - mnve = traits.Int(desc="Minimum number of voxels in kernel used for estimation.", argstr="--mnve %d") - minnstd = traits.Int(desc="Minimum allowed noise standard deviation.", argstr="--minnstd %d") - maxnstd = traits.Int(desc="Maximum allowed noise standard deviation.", argstr="--maxnstd %d") - hrf = traits.Float(desc="How many histogram bins per unit interval.", argstr="--hrf %f") - uav = traits.Bool(desc="Use absolute value in case of negative square.", argstr="--uav ") - inputVolume = File(position=-2, desc="Input DWI volume.", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output DWI volume.", argstr="%s") - compressOutput = traits.Bool(desc="Compress the data of the compressed file using gzip", argstr="--compressOutput ") + iter = traits.Int( + desc="Number of iterations for the noise removal filter.", + argstr="--iter %d") + re = InputMultiPath( + traits.Int, desc="Estimation radius.", sep=",", argstr="--re %s") + rf = InputMultiPath( + traits.Int, desc="Filtering radius.", sep=",", argstr="--rf %s") + mnvf = traits.Int( + desc="Minimum number of voxels in kernel used for filtering.", + argstr="--mnvf %d") + mnve = traits.Int( + desc="Minimum number of voxels in kernel used for estimation.", + argstr="--mnve %d") + minnstd = traits.Int( + desc="Minimum allowed noise standard deviation.", + argstr="--minnstd %d") + maxnstd = traits.Int( + desc="Maximum allowed noise standard deviation.", + argstr="--maxnstd %d") + hrf = traits.Float( + desc="How many histogram bins per unit interval.", argstr="--hrf %f") + uav = traits.Bool( + desc="Use absolute value in case of negative square.", argstr="--uav ") + inputVolume = File( + position=-2, desc="Input DWI volume.", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output DWI volume.", + argstr="%s") + compressOutput = traits.Bool( + desc="Compress the data of the compressed file using gzip", + argstr="--compressOutput ") class DWIRicianLMMSEFilterOutputSpec(TraitedSpec): @@ -109,28 +233,69 @@ class DWIRicianLMMSEFilter(SEMLikeCommandLine): class TractographyLabelMapSeedingInputSpec(CommandLineInputSpec): - InputVolume = File(position=-2, desc="Input DTI volume", exists=True, argstr="%s") - inputroi = File(desc="Label map with seeding ROIs", exists=True, argstr="--inputroi %s") - OutputFibers = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Tractography result", argstr="%s") - useindexspace = traits.Bool(desc="Seed at IJK voxel grid", argstr="--useindexspace ") - seedspacing = traits.Float(desc="Spacing (in mm) between seed points, only matters if use Use Index Space is off", argstr="--seedspacing %f") - randomgrid = traits.Bool(desc="Enable random placing of seeds", argstr="--randomgrid ") - clthreshold = traits.Float(desc="Minimum Linear Measure for the seeding to start.", argstr="--clthreshold %f") - minimumlength = traits.Float(desc="Minimum length of the fibers (in mm)", argstr="--minimumlength %f") - maximumlength = traits.Float(desc="Maximum length of fibers (in mm)", argstr="--maximumlength %f") - stoppingmode = traits.Enum("LinearMeasure", "FractionalAnisotropy", desc="Tensor measurement used to stop the tractography", argstr="--stoppingmode %s") - stoppingvalue = traits.Float(desc="Tractography will stop when the stopping measurement drops below this value", argstr="--stoppingvalue %f") - stoppingcurvature = traits.Float(desc="Tractography will stop if radius of curvature becomes smaller than this number units are degrees per mm", argstr="--stoppingcurvature %f") - integrationsteplength = traits.Float(desc="Distance between points on the same fiber in mm", argstr="--integrationsteplength %f") - label = traits.Int(desc="Label value that defines seeding region.", argstr="--label %d") - writetofile = traits.Bool(desc="Write fibers to disk or create in the scene?", argstr="--writetofile ") - outputdirectory = traits.Either(traits.Bool, Directory(), hash_files=False, desc="Directory in which to save fiber(s)", argstr="--outputdirectory %s") + InputVolume = File( + position=-2, desc="Input DTI volume", exists=True, argstr="%s") + inputroi = File( + desc="Label map with seeding ROIs", + exists=True, + argstr="--inputroi %s") + OutputFibers = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Tractography result", + argstr="%s") + useindexspace = traits.Bool( + desc="Seed at IJK voxel grid", argstr="--useindexspace ") + seedspacing = traits.Float( + desc= + "Spacing (in mm) between seed points, only matters if use Use Index Space is off", + argstr="--seedspacing %f") + randomgrid = traits.Bool( + desc="Enable random placing of seeds", argstr="--randomgrid ") + clthreshold = traits.Float( + desc="Minimum Linear Measure for the seeding to start.", + argstr="--clthreshold %f") + minimumlength = traits.Float( + desc="Minimum length of the fibers (in mm)", + argstr="--minimumlength %f") + maximumlength = traits.Float( + desc="Maximum length of fibers (in mm)", argstr="--maximumlength %f") + stoppingmode = traits.Enum( + "LinearMeasure", + "FractionalAnisotropy", + desc="Tensor measurement used to stop the tractography", + argstr="--stoppingmode %s") + stoppingvalue = traits.Float( + desc= + "Tractography will stop when the stopping measurement drops below this value", + argstr="--stoppingvalue %f") + stoppingcurvature = traits.Float( + desc= + "Tractography will stop if radius of curvature becomes smaller than this number units are degrees per mm", + argstr="--stoppingcurvature %f") + integrationsteplength = traits.Float( + desc="Distance between points on the same fiber in mm", + argstr="--integrationsteplength %f") + label = traits.Int( + desc="Label value that defines seeding region.", argstr="--label %d") + writetofile = traits.Bool( + desc="Write fibers to disk or create in the scene?", + argstr="--writetofile ") + outputdirectory = traits.Either( + traits.Bool, + Directory(), + hash_files=False, + desc="Directory in which to save fiber(s)", + argstr="--outputdirectory %s") name = traits.Str(desc="Name to use for fiber files", argstr="--name %s") class TractographyLabelMapSeedingOutputSpec(TraitedSpec): OutputFibers = File(position=-1, desc="Tractography result", exists=True) - outputdirectory = Directory(desc="Directory in which to save fiber(s)", exists=True) + outputdirectory = Directory( + desc="Directory in which to save fiber(s)", exists=True) class TractographyLabelMapSeeding(SEMLikeCommandLine): @@ -155,16 +320,33 @@ class TractographyLabelMapSeeding(SEMLikeCommandLine): input_spec = TractographyLabelMapSeedingInputSpec output_spec = TractographyLabelMapSeedingOutputSpec _cmd = "TractographyLabelMapSeeding " - _outputs_filenames = {'OutputFibers': 'OutputFibers.vtk', 'outputdirectory': 'outputdirectory'} + _outputs_filenames = { + 'OutputFibers': 'OutputFibers.vtk', + 'outputdirectory': 'outputdirectory' + } class DWIJointRicianLMMSEFilterInputSpec(CommandLineInputSpec): - re = InputMultiPath(traits.Int, desc="Estimation radius.", sep=",", argstr="--re %s") - rf = InputMultiPath(traits.Int, desc="Filtering radius.", sep=",", argstr="--rf %s") - ng = traits.Int(desc="The number of the closest gradients that are used to jointly filter a given gradient direction (0 to use all).", argstr="--ng %d") - inputVolume = File(position=-2, desc="Input DWI volume.", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output DWI volume.", argstr="%s") - compressOutput = traits.Bool(desc="Compress the data of the compressed file using gzip", argstr="--compressOutput ") + re = InputMultiPath( + traits.Int, desc="Estimation radius.", sep=",", argstr="--re %s") + rf = InputMultiPath( + traits.Int, desc="Filtering radius.", sep=",", argstr="--rf %s") + ng = traits.Int( + desc= + "The number of the closest gradients that are used to jointly filter a given gradient direction (0 to use all).", + argstr="--ng %d") + inputVolume = File( + position=-2, desc="Input DWI volume.", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output DWI volume.", + argstr="%s") + compressOutput = traits.Bool( + desc="Compress the data of the compressed file using gzip", + argstr="--compressOutput ") class DWIJointRicianLMMSEFilterOutputSpec(TraitedSpec): @@ -198,15 +380,33 @@ class DWIJointRicianLMMSEFilter(SEMLikeCommandLine): class DiffusionWeightedVolumeMaskingInputSpec(CommandLineInputSpec): - inputVolume = File(position=-4, desc="Input DWI volume", exists=True, argstr="%s") - outputBaseline = traits.Either(traits.Bool, File(), position=-2, hash_files=False, desc="Estimated baseline volume", argstr="%s") - thresholdMask = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Otsu Threshold Mask", argstr="%s") - otsuomegathreshold = traits.Float(desc="Control the sharpness of the threshold in the Otsu computation. 0: lower threshold, 1: higher threhold", argstr="--otsuomegathreshold %f") - removeislands = traits.Bool(desc="Remove Islands in Threshold Mask?", argstr="--removeislands ") + inputVolume = File( + position=-4, desc="Input DWI volume", exists=True, argstr="%s") + outputBaseline = traits.Either( + traits.Bool, + File(), + position=-2, + hash_files=False, + desc="Estimated baseline volume", + argstr="%s") + thresholdMask = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Otsu Threshold Mask", + argstr="%s") + otsuomegathreshold = traits.Float( + desc= + "Control the sharpness of the threshold in the Otsu computation. 0: lower threshold, 1: higher threhold", + argstr="--otsuomegathreshold %f") + removeislands = traits.Bool( + desc="Remove Islands in Threshold Mask?", argstr="--removeislands ") class DiffusionWeightedVolumeMaskingOutputSpec(TraitedSpec): - outputBaseline = File(position=-2, desc="Estimated baseline volume", exists=True) + outputBaseline = File( + position=-2, desc="Estimated baseline volume", exists=True) thresholdMask = File(position=-1, desc="Otsu Threshold Mask", exists=True) @@ -230,13 +430,26 @@ class DiffusionWeightedVolumeMasking(SEMLikeCommandLine): input_spec = DiffusionWeightedVolumeMaskingInputSpec output_spec = DiffusionWeightedVolumeMaskingOutputSpec _cmd = "DiffusionWeightedVolumeMasking " - _outputs_filenames = {'outputBaseline': 'outputBaseline.nii', 'thresholdMask': 'thresholdMask.nii'} + _outputs_filenames = { + 'outputBaseline': 'outputBaseline.nii', + 'thresholdMask': 'thresholdMask.nii' + } class DTIimportInputSpec(CommandLineInputSpec): - inputFile = File(position=-2, desc="Input DTI file", exists=True, argstr="%s") - outputTensor = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output DTI volume", argstr="%s") - testingmode = traits.Bool(desc="Enable testing mode. Sample helix file (helix-DTI.nhdr) will be loaded into Slicer and converted in Nifti.", argstr="--testingmode ") + inputFile = File( + position=-2, desc="Input DTI file", exists=True, argstr="%s") + outputTensor = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output DTI volume", + argstr="%s") + testingmode = traits.Bool( + desc= + "Enable testing mode. Sample helix file (helix-DTI.nhdr) will be loaded into Slicer and converted in Nifti.", + argstr="--testingmode ") class DTIimportOutputSpec(TraitedSpec): @@ -267,17 +480,41 @@ class DTIimport(SEMLikeCommandLine): class DWIToDTIEstimationInputSpec(CommandLineInputSpec): - inputVolume = File(position=-3, desc="Input DWI volume", exists=True, argstr="%s") - mask = File(desc="Mask where the tensors will be computed", exists=True, argstr="--mask %s") - outputTensor = traits.Either(traits.Bool, File(), position=-2, hash_files=False, desc="Estimated DTI volume", argstr="%s") - outputBaseline = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Estimated baseline volume", argstr="%s") - enumeration = traits.Enum("LS", "WLS", desc="LS: Least Squares, WLS: Weighted Least Squares", argstr="--enumeration %s") - shiftNeg = traits.Bool(desc="Shift eigenvalues so all are positive (accounts for bad tensors related to noise or acquisition error)", argstr="--shiftNeg ") + inputVolume = File( + position=-3, desc="Input DWI volume", exists=True, argstr="%s") + mask = File( + desc="Mask where the tensors will be computed", + exists=True, + argstr="--mask %s") + outputTensor = traits.Either( + traits.Bool, + File(), + position=-2, + hash_files=False, + desc="Estimated DTI volume", + argstr="%s") + outputBaseline = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Estimated baseline volume", + argstr="%s") + enumeration = traits.Enum( + "LS", + "WLS", + desc="LS: Least Squares, WLS: Weighted Least Squares", + argstr="--enumeration %s") + shiftNeg = traits.Bool( + desc= + "Shift eigenvalues so all are positive (accounts for bad tensors related to noise or acquisition error)", + argstr="--shiftNeg ") class DWIToDTIEstimationOutputSpec(TraitedSpec): outputTensor = File(position=-2, desc="Estimated DTI volume", exists=True) - outputBaseline = File(position=-1, desc="Estimated baseline volume", exists=True) + outputBaseline = File( + position=-1, desc="Estimated baseline volume", exists=True) class DWIToDTIEstimation(SEMLikeCommandLine): @@ -304,17 +541,55 @@ class DWIToDTIEstimation(SEMLikeCommandLine): input_spec = DWIToDTIEstimationInputSpec output_spec = DWIToDTIEstimationOutputSpec _cmd = "DWIToDTIEstimation " - _outputs_filenames = {'outputTensor': 'outputTensor.nii', 'outputBaseline': 'outputBaseline.nii'} + _outputs_filenames = { + 'outputTensor': 'outputTensor.nii', + 'outputBaseline': 'outputBaseline.nii' + } class DiffusionTensorScalarMeasurementsInputSpec(CommandLineInputSpec): - inputVolume = File(position=-3, desc="Input DTI volume", exists=True, argstr="%s") - outputScalar = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Scalar volume derived from tensor", argstr="%s") - enumeration = traits.Enum("Trace", "Determinant", "RelativeAnisotropy", "FractionalAnisotropy", "Mode", "LinearMeasure", "PlanarMeasure", "SphericalMeasure", "MinEigenvalue", "MidEigenvalue", "MaxEigenvalue", "MaxEigenvalueProjectionX", "MaxEigenvalueProjectionY", "MaxEigenvalueProjectionZ", "RAIMaxEigenvecX", "RAIMaxEigenvecY", "RAIMaxEigenvecZ", "MaxEigenvecX", "MaxEigenvecY", "MaxEigenvecZ", "D11", "D22", "D33", "ParallelDiffusivity", "PerpendicularDffusivity", desc="An enumeration of strings", argstr="--enumeration %s") + inputVolume = File( + position=-3, desc="Input DTI volume", exists=True, argstr="%s") + outputScalar = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Scalar volume derived from tensor", + argstr="%s") + enumeration = traits.Enum( + "Trace", + "Determinant", + "RelativeAnisotropy", + "FractionalAnisotropy", + "Mode", + "LinearMeasure", + "PlanarMeasure", + "SphericalMeasure", + "MinEigenvalue", + "MidEigenvalue", + "MaxEigenvalue", + "MaxEigenvalueProjectionX", + "MaxEigenvalueProjectionY", + "MaxEigenvalueProjectionZ", + "RAIMaxEigenvecX", + "RAIMaxEigenvecY", + "RAIMaxEigenvecZ", + "MaxEigenvecX", + "MaxEigenvecY", + "MaxEigenvecZ", + "D11", + "D22", + "D33", + "ParallelDiffusivity", + "PerpendicularDffusivity", + desc="An enumeration of strings", + argstr="--enumeration %s") class DiffusionTensorScalarMeasurementsOutputSpec(TraitedSpec): - outputScalar = File(position=-1, desc="Scalar volume derived from tensor", exists=True) + outputScalar = File( + position=-1, desc="Scalar volume derived from tensor", exists=True) class DiffusionTensorScalarMeasurements(SEMLikeCommandLine): @@ -341,8 +616,15 @@ class DiffusionTensorScalarMeasurements(SEMLikeCommandLine): class DTIexportInputSpec(CommandLineInputSpec): - inputTensor = File(position=-2, desc="Input DTI volume", exists=True, argstr="%s") - outputFile = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output DTI file", argstr="%s") + inputTensor = File( + position=-2, desc="Input DTI volume", exists=True, argstr="%s") + outputFile = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output DTI file", + argstr="%s") class DTIexportOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py index d3c499df21..49a1b8987a 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py @@ -4,37 +4,38 @@ def test_DTIexport_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputTensor=dict(argstr='%s', - position=-2, - ), - outputFile=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputTensor=dict( + argstr='%s', + position=-2, + ), + outputFile=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DTIexport.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTIexport_outputs(): - output_map = dict(outputFile=dict(position=-1, - ), - ) + output_map = dict(outputFile=dict(position=-1, ), ) outputs = DTIexport.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py index cd4ae462f4..3aa2e880ef 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py @@ -4,39 +4,39 @@ def test_DTIimport_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputFile=dict(argstr='%s', - position=-2, - ), - outputTensor=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - testingmode=dict(argstr='--testingmode ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputFile=dict( + argstr='%s', + position=-2, + ), + outputTensor=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + testingmode=dict(argstr='--testingmode ', ), ) inputs = DTIimport.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DTIimport_outputs(): - output_map = dict(outputTensor=dict(position=-1, - ), - ) + output_map = dict(outputTensor=dict(position=-1, ), ) outputs = DTIimport.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py index 2a97030210..4a39330c22 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py @@ -4,47 +4,48 @@ def test_DWIJointRicianLMMSEFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - compressOutput=dict(argstr='--compressOutput ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - ng=dict(argstr='--ng %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - re=dict(argstr='--re %s', - sep=',', - ), - rf=dict(argstr='--rf %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + compressOutput=dict(argstr='--compressOutput ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + ng=dict(argstr='--ng %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + re=dict( + argstr='--re %s', + sep=',', + ), + rf=dict( + argstr='--rf %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWIJointRicianLMMSEFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWIJointRicianLMMSEFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = DWIJointRicianLMMSEFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py index e71ae3106a..750668c266 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py @@ -4,59 +4,54 @@ def test_DWIRicianLMMSEFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - compressOutput=dict(argstr='--compressOutput ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hrf=dict(argstr='--hrf %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - iter=dict(argstr='--iter %d', - ), - maxnstd=dict(argstr='--maxnstd %d', - ), - minnstd=dict(argstr='--minnstd %d', - ), - mnve=dict(argstr='--mnve %d', - ), - mnvf=dict(argstr='--mnvf %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - re=dict(argstr='--re %s', - sep=',', - ), - rf=dict(argstr='--rf %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uav=dict(argstr='--uav ', - ), + input_map = dict( + args=dict(argstr='%s', ), + compressOutput=dict(argstr='--compressOutput ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + hrf=dict(argstr='--hrf %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + iter=dict(argstr='--iter %d', ), + maxnstd=dict(argstr='--maxnstd %d', ), + minnstd=dict(argstr='--minnstd %d', ), + mnve=dict(argstr='--mnve %d', ), + mnvf=dict(argstr='--mnvf %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + re=dict( + argstr='--re %s', + sep=',', + ), + rf=dict( + argstr='--rf %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uav=dict(argstr='--uav ', ), ) inputs = DWIRicianLMMSEFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWIRicianLMMSEFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = DWIRicianLMMSEFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py index 938855c9cf..23917323a6 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py @@ -4,48 +4,48 @@ def test_DWIToDTIEstimation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - enumeration=dict(argstr='--enumeration %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-3, - ), - mask=dict(argstr='--mask %s', - ), - outputBaseline=dict(argstr='%s', - hash_files=False, - position=-1, - ), - outputTensor=dict(argstr='%s', - hash_files=False, - position=-2, - ), - shiftNeg=dict(argstr='--shiftNeg ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + enumeration=dict(argstr='--enumeration %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-3, + ), + mask=dict(argstr='--mask %s', ), + outputBaseline=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + outputTensor=dict( + argstr='%s', + hash_files=False, + position=-2, + ), + shiftNeg=dict(argstr='--shiftNeg ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWIToDTIEstimation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWIToDTIEstimation_outputs(): - output_map = dict(outputBaseline=dict(position=-1, - ), - outputTensor=dict(position=-2, - ), + output_map = dict( + outputBaseline=dict(position=-1, ), + outputTensor=dict(position=-2, ), ) outputs = DWIToDTIEstimation.output_spec() diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py index 80b9d9b745..4c862d7456 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py @@ -4,39 +4,39 @@ def test_DiffusionTensorScalarMeasurements_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - enumeration=dict(argstr='--enumeration %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-3, - ), - outputScalar=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + enumeration=dict(argstr='--enumeration %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-3, + ), + outputScalar=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DiffusionTensorScalarMeasurements.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DiffusionTensorScalarMeasurements_outputs(): - output_map = dict(outputScalar=dict(position=-1, - ), - ) + output_map = dict(outputScalar=dict(position=-1, ), ) outputs = DiffusionTensorScalarMeasurements.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py index 247cd2612a..2576eae0ae 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py @@ -4,46 +4,47 @@ def test_DiffusionWeightedVolumeMasking_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-4, - ), - otsuomegathreshold=dict(argstr='--otsuomegathreshold %f', - ), - outputBaseline=dict(argstr='%s', - hash_files=False, - position=-2, - ), - removeislands=dict(argstr='--removeislands ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresholdMask=dict(argstr='%s', - hash_files=False, - position=-1, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-4, + ), + otsuomegathreshold=dict(argstr='--otsuomegathreshold %f', ), + outputBaseline=dict( + argstr='%s', + hash_files=False, + position=-2, + ), + removeislands=dict(argstr='--removeislands ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresholdMask=dict( + argstr='%s', + hash_files=False, + position=-1, + ), ) inputs = DiffusionWeightedVolumeMasking.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DiffusionWeightedVolumeMasking_outputs(): - output_map = dict(outputBaseline=dict(position=-2, - ), - thresholdMask=dict(position=-1, - ), + output_map = dict( + outputBaseline=dict(position=-2, ), + thresholdMask=dict(position=-1, ), ) outputs = DiffusionWeightedVolumeMasking.output_spec() diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py index 423ef009be..51c7a19ea4 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py @@ -4,89 +4,75 @@ def test_ResampleDTIVolume_inputs(): - input_map = dict(Inverse_ITK_Transformation=dict(argstr='--Inverse_ITK_Transformation ', - ), - Reference=dict(argstr='--Reference %s', - ), - args=dict(argstr='%s', - ), - centered_transform=dict(argstr='--centered_transform ', - ), - correction=dict(argstr='--correction %s', - ), - defField=dict(argstr='--defField %s', - ), - default_pixel_value=dict(argstr='--default_pixel_value %f', - ), - direction_matrix=dict(argstr='--direction_matrix %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hfieldtype=dict(argstr='--hfieldtype %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_center=dict(argstr='--image_center %s', - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - interpolation=dict(argstr='--interpolation %s', - ), - notbulk=dict(argstr='--notbulk ', - ), - number_of_thread=dict(argstr='--number_of_thread %d', - ), - origin=dict(argstr='--origin %s', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - rotation_point=dict(argstr='--rotation_point %s', - ), - size=dict(argstr='--size %s', - sep=',', - ), - spaceChange=dict(argstr='--spaceChange ', - ), - spacing=dict(argstr='--spacing %s', - sep=',', - ), - spline_order=dict(argstr='--spline_order %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='--transform %s', - ), - transform_matrix=dict(argstr='--transform_matrix %s', - sep=',', - ), - transform_order=dict(argstr='--transform_order %s', - ), - transform_tensor_method=dict(argstr='--transform_tensor_method %s', - ), - transformationFile=dict(argstr='--transformationFile %s', - ), - window_function=dict(argstr='--window_function %s', - ), + input_map = dict( + Inverse_ITK_Transformation=dict( + argstr='--Inverse_ITK_Transformation ', ), + Reference=dict(argstr='--Reference %s', ), + args=dict(argstr='%s', ), + centered_transform=dict(argstr='--centered_transform ', ), + correction=dict(argstr='--correction %s', ), + defField=dict(argstr='--defField %s', ), + default_pixel_value=dict(argstr='--default_pixel_value %f', ), + direction_matrix=dict( + argstr='--direction_matrix %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hfieldtype=dict(argstr='--hfieldtype %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_center=dict(argstr='--image_center %s', ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + interpolation=dict(argstr='--interpolation %s', ), + notbulk=dict(argstr='--notbulk ', ), + number_of_thread=dict(argstr='--number_of_thread %d', ), + origin=dict(argstr='--origin %s', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + rotation_point=dict(argstr='--rotation_point %s', ), + size=dict( + argstr='--size %s', + sep=',', + ), + spaceChange=dict(argstr='--spaceChange ', ), + spacing=dict( + argstr='--spacing %s', + sep=',', + ), + spline_order=dict(argstr='--spline_order %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict(argstr='--transform %s', ), + transform_matrix=dict( + argstr='--transform_matrix %s', + sep=',', + ), + transform_order=dict(argstr='--transform_order %s', ), + transform_tensor_method=dict(argstr='--transform_tensor_method %s', ), + transformationFile=dict(argstr='--transformationFile %s', ), + window_function=dict(argstr='--window_function %s', ), ) inputs = ResampleDTIVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ResampleDTIVolume_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = ResampleDTIVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py index 2dc06051ca..f88a89a4ca 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py @@ -4,68 +4,58 @@ def test_TractographyLabelMapSeeding_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-2, - ), - OutputFibers=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - clthreshold=dict(argstr='--clthreshold %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputroi=dict(argstr='--inputroi %s', - ), - integrationsteplength=dict(argstr='--integrationsteplength %f', - ), - label=dict(argstr='--label %d', - ), - maximumlength=dict(argstr='--maximumlength %f', - ), - minimumlength=dict(argstr='--minimumlength %f', - ), - name=dict(argstr='--name %s', - ), - outputdirectory=dict(argstr='--outputdirectory %s', - hash_files=False, - ), - randomgrid=dict(argstr='--randomgrid ', - ), - seedspacing=dict(argstr='--seedspacing %f', - ), - stoppingcurvature=dict(argstr='--stoppingcurvature %f', - ), - stoppingmode=dict(argstr='--stoppingmode %s', - ), - stoppingvalue=dict(argstr='--stoppingvalue %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - useindexspace=dict(argstr='--useindexspace ', - ), - writetofile=dict(argstr='--writetofile ', - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-2, + ), + OutputFibers=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + clthreshold=dict(argstr='--clthreshold %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputroi=dict(argstr='--inputroi %s', ), + integrationsteplength=dict(argstr='--integrationsteplength %f', ), + label=dict(argstr='--label %d', ), + maximumlength=dict(argstr='--maximumlength %f', ), + minimumlength=dict(argstr='--minimumlength %f', ), + name=dict(argstr='--name %s', ), + outputdirectory=dict( + argstr='--outputdirectory %s', + hash_files=False, + ), + randomgrid=dict(argstr='--randomgrid ', ), + seedspacing=dict(argstr='--seedspacing %f', ), + stoppingcurvature=dict(argstr='--stoppingcurvature %f', ), + stoppingmode=dict(argstr='--stoppingmode %s', ), + stoppingvalue=dict(argstr='--stoppingvalue %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + useindexspace=dict(argstr='--useindexspace ', ), + writetofile=dict(argstr='--writetofile ', ), ) inputs = TractographyLabelMapSeeding.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TractographyLabelMapSeeding_outputs(): - output_map = dict(OutputFibers=dict(position=-1, - ), - outputdirectory=dict(), + output_map = dict( + OutputFibers=dict(position=-1, ), + outputdirectory=dict(), ) outputs = TractographyLabelMapSeeding.output_spec() diff --git a/nipype/interfaces/slicer/filtering/__init__.py b/nipype/interfaces/slicer/filtering/__init__.py index d4dbd9e220..30ace1d2f2 100644 --- a/nipype/interfaces/slicer/filtering/__init__.py +++ b/nipype/interfaces/slicer/filtering/__init__.py @@ -1,8 +1,13 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import -from .morphology import GrayscaleGrindPeakImageFilter, GrayscaleFillHoleImageFilter -from .denoising import GradientAnisotropicDiffusion, CurvatureAnisotropicDiffusion, GaussianBlurImageFilter, MedianImageFilter -from .arithmetic import MultiplyScalarVolumes, MaskScalarVolume, SubtractScalarVolumes, AddScalarVolumes, CastScalarVolume +from .morphology import (GrayscaleGrindPeakImageFilter, + GrayscaleFillHoleImageFilter) +from .denoising import (GradientAnisotropicDiffusion, + CurvatureAnisotropicDiffusion, GaussianBlurImageFilter, + MedianImageFilter) +from .arithmetic import (MultiplyScalarVolumes, MaskScalarVolume, + SubtractScalarVolumes, AddScalarVolumes, + CastScalarVolume) from .extractskeleton import ExtractSkeleton from .histogrammatching import HistogramMatching from .thresholdscalarvolume import ThresholdScalarVolume diff --git a/nipype/interfaces/slicer/filtering/arithmetic.py b/nipype/interfaces/slicer/filtering/arithmetic.py index c6bb024507..22785e32e1 100644 --- a/nipype/interfaces/slicer/filtering/arithmetic.py +++ b/nipype/interfaces/slicer/filtering/arithmetic.py @@ -8,10 +8,25 @@ class MultiplyScalarVolumesInputSpec(CommandLineInputSpec): - inputVolume1 = File(position=-3, desc="Input volume 1", exists=True, argstr="%s") - inputVolume2 = File(position=-2, desc="Input volume 2", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Volume1 * Volume2", argstr="%s") - order = traits.Enum("0", "1", "2", "3", desc="Interpolation order if two images are in different coordinate frames or have different sampling.", argstr="--order %s") + inputVolume1 = File( + position=-3, desc="Input volume 1", exists=True, argstr="%s") + inputVolume2 = File( + position=-2, desc="Input volume 2", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Volume1 * Volume2", + argstr="%s") + order = traits.Enum( + "0", + "1", + "2", + "3", + desc= + "Interpolation order if two images are in different coordinate frames or have different sampling.", + argstr="--order %s") class MultiplyScalarVolumesOutputSpec(TraitedSpec): @@ -42,15 +57,38 @@ class MultiplyScalarVolumes(SEMLikeCommandLine): class MaskScalarVolumeInputSpec(CommandLineInputSpec): - InputVolume = File(position=-3, desc="Input volume to be masked", exists=True, argstr="%s") - MaskVolume = File(position=-2, desc="Label volume containing the mask", exists=True, argstr="%s") - OutputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output volume: Input Volume masked by label value from Mask Volume", argstr="%s") - label = traits.Int(desc="Label value in the Mask Volume to use as the mask", argstr="--label %d") - replace = traits.Int(desc="Value to use for the output volume outside of the mask", argstr="--replace %d") + InputVolume = File( + position=-3, + desc="Input volume to be masked", + exists=True, + argstr="%s") + MaskVolume = File( + position=-2, + desc="Label volume containing the mask", + exists=True, + argstr="%s") + OutputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc= + "Output volume: Input Volume masked by label value from Mask Volume", + argstr="%s") + label = traits.Int( + desc="Label value in the Mask Volume to use as the mask", + argstr="--label %d") + replace = traits.Int( + desc="Value to use for the output volume outside of the mask", + argstr="--replace %d") class MaskScalarVolumeOutputSpec(TraitedSpec): - OutputVolume = File(position=-1, desc="Output volume: Input Volume masked by label value from Mask Volume", exists=True) + OutputVolume = File( + position=-1, + desc= + "Output volume: Input Volume masked by label value from Mask Volume", + exists=True) class MaskScalarVolume(SEMLikeCommandLine): @@ -77,10 +115,25 @@ class MaskScalarVolume(SEMLikeCommandLine): class SubtractScalarVolumesInputSpec(CommandLineInputSpec): - inputVolume1 = File(position=-3, desc="Input volume 1", exists=True, argstr="%s") - inputVolume2 = File(position=-2, desc="Input volume 2", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Volume1 - Volume2", argstr="%s") - order = traits.Enum("0", "1", "2", "3", desc="Interpolation order if two images are in different coordinate frames or have different sampling.", argstr="--order %s") + inputVolume1 = File( + position=-3, desc="Input volume 1", exists=True, argstr="%s") + inputVolume2 = File( + position=-2, desc="Input volume 2", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Volume1 - Volume2", + argstr="%s") + order = traits.Enum( + "0", + "1", + "2", + "3", + desc= + "Interpolation order if two images are in different coordinate frames or have different sampling.", + argstr="--order %s") class SubtractScalarVolumesOutputSpec(TraitedSpec): @@ -111,10 +164,25 @@ class SubtractScalarVolumes(SEMLikeCommandLine): class AddScalarVolumesInputSpec(CommandLineInputSpec): - inputVolume1 = File(position=-3, desc="Input volume 1", exists=True, argstr="%s") - inputVolume2 = File(position=-2, desc="Input volume 2", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Volume1 + Volume2", argstr="%s") - order = traits.Enum("0", "1", "2", "3", desc="Interpolation order if two images are in different coordinate frames or have different sampling.", argstr="--order %s") + inputVolume1 = File( + position=-3, desc="Input volume 1", exists=True, argstr="%s") + inputVolume2 = File( + position=-2, desc="Input volume 2", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Volume1 + Volume2", + argstr="%s") + order = traits.Enum( + "0", + "1", + "2", + "3", + desc= + "Interpolation order if two images are in different coordinate frames or have different sampling.", + argstr="--order %s") class AddScalarVolumesOutputSpec(TraitedSpec): @@ -145,13 +213,34 @@ class AddScalarVolumes(SEMLikeCommandLine): class CastScalarVolumeInputSpec(CommandLineInputSpec): - InputVolume = File(position=-2, desc="Input volume, the volume to cast.", exists=True, argstr="%s") - OutputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output volume, cast to the new type.", argstr="%s") - type = traits.Enum("Char", "UnsignedChar", "Short", "UnsignedShort", "Int", "UnsignedInt", "Float", "Double", desc="Type for the new output volume.", argstr="--type %s") + InputVolume = File( + position=-2, + desc="Input volume, the volume to cast.", + exists=True, + argstr="%s") + OutputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output volume, cast to the new type.", + argstr="%s") + type = traits.Enum( + "Char", + "UnsignedChar", + "Short", + "UnsignedShort", + "Int", + "UnsignedInt", + "Float", + "Double", + desc="Type for the new output volume.", + argstr="--type %s") class CastScalarVolumeOutputSpec(TraitedSpec): - OutputVolume = File(position=-1, desc="Output volume, cast to the new type.", exists=True) + OutputVolume = File( + position=-1, desc="Output volume, cast to the new type.", exists=True) class CastScalarVolume(SEMLikeCommandLine): diff --git a/nipype/interfaces/slicer/filtering/checkerboardfilter.py b/nipype/interfaces/slicer/filtering/checkerboardfilter.py index 9e4da45e1a..e4ad85dc5e 100644 --- a/nipype/interfaces/slicer/filtering/checkerboardfilter.py +++ b/nipype/interfaces/slicer/filtering/checkerboardfilter.py @@ -8,10 +8,23 @@ class CheckerBoardFilterInputSpec(CommandLineInputSpec): - checkerPattern = InputMultiPath(traits.Int, desc="The pattern of input 1 and input 2 in the output image. The user can specify the number of checkers in each dimension. A checkerPattern of 2,2,1 means that images will alternate in every other checker in the first two dimensions. The same pattern will be used in the 3rd dimension.", sep=",", argstr="--checkerPattern %s") - inputVolume1 = File(position=-3, desc="First Input volume", exists=True, argstr="%s") - inputVolume2 = File(position=-2, desc="Second Input volume", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + checkerPattern = InputMultiPath( + traits.Int, + desc= + "The pattern of input 1 and input 2 in the output image. The user can specify the number of checkers in each dimension. A checkerPattern of 2,2,1 means that images will alternate in every other checker in the first two dimensions. The same pattern will be used in the 3rd dimension.", + sep=",", + argstr="--checkerPattern %s") + inputVolume1 = File( + position=-3, desc="First Input volume", exists=True, argstr="%s") + inputVolume2 = File( + position=-2, desc="Second Input volume", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class CheckerBoardFilterOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/filtering/denoising.py b/nipype/interfaces/slicer/filtering/denoising.py index 9861585de9..0dbaaebf74 100644 --- a/nipype/interfaces/slicer/filtering/denoising.py +++ b/nipype/interfaces/slicer/filtering/denoising.py @@ -8,11 +8,30 @@ class GradientAnisotropicDiffusionInputSpec(CommandLineInputSpec): - conductance = traits.Float(desc="Conductance controls the sensitivity of the conductance term. As a general rule, the lower the value, the more strongly the filter preserves edges. A high value will cause diffusion (smoothing) across edges. Note that the number of iterations controls how much smoothing is done within regions bounded by edges.", argstr="--conductance %f") - iterations = traits.Int(desc="The more iterations, the more smoothing. Each iteration takes the same amount of time. If it takes 10 seconds for one iteration, then it will take 100 seconds for 10 iterations. Note that the conductance controls how much each iteration smooths across edges.", argstr="--iterations %d") - timeStep = traits.Float(desc="The time step depends on the dimensionality of the image. In Slicer the images are 3D and the default (.0625) time step will provide a stable solution.", argstr="--timeStep %f") - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + conductance = traits.Float( + desc= + "Conductance controls the sensitivity of the conductance term. As a general rule, the lower the value, the more strongly the filter preserves edges. A high value will cause diffusion (smoothing) across edges. Note that the number of iterations controls how much smoothing is done within regions bounded by edges.", + argstr="--conductance %f") + iterations = traits.Int( + desc= + "The more iterations, the more smoothing. Each iteration takes the same amount of time. If it takes 10 seconds for one iteration, then it will take 100 seconds for 10 iterations. Note that the conductance controls how much each iteration smooths across edges.", + argstr="--iterations %d") + timeStep = traits.Float( + desc= + "The time step depends on the dimensionality of the image. In Slicer the images are 3D and the default (.0625) time step will provide a stable solution.", + argstr="--timeStep %f") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class GradientAnisotropicDiffusionOutputSpec(TraitedSpec): @@ -45,11 +64,30 @@ class GradientAnisotropicDiffusion(SEMLikeCommandLine): class CurvatureAnisotropicDiffusionInputSpec(CommandLineInputSpec): - conductance = traits.Float(desc="Conductance controls the sensitivity of the conductance term. As a general rule, the lower the value, the more strongly the filter preserves edges. A high value will cause diffusion (smoothing) across edges. Note that the number of iterations controls how much smoothing is done within regions bounded by edges.", argstr="--conductance %f") - iterations = traits.Int(desc="The more iterations, the more smoothing. Each iteration takes the same amount of time. If it takes 10 seconds for one iteration, then it will take 100 seconds for 10 iterations. Note that the conductance controls how much each iteration smooths across edges.", argstr="--iterations %d") - timeStep = traits.Float(desc="The time step depends on the dimensionality of the image. In Slicer the images are 3D and the default (.0625) time step will provide a stable solution.", argstr="--timeStep %f") - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + conductance = traits.Float( + desc= + "Conductance controls the sensitivity of the conductance term. As a general rule, the lower the value, the more strongly the filter preserves edges. A high value will cause diffusion (smoothing) across edges. Note that the number of iterations controls how much smoothing is done within regions bounded by edges.", + argstr="--conductance %f") + iterations = traits.Int( + desc= + "The more iterations, the more smoothing. Each iteration takes the same amount of time. If it takes 10 seconds for one iteration, then it will take 100 seconds for 10 iterations. Note that the conductance controls how much each iteration smooths across edges.", + argstr="--iterations %d") + timeStep = traits.Float( + desc= + "The time step depends on the dimensionality of the image. In Slicer the images are 3D and the default (.0625) time step will provide a stable solution.", + argstr="--timeStep %f") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class CurvatureAnisotropicDiffusionOutputSpec(TraitedSpec): @@ -84,9 +122,18 @@ class CurvatureAnisotropicDiffusion(SEMLikeCommandLine): class GaussianBlurImageFilterInputSpec(CommandLineInputSpec): - sigma = traits.Float(desc="Sigma value in physical units (e.g., mm) of the Gaussian kernel", argstr="--sigma %f") - inputVolume = File(position=-2, desc="Input volume", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Blurred Volume", argstr="%s") + sigma = traits.Float( + desc="Sigma value in physical units (e.g., mm) of the Gaussian kernel", + argstr="--sigma %f") + inputVolume = File( + position=-2, desc="Input volume", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Blurred Volume", + argstr="%s") class GaussianBlurImageFilterOutputSpec(TraitedSpec): @@ -117,9 +164,23 @@ class GaussianBlurImageFilter(SEMLikeCommandLine): class MedianImageFilterInputSpec(CommandLineInputSpec): - neighborhood = InputMultiPath(traits.Int, desc="The size of the neighborhood in each dimension", sep=",", argstr="--neighborhood %s") - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + neighborhood = InputMultiPath( + traits.Int, + desc="The size of the neighborhood in each dimension", + sep=",", + argstr="--neighborhood %s") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class MedianImageFilterOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/filtering/extractskeleton.py b/nipype/interfaces/slicer/filtering/extractskeleton.py index e536fe14b5..d7770c8f2e 100644 --- a/nipype/interfaces/slicer/filtering/extractskeleton.py +++ b/nipype/interfaces/slicer/filtering/extractskeleton.py @@ -8,16 +8,32 @@ class ExtractSkeletonInputSpec(CommandLineInputSpec): - InputImageFileName = File(position=-2, desc="Input image", exists=True, argstr="%s") - OutputImageFileName = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Skeleton of the input image", argstr="%s") - type = traits.Enum("1D", "2D", desc="Type of skeleton to create", argstr="--type %s") - dontPrune = traits.Bool(desc="Return the full skeleton, not just the maximal skeleton", argstr="--dontPrune ") - numPoints = traits.Int(desc="Number of points used to represent the skeleton", argstr="--numPoints %d") - pointsFile = traits.Str(desc="Name of the file to store the coordinates of the central (1D) skeleton points", argstr="--pointsFile %s") + InputImageFileName = File( + position=-2, desc="Input image", exists=True, argstr="%s") + OutputImageFileName = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Skeleton of the input image", + argstr="%s") + type = traits.Enum( + "1D", "2D", desc="Type of skeleton to create", argstr="--type %s") + dontPrune = traits.Bool( + desc="Return the full skeleton, not just the maximal skeleton", + argstr="--dontPrune ") + numPoints = traits.Int( + desc="Number of points used to represent the skeleton", + argstr="--numPoints %d") + pointsFile = traits.Str( + desc= + "Name of the file to store the coordinates of the central (1D) skeleton points", + argstr="--pointsFile %s") class ExtractSkeletonOutputSpec(TraitedSpec): - OutputImageFileName = File(position=-1, desc="Skeleton of the input image", exists=True) + OutputImageFileName = File( + position=-1, desc="Skeleton of the input image", exists=True) class ExtractSkeleton(SEMLikeCommandLine): diff --git a/nipype/interfaces/slicer/filtering/histogrammatching.py b/nipype/interfaces/slicer/filtering/histogrammatching.py index d25b010842..1b3b26b061 100644 --- a/nipype/interfaces/slicer/filtering/histogrammatching.py +++ b/nipype/interfaces/slicer/filtering/histogrammatching.py @@ -8,16 +8,42 @@ class HistogramMatchingInputSpec(CommandLineInputSpec): - numberOfHistogramLevels = traits.Int(desc="The number of hisogram levels to use", argstr="--numberOfHistogramLevels %d") - numberOfMatchPoints = traits.Int(desc="The number of match points to use", argstr="--numberOfMatchPoints %d") - threshold = traits.Bool(desc="If on, only pixels above the mean in each volume are thresholded.", argstr="--threshold ") - inputVolume = File(position=-3, desc="Input volume to be filtered", exists=True, argstr="%s") - referenceVolume = File(position=-2, desc="Input volume whose histogram will be matched", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output volume. This is the input volume with intensities matched to the reference volume.", argstr="%s") + numberOfHistogramLevels = traits.Int( + desc="The number of hisogram levels to use", + argstr="--numberOfHistogramLevels %d") + numberOfMatchPoints = traits.Int( + desc="The number of match points to use", + argstr="--numberOfMatchPoints %d") + threshold = traits.Bool( + desc= + "If on, only pixels above the mean in each volume are thresholded.", + argstr="--threshold ") + inputVolume = File( + position=-3, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + referenceVolume = File( + position=-2, + desc="Input volume whose histogram will be matched", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc= + "Output volume. This is the input volume with intensities matched to the reference volume.", + argstr="%s") class HistogramMatchingOutputSpec(TraitedSpec): - outputVolume = File(position=-1, desc="Output volume. This is the input volume with intensities matched to the reference volume.", exists=True) + outputVolume = File( + position=-1, + desc= + "Output volume. This is the input volume with intensities matched to the reference volume.", + exists=True) class HistogramMatching(SEMLikeCommandLine): diff --git a/nipype/interfaces/slicer/filtering/imagelabelcombine.py b/nipype/interfaces/slicer/filtering/imagelabelcombine.py index a9c8455740..067a575045 100644 --- a/nipype/interfaces/slicer/filtering/imagelabelcombine.py +++ b/nipype/interfaces/slicer/filtering/imagelabelcombine.py @@ -8,14 +8,25 @@ class ImageLabelCombineInputSpec(CommandLineInputSpec): - InputLabelMap_A = File(position=-3, desc="Label map image", exists=True, argstr="%s") - InputLabelMap_B = File(position=-2, desc="Label map image", exists=True, argstr="%s") - OutputLabelMap = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Resulting Label map image", argstr="%s") - first_overwrites = traits.Bool(desc="Use first or second label when both are present", argstr="--first_overwrites ") + InputLabelMap_A = File( + position=-3, desc="Label map image", exists=True, argstr="%s") + InputLabelMap_B = File( + position=-2, desc="Label map image", exists=True, argstr="%s") + OutputLabelMap = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Resulting Label map image", + argstr="%s") + first_overwrites = traits.Bool( + desc="Use first or second label when both are present", + argstr="--first_overwrites ") class ImageLabelCombineOutputSpec(TraitedSpec): - OutputLabelMap = File(position=-1, desc="Resulting Label map image", exists=True) + OutputLabelMap = File( + position=-1, desc="Resulting Label map image", exists=True) class ImageLabelCombine(SEMLikeCommandLine): diff --git a/nipype/interfaces/slicer/filtering/morphology.py b/nipype/interfaces/slicer/filtering/morphology.py index 31d31738a2..913c63d5ab 100644 --- a/nipype/interfaces/slicer/filtering/morphology.py +++ b/nipype/interfaces/slicer/filtering/morphology.py @@ -8,8 +8,18 @@ class GrayscaleGrindPeakImageFilterInputSpec(CommandLineInputSpec): - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class GrayscaleGrindPeakImageFilterOutputSpec(TraitedSpec): @@ -50,8 +60,18 @@ class GrayscaleGrindPeakImageFilter(SEMLikeCommandLine): class GrayscaleFillHoleImageFilterInputSpec(CommandLineInputSpec): - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class GrayscaleFillHoleImageFilterOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py b/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py index b4102e8ede..28f694f77e 100644 --- a/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py +++ b/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py @@ -8,18 +8,63 @@ class N4ITKBiasFieldCorrectionInputSpec(CommandLineInputSpec): - inputimage = File(desc="Input image where you observe signal inhomegeneity", exists=True, argstr="--inputimage %s") - maskimage = File(desc="Binary mask that defines the structure of your interest. NOTE: This parameter is OPTIONAL. If the mask is not specified, the module will use internally Otsu thresholding to define this mask. Better processing results can often be obtained when a meaningful mask is defined.", exists=True, argstr="--maskimage %s") - outputimage = traits.Either(traits.Bool, File(), hash_files=False, desc="Result of processing", argstr="--outputimage %s") - outputbiasfield = traits.Either(traits.Bool, File(), hash_files=False, desc="Recovered bias field (OPTIONAL)", argstr="--outputbiasfield %s") - iterations = InputMultiPath(traits.Int, desc="Maximum number of iterations at each level of resolution. Larger values will increase execution time, but may lead to better results.", sep=",", argstr="--iterations %s") - convergencethreshold = traits.Float(desc="Stopping criterion for the iterative bias estimation. Larger values will lead to smaller execution time.", argstr="--convergencethreshold %f") - meshresolution = InputMultiPath(traits.Float, desc="Resolution of the initial bspline grid defined as a sequence of three numbers. The actual resolution will be defined by adding the bspline order (default is 3) to the resolution in each dimension specified here. For example, 1,1,1 will result in a 4x4x4 grid of control points. This parameter may need to be adjusted based on your input image. In the multi-resolution N4 framework, the resolution of the bspline grid at subsequent iterations will be doubled. The number of resolutions is implicitly defined by Number of iterations parameter (the size of this list is the number of resolutions)", sep=",", argstr="--meshresolution %s") - splinedistance = traits.Float(desc="An alternative means to define the spline grid, by setting the distance between the control points. This parameter is used only if the grid resolution is not specified.", argstr="--splinedistance %f") - shrinkfactor = traits.Int(desc="Defines how much the image should be upsampled before estimating the inhomogeneity field. Increase if you want to reduce the execution time. 1 corresponds to the original resolution. Larger values will significantly reduce the computation time.", argstr="--shrinkfactor %d") - bsplineorder = traits.Int(desc="Order of B-spline used in the approximation. Larger values will lead to longer execution times, may result in overfitting and poor result.", argstr="--bsplineorder %d") - weightimage = File(desc="Weight Image", exists=True, argstr="--weightimage %s") - histogramsharpening = InputMultiPath(traits.Float, desc="A vector of up to three values. Non-zero values correspond to Bias Field Full Width at Half Maximum, Wiener filter noise, and Number of histogram bins.", sep=",", argstr="--histogramsharpening %s") + inputimage = File( + desc="Input image where you observe signal inhomegeneity", + exists=True, + argstr="--inputimage %s") + maskimage = File( + desc= + "Binary mask that defines the structure of your interest. NOTE: This parameter is OPTIONAL. If the mask is not specified, the module will use internally Otsu thresholding to define this mask. Better processing results can often be obtained when a meaningful mask is defined.", + exists=True, + argstr="--maskimage %s") + outputimage = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Result of processing", + argstr="--outputimage %s") + outputbiasfield = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Recovered bias field (OPTIONAL)", + argstr="--outputbiasfield %s") + iterations = InputMultiPath( + traits.Int, + desc= + "Maximum number of iterations at each level of resolution. Larger values will increase execution time, but may lead to better results.", + sep=",", + argstr="--iterations %s") + convergencethreshold = traits.Float( + desc= + "Stopping criterion for the iterative bias estimation. Larger values will lead to smaller execution time.", + argstr="--convergencethreshold %f") + meshresolution = InputMultiPath( + traits.Float, + desc= + "Resolution of the initial bspline grid defined as a sequence of three numbers. The actual resolution will be defined by adding the bspline order (default is 3) to the resolution in each dimension specified here. For example, 1,1,1 will result in a 4x4x4 grid of control points. This parameter may need to be adjusted based on your input image. In the multi-resolution N4 framework, the resolution of the bspline grid at subsequent iterations will be doubled. The number of resolutions is implicitly defined by Number of iterations parameter (the size of this list is the number of resolutions)", + sep=",", + argstr="--meshresolution %s") + splinedistance = traits.Float( + desc= + "An alternative means to define the spline grid, by setting the distance between the control points. This parameter is used only if the grid resolution is not specified.", + argstr="--splinedistance %f") + shrinkfactor = traits.Int( + desc= + "Defines how much the image should be upsampled before estimating the inhomogeneity field. Increase if you want to reduce the execution time. 1 corresponds to the original resolution. Larger values will significantly reduce the computation time.", + argstr="--shrinkfactor %d") + bsplineorder = traits.Int( + desc= + "Order of B-spline used in the approximation. Larger values will lead to longer execution times, may result in overfitting and poor result.", + argstr="--bsplineorder %d") + weightimage = File( + desc="Weight Image", exists=True, argstr="--weightimage %s") + histogramsharpening = InputMultiPath( + traits.Float, + desc= + "A vector of up to three values. Non-zero values correspond to Bias Field Full Width at Half Maximum, Wiener filter noise, and Number of histogram bins.", + sep=",", + argstr="--histogramsharpening %s") class N4ITKBiasFieldCorrectionOutputSpec(TraitedSpec): @@ -47,4 +92,7 @@ class N4ITKBiasFieldCorrection(SEMLikeCommandLine): input_spec = N4ITKBiasFieldCorrectionInputSpec output_spec = N4ITKBiasFieldCorrectionOutputSpec _cmd = "N4ITKBiasFieldCorrection " - _outputs_filenames = {'outputimage': 'outputimage.nii', 'outputbiasfield': 'outputbiasfield.nii'} + _outputs_filenames = { + 'outputimage': 'outputimage.nii', + 'outputbiasfield': 'outputbiasfield.nii' + } diff --git a/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py b/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py index 9f6ebe45bc..6205b76b54 100644 --- a/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py +++ b/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py @@ -8,30 +8,118 @@ class ResampleScalarVectorDWIVolumeInputSpec(CommandLineInputSpec): - inputVolume = File(position=-2, desc="Input Volume to be resampled", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Resampled Volume", argstr="%s") - Reference = File(desc="Reference Volume (spacing,size,orientation,origin)", exists=True, argstr="--Reference %s") + inputVolume = File( + position=-2, + desc="Input Volume to be resampled", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Resampled Volume", + argstr="%s") + Reference = File( + desc="Reference Volume (spacing,size,orientation,origin)", + exists=True, + argstr="--Reference %s") transformationFile = File(exists=True, argstr="--transformationFile %s") - defField = File(desc="File containing the deformation field (3D vector image containing vectors with 3 components)", exists=True, argstr="--defField %s") - hfieldtype = traits.Enum("displacement", "h-Field", desc="Set if the deformation field is an h-Field", argstr="--hfieldtype %s") - interpolation = traits.Enum("linear", "nn", "ws", "bs", desc="Sampling algorithm (linear or nn (nearest neighborhoor), ws (WindowedSinc), bs (BSpline) )", argstr="--interpolation %s") - transform_order = traits.Enum("input-to-output", "output-to-input", desc="Select in what order the transforms are read", argstr="--transform_order %s") - notbulk = traits.Bool(desc="The transform following the BSpline transform is not set as a bulk transform for the BSpline transform", argstr="--notbulk ") - spaceChange = traits.Bool(desc="Space Orientation between transform and image is different (RAS/LPS) (warning: if the transform is a Transform Node in Slicer3, do not select)", argstr="--spaceChange ") - rotation_point = traits.List(desc="Rotation Point in case of rotation around a point (otherwise useless)", argstr="--rotation_point %s") - centered_transform = traits.Bool(desc="Set the center of the transformation to the center of the input image", argstr="--centered_transform ") - image_center = traits.Enum("input", "output", desc="Image to use to center the transform (used only if \'Centered Transform\' is selected)", argstr="--image_center %s") - Inverse_ITK_Transformation = traits.Bool(desc="Inverse the transformation before applying it from output image to input image", argstr="--Inverse_ITK_Transformation ") - spacing = InputMultiPath(traits.Float, desc="Spacing along each dimension (0 means use input spacing)", sep=",", argstr="--spacing %s") - size = InputMultiPath(traits.Float, desc="Size along each dimension (0 means use input size)", sep=",", argstr="--size %s") - origin = traits.List(desc="Origin of the output Image", argstr="--origin %s") - direction_matrix = InputMultiPath(traits.Float, desc="9 parameters of the direction matrix by rows (ijk to LPS if LPS transform, ijk to RAS if RAS transform)", sep=",", argstr="--direction_matrix %s") - number_of_thread = traits.Int(desc="Number of thread used to compute the output image", argstr="--number_of_thread %d") - default_pixel_value = traits.Float(desc="Default pixel value for samples falling outside of the input region", argstr="--default_pixel_value %f") - window_function = traits.Enum("h", "c", "w", "l", "b", desc="Window Function , h = Hamming , c = Cosine , w = Welch , l = Lanczos , b = Blackman", argstr="--window_function %s") + defField = File( + desc= + "File containing the deformation field (3D vector image containing vectors with 3 components)", + exists=True, + argstr="--defField %s") + hfieldtype = traits.Enum( + "displacement", + "h-Field", + desc="Set if the deformation field is an h-Field", + argstr="--hfieldtype %s") + interpolation = traits.Enum( + "linear", + "nn", + "ws", + "bs", + desc= + "Sampling algorithm (linear or nn (nearest neighborhoor), ws (WindowedSinc), bs (BSpline) )", + argstr="--interpolation %s") + transform_order = traits.Enum( + "input-to-output", + "output-to-input", + desc="Select in what order the transforms are read", + argstr="--transform_order %s") + notbulk = traits.Bool( + desc= + "The transform following the BSpline transform is not set as a bulk transform for the BSpline transform", + argstr="--notbulk ") + spaceChange = traits.Bool( + desc= + "Space Orientation between transform and image is different (RAS/LPS) (warning: if the transform is a Transform Node in Slicer3, do not select)", + argstr="--spaceChange ") + rotation_point = traits.List( + desc= + "Rotation Point in case of rotation around a point (otherwise useless)", + argstr="--rotation_point %s") + centered_transform = traits.Bool( + desc= + "Set the center of the transformation to the center of the input image", + argstr="--centered_transform ") + image_center = traits.Enum( + "input", + "output", + desc= + "Image to use to center the transform (used only if \'Centered Transform\' is selected)", + argstr="--image_center %s") + Inverse_ITK_Transformation = traits.Bool( + desc= + "Inverse the transformation before applying it from output image to input image", + argstr="--Inverse_ITK_Transformation ") + spacing = InputMultiPath( + traits.Float, + desc="Spacing along each dimension (0 means use input spacing)", + sep=",", + argstr="--spacing %s") + size = InputMultiPath( + traits.Float, + desc="Size along each dimension (0 means use input size)", + sep=",", + argstr="--size %s") + origin = traits.List( + desc="Origin of the output Image", argstr="--origin %s") + direction_matrix = InputMultiPath( + traits.Float, + desc= + "9 parameters of the direction matrix by rows (ijk to LPS if LPS transform, ijk to RAS if RAS transform)", + sep=",", + argstr="--direction_matrix %s") + number_of_thread = traits.Int( + desc="Number of thread used to compute the output image", + argstr="--number_of_thread %d") + default_pixel_value = traits.Float( + desc= + "Default pixel value for samples falling outside of the input region", + argstr="--default_pixel_value %f") + window_function = traits.Enum( + "h", + "c", + "w", + "l", + "b", + desc= + "Window Function , h = Hamming , c = Cosine , w = Welch , l = Lanczos , b = Blackman", + argstr="--window_function %s") spline_order = traits.Int(desc="Spline Order", argstr="--spline_order %d") - transform_matrix = InputMultiPath(traits.Float, desc="12 parameters of the transform matrix by rows ( --last 3 being translation-- )", sep=",", argstr="--transform_matrix %s") - transform = traits.Enum("rt", "a", desc="Transform algorithm, rt = Rigid Transform, a = Affine Transform", argstr="--transform %s") + transform_matrix = InputMultiPath( + traits.Float, + desc= + "12 parameters of the transform matrix by rows ( --last 3 being translation-- )", + sep=",", + argstr="--transform_matrix %s") + transform = traits.Enum( + "rt", + "a", + desc="Transform algorithm, rt = Rigid Transform, a = Affine Transform", + argstr="--transform %s") class ResampleScalarVectorDWIVolumeOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py b/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py index 6d4ab7458b..4aee4b066c 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py @@ -4,42 +4,43 @@ def test_AddScalarVolumes_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='%s', - position=-3, - ), - inputVolume2=dict(argstr='%s', - position=-2, - ), - order=dict(argstr='--order %s', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr='%s', + position=-3, + ), + inputVolume2=dict( + argstr='%s', + position=-2, + ), + order=dict(argstr='--order %s', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = AddScalarVolumes.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AddScalarVolumes_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = AddScalarVolumes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py index 5a0c99453a..d78c17d8dc 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py @@ -4,39 +4,39 @@ def test_CastScalarVolume_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-2, - ), - OutputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - type=dict(argstr='--type %s', - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-2, + ), + OutputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + type=dict(argstr='--type %s', ), ) inputs = CastScalarVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CastScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(position=-1, - ), - ) + output_map = dict(OutputVolume=dict(position=-1, ), ) outputs = CastScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py index 0fe407f1de..209241a6d6 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py @@ -4,43 +4,46 @@ def test_CheckerBoardFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - checkerPattern=dict(argstr='--checkerPattern %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='%s', - position=-3, - ), - inputVolume2=dict(argstr='%s', - position=-2, - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + checkerPattern=dict( + argstr='--checkerPattern %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr='%s', + position=-3, + ), + inputVolume2=dict( + argstr='%s', + position=-2, + ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = CheckerBoardFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CheckerBoardFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = CheckerBoardFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py b/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py index 7139b3f13a..f1e6a09d21 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py @@ -4,43 +4,41 @@ def test_CurvatureAnisotropicDiffusion_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - conductance=dict(argstr='--conductance %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - iterations=dict(argstr='--iterations %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timeStep=dict(argstr='--timeStep %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + conductance=dict(argstr='--conductance %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + iterations=dict(argstr='--iterations %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timeStep=dict(argstr='--timeStep %f', ), ) inputs = CurvatureAnisotropicDiffusion.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CurvatureAnisotropicDiffusion_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = CurvatureAnisotropicDiffusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py index f41d25c28d..a6554c6764 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py @@ -4,45 +4,42 @@ def test_ExtractSkeleton_inputs(): - input_map = dict(InputImageFileName=dict(argstr='%s', - position=-2, - ), - OutputImageFileName=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - dontPrune=dict(argstr='--dontPrune ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - numPoints=dict(argstr='--numPoints %d', - ), - pointsFile=dict(argstr='--pointsFile %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - type=dict(argstr='--type %s', - ), + input_map = dict( + InputImageFileName=dict( + argstr='%s', + position=-2, + ), + OutputImageFileName=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + dontPrune=dict(argstr='--dontPrune ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + numPoints=dict(argstr='--numPoints %d', ), + pointsFile=dict(argstr='--pointsFile %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + type=dict(argstr='--type %s', ), ) inputs = ExtractSkeleton.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ExtractSkeleton_outputs(): - output_map = dict(OutputImageFileName=dict(position=-1, - ), - ) + output_map = dict(OutputImageFileName=dict(position=-1, ), ) outputs = ExtractSkeleton.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py index 0ef6a909ca..b1731925e4 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py @@ -4,39 +4,39 @@ def test_GaussianBlurImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - sigma=dict(argstr='--sigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + sigma=dict(argstr='--sigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GaussianBlurImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GaussianBlurImageFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = GaussianBlurImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py index a041642006..fa80082fc0 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py @@ -4,43 +4,41 @@ def test_GradientAnisotropicDiffusion_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - conductance=dict(argstr='--conductance %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - iterations=dict(argstr='--iterations %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timeStep=dict(argstr='--timeStep %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + conductance=dict(argstr='--conductance %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + iterations=dict(argstr='--iterations %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timeStep=dict(argstr='--timeStep %f', ), ) inputs = GradientAnisotropicDiffusion.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GradientAnisotropicDiffusion_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = GradientAnisotropicDiffusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py index e42fe05e13..c1dabae00d 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py @@ -4,37 +4,38 @@ def test_GrayscaleFillHoleImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GrayscaleFillHoleImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GrayscaleFillHoleImageFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = GrayscaleFillHoleImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py index 6f1257ee41..81ddf76174 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py @@ -4,37 +4,38 @@ def test_GrayscaleGrindPeakImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = GrayscaleGrindPeakImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GrayscaleGrindPeakImageFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = GrayscaleGrindPeakImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py b/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py index 36223bd829..f654392b55 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py @@ -4,46 +4,45 @@ def test_HistogramMatching_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-3, - ), - numberOfHistogramLevels=dict(argstr='--numberOfHistogramLevels %d', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - referenceVolume=dict(argstr='%s', - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--threshold ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-3, + ), + numberOfHistogramLevels=dict(argstr='--numberOfHistogramLevels %d', ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + referenceVolume=dict( + argstr='%s', + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='--threshold ', ), ) inputs = HistogramMatching.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_HistogramMatching_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = HistogramMatching.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py index 2ba011470b..3e351048a5 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py @@ -4,42 +4,43 @@ def test_ImageLabelCombine_inputs(): - input_map = dict(InputLabelMap_A=dict(argstr='%s', - position=-3, - ), - InputLabelMap_B=dict(argstr='%s', - position=-2, - ), - OutputLabelMap=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - first_overwrites=dict(argstr='--first_overwrites ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + InputLabelMap_A=dict( + argstr='%s', + position=-3, + ), + InputLabelMap_B=dict( + argstr='%s', + position=-2, + ), + OutputLabelMap=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + first_overwrites=dict(argstr='--first_overwrites ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ImageLabelCombine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ImageLabelCombine_outputs(): - output_map = dict(OutputLabelMap=dict(position=-1, - ), - ) + output_map = dict(OutputLabelMap=dict(position=-1, ), ) outputs = ImageLabelCombine.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py index 77a20ffe64..55584e9e61 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py @@ -4,44 +4,44 @@ def test_MaskScalarVolume_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-3, - ), - MaskVolume=dict(argstr='%s', - position=-2, - ), - OutputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - label=dict(argstr='--label %d', - ), - replace=dict(argstr='--replace %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-3, + ), + MaskVolume=dict( + argstr='%s', + position=-2, + ), + OutputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + label=dict(argstr='--label %d', ), + replace=dict(argstr='--replace %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MaskScalarVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MaskScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(position=-1, - ), - ) + output_map = dict(OutputVolume=dict(position=-1, ), ) outputs = MaskScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py index d0409009ec..3f82c7e79e 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py @@ -4,40 +4,42 @@ def test_MedianImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - neighborhood=dict(argstr='--neighborhood %s', - sep=',', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + neighborhood=dict( + argstr='--neighborhood %s', + sep=',', + ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MedianImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MedianImageFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = MedianImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py b/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py index ed171521a8..ee4336c077 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py @@ -4,42 +4,43 @@ def test_MultiplyScalarVolumes_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='%s', - position=-3, - ), - inputVolume2=dict(argstr='%s', - position=-2, - ), - order=dict(argstr='--order %s', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr='%s', + position=-3, + ), + inputVolume2=dict( + argstr='%s', + position=-2, + ), + order=dict(argstr='--order %s', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MultiplyScalarVolumes.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MultiplyScalarVolumes_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = MultiplyScalarVolumes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py b/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py index 8397f5f1c5..2a902aff66 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py @@ -4,58 +4,58 @@ def test_N4ITKBiasFieldCorrection_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bsplineorder=dict(argstr='--bsplineorder %d', - ), - convergencethreshold=dict(argstr='--convergencethreshold %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - histogramsharpening=dict(argstr='--histogramsharpening %s', - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputimage=dict(argstr='--inputimage %s', - ), - iterations=dict(argstr='--iterations %s', - sep=',', - ), - maskimage=dict(argstr='--maskimage %s', - ), - meshresolution=dict(argstr='--meshresolution %s', - sep=',', - ), - outputbiasfield=dict(argstr='--outputbiasfield %s', - hash_files=False, - ), - outputimage=dict(argstr='--outputimage %s', - hash_files=False, - ), - shrinkfactor=dict(argstr='--shrinkfactor %d', - ), - splinedistance=dict(argstr='--splinedistance %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - weightimage=dict(argstr='--weightimage %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + bsplineorder=dict(argstr='--bsplineorder %d', ), + convergencethreshold=dict(argstr='--convergencethreshold %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + histogramsharpening=dict( + argstr='--histogramsharpening %s', + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputimage=dict(argstr='--inputimage %s', ), + iterations=dict( + argstr='--iterations %s', + sep=',', + ), + maskimage=dict(argstr='--maskimage %s', ), + meshresolution=dict( + argstr='--meshresolution %s', + sep=',', + ), + outputbiasfield=dict( + argstr='--outputbiasfield %s', + hash_files=False, + ), + outputimage=dict( + argstr='--outputimage %s', + hash_files=False, + ), + shrinkfactor=dict(argstr='--shrinkfactor %d', ), + splinedistance=dict(argstr='--splinedistance %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + weightimage=dict(argstr='--weightimage %s', ), ) inputs = N4ITKBiasFieldCorrection.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_N4ITKBiasFieldCorrection_outputs(): - output_map = dict(outputbiasfield=dict(), - outputimage=dict(), + output_map = dict( + outputbiasfield=dict(), + outputimage=dict(), ) outputs = N4ITKBiasFieldCorrection.output_spec() diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py index 23be2e6372..dabd9409ff 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py @@ -4,85 +4,73 @@ def test_ResampleScalarVectorDWIVolume_inputs(): - input_map = dict(Inverse_ITK_Transformation=dict(argstr='--Inverse_ITK_Transformation ', - ), - Reference=dict(argstr='--Reference %s', - ), - args=dict(argstr='%s', - ), - centered_transform=dict(argstr='--centered_transform ', - ), - defField=dict(argstr='--defField %s', - ), - default_pixel_value=dict(argstr='--default_pixel_value %f', - ), - direction_matrix=dict(argstr='--direction_matrix %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hfieldtype=dict(argstr='--hfieldtype %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_center=dict(argstr='--image_center %s', - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - interpolation=dict(argstr='--interpolation %s', - ), - notbulk=dict(argstr='--notbulk ', - ), - number_of_thread=dict(argstr='--number_of_thread %d', - ), - origin=dict(argstr='--origin %s', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - rotation_point=dict(argstr='--rotation_point %s', - ), - size=dict(argstr='--size %s', - sep=',', - ), - spaceChange=dict(argstr='--spaceChange ', - ), - spacing=dict(argstr='--spacing %s', - sep=',', - ), - spline_order=dict(argstr='--spline_order %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform=dict(argstr='--transform %s', - ), - transform_matrix=dict(argstr='--transform_matrix %s', - sep=',', - ), - transform_order=dict(argstr='--transform_order %s', - ), - transformationFile=dict(argstr='--transformationFile %s', - ), - window_function=dict(argstr='--window_function %s', - ), + input_map = dict( + Inverse_ITK_Transformation=dict( + argstr='--Inverse_ITK_Transformation ', ), + Reference=dict(argstr='--Reference %s', ), + args=dict(argstr='%s', ), + centered_transform=dict(argstr='--centered_transform ', ), + defField=dict(argstr='--defField %s', ), + default_pixel_value=dict(argstr='--default_pixel_value %f', ), + direction_matrix=dict( + argstr='--direction_matrix %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hfieldtype=dict(argstr='--hfieldtype %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_center=dict(argstr='--image_center %s', ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + interpolation=dict(argstr='--interpolation %s', ), + notbulk=dict(argstr='--notbulk ', ), + number_of_thread=dict(argstr='--number_of_thread %d', ), + origin=dict(argstr='--origin %s', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + rotation_point=dict(argstr='--rotation_point %s', ), + size=dict( + argstr='--size %s', + sep=',', + ), + spaceChange=dict(argstr='--spaceChange ', ), + spacing=dict( + argstr='--spacing %s', + sep=',', + ), + spline_order=dict(argstr='--spline_order %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform=dict(argstr='--transform %s', ), + transform_matrix=dict( + argstr='--transform_matrix %s', + sep=',', + ), + transform_order=dict(argstr='--transform_order %s', ), + transformationFile=dict(argstr='--transformationFile %s', ), + window_function=dict(argstr='--window_function %s', ), ) inputs = ResampleScalarVectorDWIVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ResampleScalarVectorDWIVolume_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = ResampleScalarVectorDWIVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py b/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py index b46b24dc6a..00ccddf9d2 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py @@ -4,42 +4,43 @@ def test_SubtractScalarVolumes_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='%s', - position=-3, - ), - inputVolume2=dict(argstr='%s', - position=-2, - ), - order=dict(argstr='--order %s', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr='%s', + position=-3, + ), + inputVolume2=dict( + argstr='%s', + position=-2, + ), + order=dict(argstr='--order %s', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SubtractScalarVolumes.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SubtractScalarVolumes_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = SubtractScalarVolumes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py index 49c3a67455..130e53b153 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py @@ -4,47 +4,43 @@ def test_ThresholdScalarVolume_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-2, - ), - OutputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - lower=dict(argstr='--lower %d', - ), - outsidevalue=dict(argstr='--outsidevalue %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--threshold %d', - ), - thresholdtype=dict(argstr='--thresholdtype %s', - ), - upper=dict(argstr='--upper %d', - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-2, + ), + OutputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + lower=dict(argstr='--lower %d', ), + outsidevalue=dict(argstr='--outsidevalue %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='--threshold %d', ), + thresholdtype=dict(argstr='--thresholdtype %s', ), + upper=dict(argstr='--upper %d', ), ) inputs = ThresholdScalarVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ThresholdScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(position=-1, - ), - ) + output_map = dict(OutputVolume=dict(position=-1, ), ) outputs = ThresholdScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py index fd98549305..c4a81c6676 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py @@ -4,46 +4,45 @@ def test_VotingBinaryHoleFillingImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - background=dict(argstr='--background %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - foreground=dict(argstr='--foreground %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - majorityThreshold=dict(argstr='--majorityThreshold %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - radius=dict(argstr='--radius %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + background=dict(argstr='--background %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + foreground=dict(argstr='--foreground %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + majorityThreshold=dict(argstr='--majorityThreshold %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + radius=dict( + argstr='--radius %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = VotingBinaryHoleFillingImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VotingBinaryHoleFillingImageFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = VotingBinaryHoleFillingImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py b/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py index 7d4d8d9070..041ce10990 100644 --- a/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py +++ b/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py @@ -8,17 +8,34 @@ class ThresholdScalarVolumeInputSpec(CommandLineInputSpec): - InputVolume = File(position=-2, desc="Input volume", exists=True, argstr="%s") - OutputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Thresholded input volume", argstr="%s") + InputVolume = File( + position=-2, desc="Input volume", exists=True, argstr="%s") + OutputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Thresholded input volume", + argstr="%s") threshold = traits.Int(desc="Threshold value", argstr="--threshold %d") lower = traits.Int(desc="Lower threshold value", argstr="--lower %d") upper = traits.Int(desc="Upper threshold value", argstr="--upper %d") - outsidevalue = traits.Int(desc="Set the voxels to this value if they fall outside the threshold range", argstr="--outsidevalue %d") - thresholdtype = traits.Enum("Below", "Above", "Outside", desc="What kind of threshold to perform. If Outside is selected, uses Upper and Lower values. If Below is selected, uses the ThresholdValue, if Above is selected, uses the ThresholdValue.", argstr="--thresholdtype %s") + outsidevalue = traits.Int( + desc= + "Set the voxels to this value if they fall outside the threshold range", + argstr="--outsidevalue %d") + thresholdtype = traits.Enum( + "Below", + "Above", + "Outside", + desc= + "What kind of threshold to perform. If Outside is selected, uses Upper and Lower values. If Below is selected, uses the ThresholdValue, if Above is selected, uses the ThresholdValue.", + argstr="--thresholdtype %s") class ThresholdScalarVolumeOutputSpec(TraitedSpec): - OutputVolume = File(position=-1, desc="Thresholded input volume", exists=True) + OutputVolume = File( + position=-1, desc="Thresholded input volume", exists=True) class ThresholdScalarVolume(SEMLikeCommandLine): diff --git a/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py b/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py index e885b76ec5..9c19799d04 100644 --- a/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py +++ b/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py @@ -8,12 +8,33 @@ class VotingBinaryHoleFillingImageFilterInputSpec(CommandLineInputSpec): - radius = InputMultiPath(traits.Int, desc="The radius of a hole to be filled", sep=",", argstr="--radius %s") - majorityThreshold = traits.Int(desc="The number of pixels over 50% that will decide whether an OFF pixel will become ON or not. For example, if the neighborhood of a pixel has 124 pixels (excluding itself), the 50% will be 62, and if you set a Majority threshold of 5, that means that the filter will require 67 or more neighbor pixels to be ON in order to switch the current OFF pixel to ON.", argstr="--majorityThreshold %d") - background = traits.Int(desc="The value associated with the background (not object)", argstr="--background %d") - foreground = traits.Int(desc="The value associated with the foreground (object)", argstr="--foreground %d") - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + radius = InputMultiPath( + traits.Int, + desc="The radius of a hole to be filled", + sep=",", + argstr="--radius %s") + majorityThreshold = traits.Int( + desc= + "The number of pixels over 50% that will decide whether an OFF pixel will become ON or not. For example, if the neighborhood of a pixel has 124 pixels (excluding itself), the 50% will be 62, and if you set a Majority threshold of 5, that means that the filter will require 67 or more neighbor pixels to be ON in order to switch the current OFF pixel to ON.", + argstr="--majorityThreshold %d") + background = traits.Int( + desc="The value associated with the background (not object)", + argstr="--background %d") + foreground = traits.Int( + desc="The value associated with the foreground (object)", + argstr="--foreground %d") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class VotingBinaryHoleFillingImageFilterOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/generate_classes.py b/nipype/interfaces/slicer/generate_classes.py index f0bc8274bb..6fe3ae927f 100644 --- a/nipype/interfaces/slicer/generate_classes.py +++ b/nipype/interfaces/slicer/generate_classes.py @@ -3,7 +3,8 @@ modules are selected from the hardcoded list below and generated code is placed in the cli_modules.py file (and imported in __init__.py). For this to work correctly you must have your CLI executabes in $PATH""" -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, bytes, open import xml.dom.minidom import subprocess @@ -36,8 +37,10 @@ def add_class_to_package(class_codes, class_names, module_name, package_dir): f_i = open(os.path.join(package_dir, "__init__.py"), 'a+') f_m.write("""# -*- coding: utf-8 -*- \"\"\"Autogenerated file - DO NOT EDIT -If you spot a bug, please report it on the mailing list and/or change the generator.\"\"\"\n\n""") - imports = """from __future__ import print_function, division, unicode_literals, absolute_import +If you spot a bug, please report it on the mailing list and/or change the generator.\"\"\"\n\n""" + ) + imports = """from __future__ import (print_function, division, unicode_literals, + absolute_import) from ..base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath) import os\n\n\n""" @@ -55,13 +58,14 @@ def crawl_code_struct(code_struct, package_dir): module_name = k.lower() class_name = k class_code = v - add_class_to_package( - [class_code], [class_name], module_name, package_dir) + add_class_to_package([class_code], [class_name], module_name, + package_dir) else: l1 = {} l2 = {} for key in list(v.keys()): - if (isinstance(v[key], str) or isinstance(v[key], (str, bytes))): + if (isinstance(v[key], str) + or isinstance(v[key], (str, bytes))): l1[key] = v[key] else: l2[key] = v[key] @@ -86,7 +90,8 @@ def crawl_code_struct(code_struct, package_dir): list(v.values()), list(v.keys()), module_name, package_dir) if subpackages: f = open(os.path.join(package_dir, "setup.py"), 'w') - f.write("""# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- + f.write( + """# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration @@ -100,11 +105,17 @@ def configuration(parent_package='',top_path=None): if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) -""".format(pkg_name=package_dir.split("/")[-1], sub_pks="\n ".join(["config.add_data_dir('%s')" % sub_pkg for sub_pkg in subpackages]))) +""".format(pkg_name=package_dir.split("/")[-1], + sub_pks="\n ".join([ + "config.add_data_dir('%s')" % sub_pkg for sub_pkg in subpackages + ]))) f.close() -def generate_all_classes(modules_list=[], launcher=[], redirect_x=False, mipav_hacks=False): +def generate_all_classes(modules_list=[], + launcher=[], + redirect_x=False, + mipav_hacks=False): """ modules_list contains all the SEM compliant tools that should have wrappers created for them. launcher containtains the command line prefix wrapper arugments needed to prepare a proper environment for each of the modules. @@ -114,7 +125,8 @@ def generate_all_classes(modules_list=[], launcher=[], redirect_x=False, mipav_h print("=" * 80) print("Generating Definition for module {0}".format(module)) print("^" * 80) - package, code, module = generate_class(module, launcher, redirect_x=redirect_x, mipav_hacks=mipav_hacks) + package, code, module = generate_class( + module, launcher, redirect_x=redirect_x, mipav_hacks=mipav_hacks) cur_package = all_code module_name = package.strip().split(" ")[0].split(".")[-1] for package in package.strip().split(" ")[0].split(".")[:-1]: @@ -129,7 +141,11 @@ def generate_all_classes(modules_list=[], launcher=[], redirect_x=False, mipav_h crawl_code_struct(all_code, os.getcwd()) -def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=False, mipav_hacks=False): +def generate_class(module, + launcher, + strip_module_name_prefix=True, + redirect_x=False, + mipav_hacks=False): dom = grab_xml(module, launcher, mipav_hacks=mipav_hacks) if strip_module_name_prefix: module_name = module.split(".")[-1] @@ -143,12 +159,14 @@ def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=F class_string = "\"\"\"" - for desc_str in ['title', 'category', 'description', 'version', - 'documentation-url', 'license', 'contributor', - 'acknowledgements']: + for desc_str in [ + 'title', 'category', 'description', 'version', 'documentation-url', + 'license', 'contributor', 'acknowledgements' + ]: el = dom.getElementsByTagName(desc_str) if el and el[0].firstChild and el[0].firstChild.nodeValue.strip(): - class_string += desc_str + ": " + el[0].firstChild.nodeValue.strip() + "\n\n" + class_string += desc_str + ": " + el[0].firstChild.nodeValue.strip( + ) + "\n\n" if desc_str == 'category': category = el[0].firstChild.nodeValue.strip() class_string += "\"\"\"" @@ -178,23 +196,38 @@ def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=F name = force_to_valid_python_variable_name(name) traitsParams["argstr"] = "--" + longFlagName + " " else: - name = param.getElementsByTagName( - 'name')[0].firstChild.nodeValue + name = param.getElementsByTagName('name')[ + 0].firstChild.nodeValue name = force_to_valid_python_variable_name(name) if param.getElementsByTagName('index'): traitsParams["argstr"] = "" else: traitsParams["argstr"] = "--" + name + " " - if param.getElementsByTagName('description') and param.getElementsByTagName('description')[0].firstChild: - traitsParams["desc"] = param.getElementsByTagName('description')[0].firstChild.nodeValue.replace('"', "\\\"").replace("\n", ", ") - - argsDict = {'directory': '%s', 'file': '%s', 'integer': "%d", - 'double': "%f", 'float': "%f", 'image': "%s", - 'transform': "%s", 'boolean': '', - 'string-enumeration': '%s', 'string': "%s", - 'integer-enumeration': '%s', - 'table': '%s', 'point': '%s', 'region': '%s', 'geometry': '%s'} + if param.getElementsByTagName( + 'description') and param.getElementsByTagName( + 'description')[0].firstChild: + traitsParams["desc"] = param.getElementsByTagName( + 'description')[0].firstChild.nodeValue.replace( + '"', "\\\"").replace("\n", ", ") + + argsDict = { + 'directory': '%s', + 'file': '%s', + 'integer': "%d", + 'double': "%f", + 'float': "%f", + 'image': "%s", + 'transform': "%s", + 'boolean': '', + 'string-enumeration': '%s', + 'string': "%s", + 'integer-enumeration': '%s', + 'table': '%s', + 'point': '%s', + 'region': '%s', + 'geometry': '%s' + } if param.nodeName.endswith('-vector'): traitsParams["argstr"] += "%s" @@ -210,21 +243,38 @@ def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=F if index: traitsParams["desc"] = desc[0].firstChild.nodeValue - typesDict = {'integer': "traits.Int", 'double': "traits.Float", - 'float': "traits.Float", 'image': "File", - 'transform': "File", 'boolean': "traits.Bool", - 'string': "traits.Str", 'file': "File", 'geometry': "File", - 'directory': "Directory", 'table': "File", - 'point': "traits.List", 'region': "traits.List"} + typesDict = { + 'integer': "traits.Int", + 'double': "traits.Float", + 'float': "traits.Float", + 'image': "File", + 'transform': "File", + 'boolean': "traits.Bool", + 'string': "traits.Str", + 'file': "File", + 'geometry': "File", + 'directory': "Directory", + 'table': "File", + 'point': "traits.List", + 'region': "traits.List" + } if param.nodeName.endswith('-enumeration'): type = "traits.Enum" - values = ['"%s"' % str(el.firstChild.nodeValue).replace('"', '') for el in param.getElementsByTagName('element')] + values = [ + '"%s"' % str(el.firstChild.nodeValue).replace('"', '') + for el in param.getElementsByTagName('element') + ] elif param.nodeName.endswith('-vector'): type = "InputMultiPath" - if param.nodeName in ['file', 'directory', 'image', 'geometry', 'transform', 'table']: - values = ["%s(exists=True)" % typesDict[ - param.nodeName.replace('-vector', '')]] + if param.nodeName in [ + 'file', 'directory', 'image', 'geometry', 'transform', + 'table' + ]: + values = [ + "%s(exists=True)" % typesDict[param.nodeName.replace( + '-vector', '')] + ] else: values = [typesDict[param.nodeName.replace('-vector', '')]] if mipav_hacks is True: @@ -233,11 +283,16 @@ def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=F traitsParams["sep"] = ',' elif param.getAttribute('multiple') == "true": type = "InputMultiPath" - if param.nodeName in ['file', 'directory', 'image', 'geometry', 'transform', 'table']: + if param.nodeName in [ + 'file', 'directory', 'image', 'geometry', 'transform', + 'table' + ]: values = ["%s(exists=True)" % typesDict[param.nodeName]] elif param.nodeName in ['point', 'region']: - values = ["%s(traits.Float(), minlen=3, maxlen=3)" % - typesDict[param.nodeName]] + values = [ + "%s(traits.Float(), minlen=3, maxlen=3)" % + typesDict[param.nodeName] + ] else: values = [typesDict[param.nodeName]] traitsParams["argstr"] += "..." @@ -245,40 +300,62 @@ def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=F values = [] type = typesDict[param.nodeName] - if param.nodeName in ['file', 'directory', 'image', 'geometry', 'transform', 'table']: + if param.nodeName in [ + 'file', 'directory', 'image', 'geometry', 'transform', + 'table' + ]: if not param.getElementsByTagName('channel'): - raise RuntimeError("Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field.\n{0}".format(traitsParams)) - elif param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output': + raise RuntimeError( + "Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field.\n{0}". + format(traitsParams)) + elif param.getElementsByTagName('channel')[ + 0].firstChild.nodeValue == 'output': traitsParams["hash_files"] = False inputTraits.append( - "%s = traits.Either(traits.Bool, %s(%s), %s)" % (name, - type, - parse_values( - values).replace("exists=True", ""), - parse_params(traitsParams))) + "%s = traits.Either(traits.Bool, %s(%s), %s)" % + (name, type, + parse_values(values).replace("exists=True", ""), + parse_params(traitsParams))) traitsParams["exists"] = True traitsParams.pop("argstr") traitsParams.pop("hash_files") - outputTraits.append("%s = %s(%s%s)" % (name, type.replace("Input", "Output"), parse_values(values), parse_params(traitsParams))) - - outputs_filenames[ - name] = gen_filename_from_param(param, name) - elif param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'input': - if param.nodeName in ['file', 'directory', 'image', 'geometry', 'transform', 'table'] and type not in ["InputMultiPath", "traits.List"]: + outputTraits.append("%s = %s(%s%s)" % + (name, type.replace("Input", "Output"), + parse_values(values), + parse_params(traitsParams))) + + outputs_filenames[name] = gen_filename_from_param( + param, name) + elif param.getElementsByTagName('channel')[ + 0].firstChild.nodeValue == 'input': + if param.nodeName in [ + 'file', 'directory', 'image', 'geometry', + 'transform', 'table' + ] and type not in ["InputMultiPath", "traits.List"]: traitsParams["exists"] = True - inputTraits.append("%s = %s(%s%s)" % (name, type, parse_values(values), parse_params(traitsParams))) + inputTraits.append("%s = %s(%s%s)" % + (name, type, parse_values(values), + parse_params(traitsParams))) else: - raise RuntimeError("Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field to be in ['input','output'].\n{0}".format(traitsParams)) + raise RuntimeError( + "Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field to be in ['input','output'].\n{0}". + format(traitsParams)) else: # For all other parameter types, they are implicitly only input types - inputTraits.append("%s = %s(%s%s)" % (name, type, parse_values( - values), parse_params(traitsParams))) + inputTraits.append("%s = %s(%s%s)" % + (name, type, parse_values(values), + parse_params(traitsParams))) if mipav_hacks: blacklisted_inputs = ["maxMemoryUsage"] - inputTraits = [trait for trait in inputTraits if trait.split()[0] not in blacklisted_inputs] - - compulsory_inputs = ['xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d")', - 'xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True)'] + inputTraits = [ + trait for trait in inputTraits + if trait.split()[0] not in blacklisted_inputs + ] + + compulsory_inputs = [ + 'xDefaultMem = traits.Int(desc="Set default maximum heap size", argstr="-xDefaultMem %d")', + 'xMaxProcess = traits.Int(1, desc="Set default maximum number of processes.", argstr="-xMaxProcess %d", usedefault=True)' + ] inputTraits += compulsory_inputs input_spec_code = "class " + module_name + "InputSpec(CommandLineInputSpec):\n" @@ -293,8 +370,9 @@ def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=F output_spec_code += " " + trait + "\n" output_filenames_code = "_outputs_filenames = {" - output_filenames_code += ",".join(["'%s':'%s'" % ( - key, value) for key, value in outputs_filenames.items()]) + output_filenames_code += ",".join([ + "'%s':'%s'" % (key, value) for key, value in outputs_filenames.items() + ]) output_filenames_code += "}" input_spec_code += "\n\n" @@ -309,7 +387,10 @@ def generate_class(module, launcher, strip_module_name_prefix=True, redirect_x=F %output_filenames_code%\n""" template += " _redirect_x = {0}\n".format(str(redirect_x)) - main_class = template.replace('%class_str%', class_string).replace("%module_name%", module_name).replace("%name%", module).replace("%output_filenames_code%", output_filenames_code).replace("%launcher%", " ".join(launcher)) + main_class = template.replace('%class_str%', class_string).replace( + "%module_name%", module_name).replace("%name%", module).replace( + "%output_filenames_code%", output_filenames_code).replace( + "%launcher%", " ".join(launcher)) return category, input_spec_code + output_spec_code + main_class, module_name @@ -341,14 +422,18 @@ def grab_xml(module, launcher, mipav_hacks=False): # workaround for a JIST bug https://www.nitrc.org/tracker/index.php?func=detail&aid=7233&group_id=228&atid=942 if xmlReturnValue.strip().endswith("XML"): xmlReturnValue = xmlReturnValue.strip()[:-3] - if xmlReturnValue.strip().startswith("Error: Unable to set default atlas"): - xmlReturnValue = xmlReturnValue.strip()[len("Error: Unable to set default atlas"):] + if xmlReturnValue.strip().startswith( + "Error: Unable to set default atlas"): + xmlReturnValue = xmlReturnValue.strip()[len( + "Error: Unable to set default atlas"):] try: dom = xml.dom.minidom.parseString(xmlReturnValue.strip()) except Exception as e: print(xmlReturnValue.strip()) raise e return dom + + # if ret.runtime.returncode == 0: # return xml.dom.minidom.parseString(ret.runtime.stdout) # else: @@ -383,76 +468,84 @@ def gen_filename_from_param(param, base): firstFileExtension = fileExtensions.split(',')[0] ext = firstFileExtension else: - ext = {'image': '.nii', 'transform': '.mat', 'file': '', - 'directory': '', 'geometry': '.vtk'}[param.nodeName] + ext = { + 'image': '.nii', + 'transform': '.mat', + 'file': '', + 'directory': '', + 'geometry': '.vtk' + }[param.nodeName] return base + ext + if __name__ == "__main__": # NOTE: For now either the launcher needs to be found on the default path, or # every tool in the modules list must be found on the default path # AND calling the module with --xml must be supported and compliant. - modules_list = ['MedianImageFilter', - 'CheckerBoardFilter', - 'EMSegmentCommandLine', - 'GrayscaleFillHoleImageFilter', - # 'CreateDICOMSeries', #missing channel - 'TractographyLabelMapSeeding', - 'IntensityDifferenceMetric', - 'DWIToDTIEstimation', - 'MaskScalarVolume', - 'ImageLabelCombine', - 'DTIimport', - 'OtsuThresholdImageFilter', - 'ExpertAutomatedRegistration', - 'ThresholdScalarVolume', - 'DWIUnbiasedNonLocalMeansFilter', - 'BRAINSFit', - 'MergeModels', - 'ResampleDTIVolume', - 'MultiplyScalarVolumes', - 'LabelMapSmoothing', - 'RigidRegistration', - 'VotingBinaryHoleFillingImageFilter', - 'BRAINSROIAuto', - 'RobustStatisticsSegmenter', - 'GradientAnisotropicDiffusion', - 'ProbeVolumeWithModel', - 'ModelMaker', - 'ExtractSkeleton', - 'GrayscaleGrindPeakImageFilter', - 'N4ITKBiasFieldCorrection', - 'BRAINSResample', - 'DTIexport', - 'VBRAINSDemonWarp', - 'ResampleScalarVectorDWIVolume', - 'ResampleScalarVolume', - 'OtsuThresholdSegmentation', - # 'ExecutionModelTour', - 'HistogramMatching', - 'BRAINSDemonWarp', - 'ModelToLabelMap', - 'GaussianBlurImageFilter', - 'DiffusionWeightedVolumeMasking', - 'GrayscaleModelMaker', - 'CastScalarVolume', - 'DicomToNrrdConverter', - 'AffineRegistration', - 'AddScalarVolumes', - 'LinearRegistration', - 'SimpleRegionGrowingSegmentation', - 'DWIJointRicianLMMSEFilter', - 'MultiResolutionAffineRegistration', - 'SubtractScalarVolumes', - 'DWIRicianLMMSEFilter', - 'OrientScalarVolume', - 'FiducialRegistration', - 'BSplineDeformableRegistration', - 'CurvatureAnisotropicDiffusion', - 'PETStandardUptakeValueComputation', - 'DiffusionTensorScalarMeasurements', - 'ACPCTransform', - 'EMSegmentTransformToNewFormat', - 'BSplineToDeformationField'] + modules_list = [ + 'MedianImageFilter', + 'CheckerBoardFilter', + 'EMSegmentCommandLine', + 'GrayscaleFillHoleImageFilter', + # 'CreateDICOMSeries', #missing channel + 'TractographyLabelMapSeeding', + 'IntensityDifferenceMetric', + 'DWIToDTIEstimation', + 'MaskScalarVolume', + 'ImageLabelCombine', + 'DTIimport', + 'OtsuThresholdImageFilter', + 'ExpertAutomatedRegistration', + 'ThresholdScalarVolume', + 'DWIUnbiasedNonLocalMeansFilter', + 'BRAINSFit', + 'MergeModels', + 'ResampleDTIVolume', + 'MultiplyScalarVolumes', + 'LabelMapSmoothing', + 'RigidRegistration', + 'VotingBinaryHoleFillingImageFilter', + 'BRAINSROIAuto', + 'RobustStatisticsSegmenter', + 'GradientAnisotropicDiffusion', + 'ProbeVolumeWithModel', + 'ModelMaker', + 'ExtractSkeleton', + 'GrayscaleGrindPeakImageFilter', + 'N4ITKBiasFieldCorrection', + 'BRAINSResample', + 'DTIexport', + 'VBRAINSDemonWarp', + 'ResampleScalarVectorDWIVolume', + 'ResampleScalarVolume', + 'OtsuThresholdSegmentation', + # 'ExecutionModelTour', + 'HistogramMatching', + 'BRAINSDemonWarp', + 'ModelToLabelMap', + 'GaussianBlurImageFilter', + 'DiffusionWeightedVolumeMasking', + 'GrayscaleModelMaker', + 'CastScalarVolume', + 'DicomToNrrdConverter', + 'AffineRegistration', + 'AddScalarVolumes', + 'LinearRegistration', + 'SimpleRegionGrowingSegmentation', + 'DWIJointRicianLMMSEFilter', + 'MultiResolutionAffineRegistration', + 'SubtractScalarVolumes', + 'DWIRicianLMMSEFilter', + 'OrientScalarVolume', + 'FiducialRegistration', + 'BSplineDeformableRegistration', + 'CurvatureAnisotropicDiffusion', + 'PETStandardUptakeValueComputation', + 'DiffusionTensorScalarMeasurements', + 'ACPCTransform', + 'EMSegmentTransformToNewFormat', + 'BSplineToDeformationField' + ] # SlicerExecutionModel compliant tools that are usually statically built, and don't need the Slicer3 --launcher generate_all_classes(modules_list=modules_list, launcher=[]) diff --git a/nipype/interfaces/slicer/legacy/__init__.py b/nipype/interfaces/slicer/legacy/__init__.py index ee9d79b38c..75c6b9d327 100644 --- a/nipype/interfaces/slicer/legacy/__init__.py +++ b/nipype/interfaces/slicer/legacy/__init__.py @@ -4,4 +4,7 @@ from .segmentation import OtsuThresholdSegmentation from .filtering import OtsuThresholdImageFilter, ResampleScalarVolume from .converters import BSplineToDeformationField -from .registration import BSplineDeformableRegistration, AffineRegistration, MultiResolutionAffineRegistration, RigidRegistration, LinearRegistration, ExpertAutomatedRegistration +from .registration import (BSplineDeformableRegistration, AffineRegistration, + MultiResolutionAffineRegistration, + RigidRegistration, LinearRegistration, + ExpertAutomatedRegistration) diff --git a/nipype/interfaces/slicer/legacy/converters.py b/nipype/interfaces/slicer/legacy/converters.py index 509dbd80cf..f5af1ad29b 100644 --- a/nipype/interfaces/slicer/legacy/converters.py +++ b/nipype/interfaces/slicer/legacy/converters.py @@ -10,7 +10,8 @@ class BSplineToDeformationFieldInputSpec(CommandLineInputSpec): tfm = File(exists=True, argstr="--tfm %s") refImage = File(exists=True, argstr="--refImage %s") - defImage = traits.Either(traits.Bool, File(), hash_files=False, argstr="--defImage %s") + defImage = traits.Either( + traits.Bool, File(), hash_files=False, argstr="--defImage %s") class BSplineToDeformationFieldOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/legacy/diffusion/denoising.py b/nipype/interfaces/slicer/legacy/diffusion/denoising.py index f306797a1a..0cc8cce0f6 100644 --- a/nipype/interfaces/slicer/legacy/diffusion/denoising.py +++ b/nipype/interfaces/slicer/legacy/diffusion/denoising.py @@ -8,13 +8,41 @@ class DWIUnbiasedNonLocalMeansFilterInputSpec(CommandLineInputSpec): - rs = InputMultiPath(traits.Int, desc="The algorithm search for similar voxels in a neighborhood of this size (larger sizes than the default one are extremely slow).", sep=",", argstr="--rs %s") - rc = InputMultiPath(traits.Int, desc="Similarity between blocks is measured using windows of this size.", sep=",", argstr="--rc %s") - hp = traits.Float(desc="This parameter is related to noise; the larger the parameter, the more agressive the filtering. Should be near 1, and only values between 0.8 and 1.2 are allowed", argstr="--hp %f") - ng = traits.Int(desc="The number of the closest gradients that are used to jointly filter a given gradient direction (a maximum of 5 is allowed).", argstr="--ng %d") - re = InputMultiPath(traits.Int, desc="A neighborhood of this size is used to compute the statistics for noise estimation.", sep=",", argstr="--re %s") - inputVolume = File(position=-2, desc="Input DWI volume.", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output DWI volume.", argstr="%s") + rs = InputMultiPath( + traits.Int, + desc= + "The algorithm search for similar voxels in a neighborhood of this size (larger sizes than the default one are extremely slow).", + sep=",", + argstr="--rs %s") + rc = InputMultiPath( + traits.Int, + desc= + "Similarity between blocks is measured using windows of this size.", + sep=",", + argstr="--rc %s") + hp = traits.Float( + desc= + "This parameter is related to noise; the larger the parameter, the more agressive the filtering. Should be near 1, and only values between 0.8 and 1.2 are allowed", + argstr="--hp %f") + ng = traits.Int( + desc= + "The number of the closest gradients that are used to jointly filter a given gradient direction (a maximum of 5 is allowed).", + argstr="--ng %d") + re = InputMultiPath( + traits.Int, + desc= + "A neighborhood of this size is used to compute the statistics for noise estimation.", + sep=",", + argstr="--re %s") + inputVolume = File( + position=-2, desc="Input DWI volume.", exists=True, argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output DWI volume.", + argstr="%s") class DWIUnbiasedNonLocalMeansFilterOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py b/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py index 7f25ed92cc..d192809a58 100644 --- a/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py +++ b/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py @@ -4,50 +4,52 @@ def test_DWIUnbiasedNonLocalMeansFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - hp=dict(argstr='--hp %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - ng=dict(argstr='--ng %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - rc=dict(argstr='--rc %s', - sep=',', - ), - re=dict(argstr='--re %s', - sep=',', - ), - rs=dict(argstr='--rs %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + hp=dict(argstr='--hp %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + ng=dict(argstr='--ng %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + rc=dict( + argstr='--rc %s', + sep=',', + ), + re=dict( + argstr='--re %s', + sep=',', + ), + rs=dict( + argstr='--rs %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = DWIUnbiasedNonLocalMeansFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DWIUnbiasedNonLocalMeansFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = DWIUnbiasedNonLocalMeansFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/filtering.py b/nipype/interfaces/slicer/legacy/filtering.py index 1faa3191d8..aaed2350e0 100644 --- a/nipype/interfaces/slicer/legacy/filtering.py +++ b/nipype/interfaces/slicer/legacy/filtering.py @@ -7,11 +7,30 @@ class OtsuThresholdImageFilterInputSpec(CommandLineInputSpec): - insideValue = traits.Int(desc="The value assigned to pixels that are inside the computed threshold", argstr="--insideValue %d") - outsideValue = traits.Int(desc="The value assigned to pixels that are outside the computed threshold", argstr="--outsideValue %d") - numberOfBins = traits.Int(desc="This is an advanced parameter. The number of bins in the histogram used to model the probability mass function of the two intensity distributions. Small numbers of bins may result in a more conservative threshold. The default should suffice for most applications. Experimentation is the only way to see the effect of varying this parameter.", argstr="--numberOfBins %d") - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + insideValue = traits.Int( + desc= + "The value assigned to pixels that are inside the computed threshold", + argstr="--insideValue %d") + outsideValue = traits.Int( + desc= + "The value assigned to pixels that are outside the computed threshold", + argstr="--outsideValue %d") + numberOfBins = traits.Int( + desc= + "This is an advanced parameter. The number of bins in the histogram used to model the probability mass function of the two intensity distributions. Small numbers of bins may result in a more conservative threshold. The default should suffice for most applications. Experimentation is the only way to see the effect of varying this parameter.", + argstr="--numberOfBins %d") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class OtsuThresholdImageFilterOutputSpec(TraitedSpec): @@ -46,10 +65,35 @@ class OtsuThresholdImageFilter(SEMLikeCommandLine): class ResampleScalarVolumeInputSpec(CommandLineInputSpec): - spacing = InputMultiPath(traits.Float, desc="Spacing along each dimension (0 means use input spacing)", sep=",", argstr="--spacing %s") - interpolation = traits.Enum("linear", "nearestNeighbor", "bspline", "hamming", "cosine", "welch", "lanczos", "blackman", desc="Sampling algorithm (linear, nearest neighbor, bspline(cubic) or windowed sinc). There are several sinc algorithms available as described in the following publication: Erik H. W. Meijering, Wiro J. Niessen, Josien P. W. Pluim, Max A. Viergever: Quantitative Comparison of Sinc-Approximating Kernels for Medical Image Interpolation. MICCAI 1999, pp. 210-217. Each window has a radius of 3;", argstr="--interpolation %s") - InputVolume = File(position=-2, desc="Input volume to be resampled", exists=True, argstr="%s") - OutputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Resampled Volume", argstr="%s") + spacing = InputMultiPath( + traits.Float, + desc="Spacing along each dimension (0 means use input spacing)", + sep=",", + argstr="--spacing %s") + interpolation = traits.Enum( + "linear", + "nearestNeighbor", + "bspline", + "hamming", + "cosine", + "welch", + "lanczos", + "blackman", + desc= + "Sampling algorithm (linear, nearest neighbor, bspline(cubic) or windowed sinc). There are several sinc algorithms available as described in the following publication: Erik H. W. Meijering, Wiro J. Niessen, Josien P. W. Pluim, Max A. Viergever: Quantitative Comparison of Sinc-Approximating Kernels for Medical Image Interpolation. MICCAI 1999, pp. 210-217. Each window has a radius of 3;", + argstr="--interpolation %s") + InputVolume = File( + position=-2, + desc="Input volume to be resampled", + exists=True, + argstr="%s") + OutputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Resampled Volume", + argstr="%s") class ResampleScalarVolumeOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/legacy/registration.py b/nipype/interfaces/slicer/legacy/registration.py index 7570de7431..7f73d85d82 100644 --- a/nipype/interfaces/slicer/legacy/registration.py +++ b/nipype/interfaces/slicer/legacy/registration.py @@ -8,25 +8,80 @@ class BSplineDeformableRegistrationInputSpec(CommandLineInputSpec): - iterations = traits.Int(desc="Number of iterations", argstr="--iterations %d") - gridSize = traits.Int(desc="Number of grid points on interior of the fixed image. Larger grid sizes allow for finer registrations.", argstr="--gridSize %d") - histogrambins = traits.Int(desc="Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a deformable registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", argstr="--histogrambins %d") - spatialsamples = traits.Int(desc="Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", argstr="--spatialsamples %d") - constrain = traits.Bool(desc="Constrain the deformation to the amount specified in Maximum Deformation", argstr="--constrain ") - maximumDeformation = traits.Float(desc="If Constrain Deformation is checked, limit the deformation to this amount.", argstr="--maximumDeformation %f") - default = traits.Int(desc="Default pixel value used if resampling a pixel outside of the volume.", argstr="--default %d") - initialtransform = File(desc="Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. This transform should be an affine or rigid transform. It is used an a bulk transform for the BSpline. Optional.", exists=True, argstr="--initialtransform %s") - FixedImageFileName = File(position=-2, desc="Fixed image to which to register", exists=True, argstr="%s") - MovingImageFileName = File(position=-1, desc="Moving image", exists=True, argstr="%s") - outputtransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Transform calculated that aligns the fixed and moving image. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--outputtransform %s") - outputwarp = traits.Either(traits.Bool, File(), hash_files=False, desc="Vector field that applies an equivalent warp as the BSpline. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional.", argstr="--outputwarp %s") - resampledmovingfilename = traits.Either(traits.Bool, File(), hash_files=False, desc="Resampled moving image to fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--resampledmovingfilename %s") + iterations = traits.Int( + desc="Number of iterations", argstr="--iterations %d") + gridSize = traits.Int( + desc= + "Number of grid points on interior of the fixed image. Larger grid sizes allow for finer registrations.", + argstr="--gridSize %d") + histogrambins = traits.Int( + desc= + "Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a deformable registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", + argstr="--histogrambins %d") + spatialsamples = traits.Int( + desc= + "Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", + argstr="--spatialsamples %d") + constrain = traits.Bool( + desc= + "Constrain the deformation to the amount specified in Maximum Deformation", + argstr="--constrain ") + maximumDeformation = traits.Float( + desc= + "If Constrain Deformation is checked, limit the deformation to this amount.", + argstr="--maximumDeformation %f") + default = traits.Int( + desc= + "Default pixel value used if resampling a pixel outside of the volume.", + argstr="--default %d") + initialtransform = File( + desc= + "Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. This transform should be an affine or rigid transform. It is used an a bulk transform for the BSpline. Optional.", + exists=True, + argstr="--initialtransform %s") + FixedImageFileName = File( + position=-2, + desc="Fixed image to which to register", + exists=True, + argstr="%s") + MovingImageFileName = File( + position=-1, desc="Moving image", exists=True, argstr="%s") + outputtransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--outputtransform %s") + outputwarp = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Vector field that applies an equivalent warp as the BSpline. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional.", + argstr="--outputwarp %s") + resampledmovingfilename = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Resampled moving image to fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--resampledmovingfilename %s") class BSplineDeformableRegistrationOutputSpec(TraitedSpec): - outputtransform = File(desc="Transform calculated that aligns the fixed and moving image. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) - outputwarp = File(desc="Vector field that applies an equivalent warp as the BSpline. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional.", exists=True) - resampledmovingfilename = File(desc="Resampled moving image to fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) + outputtransform = File( + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) + outputwarp = File( + desc= + "Vector field that applies an equivalent warp as the BSpline. Maps positions from the fixed coordinate frame to the moving coordinate frame. Optional.", + exists=True) + resampledmovingfilename = File( + desc= + "Resampled moving image to fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) class BSplineDeformableRegistration(SEMLikeCommandLine): @@ -49,26 +104,73 @@ class BSplineDeformableRegistration(SEMLikeCommandLine): input_spec = BSplineDeformableRegistrationInputSpec output_spec = BSplineDeformableRegistrationOutputSpec _cmd = "BSplineDeformableRegistration " - _outputs_filenames = {'resampledmovingfilename': 'resampledmovingfilename.nii', 'outputtransform': 'outputtransform.txt', 'outputwarp': 'outputwarp.nrrd'} + _outputs_filenames = { + 'resampledmovingfilename': 'resampledmovingfilename.nii', + 'outputtransform': 'outputtransform.txt', + 'outputwarp': 'outputwarp.nrrd' + } class AffineRegistrationInputSpec(CommandLineInputSpec): - fixedsmoothingfactor = traits.Int(desc="Amount of smoothing applied to fixed image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", argstr="--fixedsmoothingfactor %d") - movingsmoothingfactor = traits.Int(desc="Amount of smoothing applied to moving image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", argstr="--movingsmoothingfactor %d") - histogrambins = traits.Int(desc="Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", argstr="--histogrambins %d") - spatialsamples = traits.Int(desc="Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", argstr="--spatialsamples %d") - iterations = traits.Int(desc="Number of iterations", argstr="--iterations %d") - translationscale = traits.Float(desc="Relative scale of translations to rotations, i.e. a value of 100 means 10mm = 1 degree. (Actual scale used is 1/(TranslationScale^2)). This parameter is used to \'weight\' or \'standardized\' the transform parameters and their effect on the registration objective function.", argstr="--translationscale %f") - initialtransform = File(desc="Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. Optional.", exists=True, argstr="--initialtransform %s") - FixedImageFileName = File(position=-2, desc="Fixed image to which to register", exists=True, argstr="%s") - MovingImageFileName = File(position=-1, desc="Moving image", exists=True, argstr="%s") - outputtransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--outputtransform %s") - resampledmovingfilename = traits.Either(traits.Bool, File(), hash_files=False, desc="Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--resampledmovingfilename %s") + fixedsmoothingfactor = traits.Int( + desc= + "Amount of smoothing applied to fixed image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", + argstr="--fixedsmoothingfactor %d") + movingsmoothingfactor = traits.Int( + desc= + "Amount of smoothing applied to moving image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", + argstr="--movingsmoothingfactor %d") + histogrambins = traits.Int( + desc= + "Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", + argstr="--histogrambins %d") + spatialsamples = traits.Int( + desc= + "Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", + argstr="--spatialsamples %d") + iterations = traits.Int( + desc="Number of iterations", argstr="--iterations %d") + translationscale = traits.Float( + desc= + "Relative scale of translations to rotations, i.e. a value of 100 means 10mm = 1 degree. (Actual scale used is 1/(TranslationScale^2)). This parameter is used to \'weight\' or \'standardized\' the transform parameters and their effect on the registration objective function.", + argstr="--translationscale %f") + initialtransform = File( + desc= + "Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. Optional.", + exists=True, + argstr="--initialtransform %s") + FixedImageFileName = File( + position=-2, + desc="Fixed image to which to register", + exists=True, + argstr="%s") + MovingImageFileName = File( + position=-1, desc="Moving image", exists=True, argstr="%s") + outputtransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--outputtransform %s") + resampledmovingfilename = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--resampledmovingfilename %s") class AffineRegistrationOutputSpec(TraitedSpec): - outputtransform = File(desc="Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) - resampledmovingfilename = File(desc="Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) + outputtransform = File( + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) + resampledmovingfilename = File( + desc= + "Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) class AffineRegistration(SEMLikeCommandLine): @@ -97,26 +199,63 @@ class AffineRegistration(SEMLikeCommandLine): input_spec = AffineRegistrationInputSpec output_spec = AffineRegistrationOutputSpec _cmd = "AffineRegistration " - _outputs_filenames = {'resampledmovingfilename': 'resampledmovingfilename.nii', 'outputtransform': 'outputtransform.txt'} + _outputs_filenames = { + 'resampledmovingfilename': 'resampledmovingfilename.nii', + 'outputtransform': 'outputtransform.txt' + } class MultiResolutionAffineRegistrationInputSpec(CommandLineInputSpec): - fixedImage = File(position=-2, desc="Image which defines the space into which the moving image is registered", exists=True, argstr="%s") - movingImage = File(position=-1, desc="The transform goes from the fixed image's space into the moving image's space", exists=True, argstr="%s") - resampledImage = traits.Either(traits.Bool, File(), hash_files=False, desc="Registration results", argstr="--resampledImage %s") - saveTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Save the output transform from the registration", argstr="--saveTransform %s") - fixedImageMask = File(desc="Label image which defines a mask of interest for the fixed image", exists=True, argstr="--fixedImageMask %s") - fixedImageROI = traits.List(desc="Label image which defines a ROI of interest for the fixed image", argstr="--fixedImageROI %s") - numIterations = traits.Int(desc="Number of iterations to run at each resolution level.", argstr="--numIterations %d") - numLineIterations = traits.Int(desc="Number of iterations to run at each resolution level.", argstr="--numLineIterations %d") - stepSize = traits.Float(desc="The maximum step size of the optimizer in voxels", argstr="--stepSize %f") - stepTolerance = traits.Float(desc="The maximum step size of the optimizer in voxels", argstr="--stepTolerance %f") + fixedImage = File( + position=-2, + desc= + "Image which defines the space into which the moving image is registered", + exists=True, + argstr="%s") + movingImage = File( + position=-1, + desc= + "The transform goes from the fixed image's space into the moving image's space", + exists=True, + argstr="%s") + resampledImage = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Registration results", + argstr="--resampledImage %s") + saveTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Save the output transform from the registration", + argstr="--saveTransform %s") + fixedImageMask = File( + desc="Label image which defines a mask of interest for the fixed image", + exists=True, + argstr="--fixedImageMask %s") + fixedImageROI = traits.List( + desc="Label image which defines a ROI of interest for the fixed image", + argstr="--fixedImageROI %s") + numIterations = traits.Int( + desc="Number of iterations to run at each resolution level.", + argstr="--numIterations %d") + numLineIterations = traits.Int( + desc="Number of iterations to run at each resolution level.", + argstr="--numLineIterations %d") + stepSize = traits.Float( + desc="The maximum step size of the optimizer in voxels", + argstr="--stepSize %f") + stepTolerance = traits.Float( + desc="The maximum step size of the optimizer in voxels", + argstr="--stepTolerance %f") metricTolerance = traits.Float(argstr="--metricTolerance %f") class MultiResolutionAffineRegistrationOutputSpec(TraitedSpec): resampledImage = File(desc="Registration results", exists=True) - saveTransform = File(desc="Save the output transform from the registration", exists=True) + saveTransform = File( + desc="Save the output transform from the registration", exists=True) class MultiResolutionAffineRegistration(SEMLikeCommandLine): @@ -139,28 +278,86 @@ class MultiResolutionAffineRegistration(SEMLikeCommandLine): input_spec = MultiResolutionAffineRegistrationInputSpec output_spec = MultiResolutionAffineRegistrationOutputSpec _cmd = "MultiResolutionAffineRegistration " - _outputs_filenames = {'resampledImage': 'resampledImage.nii', 'saveTransform': 'saveTransform.txt'} + _outputs_filenames = { + 'resampledImage': 'resampledImage.nii', + 'saveTransform': 'saveTransform.txt' + } class RigidRegistrationInputSpec(CommandLineInputSpec): - fixedsmoothingfactor = traits.Int(desc="Amount of smoothing applied to fixed image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", argstr="--fixedsmoothingfactor %d") - movingsmoothingfactor = traits.Int(desc="Amount of smoothing applied to moving image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", argstr="--movingsmoothingfactor %d") - testingmode = traits.Bool(desc="Enable testing mode. Input transform will be used to construct floating image. The floating image will be ignored if passed.", argstr="--testingmode ") - histogrambins = traits.Int(desc="Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", argstr="--histogrambins %d") - spatialsamples = traits.Int(desc="Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", argstr="--spatialsamples %d") - iterations = InputMultiPath(traits.Int, desc="Comma separated list of iterations. Must have the same number of elements as the learning rate.", sep=",", argstr="--iterations %s") - learningrate = InputMultiPath(traits.Float, desc="Comma separated list of learning rates. Learning rate is a scale factor on the gradient of the registration objective function (gradient with respect to the parameters of the transformation) used to update the parameters of the transformation during optimization. Smaller values cause the optimizer to take smaller steps through the parameter space. Larger values are typically used early in the registration process to take large jumps in parameter space followed by smaller values to home in on the optimum value of the registration objective function. Default is: 0.01, 0.005, 0.0005, 0.0002. Must have the same number of elements as iterations.", sep=",", argstr="--learningrate %s") - translationscale = traits.Float(desc="Relative scale of translations to rotations, i.e. a value of 100 means 10mm = 1 degree. (Actual scale used 1/(TranslationScale^2)). This parameter is used to \'weight\' or \'standardized\' the transform parameters and their effect on the registration objective function.", argstr="--translationscale %f") - initialtransform = File(desc="Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. Optional.", exists=True, argstr="--initialtransform %s") - FixedImageFileName = File(position=-2, desc="Fixed image to which to register", exists=True, argstr="%s") - MovingImageFileName = File(position=-1, desc="Moving image", exists=True, argstr="%s") - outputtransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--outputtransform %s") - resampledmovingfilename = traits.Either(traits.Bool, File(), hash_files=False, desc="Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--resampledmovingfilename %s") + fixedsmoothingfactor = traits.Int( + desc= + "Amount of smoothing applied to fixed image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", + argstr="--fixedsmoothingfactor %d") + movingsmoothingfactor = traits.Int( + desc= + "Amount of smoothing applied to moving image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", + argstr="--movingsmoothingfactor %d") + testingmode = traits.Bool( + desc= + "Enable testing mode. Input transform will be used to construct floating image. The floating image will be ignored if passed.", + argstr="--testingmode ") + histogrambins = traits.Int( + desc= + "Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", + argstr="--histogrambins %d") + spatialsamples = traits.Int( + desc= + "Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", + argstr="--spatialsamples %d") + iterations = InputMultiPath( + traits.Int, + desc= + "Comma separated list of iterations. Must have the same number of elements as the learning rate.", + sep=",", + argstr="--iterations %s") + learningrate = InputMultiPath( + traits.Float, + desc= + "Comma separated list of learning rates. Learning rate is a scale factor on the gradient of the registration objective function (gradient with respect to the parameters of the transformation) used to update the parameters of the transformation during optimization. Smaller values cause the optimizer to take smaller steps through the parameter space. Larger values are typically used early in the registration process to take large jumps in parameter space followed by smaller values to home in on the optimum value of the registration objective function. Default is: 0.01, 0.005, 0.0005, 0.0002. Must have the same number of elements as iterations.", + sep=",", + argstr="--learningrate %s") + translationscale = traits.Float( + desc= + "Relative scale of translations to rotations, i.e. a value of 100 means 10mm = 1 degree. (Actual scale used 1/(TranslationScale^2)). This parameter is used to \'weight\' or \'standardized\' the transform parameters and their effect on the registration objective function.", + argstr="--translationscale %f") + initialtransform = File( + desc= + "Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. Optional.", + exists=True, + argstr="--initialtransform %s") + FixedImageFileName = File( + position=-2, + desc="Fixed image to which to register", + exists=True, + argstr="%s") + MovingImageFileName = File( + position=-1, desc="Moving image", exists=True, argstr="%s") + outputtransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--outputtransform %s") + resampledmovingfilename = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--resampledmovingfilename %s") class RigidRegistrationOutputSpec(TraitedSpec): - outputtransform = File(desc="Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) - resampledmovingfilename = File(desc="Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) + outputtransform = File( + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) + resampledmovingfilename = File( + desc= + "Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) class RigidRegistration(SEMLikeCommandLine): @@ -193,27 +390,82 @@ class RigidRegistration(SEMLikeCommandLine): input_spec = RigidRegistrationInputSpec output_spec = RigidRegistrationOutputSpec _cmd = "RigidRegistration " - _outputs_filenames = {'resampledmovingfilename': 'resampledmovingfilename.nii', 'outputtransform': 'outputtransform.txt'} + _outputs_filenames = { + 'resampledmovingfilename': 'resampledmovingfilename.nii', + 'outputtransform': 'outputtransform.txt' + } class LinearRegistrationInputSpec(CommandLineInputSpec): - fixedsmoothingfactor = traits.Int(desc="Amount of smoothing applied to fixed image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", argstr="--fixedsmoothingfactor %d") - movingsmoothingfactor = traits.Int(desc="Amount of smoothing applied to moving image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", argstr="--movingsmoothingfactor %d") - histogrambins = traits.Int(desc="Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", argstr="--histogrambins %d") - spatialsamples = traits.Int(desc="Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", argstr="--spatialsamples %d") - iterations = InputMultiPath(traits.Int, desc="Comma separated list of iterations. Must have the same number of elements as the learning rate.", sep=",", argstr="--iterations %s") - learningrate = InputMultiPath(traits.Float, desc="Comma separated list of learning rates. Learning rate is a scale factor on the gradient of the registration objective function (gradient with respect to the parameters of the transformation) used to update the parameters of the transformation during optimization. Smaller values cause the optimizer to take smaller steps through the parameter space. Larger values are typically used early in the registration process to take large jumps in parameter space followed by smaller values to home in on the optimum value of the registration objective function. Default is: 0.01, 0.005, 0.0005, 0.0002. Must have the same number of elements as iterations.", sep=",", argstr="--learningrate %s") - translationscale = traits.Float(desc="Relative scale of translations to rotations, i.e. a value of 100 means 10mm = 1 degree. (Actual scale used 1/(TranslationScale^2)). This parameter is used to \'weight\' or \'standardized\' the transform parameters and their effect on the registration objective function.", argstr="--translationscale %f") - initialtransform = File(desc="Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. Optional.", exists=True, argstr="--initialtransform %s") - FixedImageFileName = File(position=-2, desc="Fixed image to which to register", exists=True, argstr="%s") - MovingImageFileName = File(position=-1, desc="Moving image", exists=True, argstr="%s") - outputtransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--outputtransform %s") - resampledmovingfilename = traits.Either(traits.Bool, File(), hash_files=False, desc="Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", argstr="--resampledmovingfilename %s") + fixedsmoothingfactor = traits.Int( + desc= + "Amount of smoothing applied to fixed image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", + argstr="--fixedsmoothingfactor %d") + movingsmoothingfactor = traits.Int( + desc= + "Amount of smoothing applied to moving image prior to registration. Default is 0 (none). Range is 0-5 (unitless). Consider smoothing the input data if there is considerable amounts of noise or the noise pattern in the fixed and moving images is very different.", + argstr="--movingsmoothingfactor %d") + histogrambins = traits.Int( + desc= + "Number of histogram bins to use for Mattes Mutual Information. Reduce the number of bins if a registration fails. If the number of bins is too large, the estimated PDFs will be a field of impulses and will inhibit reliable registration estimation.", + argstr="--histogrambins %d") + spatialsamples = traits.Int( + desc= + "Number of spatial samples to use in estimating Mattes Mutual Information. Larger values yield more accurate PDFs and improved registration quality.", + argstr="--spatialsamples %d") + iterations = InputMultiPath( + traits.Int, + desc= + "Comma separated list of iterations. Must have the same number of elements as the learning rate.", + sep=",", + argstr="--iterations %s") + learningrate = InputMultiPath( + traits.Float, + desc= + "Comma separated list of learning rates. Learning rate is a scale factor on the gradient of the registration objective function (gradient with respect to the parameters of the transformation) used to update the parameters of the transformation during optimization. Smaller values cause the optimizer to take smaller steps through the parameter space. Larger values are typically used early in the registration process to take large jumps in parameter space followed by smaller values to home in on the optimum value of the registration objective function. Default is: 0.01, 0.005, 0.0005, 0.0002. Must have the same number of elements as iterations.", + sep=",", + argstr="--learningrate %s") + translationscale = traits.Float( + desc= + "Relative scale of translations to rotations, i.e. a value of 100 means 10mm = 1 degree. (Actual scale used 1/(TranslationScale^2)). This parameter is used to \'weight\' or \'standardized\' the transform parameters and their effect on the registration objective function.", + argstr="--translationscale %f") + initialtransform = File( + desc= + "Initial transform for aligning the fixed and moving image. Maps positions in the fixed coordinate frame to positions in the moving coordinate frame. Optional.", + exists=True, + argstr="--initialtransform %s") + FixedImageFileName = File( + position=-2, + desc="Fixed image to which to register", + exists=True, + argstr="%s") + MovingImageFileName = File( + position=-1, desc="Moving image", exists=True, argstr="%s") + outputtransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--outputtransform %s") + resampledmovingfilename = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + argstr="--resampledmovingfilename %s") class LinearRegistrationOutputSpec(TraitedSpec): - outputtransform = File(desc="Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) - resampledmovingfilename = File(desc="Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", exists=True) + outputtransform = File( + desc= + "Transform calculated that aligns the fixed and moving image. Maps positions in the fixed coordinate frame to the moving coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) + resampledmovingfilename = File( + desc= + "Resampled moving image to the fixed image coordinate frame. Optional (specify an output transform or an output volume or both).", + exists=True) class LinearRegistration(SEMLikeCommandLine): @@ -236,43 +488,145 @@ class LinearRegistration(SEMLikeCommandLine): input_spec = LinearRegistrationInputSpec output_spec = LinearRegistrationOutputSpec _cmd = "LinearRegistration " - _outputs_filenames = {'resampledmovingfilename': 'resampledmovingfilename.nii', 'outputtransform': 'outputtransform.txt'} + _outputs_filenames = { + 'resampledmovingfilename': 'resampledmovingfilename.nii', + 'outputtransform': 'outputtransform.txt' + } class ExpertAutomatedRegistrationInputSpec(CommandLineInputSpec): - fixedImage = File(position=-2, desc="Image which defines the space into which the moving image is registered", exists=True, argstr="%s") - movingImage = File(position=-1, desc="The transform goes from the fixed image's space into the moving image's space", exists=True, argstr="%s") - resampledImage = traits.Either(traits.Bool, File(), hash_files=False, desc="Registration results", argstr="--resampledImage %s") - loadTransform = File(desc="Load a transform that is immediately applied to the moving image", exists=True, argstr="--loadTransform %s") - saveTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Save the transform that results from registration", argstr="--saveTransform %s") - initialization = traits.Enum("None", "Landmarks", "ImageCenters", "CentersOfMass", "SecondMoments", desc="Method to prime the registration process", argstr="--initialization %s") - registration = traits.Enum("None", "Initial", "Rigid", "Affine", "BSpline", "PipelineRigid", "PipelineAffine", "PipelineBSpline", desc="Method for the registration process", argstr="--registration %s") - metric = traits.Enum("MattesMI", "NormCorr", "MeanSqrd", desc="Method to quantify image match", argstr="--metric %s") - expectedOffset = traits.Float(desc="Expected misalignment after initialization", argstr="--expectedOffset %f") - expectedRotation = traits.Float(desc="Expected misalignment after initialization", argstr="--expectedRotation %f") - expectedScale = traits.Float(desc="Expected misalignment after initialization", argstr="--expectedScale %f") - expectedSkew = traits.Float(desc="Expected misalignment after initialization", argstr="--expectedSkew %f") - verbosityLevel = traits.Enum("Silent", "Standard", "Verbose", desc="Level of detail of reporting progress", argstr="--verbosityLevel %s") - sampleFromOverlap = traits.Bool(desc="Limit metric evaluation to the fixed image region overlapped by the moving image", argstr="--sampleFromOverlap ") - fixedImageMask = File(desc="Image which defines a mask for the fixed image", exists=True, argstr="--fixedImageMask %s") - randomNumberSeed = traits.Int(desc="Seed to generate a consistent random number sequence", argstr="--randomNumberSeed %d") - numberOfThreads = traits.Int(desc="Number of CPU threads to use", argstr="--numberOfThreads %d") - minimizeMemory = traits.Bool(desc="Reduce the amount of memory required at the cost of increased computation time", argstr="--minimizeMemory ") - interpolation = traits.Enum("NearestNeighbor", "Linear", "BSpline", desc="Method for interpolation within the optimization process", argstr="--interpolation %s") - fixedLandmarks = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="Ordered list of landmarks in the fixed image", argstr="--fixedLandmarks %s...") - movingLandmarks = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="Ordered list of landmarks in the moving image", argstr="--movingLandmarks %s...") - rigidMaxIterations = traits.Int(desc="Maximum number of rigid optimization iterations", argstr="--rigidMaxIterations %d") - rigidSamplingRatio = traits.Float(desc="Portion of the image to use in computing the metric during rigid registration", argstr="--rigidSamplingRatio %f") - affineMaxIterations = traits.Int(desc="Maximum number of affine optimization iterations", argstr="--affineMaxIterations %d") - affineSamplingRatio = traits.Float(desc="Portion of the image to use in computing the metric during affine registration", argstr="--affineSamplingRatio %f") - bsplineMaxIterations = traits.Int(desc="Maximum number of bspline optimization iterations", argstr="--bsplineMaxIterations %d") - bsplineSamplingRatio = traits.Float(desc="Portion of the image to use in computing the metric during BSpline registration", argstr="--bsplineSamplingRatio %f") - controlPointSpacing = traits.Int(desc="Number of pixels between control points", argstr="--controlPointSpacing %d") + fixedImage = File( + position=-2, + desc= + "Image which defines the space into which the moving image is registered", + exists=True, + argstr="%s") + movingImage = File( + position=-1, + desc= + "The transform goes from the fixed image's space into the moving image's space", + exists=True, + argstr="%s") + resampledImage = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Registration results", + argstr="--resampledImage %s") + loadTransform = File( + desc="Load a transform that is immediately applied to the moving image", + exists=True, + argstr="--loadTransform %s") + saveTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Save the transform that results from registration", + argstr="--saveTransform %s") + initialization = traits.Enum( + "None", + "Landmarks", + "ImageCenters", + "CentersOfMass", + "SecondMoments", + desc="Method to prime the registration process", + argstr="--initialization %s") + registration = traits.Enum( + "None", + "Initial", + "Rigid", + "Affine", + "BSpline", + "PipelineRigid", + "PipelineAffine", + "PipelineBSpline", + desc="Method for the registration process", + argstr="--registration %s") + metric = traits.Enum( + "MattesMI", + "NormCorr", + "MeanSqrd", + desc="Method to quantify image match", + argstr="--metric %s") + expectedOffset = traits.Float( + desc="Expected misalignment after initialization", + argstr="--expectedOffset %f") + expectedRotation = traits.Float( + desc="Expected misalignment after initialization", + argstr="--expectedRotation %f") + expectedScale = traits.Float( + desc="Expected misalignment after initialization", + argstr="--expectedScale %f") + expectedSkew = traits.Float( + desc="Expected misalignment after initialization", + argstr="--expectedSkew %f") + verbosityLevel = traits.Enum( + "Silent", + "Standard", + "Verbose", + desc="Level of detail of reporting progress", + argstr="--verbosityLevel %s") + sampleFromOverlap = traits.Bool( + desc= + "Limit metric evaluation to the fixed image region overlapped by the moving image", + argstr="--sampleFromOverlap ") + fixedImageMask = File( + desc="Image which defines a mask for the fixed image", + exists=True, + argstr="--fixedImageMask %s") + randomNumberSeed = traits.Int( + desc="Seed to generate a consistent random number sequence", + argstr="--randomNumberSeed %d") + numberOfThreads = traits.Int( + desc="Number of CPU threads to use", argstr="--numberOfThreads %d") + minimizeMemory = traits.Bool( + desc= + "Reduce the amount of memory required at the cost of increased computation time", + argstr="--minimizeMemory ") + interpolation = traits.Enum( + "NearestNeighbor", + "Linear", + "BSpline", + desc="Method for interpolation within the optimization process", + argstr="--interpolation %s") + fixedLandmarks = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc="Ordered list of landmarks in the fixed image", + argstr="--fixedLandmarks %s...") + movingLandmarks = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc="Ordered list of landmarks in the moving image", + argstr="--movingLandmarks %s...") + rigidMaxIterations = traits.Int( + desc="Maximum number of rigid optimization iterations", + argstr="--rigidMaxIterations %d") + rigidSamplingRatio = traits.Float( + desc= + "Portion of the image to use in computing the metric during rigid registration", + argstr="--rigidSamplingRatio %f") + affineMaxIterations = traits.Int( + desc="Maximum number of affine optimization iterations", + argstr="--affineMaxIterations %d") + affineSamplingRatio = traits.Float( + desc= + "Portion of the image to use in computing the metric during affine registration", + argstr="--affineSamplingRatio %f") + bsplineMaxIterations = traits.Int( + desc="Maximum number of bspline optimization iterations", + argstr="--bsplineMaxIterations %d") + bsplineSamplingRatio = traits.Float( + desc= + "Portion of the image to use in computing the metric during BSpline registration", + argstr="--bsplineSamplingRatio %f") + controlPointSpacing = traits.Int( + desc="Number of pixels between control points", + argstr="--controlPointSpacing %d") class ExpertAutomatedRegistrationOutputSpec(TraitedSpec): resampledImage = File(desc="Registration results", exists=True) - saveTransform = File(desc="Save the transform that results from registration", exists=True) + saveTransform = File( + desc="Save the transform that results from registration", exists=True) class ExpertAutomatedRegistration(SEMLikeCommandLine): @@ -295,4 +649,7 @@ class ExpertAutomatedRegistration(SEMLikeCommandLine): input_spec = ExpertAutomatedRegistrationInputSpec output_spec = ExpertAutomatedRegistrationOutputSpec _cmd = "ExpertAutomatedRegistration " - _outputs_filenames = {'resampledImage': 'resampledImage.nii', 'saveTransform': 'saveTransform.txt'} + _outputs_filenames = { + 'resampledImage': 'resampledImage.nii', + 'saveTransform': 'saveTransform.txt' + } diff --git a/nipype/interfaces/slicer/legacy/segmentation.py b/nipype/interfaces/slicer/legacy/segmentation.py index b55e0b6245..3500d50d50 100644 --- a/nipype/interfaces/slicer/legacy/segmentation.py +++ b/nipype/interfaces/slicer/legacy/segmentation.py @@ -8,12 +8,34 @@ class OtsuThresholdSegmentationInputSpec(CommandLineInputSpec): - brightObjects = traits.Bool(desc="Segmenting bright objects on a dark background or dark objects on a bright background.", argstr="--brightObjects ") - numberOfBins = traits.Int(desc="This is an advanced parameter. The number of bins in the histogram used to model the probability mass function of the two intensity distributions. Small numbers of bins may result in a more conservative threshold. The default should suffice for most applications. Experimentation is the only way to see the effect of varying this parameter.", argstr="--numberOfBins %d") - faceConnected = traits.Bool(desc="This is an advanced parameter. Adjacent voxels are face connected. This affects the connected component algorithm. If this parameter is false, more regions are likely to be identified.", argstr="--faceConnected ") - minimumObjectSize = traits.Int(desc="Minimum size of object to retain. This parameter can be used to get rid of small regions in noisy images.", argstr="--minimumObjectSize %d") - inputVolume = File(position=-2, desc="Input volume to be segmented", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + brightObjects = traits.Bool( + desc= + "Segmenting bright objects on a dark background or dark objects on a bright background.", + argstr="--brightObjects ") + numberOfBins = traits.Int( + desc= + "This is an advanced parameter. The number of bins in the histogram used to model the probability mass function of the two intensity distributions. Small numbers of bins may result in a more conservative threshold. The default should suffice for most applications. Experimentation is the only way to see the effect of varying this parameter.", + argstr="--numberOfBins %d") + faceConnected = traits.Bool( + desc= + "This is an advanced parameter. Adjacent voxels are face connected. This affects the connected component algorithm. If this parameter is false, more regions are likely to be identified.", + argstr="--faceConnected ") + minimumObjectSize = traits.Int( + desc= + "Minimum size of object to retain. This parameter can be used to get rid of small regions in noisy images.", + argstr="--minimumObjectSize %d") + inputVolume = File( + position=-2, + desc="Input volume to be segmented", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class OtsuThresholdSegmentationOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py index 91f4b37591..e26b1a958e 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py @@ -4,55 +4,54 @@ def test_AffineRegistration_inputs(): - input_map = dict(FixedImageFileName=dict(argstr='%s', - position=-2, - ), - MovingImageFileName=dict(argstr='%s', - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedsmoothingfactor=dict(argstr='--fixedsmoothingfactor %d', - ), - histogrambins=dict(argstr='--histogrambins %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialtransform=dict(argstr='--initialtransform %s', - ), - iterations=dict(argstr='--iterations %d', - ), - movingsmoothingfactor=dict(argstr='--movingsmoothingfactor %d', - ), - outputtransform=dict(argstr='--outputtransform %s', - hash_files=False, - ), - resampledmovingfilename=dict(argstr='--resampledmovingfilename %s', - hash_files=False, - ), - spatialsamples=dict(argstr='--spatialsamples %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - translationscale=dict(argstr='--translationscale %f', - ), + input_map = dict( + FixedImageFileName=dict( + argstr='%s', + position=-2, + ), + MovingImageFileName=dict( + argstr='%s', + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedsmoothingfactor=dict(argstr='--fixedsmoothingfactor %d', ), + histogrambins=dict(argstr='--histogrambins %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialtransform=dict(argstr='--initialtransform %s', ), + iterations=dict(argstr='--iterations %d', ), + movingsmoothingfactor=dict(argstr='--movingsmoothingfactor %d', ), + outputtransform=dict( + argstr='--outputtransform %s', + hash_files=False, + ), + resampledmovingfilename=dict( + argstr='--resampledmovingfilename %s', + hash_files=False, + ), + spatialsamples=dict(argstr='--spatialsamples %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + translationscale=dict(argstr='--translationscale %f', ), ) inputs = AffineRegistration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_AffineRegistration_outputs(): - output_map = dict(outputtransform=dict(), - resampledmovingfilename=dict(), + output_map = dict( + outputtransform=dict(), + resampledmovingfilename=dict(), ) outputs = AffineRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py index 98be6fbe12..2fddc2c40a 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py @@ -4,61 +4,60 @@ def test_BSplineDeformableRegistration_inputs(): - input_map = dict(FixedImageFileName=dict(argstr='%s', - position=-2, - ), - MovingImageFileName=dict(argstr='%s', - position=-1, - ), - args=dict(argstr='%s', - ), - constrain=dict(argstr='--constrain ', - ), - default=dict(argstr='--default %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gridSize=dict(argstr='--gridSize %d', - ), - histogrambins=dict(argstr='--histogrambins %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialtransform=dict(argstr='--initialtransform %s', - ), - iterations=dict(argstr='--iterations %d', - ), - maximumDeformation=dict(argstr='--maximumDeformation %f', - ), - outputtransform=dict(argstr='--outputtransform %s', - hash_files=False, - ), - outputwarp=dict(argstr='--outputwarp %s', - hash_files=False, - ), - resampledmovingfilename=dict(argstr='--resampledmovingfilename %s', - hash_files=False, - ), - spatialsamples=dict(argstr='--spatialsamples %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + FixedImageFileName=dict( + argstr='%s', + position=-2, + ), + MovingImageFileName=dict( + argstr='%s', + position=-1, + ), + args=dict(argstr='%s', ), + constrain=dict(argstr='--constrain ', ), + default=dict(argstr='--default %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridSize=dict(argstr='--gridSize %d', ), + histogrambins=dict(argstr='--histogrambins %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialtransform=dict(argstr='--initialtransform %s', ), + iterations=dict(argstr='--iterations %d', ), + maximumDeformation=dict(argstr='--maximumDeformation %f', ), + outputtransform=dict( + argstr='--outputtransform %s', + hash_files=False, + ), + outputwarp=dict( + argstr='--outputwarp %s', + hash_files=False, + ), + resampledmovingfilename=dict( + argstr='--resampledmovingfilename %s', + hash_files=False, + ), + spatialsamples=dict(argstr='--spatialsamples %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = BSplineDeformableRegistration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BSplineDeformableRegistration_outputs(): - output_map = dict(outputtransform=dict(), - outputwarp=dict(), - resampledmovingfilename=dict(), + output_map = dict( + outputtransform=dict(), + outputwarp=dict(), + resampledmovingfilename=dict(), ) outputs = BSplineDeformableRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py index e984395aa4..24261cb6a7 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py @@ -4,36 +4,35 @@ def test_BSplineToDeformationField_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - defImage=dict(argstr='--defImage %s', - hash_files=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - refImage=dict(argstr='--refImage %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - tfm=dict(argstr='--tfm %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + defImage=dict( + argstr='--defImage %s', + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + refImage=dict(argstr='--refImage %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + tfm=dict(argstr='--tfm %s', ), ) inputs = BSplineToDeformationField.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BSplineToDeformationField_outputs(): - output_map = dict(defImage=dict(), - ) + output_map = dict(defImage=dict(), ) outputs = BSplineToDeformationField.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py index 9b90f3dc9b..bc0998f3ee 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py @@ -4,89 +4,71 @@ def test_ExpertAutomatedRegistration_inputs(): - input_map = dict(affineMaxIterations=dict(argstr='--affineMaxIterations %d', - ), - affineSamplingRatio=dict(argstr='--affineSamplingRatio %f', - ), - args=dict(argstr='%s', - ), - bsplineMaxIterations=dict(argstr='--bsplineMaxIterations %d', - ), - bsplineSamplingRatio=dict(argstr='--bsplineSamplingRatio %f', - ), - controlPointSpacing=dict(argstr='--controlPointSpacing %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - expectedOffset=dict(argstr='--expectedOffset %f', - ), - expectedRotation=dict(argstr='--expectedRotation %f', - ), - expectedScale=dict(argstr='--expectedScale %f', - ), - expectedSkew=dict(argstr='--expectedSkew %f', - ), - fixedImage=dict(argstr='%s', - position=-2, - ), - fixedImageMask=dict(argstr='--fixedImageMask %s', - ), - fixedLandmarks=dict(argstr='--fixedLandmarks %s...', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialization=dict(argstr='--initialization %s', - ), - interpolation=dict(argstr='--interpolation %s', - ), - loadTransform=dict(argstr='--loadTransform %s', - ), - metric=dict(argstr='--metric %s', - ), - minimizeMemory=dict(argstr='--minimizeMemory ', - ), - movingImage=dict(argstr='%s', - position=-1, - ), - movingLandmarks=dict(argstr='--movingLandmarks %s...', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - randomNumberSeed=dict(argstr='--randomNumberSeed %d', - ), - registration=dict(argstr='--registration %s', - ), - resampledImage=dict(argstr='--resampledImage %s', - hash_files=False, - ), - rigidMaxIterations=dict(argstr='--rigidMaxIterations %d', - ), - rigidSamplingRatio=dict(argstr='--rigidSamplingRatio %f', - ), - sampleFromOverlap=dict(argstr='--sampleFromOverlap ', - ), - saveTransform=dict(argstr='--saveTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbosityLevel=dict(argstr='--verbosityLevel %s', - ), + input_map = dict( + affineMaxIterations=dict(argstr='--affineMaxIterations %d', ), + affineSamplingRatio=dict(argstr='--affineSamplingRatio %f', ), + args=dict(argstr='%s', ), + bsplineMaxIterations=dict(argstr='--bsplineMaxIterations %d', ), + bsplineSamplingRatio=dict(argstr='--bsplineSamplingRatio %f', ), + controlPointSpacing=dict(argstr='--controlPointSpacing %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + expectedOffset=dict(argstr='--expectedOffset %f', ), + expectedRotation=dict(argstr='--expectedRotation %f', ), + expectedScale=dict(argstr='--expectedScale %f', ), + expectedSkew=dict(argstr='--expectedSkew %f', ), + fixedImage=dict( + argstr='%s', + position=-2, + ), + fixedImageMask=dict(argstr='--fixedImageMask %s', ), + fixedLandmarks=dict(argstr='--fixedLandmarks %s...', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialization=dict(argstr='--initialization %s', ), + interpolation=dict(argstr='--interpolation %s', ), + loadTransform=dict(argstr='--loadTransform %s', ), + metric=dict(argstr='--metric %s', ), + minimizeMemory=dict(argstr='--minimizeMemory ', ), + movingImage=dict( + argstr='%s', + position=-1, + ), + movingLandmarks=dict(argstr='--movingLandmarks %s...', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + randomNumberSeed=dict(argstr='--randomNumberSeed %d', ), + registration=dict(argstr='--registration %s', ), + resampledImage=dict( + argstr='--resampledImage %s', + hash_files=False, + ), + rigidMaxIterations=dict(argstr='--rigidMaxIterations %d', ), + rigidSamplingRatio=dict(argstr='--rigidSamplingRatio %f', ), + sampleFromOverlap=dict(argstr='--sampleFromOverlap ', ), + saveTransform=dict( + argstr='--saveTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbosityLevel=dict(argstr='--verbosityLevel %s', ), ) inputs = ExpertAutomatedRegistration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ExpertAutomatedRegistration_outputs(): - output_map = dict(resampledImage=dict(), - saveTransform=dict(), + output_map = dict( + resampledImage=dict(), + saveTransform=dict(), ) outputs = ExpertAutomatedRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py index c80b8b66fb..1f7f0c6b5d 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py @@ -4,59 +4,61 @@ def test_LinearRegistration_inputs(): - input_map = dict(FixedImageFileName=dict(argstr='%s', - position=-2, - ), - MovingImageFileName=dict(argstr='%s', - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedsmoothingfactor=dict(argstr='--fixedsmoothingfactor %d', - ), - histogrambins=dict(argstr='--histogrambins %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialtransform=dict(argstr='--initialtransform %s', - ), - iterations=dict(argstr='--iterations %s', - sep=',', - ), - learningrate=dict(argstr='--learningrate %s', - sep=',', - ), - movingsmoothingfactor=dict(argstr='--movingsmoothingfactor %d', - ), - outputtransform=dict(argstr='--outputtransform %s', - hash_files=False, - ), - resampledmovingfilename=dict(argstr='--resampledmovingfilename %s', - hash_files=False, - ), - spatialsamples=dict(argstr='--spatialsamples %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - translationscale=dict(argstr='--translationscale %f', - ), + input_map = dict( + FixedImageFileName=dict( + argstr='%s', + position=-2, + ), + MovingImageFileName=dict( + argstr='%s', + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedsmoothingfactor=dict(argstr='--fixedsmoothingfactor %d', ), + histogrambins=dict(argstr='--histogrambins %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialtransform=dict(argstr='--initialtransform %s', ), + iterations=dict( + argstr='--iterations %s', + sep=',', + ), + learningrate=dict( + argstr='--learningrate %s', + sep=',', + ), + movingsmoothingfactor=dict(argstr='--movingsmoothingfactor %d', ), + outputtransform=dict( + argstr='--outputtransform %s', + hash_files=False, + ), + resampledmovingfilename=dict( + argstr='--resampledmovingfilename %s', + hash_files=False, + ), + spatialsamples=dict(argstr='--spatialsamples %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + translationscale=dict(argstr='--translationscale %f', ), ) inputs = LinearRegistration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LinearRegistration_outputs(): - output_map = dict(outputtransform=dict(), - resampledmovingfilename=dict(), + output_map = dict( + outputtransform=dict(), + resampledmovingfilename=dict(), ) outputs = LinearRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py index d1262047eb..96ba92f7f2 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py @@ -4,55 +4,54 @@ def test_MultiResolutionAffineRegistration_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedImage=dict(argstr='%s', - position=-2, - ), - fixedImageMask=dict(argstr='--fixedImageMask %s', - ), - fixedImageROI=dict(argstr='--fixedImageROI %s', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - metricTolerance=dict(argstr='--metricTolerance %f', - ), - movingImage=dict(argstr='%s', - position=-1, - ), - numIterations=dict(argstr='--numIterations %d', - ), - numLineIterations=dict(argstr='--numLineIterations %d', - ), - resampledImage=dict(argstr='--resampledImage %s', - hash_files=False, - ), - saveTransform=dict(argstr='--saveTransform %s', - hash_files=False, - ), - stepSize=dict(argstr='--stepSize %f', - ), - stepTolerance=dict(argstr='--stepTolerance %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedImage=dict( + argstr='%s', + position=-2, + ), + fixedImageMask=dict(argstr='--fixedImageMask %s', ), + fixedImageROI=dict(argstr='--fixedImageROI %s', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + metricTolerance=dict(argstr='--metricTolerance %f', ), + movingImage=dict( + argstr='%s', + position=-1, + ), + numIterations=dict(argstr='--numIterations %d', ), + numLineIterations=dict(argstr='--numLineIterations %d', ), + resampledImage=dict( + argstr='--resampledImage %s', + hash_files=False, + ), + saveTransform=dict( + argstr='--saveTransform %s', + hash_files=False, + ), + stepSize=dict(argstr='--stepSize %f', ), + stepTolerance=dict(argstr='--stepTolerance %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MultiResolutionAffineRegistration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MultiResolutionAffineRegistration_outputs(): - output_map = dict(resampledImage=dict(), - saveTransform=dict(), + output_map = dict( + resampledImage=dict(), + saveTransform=dict(), ) outputs = MultiResolutionAffineRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py index 9c5fcd5c1f..28921d2c6e 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py @@ -4,43 +4,41 @@ def test_OtsuThresholdImageFilter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - insideValue=dict(argstr='--insideValue %d', - ), - numberOfBins=dict(argstr='--numberOfBins %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - outsideValue=dict(argstr='--outsideValue %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + insideValue=dict(argstr='--insideValue %d', ), + numberOfBins=dict(argstr='--numberOfBins %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + outsideValue=dict(argstr='--outsideValue %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = OtsuThresholdImageFilter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_OtsuThresholdImageFilter_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = OtsuThresholdImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py index 72a68ca5b9..99967953eb 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py @@ -4,45 +4,42 @@ def test_OtsuThresholdSegmentation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - brightObjects=dict(argstr='--brightObjects ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - faceConnected=dict(argstr='--faceConnected ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - minimumObjectSize=dict(argstr='--minimumObjectSize %d', - ), - numberOfBins=dict(argstr='--numberOfBins %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + brightObjects=dict(argstr='--brightObjects ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + faceConnected=dict(argstr='--faceConnected ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + minimumObjectSize=dict(argstr='--minimumObjectSize %d', ), + numberOfBins=dict(argstr='--numberOfBins %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = OtsuThresholdSegmentation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_OtsuThresholdSegmentation_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = OtsuThresholdSegmentation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py b/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py index 34db34c00d..b8bbd66f71 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py @@ -4,42 +4,43 @@ def test_ResampleScalarVolume_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-2, - ), - OutputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interpolation=dict(argstr='--interpolation %s', - ), - spacing=dict(argstr='--spacing %s', - sep=',', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-2, + ), + OutputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interpolation=dict(argstr='--interpolation %s', ), + spacing=dict( + argstr='--spacing %s', + sep=',', + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ResampleScalarVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ResampleScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(position=-1, - ), - ) + output_map = dict(OutputVolume=dict(position=-1, ), ) outputs = ResampleScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py index a56ad3b98e..2f1d291a0e 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py @@ -4,61 +4,62 @@ def test_RigidRegistration_inputs(): - input_map = dict(FixedImageFileName=dict(argstr='%s', - position=-2, - ), - MovingImageFileName=dict(argstr='%s', - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedsmoothingfactor=dict(argstr='--fixedsmoothingfactor %d', - ), - histogrambins=dict(argstr='--histogrambins %d', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialtransform=dict(argstr='--initialtransform %s', - ), - iterations=dict(argstr='--iterations %s', - sep=',', - ), - learningrate=dict(argstr='--learningrate %s', - sep=',', - ), - movingsmoothingfactor=dict(argstr='--movingsmoothingfactor %d', - ), - outputtransform=dict(argstr='--outputtransform %s', - hash_files=False, - ), - resampledmovingfilename=dict(argstr='--resampledmovingfilename %s', - hash_files=False, - ), - spatialsamples=dict(argstr='--spatialsamples %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - testingmode=dict(argstr='--testingmode ', - ), - translationscale=dict(argstr='--translationscale %f', - ), + input_map = dict( + FixedImageFileName=dict( + argstr='%s', + position=-2, + ), + MovingImageFileName=dict( + argstr='%s', + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedsmoothingfactor=dict(argstr='--fixedsmoothingfactor %d', ), + histogrambins=dict(argstr='--histogrambins %d', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialtransform=dict(argstr='--initialtransform %s', ), + iterations=dict( + argstr='--iterations %s', + sep=',', + ), + learningrate=dict( + argstr='--learningrate %s', + sep=',', + ), + movingsmoothingfactor=dict(argstr='--movingsmoothingfactor %d', ), + outputtransform=dict( + argstr='--outputtransform %s', + hash_files=False, + ), + resampledmovingfilename=dict( + argstr='--resampledmovingfilename %s', + hash_files=False, + ), + spatialsamples=dict(argstr='--spatialsamples %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + testingmode=dict(argstr='--testingmode ', ), + translationscale=dict(argstr='--translationscale %f', ), ) inputs = RigidRegistration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RigidRegistration_outputs(): - output_map = dict(outputtransform=dict(), - resampledmovingfilename=dict(), + output_map = dict( + outputtransform=dict(), + resampledmovingfilename=dict(), ) outputs = RigidRegistration.output_spec() diff --git a/nipype/interfaces/slicer/quantification/changequantification.py b/nipype/interfaces/slicer/quantification/changequantification.py index 51020f36c1..5abf1b1287 100644 --- a/nipype/interfaces/slicer/quantification/changequantification.py +++ b/nipype/interfaces/slicer/quantification/changequantification.py @@ -8,17 +8,50 @@ class IntensityDifferenceMetricInputSpec(CommandLineInputSpec): - sensitivityThreshold = traits.Float(desc="This parameter should be between 0 and 1, and defines how sensitive the metric should be to the intensity changes.", argstr="--sensitivityThreshold %f") - changingBandSize = traits.Int(desc="How far (in mm) from the boundary of the segmentation should the intensity changes be considered.", argstr="--changingBandSize %d") - baselineVolume = File(position=-4, desc="Baseline volume to be compared to", exists=True, argstr="%s") - baselineSegmentationVolume = File(position=-3, desc="Label volume that contains segmentation of the structure of interest in the baseline volume.", exists=True, argstr="%s") - followupVolume = File(position=-2, desc="Followup volume to be compare to the baseline", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output volume to keep the results of change quantification.", argstr="%s") - reportFileName = traits.Either(traits.Bool, File(), hash_files=False, desc="Report file name", argstr="--reportFileName %s") + sensitivityThreshold = traits.Float( + desc= + "This parameter should be between 0 and 1, and defines how sensitive the metric should be to the intensity changes.", + argstr="--sensitivityThreshold %f") + changingBandSize = traits.Int( + desc= + "How far (in mm) from the boundary of the segmentation should the intensity changes be considered.", + argstr="--changingBandSize %d") + baselineVolume = File( + position=-4, + desc="Baseline volume to be compared to", + exists=True, + argstr="%s") + baselineSegmentationVolume = File( + position=-3, + desc= + "Label volume that contains segmentation of the structure of interest in the baseline volume.", + exists=True, + argstr="%s") + followupVolume = File( + position=-2, + desc="Followup volume to be compare to the baseline", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output volume to keep the results of change quantification.", + argstr="%s") + reportFileName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Report file name", + argstr="--reportFileName %s") class IntensityDifferenceMetricOutputSpec(TraitedSpec): - outputVolume = File(position=-1, desc="Output volume to keep the results of change quantification.", exists=True) + outputVolume = File( + position=-1, + desc="Output volume to keep the results of change quantification.", + exists=True) reportFileName = File(desc="Report file name", exists=True) @@ -47,4 +80,7 @@ class IntensityDifferenceMetric(SEMLikeCommandLine): input_spec = IntensityDifferenceMetricInputSpec output_spec = IntensityDifferenceMetricOutputSpec _cmd = "IntensityDifferenceMetric " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'reportFileName': 'reportFileName'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'reportFileName': 'reportFileName' + } diff --git a/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py b/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py index c566703c95..0edfca3fbb 100644 --- a/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py +++ b/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py @@ -8,20 +8,48 @@ class PETStandardUptakeValueComputationInputSpec(CommandLineInputSpec): - petDICOMPath = Directory(desc="Input path to a directory containing a PET volume containing DICOM header information for SUV computation", exists=True, argstr="--petDICOMPath %s") - petVolume = File(desc="Input PET volume for SUVbw computation (must be the same volume as pointed to by the DICOM path!).", exists=True, argstr="--petVolume %s") - labelMap = File(desc="Input label volume containing the volumes of interest", exists=True, argstr="--labelMap %s") - color = File(desc="Color table to to map labels to colors and names", exists=True, argstr="--color %s") - csvFile = traits.Either(traits.Bool, File(), hash_files=False, desc="A file holding the output SUV values in comma separated lines, one per label. Optional.", argstr="--csvFile %s") - OutputLabel = traits.Str(desc="List of labels for which SUV values were computed", argstr="--OutputLabel %s") - OutputLabelValue = traits.Str(desc="List of label values for which SUV values were computed", argstr="--OutputLabelValue %s") + petDICOMPath = Directory( + desc= + "Input path to a directory containing a PET volume containing DICOM header information for SUV computation", + exists=True, + argstr="--petDICOMPath %s") + petVolume = File( + desc= + "Input PET volume for SUVbw computation (must be the same volume as pointed to by the DICOM path!).", + exists=True, + argstr="--petVolume %s") + labelMap = File( + desc="Input label volume containing the volumes of interest", + exists=True, + argstr="--labelMap %s") + color = File( + desc="Color table to to map labels to colors and names", + exists=True, + argstr="--color %s") + csvFile = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "A file holding the output SUV values in comma separated lines, one per label. Optional.", + argstr="--csvFile %s") + OutputLabel = traits.Str( + desc="List of labels for which SUV values were computed", + argstr="--OutputLabel %s") + OutputLabelValue = traits.Str( + desc="List of label values for which SUV values were computed", + argstr="--OutputLabelValue %s") SUVMax = traits.Str(desc="SUV max for each label", argstr="--SUVMax %s") SUVMean = traits.Str(desc="SUV mean for each label", argstr="--SUVMean %s") - SUVMin = traits.Str(desc="SUV minimum for each label", argstr="--SUVMin %s") + SUVMin = traits.Str( + desc="SUV minimum for each label", argstr="--SUVMin %s") class PETStandardUptakeValueComputationOutputSpec(TraitedSpec): - csvFile = File(desc="A file holding the output SUV values in comma separated lines, one per label. Optional.", exists=True) + csvFile = File( + desc= + "A file holding the output SUV values in comma separated lines, one per label. Optional.", + exists=True) class PETStandardUptakeValueComputation(SEMLikeCommandLine): diff --git a/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py b/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py index f4809280f9..638ce652a2 100644 --- a/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py +++ b/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py @@ -4,50 +4,54 @@ def test_IntensityDifferenceMetric_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - baselineSegmentationVolume=dict(argstr='%s', - position=-3, - ), - baselineVolume=dict(argstr='%s', - position=-4, - ), - changingBandSize=dict(argstr='--changingBandSize %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - followupVolume=dict(argstr='%s', - position=-2, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - reportFileName=dict(argstr='--reportFileName %s', - hash_files=False, - ), - sensitivityThreshold=dict(argstr='--sensitivityThreshold %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + baselineSegmentationVolume=dict( + argstr='%s', + position=-3, + ), + baselineVolume=dict( + argstr='%s', + position=-4, + ), + changingBandSize=dict(argstr='--changingBandSize %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + followupVolume=dict( + argstr='%s', + position=-2, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + reportFileName=dict( + argstr='--reportFileName %s', + hash_files=False, + ), + sensitivityThreshold=dict(argstr='--sensitivityThreshold %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = IntensityDifferenceMetric.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_IntensityDifferenceMetric_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - reportFileName=dict(), + output_map = dict( + outputVolume=dict(position=-1, ), + reportFileName=dict(), ) outputs = IntensityDifferenceMetric.output_spec() diff --git a/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py b/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py index 4dfbdc66dd..622d3fa15d 100644 --- a/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py +++ b/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py @@ -4,50 +4,42 @@ def test_PETStandardUptakeValueComputation_inputs(): - input_map = dict(OutputLabel=dict(argstr='--OutputLabel %s', - ), - OutputLabelValue=dict(argstr='--OutputLabelValue %s', - ), - SUVMax=dict(argstr='--SUVMax %s', - ), - SUVMean=dict(argstr='--SUVMean %s', - ), - SUVMin=dict(argstr='--SUVMin %s', - ), - args=dict(argstr='%s', - ), - color=dict(argstr='--color %s', - ), - csvFile=dict(argstr='--csvFile %s', - hash_files=False, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - labelMap=dict(argstr='--labelMap %s', - ), - petDICOMPath=dict(argstr='--petDICOMPath %s', - ), - petVolume=dict(argstr='--petVolume %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + OutputLabel=dict(argstr='--OutputLabel %s', ), + OutputLabelValue=dict(argstr='--OutputLabelValue %s', ), + SUVMax=dict(argstr='--SUVMax %s', ), + SUVMean=dict(argstr='--SUVMean %s', ), + SUVMin=dict(argstr='--SUVMin %s', ), + args=dict(argstr='%s', ), + color=dict(argstr='--color %s', ), + csvFile=dict( + argstr='--csvFile %s', + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + labelMap=dict(argstr='--labelMap %s', ), + petDICOMPath=dict(argstr='--petDICOMPath %s', ), + petVolume=dict(argstr='--petVolume %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = PETStandardUptakeValueComputation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PETStandardUptakeValueComputation_outputs(): - output_map = dict(csvFile=dict(), - ) + output_map = dict(csvFile=dict(), ) outputs = PETStandardUptakeValueComputation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/__init__.py b/nipype/interfaces/slicer/registration/__init__.py index f19c1faff7..375b9b5416 100644 --- a/nipype/interfaces/slicer/registration/__init__.py +++ b/nipype/interfaces/slicer/registration/__init__.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import -from .specialized import ACPCTransform, FiducialRegistration, VBRAINSDemonWarp, BRAINSDemonWarp +from .specialized import (ACPCTransform, FiducialRegistration, + VBRAINSDemonWarp, BRAINSDemonWarp) from .brainsresample import BRAINSResample from .brainsfit import BRAINSFit diff --git a/nipype/interfaces/slicer/registration/brainsfit.py b/nipype/interfaces/slicer/registration/brainsfit.py index 2e02879280..adbd733976 100644 --- a/nipype/interfaces/slicer/registration/brainsfit.py +++ b/nipype/interfaces/slicer/registration/brainsfit.py @@ -8,77 +8,343 @@ class BRAINSFitInputSpec(CommandLineInputSpec): - fixedVolume = File(desc="The fixed image for registration by mutual information optimization.", exists=True, argstr="--fixedVolume %s") - movingVolume = File(desc="The moving image for registration by mutual information optimization.", exists=True, argstr="--movingVolume %s") - bsplineTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS BSpline", argstr="--bsplineTransform %s") - linearTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS ---NOT--- BSpline", argstr="--linearTransform %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Output image for registration. NOTE: You must select either the outputTransform or the outputVolume option.", argstr="--outputVolume %s") - initialTransform = File(desc="Filename of transform used to initialize the registration. This CAN NOT be used with either CenterOfHeadLAlign, MomentsAlign, GeometryAlign, or initialTransform file.", exists=True, argstr="--initialTransform %s") - initializeTransformMode = traits.Enum("Off", "useMomentsAlign", "useCenterOfHeadAlign", "useGeometryAlign", "useCenterOfROIAlign", desc="Determine how to initialize the transform center. GeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. MomentsAlign assumes that the center of mass of the images represent similar structures. useCenterOfHeadAlign attempts to use the top of head and shape of neck to drive a center of mass estimate. Off assumes that the physical space of the images are close, and that centering in terms of the image Origins is a good starting point. This flag is mutually exclusive with the initialTransform flag.", argstr="--initializeTransformMode %s") - useRigid = traits.Bool(desc="Perform a rigid registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", argstr="--useRigid ") - useScaleVersor3D = traits.Bool(desc="Perform a ScaleVersor3D registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", argstr="--useScaleVersor3D ") - useScaleSkewVersor3D = traits.Bool(desc="Perform a ScaleSkewVersor3D registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", argstr="--useScaleSkewVersor3D ") - useAffine = traits.Bool(desc="Perform an Affine registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", argstr="--useAffine ") - useBSpline = traits.Bool(desc="Perform a BSpline registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", argstr="--useBSpline ") - numberOfSamples = traits.Int(desc="The number of voxels sampled for mutual information computation. Increase this for a slower, more careful fit. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation.", argstr="--numberOfSamples %d") - splineGridSize = InputMultiPath(traits.Int, desc="The number of subdivisions of the BSpline Grid to be centered on the image space. Each dimension must have at least 3 subdivisions for the BSpline to be correctly computed. ", sep=",", argstr="--splineGridSize %s") - numberOfIterations = InputMultiPath(traits.Int, desc="The maximum number of iterations to try before failing to converge. Use an explicit limit like 500 or 1000 to manage risk of divergence", sep=",", argstr="--numberOfIterations %s") - maskProcessingMode = traits.Enum("NOMASK", "ROIAUTO", "ROI", desc="What mode to use for using the masks. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. The Region Of Interest mode (choose ROI) uses the masks to define what parts of the image should be used for computing the transform.", argstr="--maskProcessingMode %s") - fixedBinaryVolume = File(desc="Fixed Image binary mask volume, ONLY FOR MANUAL ROI mode.", exists=True, argstr="--fixedBinaryVolume %s") - movingBinaryVolume = File(desc="Moving Image binary mask volume, ONLY FOR MANUAL ROI mode.", exists=True, argstr="--movingBinaryVolume %s") - outputFixedVolumeROI = traits.Either(traits.Bool, File(), hash_files=False, desc="The ROI automatically found in fixed image, ONLY FOR ROIAUTO mode.", argstr="--outputFixedVolumeROI %s") - outputMovingVolumeROI = traits.Either(traits.Bool, File(), hash_files=False, desc="The ROI automatically found in moving image, ONLY FOR ROIAUTO mode.", argstr="--outputMovingVolumeROI %s") - outputVolumePixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", desc="The output image Pixel Type is the scalar datatype for representation of the Output Volume.", argstr="--outputVolumePixelType %s") - backgroundFillValue = traits.Float(desc="Background fill value for output image.", argstr="--backgroundFillValue %f") - maskInferiorCutOffFromCenter = traits.Float(desc="For use with --useCenterOfHeadAlign (and --maskProcessingMode ROIAUTO): the cut-off below the image centers, in millimeters, ", argstr="--maskInferiorCutOffFromCenter %f") - scaleOutputValues = traits.Bool(desc="If true, and the voxel values do not fit within the minimum and maximum values of the desired outputVolumePixelType, then linearly scale the min/max output image voxel values to fit within the min/max range of the outputVolumePixelType.", argstr="--scaleOutputValues ") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, NearestNeighbor, BSpline, WindowedSinc, or ResampleInPlace. The ResampleInPlace option will create an image with the same discrete voxel values and will adjust the origin and direction of the physical space interpretation.", argstr="--interpolationMode %s") - minimumStepLength = InputMultiPath(traits.Float, desc="Each step in the optimization takes steps at least this big. When none are possible, registration is complete.", sep=",", argstr="--minimumStepLength %s") - translationScale = traits.Float(desc="How much to scale up changes in position compared to unit rotational changes in radians -- decrease this to put more rotation in the search pattern.", argstr="--translationScale %f") - reproportionScale = traits.Float(desc="ScaleVersor3D 'Scale' compensation factor. Increase this to put more rescaling in a ScaleVersor3D or ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", argstr="--reproportionScale %f") - skewScale = traits.Float(desc="ScaleSkewVersor3D Skew compensation factor. Increase this to put more skew in a ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", argstr="--skewScale %f") - maxBSplineDisplacement = traits.Float(desc=" Sets the maximum allowed displacements in image physical coordinates for BSpline control grid along each axis. A value of 0.0 indicates that the problem should be unbounded. NOTE: This only constrains the BSpline portion, and does not limit the displacement from the associated bulk transform. This can lead to a substantial reduction in computation time in the BSpline optimizer., ", argstr="--maxBSplineDisplacement %f") - histogramMatch = traits.Bool(desc="Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile. Do NOT use if registering images from different modailties.", argstr="--histogramMatch ") - numberOfHistogramBins = traits.Int(desc="The number of histogram levels", argstr="--numberOfHistogramBins %d") - numberOfMatchPoints = traits.Int(desc="the number of match points", argstr="--numberOfMatchPoints %d") - strippedOutputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="File name for the rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overwritten if either bsplineTransform or linearTransform is set.", argstr="--strippedOutputTransform %s") - transformType = InputMultiPath(traits.Str, desc="Specifies a list of registration types to be used. The valid types are, Rigid, ScaleVersor3D, ScaleSkewVersor3D, Affine, and BSpline. Specifiying more than one in a comma separated list will initialize the next stage with the previous results. If registrationClass flag is used, it overrides this parameter setting.", sep=",", argstr="--transformType %s") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", argstr="--outputTransform %s") - fixedVolumeTimeIndex = traits.Int(desc="The index in the time series for the 3D fixed image to fit, if 4-dimensional.", argstr="--fixedVolumeTimeIndex %d") - movingVolumeTimeIndex = traits.Int(desc="The index in the time series for the 3D moving image to fit, if 4-dimensional.", argstr="--movingVolumeTimeIndex %d") - medianFilterSize = InputMultiPath(traits.Int, desc="The radius for the optional MedianImageFilter preprocessing in all 3 directions.", sep=",", argstr="--medianFilterSize %s") - removeIntensityOutliers = traits.Float(desc="The half percentage to decide outliers of image intensities. The default value is zero, which means no outlier removal. If the value of 0.005 is given, the moduel will throw away 0.005 % of both tails, so 0.01% of intensities in total would be ignored in its statistic calculation. ", argstr="--removeIntensityOutliers %f") - useCachingOfBSplineWeightsMode = traits.Enum("ON", "OFF", desc="This is a 5x speed advantage at the expense of requiring much more memory. Only relevant when transformType is BSpline.", argstr="--useCachingOfBSplineWeightsMode %s") - useExplicitPDFDerivativesMode = traits.Enum("AUTO", "ON", "OFF", desc="Using mode AUTO means OFF for BSplineDeformableTransforms and ON for the linear transforms. The ON alternative uses more memory to sometimes do a better job.", argstr="--useExplicitPDFDerivativesMode %s") - ROIAutoDilateSize = traits.Float(desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f") - ROIAutoClosingSize = traits.Float(desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the hole closing size in mm. It is rounded up to the nearest whole pixel size in each direction. The default is to use a closing size of 9mm. For mouse data this value may need to be reset to 0.9 or smaller.", argstr="--ROIAutoClosingSize %f") - relaxationFactor = traits.Float(desc="Internal debugging parameter, and should probably never be used from the command line. This will be removed in the future.", argstr="--relaxationFactor %f") - maximumStepLength = traits.Float(desc="Internal debugging parameter, and should probably never be used from the command line. This will be removed in the future.", argstr="--maximumStepLength %f") - failureExitCode = traits.Int(desc="If the fit fails, exit with this status code. (It can be used to force a successfult exit status of (0) if the registration fails due to reaching the maximum number of iterations.", argstr="--failureExitCode %d") - writeTransformOnFailure = traits.Bool(desc="Flag to save the final transform even if the numberOfIterations are reached without convergence. (Intended for use when --failureExitCode 0 )", argstr="--writeTransformOnFailure ") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use. (default is auto-detected)", argstr="--numberOfThreads %d") - forceMINumberOfThreads = traits.Int(desc="Force the the maximum number of threads to use for non thread safe MI metric. CAUTION: Inconsistent results my arise!", argstr="--forceMINumberOfThreads %d") - debugLevel = traits.Int(desc="Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", argstr="--debugLevel %d") - costFunctionConvergenceFactor = traits.Float(desc=" From itkLBFGSBOptimizer.h: Set/Get the CostFunctionConvergenceFactor. Algorithm terminates when the reduction in cost function is less than (factor * epsmcj) where epsmch is the machine precision. Typical values for factor: 1e+12 for low accuracy; 1e+7 for moderate accuracy and 1e+1 for extremely high accuracy. 1e+9 seems to work well., ", argstr="--costFunctionConvergenceFactor %f") - projectedGradientTolerance = traits.Float(desc=" From itkLBFGSBOptimizer.h: Set/Get the ProjectedGradientTolerance. Algorithm terminates when the project gradient is below the tolerance. Default lbfgsb value is 1e-5, but 1e-4 seems to work well., ", argstr="--projectedGradientTolerance %f") - gui = traits.Bool(desc="Display intermediate image volumes for debugging. NOTE: This is not part of the standard build sytem, and probably does nothing on your installation.", argstr="--gui ") - promptUser = traits.Bool(desc="Prompt the user to hit enter each time an image is sent to the DebugImageViewer", argstr="--promptUser ") - NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 = traits.Bool(desc="DO NOT USE THIS FLAG", argstr="--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 ") - NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 = traits.Bool(desc="DO NOT USE THIS FLAG", argstr="--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 ") - NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 = traits.Bool(desc="DO NOT USE THIS FLAG", argstr="--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 ") - permitParameterVariation = InputMultiPath(traits.Int, desc="A bit vector to permit linear transform parameters to vary under optimization. The vector order corresponds with transform parameters, and beyond the end ones fill in as a default. For instance, you can choose to rotate only in x (pitch) with 1,0,0; this is mostly for expert use in turning on and off individual degrees of freedom in rotation, translation or scaling without multiplying the number of transform representations; this trick is probably meaningless when tried with the general affine transform.", sep=",", argstr="--permitParameterVariation %s") - costMetric = traits.Enum("MMI", "MSE", "NC", "MC", desc="The cost metric to be used during fitting. Defaults to MMI. Options are MMI (Mattes Mutual Information), MSE (Mean Square Error), NC (Normalized Correlation), MC (Match Cardinality for binary images)", argstr="--costMetric %s") - writeOutputTransformInFloat = traits.Bool(desc="By default, the output registration transforms (either the output composite transform or each transform component) are written to the disk in double precision. If this flag is ON, the output transforms will be written in single (float) precision. It is especially important if the output transform is a displacement field transform, or it is a composite transform that includes several displacement fields.", argstr="--writeOutputTransformInFloat ") + fixedVolume = File( + desc= + "The fixed image for registration by mutual information optimization.", + exists=True, + argstr="--fixedVolume %s") + movingVolume = File( + desc= + "The moving image for registration by mutual information optimization.", + exists=True, + argstr="--movingVolume %s") + bsplineTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS BSpline", + argstr="--bsplineTransform %s") + linearTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS ---NOT--- BSpline", + argstr="--linearTransform %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Output image for registration. NOTE: You must select either the outputTransform or the outputVolume option.", + argstr="--outputVolume %s") + initialTransform = File( + desc= + "Filename of transform used to initialize the registration. This CAN NOT be used with either CenterOfHeadLAlign, MomentsAlign, GeometryAlign, or initialTransform file.", + exists=True, + argstr="--initialTransform %s") + initializeTransformMode = traits.Enum( + "Off", + "useMomentsAlign", + "useCenterOfHeadAlign", + "useGeometryAlign", + "useCenterOfROIAlign", + desc= + "Determine how to initialize the transform center. GeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. MomentsAlign assumes that the center of mass of the images represent similar structures. useCenterOfHeadAlign attempts to use the top of head and shape of neck to drive a center of mass estimate. Off assumes that the physical space of the images are close, and that centering in terms of the image Origins is a good starting point. This flag is mutually exclusive with the initialTransform flag.", + argstr="--initializeTransformMode %s") + useRigid = traits.Bool( + desc= + "Perform a rigid registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useRigid ") + useScaleVersor3D = traits.Bool( + desc= + "Perform a ScaleVersor3D registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useScaleVersor3D ") + useScaleSkewVersor3D = traits.Bool( + desc= + "Perform a ScaleSkewVersor3D registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useScaleSkewVersor3D ") + useAffine = traits.Bool( + desc= + "Perform an Affine registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useAffine ") + useBSpline = traits.Bool( + desc= + "Perform a BSpline registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + argstr="--useBSpline ") + numberOfSamples = traits.Int( + desc= + "The number of voxels sampled for mutual information computation. Increase this for a slower, more careful fit. You can also limit the sampling focus with ROI masks and ROIAUTO mask generation.", + argstr="--numberOfSamples %d") + splineGridSize = InputMultiPath( + traits.Int, + desc= + "The number of subdivisions of the BSpline Grid to be centered on the image space. Each dimension must have at least 3 subdivisions for the BSpline to be correctly computed. ", + sep=",", + argstr="--splineGridSize %s") + numberOfIterations = InputMultiPath( + traits.Int, + desc= + "The maximum number of iterations to try before failing to converge. Use an explicit limit like 500 or 1000 to manage risk of divergence", + sep=",", + argstr="--numberOfIterations %s") + maskProcessingMode = traits.Enum( + "NOMASK", + "ROIAUTO", + "ROI", + desc= + "What mode to use for using the masks. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. The Region Of Interest mode (choose ROI) uses the masks to define what parts of the image should be used for computing the transform.", + argstr="--maskProcessingMode %s") + fixedBinaryVolume = File( + desc="Fixed Image binary mask volume, ONLY FOR MANUAL ROI mode.", + exists=True, + argstr="--fixedBinaryVolume %s") + movingBinaryVolume = File( + desc="Moving Image binary mask volume, ONLY FOR MANUAL ROI mode.", + exists=True, + argstr="--movingBinaryVolume %s") + outputFixedVolumeROI = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The ROI automatically found in fixed image, ONLY FOR ROIAUTO mode.", + argstr="--outputFixedVolumeROI %s") + outputMovingVolumeROI = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The ROI automatically found in moving image, ONLY FOR ROIAUTO mode.", + argstr="--outputMovingVolumeROI %s") + outputVolumePixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uint", + "uchar", + desc= + "The output image Pixel Type is the scalar datatype for representation of the Output Volume.", + argstr="--outputVolumePixelType %s") + backgroundFillValue = traits.Float( + desc="Background fill value for output image.", + argstr="--backgroundFillValue %f") + maskInferiorCutOffFromCenter = traits.Float( + desc= + "For use with --useCenterOfHeadAlign (and --maskProcessingMode ROIAUTO): the cut-off below the image centers, in millimeters, ", + argstr="--maskInferiorCutOffFromCenter %f") + scaleOutputValues = traits.Bool( + desc= + "If true, and the voxel values do not fit within the minimum and maximum values of the desired outputVolumePixelType, then linearly scale the min/max output image voxel values to fit within the min/max range of the outputVolumePixelType.", + argstr="--scaleOutputValues ") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, NearestNeighbor, BSpline, WindowedSinc, or ResampleInPlace. The ResampleInPlace option will create an image with the same discrete voxel values and will adjust the origin and direction of the physical space interpretation.", + argstr="--interpolationMode %s") + minimumStepLength = InputMultiPath( + traits.Float, + desc= + "Each step in the optimization takes steps at least this big. When none are possible, registration is complete.", + sep=",", + argstr="--minimumStepLength %s") + translationScale = traits.Float( + desc= + "How much to scale up changes in position compared to unit rotational changes in radians -- decrease this to put more rotation in the search pattern.", + argstr="--translationScale %f") + reproportionScale = traits.Float( + desc= + "ScaleVersor3D 'Scale' compensation factor. Increase this to put more rescaling in a ScaleVersor3D or ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", + argstr="--reproportionScale %f") + skewScale = traits.Float( + desc= + "ScaleSkewVersor3D Skew compensation factor. Increase this to put more skew in a ScaleSkewVersor3D search pattern. 1.0 works well with a translationScale of 1000.0", + argstr="--skewScale %f") + maxBSplineDisplacement = traits.Float( + desc= + " Sets the maximum allowed displacements in image physical coordinates for BSpline control grid along each axis. A value of 0.0 indicates that the problem should be unbounded. NOTE: This only constrains the BSpline portion, and does not limit the displacement from the associated bulk transform. This can lead to a substantial reduction in computation time in the BSpline optimizer., ", + argstr="--maxBSplineDisplacement %f") + histogramMatch = traits.Bool( + desc= + "Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile. Do NOT use if registering images from different modailties.", + argstr="--histogramMatch ") + numberOfHistogramBins = traits.Int( + desc="The number of histogram levels", + argstr="--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( + desc="the number of match points", argstr="--numberOfMatchPoints %d") + strippedOutputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "File name for the rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overwritten if either bsplineTransform or linearTransform is set.", + argstr="--strippedOutputTransform %s") + transformType = InputMultiPath( + traits.Str, + desc= + "Specifies a list of registration types to be used. The valid types are, Rigid, ScaleVersor3D, ScaleSkewVersor3D, Affine, and BSpline. Specifiying more than one in a comma separated list will initialize the next stage with the previous results. If registrationClass flag is used, it overrides this parameter setting.", + sep=",", + argstr="--transformType %s") + outputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", + argstr="--outputTransform %s") + fixedVolumeTimeIndex = traits.Int( + desc= + "The index in the time series for the 3D fixed image to fit, if 4-dimensional.", + argstr="--fixedVolumeTimeIndex %d") + movingVolumeTimeIndex = traits.Int( + desc= + "The index in the time series for the 3D moving image to fit, if 4-dimensional.", + argstr="--movingVolumeTimeIndex %d") + medianFilterSize = InputMultiPath( + traits.Int, + desc= + "The radius for the optional MedianImageFilter preprocessing in all 3 directions.", + sep=",", + argstr="--medianFilterSize %s") + removeIntensityOutliers = traits.Float( + desc= + "The half percentage to decide outliers of image intensities. The default value is zero, which means no outlier removal. If the value of 0.005 is given, the moduel will throw away 0.005 % of both tails, so 0.01% of intensities in total would be ignored in its statistic calculation. ", + argstr="--removeIntensityOutliers %f") + useCachingOfBSplineWeightsMode = traits.Enum( + "ON", + "OFF", + desc= + "This is a 5x speed advantage at the expense of requiring much more memory. Only relevant when transformType is BSpline.", + argstr="--useCachingOfBSplineWeightsMode %s") + useExplicitPDFDerivativesMode = traits.Enum( + "AUTO", + "ON", + "OFF", + desc= + "Using mode AUTO means OFF for BSplineDeformableTransforms and ON for the linear transforms. The ON alternative uses more memory to sometimes do a better job.", + argstr="--useExplicitPDFDerivativesMode %s") + ROIAutoDilateSize = traits.Float( + desc= + "This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", + argstr="--ROIAutoDilateSize %f") + ROIAutoClosingSize = traits.Float( + desc= + "This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the hole closing size in mm. It is rounded up to the nearest whole pixel size in each direction. The default is to use a closing size of 9mm. For mouse data this value may need to be reset to 0.9 or smaller.", + argstr="--ROIAutoClosingSize %f") + relaxationFactor = traits.Float( + desc= + "Internal debugging parameter, and should probably never be used from the command line. This will be removed in the future.", + argstr="--relaxationFactor %f") + maximumStepLength = traits.Float( + desc= + "Internal debugging parameter, and should probably never be used from the command line. This will be removed in the future.", + argstr="--maximumStepLength %f") + failureExitCode = traits.Int( + desc= + "If the fit fails, exit with this status code. (It can be used to force a successfult exit status of (0) if the registration fails due to reaching the maximum number of iterations.", + argstr="--failureExitCode %d") + writeTransformOnFailure = traits.Bool( + desc= + "Flag to save the final transform even if the numberOfIterations are reached without convergence. (Intended for use when --failureExitCode 0 )", + argstr="--writeTransformOnFailure ") + numberOfThreads = traits.Int( + desc= + "Explicitly specify the maximum number of threads to use. (default is auto-detected)", + argstr="--numberOfThreads %d") + forceMINumberOfThreads = traits.Int( + desc= + "Force the the maximum number of threads to use for non thread safe MI metric. CAUTION: Inconsistent results my arise!", + argstr="--forceMINumberOfThreads %d") + debugLevel = traits.Int( + desc= + "Display debug messages, and produce debug intermediate results. 0=OFF, 1=Minimal, 10=Maximum debugging.", + argstr="--debugLevel %d") + costFunctionConvergenceFactor = traits.Float( + desc= + " From itkLBFGSBOptimizer.h: Set/Get the CostFunctionConvergenceFactor. Algorithm terminates when the reduction in cost function is less than (factor * epsmcj) where epsmch is the machine precision. Typical values for factor: 1e+12 for low accuracy; 1e+7 for moderate accuracy and 1e+1 for extremely high accuracy. 1e+9 seems to work well., ", + argstr="--costFunctionConvergenceFactor %f") + projectedGradientTolerance = traits.Float( + desc= + " From itkLBFGSBOptimizer.h: Set/Get the ProjectedGradientTolerance. Algorithm terminates when the project gradient is below the tolerance. Default lbfgsb value is 1e-5, but 1e-4 seems to work well., ", + argstr="--projectedGradientTolerance %f") + gui = traits.Bool( + desc= + "Display intermediate image volumes for debugging. NOTE: This is not part of the standard build sytem, and probably does nothing on your installation.", + argstr="--gui ") + promptUser = traits.Bool( + desc= + "Prompt the user to hit enter each time an image is sent to the DebugImageViewer", + argstr="--promptUser ") + NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 = traits.Bool( + desc="DO NOT USE THIS FLAG", + argstr="--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 ") + NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 = traits.Bool( + desc="DO NOT USE THIS FLAG", + argstr="--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 ") + NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 = traits.Bool( + desc="DO NOT USE THIS FLAG", + argstr="--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 ") + permitParameterVariation = InputMultiPath( + traits.Int, + desc= + "A bit vector to permit linear transform parameters to vary under optimization. The vector order corresponds with transform parameters, and beyond the end ones fill in as a default. For instance, you can choose to rotate only in x (pitch) with 1,0,0; this is mostly for expert use in turning on and off individual degrees of freedom in rotation, translation or scaling without multiplying the number of transform representations; this trick is probably meaningless when tried with the general affine transform.", + sep=",", + argstr="--permitParameterVariation %s") + costMetric = traits.Enum( + "MMI", + "MSE", + "NC", + "MC", + desc= + "The cost metric to be used during fitting. Defaults to MMI. Options are MMI (Mattes Mutual Information), MSE (Mean Square Error), NC (Normalized Correlation), MC (Match Cardinality for binary images)", + argstr="--costMetric %s") + writeOutputTransformInFloat = traits.Bool( + desc= + "By default, the output registration transforms (either the output composite transform or each transform component) are written to the disk in double precision. If this flag is ON, the output transforms will be written in single (float) precision. It is especially important if the output transform is a displacement field transform, or it is a composite transform that includes several displacement fields.", + argstr="--writeOutputTransformInFloat ") class BRAINSFitOutputSpec(TraitedSpec): - bsplineTransform = File(desc="(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS BSpline", exists=True) - linearTransform = File(desc="(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS ---NOT--- BSpline", exists=True) - outputVolume = File(desc="(optional) Output image for registration. NOTE: You must select either the outputTransform or the outputVolume option.", exists=True) - outputFixedVolumeROI = File(desc="The ROI automatically found in fixed image, ONLY FOR ROIAUTO mode.", exists=True) - outputMovingVolumeROI = File(desc="The ROI automatically found in moving image, ONLY FOR ROIAUTO mode.", exists=True) - strippedOutputTransform = File(desc="File name for the rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overwritten if either bsplineTransform or linearTransform is set.", exists=True) - outputTransform = File(desc="(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", exists=True) + bsplineTransform = File( + desc= + "(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS BSpline", + exists=True) + linearTransform = File( + desc= + "(optional) Filename to which save the estimated transform. NOTE: You must set at least one output object (either a deformed image or a transform. NOTE: USE THIS ONLY IF THE FINAL TRANSFORM IS ---NOT--- BSpline", + exists=True) + outputVolume = File( + desc= + "(optional) Output image for registration. NOTE: You must select either the outputTransform or the outputVolume option.", + exists=True) + outputFixedVolumeROI = File( + desc= + "The ROI automatically found in fixed image, ONLY FOR ROIAUTO mode.", + exists=True) + outputMovingVolumeROI = File( + desc= + "The ROI automatically found in moving image, ONLY FOR ROIAUTO mode.", + exists=True) + strippedOutputTransform = File( + desc= + "File name for the rigid component of the estimated affine transform. Can be used to rigidly register the moving image to the fixed image. NOTE: This value is overwritten if either bsplineTransform or linearTransform is set.", + exists=True) + outputTransform = File( + desc= + "(optional) Filename to which save the (optional) estimated transform. NOTE: You must select either the outputTransform or the outputVolume option.", + exists=True) class BRAINSFit(SEMLikeCommandLine): @@ -103,4 +369,12 @@ class BRAINSFit(SEMLikeCommandLine): input_spec = BRAINSFitInputSpec output_spec = BRAINSFitOutputSpec _cmd = "BRAINSFit " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'bsplineTransform': 'bsplineTransform.mat', 'outputTransform': 'outputTransform.mat', 'outputFixedVolumeROI': 'outputFixedVolumeROI.nii', 'strippedOutputTransform': 'strippedOutputTransform.mat', 'outputMovingVolumeROI': 'outputMovingVolumeROI.nii', 'linearTransform': 'linearTransform.mat'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'bsplineTransform': 'bsplineTransform.mat', + 'outputTransform': 'outputTransform.mat', + 'outputFixedVolumeROI': 'outputFixedVolumeROI.nii', + 'strippedOutputTransform': 'strippedOutputTransform.mat', + 'outputMovingVolumeROI': 'outputMovingVolumeROI.nii', + 'linearTransform': 'linearTransform.mat' + } diff --git a/nipype/interfaces/slicer/registration/brainsresample.py b/nipype/interfaces/slicer/registration/brainsresample.py index fa87020b28..a3b79681fd 100644 --- a/nipype/interfaces/slicer/registration/brainsresample.py +++ b/nipype/interfaces/slicer/registration/brainsresample.py @@ -8,17 +8,68 @@ class BRAINSResampleInputSpec(CommandLineInputSpec): - inputVolume = File(desc="Image To Warp", exists=True, argstr="--inputVolume %s") - referenceVolume = File(desc="Reference image used only to define the output space. If not specified, the warping is done in the same space as the image to warp.", exists=True, argstr="--referenceVolume %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Resulting deformed image", argstr="--outputVolume %s") - pixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", "binary", desc="Specifies the pixel type for the input/output images. The \'binary\' pixel type uses a modified algorithm whereby the image is read in as unsigned char, a signed distance map is created, signed distance map is resampled, and then a thresholded image of type unsigned char is written to disk.", argstr="--pixelType %s") - deformationVolume = File(desc="Displacement Field to be used to warp the image", exists=True, argstr="--deformationVolume %s") - warpTransform = File(desc="Filename for the BRAINSFit transform used in place of the deformation field", exists=True, argstr="--warpTransform %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - inverseTransform = traits.Bool(desc="True/False is to compute inverse of given transformation. Default is false", argstr="--inverseTransform ") - defaultValue = traits.Float(desc="Default voxel value", argstr="--defaultValue %f") - gridSpacing = InputMultiPath(traits.Int, desc="Add warped grid to output image to help show the deformation that occured with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for makeing a 2D image of grid lines from the 3D space ", sep=",", argstr="--gridSpacing %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="Image To Warp", exists=True, argstr="--inputVolume %s") + referenceVolume = File( + desc= + "Reference image used only to define the output space. If not specified, the warping is done in the same space as the image to warp.", + exists=True, + argstr="--referenceVolume %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Resulting deformed image", + argstr="--outputVolume %s") + pixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uint", + "uchar", + "binary", + desc= + "Specifies the pixel type for the input/output images. The \'binary\' pixel type uses a modified algorithm whereby the image is read in as unsigned char, a signed distance map is created, signed distance map is resampled, and then a thresholded image of type unsigned char is written to disk.", + argstr="--pixelType %s") + deformationVolume = File( + desc="Displacement Field to be used to warp the image", + exists=True, + argstr="--deformationVolume %s") + warpTransform = File( + desc= + "Filename for the BRAINSFit transform used in place of the deformation field", + exists=True, + argstr="--warpTransform %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + inverseTransform = traits.Bool( + desc= + "True/False is to compute inverse of given transformation. Default is false", + argstr="--inverseTransform ") + defaultValue = traits.Float( + desc="Default voxel value", argstr="--defaultValue %f") + gridSpacing = InputMultiPath( + traits.Int, + desc= + "Add warped grid to output image to help show the deformation that occured with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for makeing a 2D image of grid lines from the 3D space ", + sep=",", + argstr="--gridSpacing %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSResampleOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/registration/specialized.py b/nipype/interfaces/slicer/registration/specialized.py index 8ccf48176f..9c6c3f5f20 100644 --- a/nipype/interfaces/slicer/registration/specialized.py +++ b/nipype/interfaces/slicer/registration/specialized.py @@ -8,14 +8,32 @@ class ACPCTransformInputSpec(CommandLineInputSpec): - acpc = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="ACPC line, two fiducial points, one at the anterior commissure and one at the posterior commissure.", argstr="--acpc %s...") - midline = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="The midline is a series of points defining the division between the hemispheres of the brain (the mid sagittal plane).", argstr="--midline %s...") - outputTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="A transform filled in from the ACPC and Midline registration calculation", argstr="--outputTransform %s") - debugSwitch = traits.Bool(desc="Click if wish to see debugging output", argstr="--debugSwitch ") + acpc = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc= + "ACPC line, two fiducial points, one at the anterior commissure and one at the posterior commissure.", + argstr="--acpc %s...") + midline = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc= + "The midline is a series of points defining the division between the hemispheres of the brain (the mid sagittal plane).", + argstr="--midline %s...") + outputTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "A transform filled in from the ACPC and Midline registration calculation", + argstr="--outputTransform %s") + debugSwitch = traits.Bool( + desc="Click if wish to see debugging output", argstr="--debugSwitch ") class ACPCTransformOutputSpec(TraitedSpec): - outputTransform = File(desc="A transform filled in from the ACPC and Midline registration calculation", exists=True) + outputTransform = File( + desc= + "A transform filled in from the ACPC and Midline registration calculation", + exists=True) class ACPCTransform(SEMLikeCommandLine): @@ -44,16 +62,35 @@ class ACPCTransform(SEMLikeCommandLine): class FiducialRegistrationInputSpec(CommandLineInputSpec): - fixedLandmarks = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="Ordered list of landmarks in the fixed image", argstr="--fixedLandmarks %s...") - movingLandmarks = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="Ordered list of landmarks in the moving image", argstr="--movingLandmarks %s...") - saveTransform = traits.Either(traits.Bool, File(), hash_files=False, desc="Save the transform that results from registration", argstr="--saveTransform %s") - transformType = traits.Enum("Translation", "Rigid", "Similarity", desc="Type of transform to produce", argstr="--transformType %s") + fixedLandmarks = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc="Ordered list of landmarks in the fixed image", + argstr="--fixedLandmarks %s...") + movingLandmarks = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc="Ordered list of landmarks in the moving image", + argstr="--movingLandmarks %s...") + saveTransform = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="Save the transform that results from registration", + argstr="--saveTransform %s") + transformType = traits.Enum( + "Translation", + "Rigid", + "Similarity", + desc="Type of transform to produce", + argstr="--transformType %s") rms = traits.Float(desc="Display RMS Error.", argstr="--rms %f") - outputMessage = traits.Str(desc="Provides more information on the output", argstr="--outputMessage %s") + outputMessage = traits.Str( + desc="Provides more information on the output", + argstr="--outputMessage %s") class FiducialRegistrationOutputSpec(TraitedSpec): - saveTransform = File(desc="Save the transform that results from registration", exists=True) + saveTransform = File( + desc="Save the transform that results from registration", exists=True) class FiducialRegistration(SEMLikeCommandLine): @@ -80,53 +117,222 @@ class FiducialRegistration(SEMLikeCommandLine): class VBRAINSDemonWarpInputSpec(CommandLineInputSpec): - movingVolume = InputMultiPath(File(exists=True), desc="Required: input moving image", argstr="--movingVolume %s...") - fixedVolume = InputMultiPath(File(exists=True), desc="Required: input fixed (target) image", argstr="--fixedVolume %s...") - inputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="Input volumes will be typecast to this format: float|short|ushort|int|uchar", argstr="--inputPixelType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", argstr="--outputVolume %s") - outputDisplacementFieldVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", argstr="--outputDisplacementFieldVolume %s") - outputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="outputVolume will be typecast to this format: float|short|ushort|int|uchar", argstr="--outputPixelType %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - registrationFilterType = traits.Enum("Demons", "FastSymmetricForces", "Diffeomorphic", "LogDemons", "SymmetricLogDemons", desc="Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic|LogDemons|SymmetricLogDemons", argstr="--registrationFilterType %s") - smoothDisplacementFieldSigma = traits.Float(desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", argstr="--smoothDisplacementFieldSigma %f") - numberOfPyramidLevels = traits.Int(desc="Number of image pyramid levels to use in the multi-resolution registration.", argstr="--numberOfPyramidLevels %d") - minimumFixedPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumFixedPyramid %s") - minimumMovingPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumMovingPyramid %s") - arrayOfPyramidLevelIterations = InputMultiPath(traits.Int, desc="The number of iterations for each pyramid level", sep=",", argstr="--arrayOfPyramidLevelIterations %s") - histogramMatch = traits.Bool(desc="Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", argstr="--histogramMatch ") - numberOfHistogramBins = traits.Int(desc="The number of histogram levels", argstr="--numberOfHistogramBins %d") - numberOfMatchPoints = traits.Int(desc="The number of match points for histrogramMatch", argstr="--numberOfMatchPoints %d") - medianFilterSize = InputMultiPath(traits.Int, desc="Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", sep=",", argstr="--medianFilterSize %s") - initializeWithDisplacementField = File(desc="Initial deformation field vector image file name", exists=True, argstr="--initializeWithDisplacementField %s") - initializeWithTransform = File(desc="Initial Transform filename", exists=True, argstr="--initializeWithTransform %s") - makeBOBF = traits.Bool(desc="Flag to make Brain-Only Background-Filled versions of the input and target volumes.", argstr="--makeBOBF ") - fixedBinaryVolume = File(desc="Mask filename for desired region of interest in the Fixed image.", exists=True, argstr="--fixedBinaryVolume %s") - movingBinaryVolume = File(desc="Mask filename for desired region of interest in the Moving image.", exists=True, argstr="--movingBinaryVolume %s") - lowerThresholdForBOBF = traits.Int(desc="Lower threshold for performing BOBF", argstr="--lowerThresholdForBOBF %d") - upperThresholdForBOBF = traits.Int(desc="Upper threshold for performing BOBF", argstr="--upperThresholdForBOBF %d") - backgroundFillValue = traits.Int(desc="Replacement value to overwrite background when performing BOBF", argstr="--backgroundFillValue %d") - seedForBOBF = InputMultiPath(traits.Int, desc="coordinates in all 3 directions for Seed when performing BOBF", sep=",", argstr="--seedForBOBF %s") - neighborhoodForBOBF = InputMultiPath(traits.Int, desc="neighborhood in all 3 directions to be included when performing BOBF", sep=",", argstr="--neighborhoodForBOBF %s") - outputDisplacementFieldPrefix = traits.Str(desc="Displacement field filename prefix for writing separate x, y, and z component images", argstr="--outputDisplacementFieldPrefix %s") - outputCheckerboardVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", argstr="--outputCheckerboardVolume %s") - checkerboardPatternSubdivisions = InputMultiPath(traits.Int, desc="Number of Checkerboard subdivisions in all 3 directions", sep=",", argstr="--checkerboardPatternSubdivisions %s") - outputNormalized = traits.Bool(desc="Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", argstr="--outputNormalized ") - outputDebug = traits.Bool(desc="Flag to write debugging images after each step.", argstr="--outputDebug ") - weightFactors = InputMultiPath(traits.Float, desc="Weight fatctors for each input images", sep=",", argstr="--weightFactors %s") - gradient_type = traits.Enum("0", "1", "2", desc="Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", argstr="--gradient_type %s") - upFieldSmoothing = traits.Float(desc="Smoothing sigma for the update field at each iteration", argstr="--upFieldSmoothing %f") - max_step_length = traits.Float(desc="Maximum length of an update vector (0: no restriction)", argstr="--max_step_length %f") - use_vanilla_dem = traits.Bool(desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") - gui = traits.Bool(desc="Display intermediate image volumes for debugging", argstr="--gui ") - promptUser = traits.Bool(desc="Prompt the user to hit enter each time an image is sent to the DebugImageViewer", argstr="--promptUser ") - numberOfBCHApproximationTerms = traits.Int(desc="Number of terms in the BCH expansion", argstr="--numberOfBCHApproximationTerms %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + movingVolume = InputMultiPath( + File(exists=True), + desc="Required: input moving image", + argstr="--movingVolume %s...") + fixedVolume = InputMultiPath( + File(exists=True), + desc="Required: input fixed (target) image", + argstr="--fixedVolume %s...") + inputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "Input volumes will be typecast to this format: float|short|ushort|int|uchar", + argstr="--inputPixelType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + argstr="--outputVolume %s") + outputDisplacementFieldVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + argstr="--outputDisplacementFieldVolume %s") + outputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "outputVolume will be typecast to this format: float|short|ushort|int|uchar", + argstr="--outputPixelType %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + registrationFilterType = traits.Enum( + "Demons", + "FastSymmetricForces", + "Diffeomorphic", + "LogDemons", + "SymmetricLogDemons", + desc= + "Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic|LogDemons|SymmetricLogDemons", + argstr="--registrationFilterType %s") + smoothDisplacementFieldSigma = traits.Float( + desc= + "A gaussian smoothing value to be applied to the deformation feild at each iteration.", + argstr="--smoothDisplacementFieldSigma %f") + numberOfPyramidLevels = traits.Int( + desc= + "Number of image pyramid levels to use in the multi-resolution registration.", + argstr="--numberOfPyramidLevels %d") + minimumFixedPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumFixedPyramid %s") + minimumMovingPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumMovingPyramid %s") + arrayOfPyramidLevelIterations = InputMultiPath( + traits.Int, + desc="The number of iterations for each pyramid level", + sep=",", + argstr="--arrayOfPyramidLevelIterations %s") + histogramMatch = traits.Bool( + desc= + "Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", + argstr="--histogramMatch ") + numberOfHistogramBins = traits.Int( + desc="The number of histogram levels", + argstr="--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( + desc="The number of match points for histrogramMatch", + argstr="--numberOfMatchPoints %d") + medianFilterSize = InputMultiPath( + traits.Int, + desc= + "Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", + sep=",", + argstr="--medianFilterSize %s") + initializeWithDisplacementField = File( + desc="Initial deformation field vector image file name", + exists=True, + argstr="--initializeWithDisplacementField %s") + initializeWithTransform = File( + desc="Initial Transform filename", + exists=True, + argstr="--initializeWithTransform %s") + makeBOBF = traits.Bool( + desc= + "Flag to make Brain-Only Background-Filled versions of the input and target volumes.", + argstr="--makeBOBF ") + fixedBinaryVolume = File( + desc="Mask filename for desired region of interest in the Fixed image.", + exists=True, + argstr="--fixedBinaryVolume %s") + movingBinaryVolume = File( + desc= + "Mask filename for desired region of interest in the Moving image.", + exists=True, + argstr="--movingBinaryVolume %s") + lowerThresholdForBOBF = traits.Int( + desc="Lower threshold for performing BOBF", + argstr="--lowerThresholdForBOBF %d") + upperThresholdForBOBF = traits.Int( + desc="Upper threshold for performing BOBF", + argstr="--upperThresholdForBOBF %d") + backgroundFillValue = traits.Int( + desc="Replacement value to overwrite background when performing BOBF", + argstr="--backgroundFillValue %d") + seedForBOBF = InputMultiPath( + traits.Int, + desc="coordinates in all 3 directions for Seed when performing BOBF", + sep=",", + argstr="--seedForBOBF %s") + neighborhoodForBOBF = InputMultiPath( + traits.Int, + desc= + "neighborhood in all 3 directions to be included when performing BOBF", + sep=",", + argstr="--neighborhoodForBOBF %s") + outputDisplacementFieldPrefix = traits.Str( + desc= + "Displacement field filename prefix for writing separate x, y, and z component images", + argstr="--outputDisplacementFieldPrefix %s") + outputCheckerboardVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + argstr="--outputCheckerboardVolume %s") + checkerboardPatternSubdivisions = InputMultiPath( + traits.Int, + desc="Number of Checkerboard subdivisions in all 3 directions", + sep=",", + argstr="--checkerboardPatternSubdivisions %s") + outputNormalized = traits.Bool( + desc= + "Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", + argstr="--outputNormalized ") + outputDebug = traits.Bool( + desc="Flag to write debugging images after each step.", + argstr="--outputDebug ") + weightFactors = InputMultiPath( + traits.Float, + desc="Weight fatctors for each input images", + sep=",", + argstr="--weightFactors %s") + gradient_type = traits.Enum( + "0", + "1", + "2", + desc= + "Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", + argstr="--gradient_type %s") + upFieldSmoothing = traits.Float( + desc="Smoothing sigma for the update field at each iteration", + argstr="--upFieldSmoothing %f") + max_step_length = traits.Float( + desc="Maximum length of an update vector (0: no restriction)", + argstr="--max_step_length %f") + use_vanilla_dem = traits.Bool( + desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") + gui = traits.Bool( + desc="Display intermediate image volumes for debugging", + argstr="--gui ") + promptUser = traits.Bool( + desc= + "Prompt the user to hit enter each time an image is sent to the DebugImageViewer", + argstr="--promptUser ") + numberOfBCHApproximationTerms = traits.Int( + desc="Number of terms in the BCH expansion", + argstr="--numberOfBCHApproximationTerms %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class VBRAINSDemonWarpOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", exists=True) - outputDisplacementFieldVolume = File(desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", exists=True) - outputCheckerboardVolume = File(desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", exists=True) + outputVolume = File( + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + exists=True) + outputDisplacementFieldVolume = File( + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + exists=True) + outputCheckerboardVolume = File( + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + exists=True) class VBRAINSDemonWarp(SEMLikeCommandLine): @@ -154,56 +360,227 @@ class VBRAINSDemonWarp(SEMLikeCommandLine): input_spec = VBRAINSDemonWarpInputSpec output_spec = VBRAINSDemonWarpOutputSpec _cmd = "VBRAINSDemonWarp " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', + 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd' + } class BRAINSDemonWarpInputSpec(CommandLineInputSpec): - movingVolume = File(desc="Required: input moving image", exists=True, argstr="--movingVolume %s") - fixedVolume = File(desc="Required: input fixed (target) image", exists=True, argstr="--fixedVolume %s") - inputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="Input volumes will be typecast to this format: float|short|ushort|int|uchar", argstr="--inputPixelType %s") - outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", argstr="--outputVolume %s") - outputDisplacementFieldVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", argstr="--outputDisplacementFieldVolume %s") - outputPixelType = traits.Enum("float", "short", "ushort", "int", "uchar", desc="outputVolume will be typecast to this format: float|short|ushort|int|uchar", argstr="--outputPixelType %s") - interpolationMode = traits.Enum("NearestNeighbor", "Linear", "ResampleInPlace", "BSpline", "WindowedSinc", "Hamming", "Cosine", "Welch", "Lanczos", "Blackman", desc="Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", argstr="--interpolationMode %s") - registrationFilterType = traits.Enum("Demons", "FastSymmetricForces", "Diffeomorphic", desc="Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic", argstr="--registrationFilterType %s") - smoothDisplacementFieldSigma = traits.Float(desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", argstr="--smoothDisplacementFieldSigma %f") - numberOfPyramidLevels = traits.Int(desc="Number of image pyramid levels to use in the multi-resolution registration.", argstr="--numberOfPyramidLevels %d") - minimumFixedPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumFixedPyramid %s") - minimumMovingPyramid = InputMultiPath(traits.Int, desc="The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", sep=",", argstr="--minimumMovingPyramid %s") - arrayOfPyramidLevelIterations = InputMultiPath(traits.Int, desc="The number of iterations for each pyramid level", sep=",", argstr="--arrayOfPyramidLevelIterations %s") - histogramMatch = traits.Bool(desc="Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", argstr="--histogramMatch ") - numberOfHistogramBins = traits.Int(desc="The number of histogram levels", argstr="--numberOfHistogramBins %d") - numberOfMatchPoints = traits.Int(desc="The number of match points for histrogramMatch", argstr="--numberOfMatchPoints %d") - medianFilterSize = InputMultiPath(traits.Int, desc="Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", sep=",", argstr="--medianFilterSize %s") - initializeWithDisplacementField = File(desc="Initial deformation field vector image file name", exists=True, argstr="--initializeWithDisplacementField %s") - initializeWithTransform = File(desc="Initial Transform filename", exists=True, argstr="--initializeWithTransform %s") - maskProcessingMode = traits.Enum("NOMASK", "ROIAUTO", "ROI", "BOBF", desc="What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", argstr="--maskProcessingMode %s") - fixedBinaryVolume = File(desc="Mask filename for desired region of interest in the Fixed image.", exists=True, argstr="--fixedBinaryVolume %s") - movingBinaryVolume = File(desc="Mask filename for desired region of interest in the Moving image.", exists=True, argstr="--movingBinaryVolume %s") - lowerThresholdForBOBF = traits.Int(desc="Lower threshold for performing BOBF", argstr="--lowerThresholdForBOBF %d") - upperThresholdForBOBF = traits.Int(desc="Upper threshold for performing BOBF", argstr="--upperThresholdForBOBF %d") - backgroundFillValue = traits.Int(desc="Replacement value to overwrite background when performing BOBF", argstr="--backgroundFillValue %d") - seedForBOBF = InputMultiPath(traits.Int, desc="coordinates in all 3 directions for Seed when performing BOBF", sep=",", argstr="--seedForBOBF %s") - neighborhoodForBOBF = InputMultiPath(traits.Int, desc="neighborhood in all 3 directions to be included when performing BOBF", sep=",", argstr="--neighborhoodForBOBF %s") - outputDisplacementFieldPrefix = traits.Str(desc="Displacement field filename prefix for writing separate x, y, and z component images", argstr="--outputDisplacementFieldPrefix %s") - outputCheckerboardVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", argstr="--outputCheckerboardVolume %s") - checkerboardPatternSubdivisions = InputMultiPath(traits.Int, desc="Number of Checkerboard subdivisions in all 3 directions", sep=",", argstr="--checkerboardPatternSubdivisions %s") - outputNormalized = traits.Bool(desc="Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", argstr="--outputNormalized ") - outputDebug = traits.Bool(desc="Flag to write debugging images after each step.", argstr="--outputDebug ") - gradient_type = traits.Enum("0", "1", "2", desc="Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", argstr="--gradient_type %s") - upFieldSmoothing = traits.Float(desc="Smoothing sigma for the update field at each iteration", argstr="--upFieldSmoothing %f") - max_step_length = traits.Float(desc="Maximum length of an update vector (0: no restriction)", argstr="--max_step_length %f") - use_vanilla_dem = traits.Bool(desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") - gui = traits.Bool(desc="Display intermediate image volumes for debugging", argstr="--gui ") - promptUser = traits.Bool(desc="Prompt the user to hit enter each time an image is sent to the DebugImageViewer", argstr="--promptUser ") - numberOfBCHApproximationTerms = traits.Int(desc="Number of terms in the BCH expansion", argstr="--numberOfBCHApproximationTerms %d") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + movingVolume = File( + desc="Required: input moving image", + exists=True, + argstr="--movingVolume %s") + fixedVolume = File( + desc="Required: input fixed (target) image", + exists=True, + argstr="--fixedVolume %s") + inputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "Input volumes will be typecast to this format: float|short|ushort|int|uchar", + argstr="--inputPixelType %s") + outputVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + argstr="--outputVolume %s") + outputDisplacementFieldVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + argstr="--outputDisplacementFieldVolume %s") + outputPixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uchar", + desc= + "outputVolume will be typecast to this format: float|short|ushort|int|uchar", + argstr="--outputPixelType %s") + interpolationMode = traits.Enum( + "NearestNeighbor", + "Linear", + "ResampleInPlace", + "BSpline", + "WindowedSinc", + "Hamming", + "Cosine", + "Welch", + "Lanczos", + "Blackman", + desc= + "Type of interpolation to be used when applying transform to moving volume. Options are Linear, ResampleInPlace, NearestNeighbor, BSpline, or WindowedSinc", + argstr="--interpolationMode %s") + registrationFilterType = traits.Enum( + "Demons", + "FastSymmetricForces", + "Diffeomorphic", + desc= + "Registration Filter Type: Demons|FastSymmetricForces|Diffeomorphic", + argstr="--registrationFilterType %s") + smoothDisplacementFieldSigma = traits.Float( + desc= + "A gaussian smoothing value to be applied to the deformation feild at each iteration.", + argstr="--smoothDisplacementFieldSigma %f") + numberOfPyramidLevels = traits.Int( + desc= + "Number of image pyramid levels to use in the multi-resolution registration.", + argstr="--numberOfPyramidLevels %d") + minimumFixedPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the fixed image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumFixedPyramid %s") + minimumMovingPyramid = InputMultiPath( + traits.Int, + desc= + "The shrink factor for the first level of the moving image pyramid. (i.e. start at 1/16 scale, then 1/8, then 1/4, then 1/2, and finally full scale)", + sep=",", + argstr="--minimumMovingPyramid %s") + arrayOfPyramidLevelIterations = InputMultiPath( + traits.Int, + desc="The number of iterations for each pyramid level", + sep=",", + argstr="--arrayOfPyramidLevelIterations %s") + histogramMatch = traits.Bool( + desc= + "Histogram Match the input images. This is suitable for images of the same modality that may have different absolute scales, but the same overall intensity profile.", + argstr="--histogramMatch ") + numberOfHistogramBins = traits.Int( + desc="The number of histogram levels", + argstr="--numberOfHistogramBins %d") + numberOfMatchPoints = traits.Int( + desc="The number of match points for histrogramMatch", + argstr="--numberOfMatchPoints %d") + medianFilterSize = InputMultiPath( + traits.Int, + desc= + "Median filter radius in all 3 directions. When images have a lot of salt and pepper noise, this step can improve the registration.", + sep=",", + argstr="--medianFilterSize %s") + initializeWithDisplacementField = File( + desc="Initial deformation field vector image file name", + exists=True, + argstr="--initializeWithDisplacementField %s") + initializeWithTransform = File( + desc="Initial Transform filename", + exists=True, + argstr="--initializeWithTransform %s") + maskProcessingMode = traits.Enum( + "NOMASK", + "ROIAUTO", + "ROI", + "BOBF", + desc= + "What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", + argstr="--maskProcessingMode %s") + fixedBinaryVolume = File( + desc="Mask filename for desired region of interest in the Fixed image.", + exists=True, + argstr="--fixedBinaryVolume %s") + movingBinaryVolume = File( + desc= + "Mask filename for desired region of interest in the Moving image.", + exists=True, + argstr="--movingBinaryVolume %s") + lowerThresholdForBOBF = traits.Int( + desc="Lower threshold for performing BOBF", + argstr="--lowerThresholdForBOBF %d") + upperThresholdForBOBF = traits.Int( + desc="Upper threshold for performing BOBF", + argstr="--upperThresholdForBOBF %d") + backgroundFillValue = traits.Int( + desc="Replacement value to overwrite background when performing BOBF", + argstr="--backgroundFillValue %d") + seedForBOBF = InputMultiPath( + traits.Int, + desc="coordinates in all 3 directions for Seed when performing BOBF", + sep=",", + argstr="--seedForBOBF %s") + neighborhoodForBOBF = InputMultiPath( + traits.Int, + desc= + "neighborhood in all 3 directions to be included when performing BOBF", + sep=",", + argstr="--neighborhoodForBOBF %s") + outputDisplacementFieldPrefix = traits.Str( + desc= + "Displacement field filename prefix for writing separate x, y, and z component images", + argstr="--outputDisplacementFieldPrefix %s") + outputCheckerboardVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + argstr="--outputCheckerboardVolume %s") + checkerboardPatternSubdivisions = InputMultiPath( + traits.Int, + desc="Number of Checkerboard subdivisions in all 3 directions", + sep=",", + argstr="--checkerboardPatternSubdivisions %s") + outputNormalized = traits.Bool( + desc= + "Flag to warp and write the normalized images to output. In normalized images the image values are fit-scaled to be between 0 and the maximum storage type value.", + argstr="--outputNormalized ") + outputDebug = traits.Bool( + desc="Flag to write debugging images after each step.", + argstr="--outputDebug ") + gradient_type = traits.Enum( + "0", + "1", + "2", + desc= + "Type of gradient used for computing the demons force (0 is symmetrized, 1 is fixed image, 2 is moving image)", + argstr="--gradient_type %s") + upFieldSmoothing = traits.Float( + desc="Smoothing sigma for the update field at each iteration", + argstr="--upFieldSmoothing %f") + max_step_length = traits.Float( + desc="Maximum length of an update vector (0: no restriction)", + argstr="--max_step_length %f") + use_vanilla_dem = traits.Bool( + desc="Run vanilla demons algorithm", argstr="--use_vanilla_dem ") + gui = traits.Bool( + desc="Display intermediate image volumes for debugging", + argstr="--gui ") + promptUser = traits.Bool( + desc= + "Prompt the user to hit enter each time an image is sent to the DebugImageViewer", + argstr="--promptUser ") + numberOfBCHApproximationTerms = traits.Int( + desc="Number of terms in the BCH expansion", + argstr="--numberOfBCHApproximationTerms %d") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSDemonWarpOutputSpec(TraitedSpec): - outputVolume = File(desc="Required: output resampled moving image (will have the same physical space as the fixedVolume).", exists=True) - outputDisplacementFieldVolume = File(desc="Output deformation field vector image (will have the same physical space as the fixedVolume).", exists=True) - outputCheckerboardVolume = File(desc="Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", exists=True) + outputVolume = File( + desc= + "Required: output resampled moving image (will have the same physical space as the fixedVolume).", + exists=True) + outputDisplacementFieldVolume = File( + desc= + "Output deformation field vector image (will have the same physical space as the fixedVolume).", + exists=True) + outputCheckerboardVolume = File( + desc= + "Genete a checkerboard image volume between the fixedVolume and the deformed movingVolume.", + exists=True) class BRAINSDemonWarp(SEMLikeCommandLine): @@ -231,4 +608,8 @@ class BRAINSDemonWarp(SEMLikeCommandLine): input_spec = BRAINSDemonWarpInputSpec output_spec = BRAINSDemonWarpOutputSpec _cmd = "BRAINSDemonWarp " - _outputs_filenames = {'outputVolume': 'outputVolume.nii', 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd'} + _outputs_filenames = { + 'outputVolume': 'outputVolume.nii', + 'outputCheckerboardVolume': 'outputCheckerboardVolume.nii', + 'outputDisplacementFieldVolume': 'outputDisplacementFieldVolume.nrrd' + } diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py b/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py index fe5c7895f4..dec0f9ebd4 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py @@ -4,38 +4,36 @@ def test_ACPCTransform_inputs(): - input_map = dict(acpc=dict(argstr='--acpc %s...', - ), - args=dict(argstr='%s', - ), - debugSwitch=dict(argstr='--debugSwitch ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - midline=dict(argstr='--midline %s...', - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + acpc=dict(argstr='--acpc %s...', ), + args=dict(argstr='%s', ), + debugSwitch=dict(argstr='--debugSwitch ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + midline=dict(argstr='--midline %s...', ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ACPCTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ACPCTransform_outputs(): - output_map = dict(outputTransform=dict(), - ) + output_map = dict(outputTransform=dict(), ) outputs = ACPCTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py index 3df134093f..535122ef38 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py @@ -4,120 +4,106 @@ def test_BRAINSDemonWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - arrayOfPyramidLevelIterations=dict(argstr='--arrayOfPyramidLevelIterations %s', - sep=',', - ), - backgroundFillValue=dict(argstr='--backgroundFillValue %d', - ), - checkerboardPatternSubdivisions=dict(argstr='--checkerboardPatternSubdivisions %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', - ), - fixedVolume=dict(argstr='--fixedVolume %s', - ), - gradient_type=dict(argstr='--gradient_type %s', - ), - gui=dict(argstr='--gui ', - ), - histogramMatch=dict(argstr='--histogramMatch ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initializeWithDisplacementField=dict(argstr='--initializeWithDisplacementField %s', - ), - initializeWithTransform=dict(argstr='--initializeWithTransform %s', - ), - inputPixelType=dict(argstr='--inputPixelType %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', - ), - maskProcessingMode=dict(argstr='--maskProcessingMode %s', - ), - max_step_length=dict(argstr='--max_step_length %f', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - minimumFixedPyramid=dict(argstr='--minimumFixedPyramid %s', - sep=',', - ), - minimumMovingPyramid=dict(argstr='--minimumMovingPyramid %s', - sep=',', - ), - movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', - ), - movingVolume=dict(argstr='--movingVolume %s', - ), - neighborhoodForBOBF=dict(argstr='--neighborhoodForBOBF %s', - sep=',', - ), - numberOfBCHApproximationTerms=dict(argstr='--numberOfBCHApproximationTerms %d', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputCheckerboardVolume=dict(argstr='--outputCheckerboardVolume %s', - hash_files=False, - ), - outputDebug=dict(argstr='--outputDebug ', - ), - outputDisplacementFieldPrefix=dict(argstr='--outputDisplacementFieldPrefix %s', - ), - outputDisplacementFieldVolume=dict(argstr='--outputDisplacementFieldVolume %s', - hash_files=False, - ), - outputNormalized=dict(argstr='--outputNormalized ', - ), - outputPixelType=dict(argstr='--outputPixelType %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - promptUser=dict(argstr='--promptUser ', - ), - registrationFilterType=dict(argstr='--registrationFilterType %s', - ), - seedForBOBF=dict(argstr='--seedForBOBF %s', - sep=',', - ), - smoothDisplacementFieldSigma=dict(argstr='--smoothDisplacementFieldSigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', - ), - upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', - ), - use_vanilla_dem=dict(argstr='--use_vanilla_dem ', - ), + input_map = dict( + args=dict(argstr='%s', ), + arrayOfPyramidLevelIterations=dict( + argstr='--arrayOfPyramidLevelIterations %s', + sep=',', + ), + backgroundFillValue=dict(argstr='--backgroundFillValue %d', ), + checkerboardPatternSubdivisions=dict( + argstr='--checkerboardPatternSubdivisions %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', ), + fixedVolume=dict(argstr='--fixedVolume %s', ), + gradient_type=dict(argstr='--gradient_type %s', ), + gui=dict(argstr='--gui ', ), + histogramMatch=dict(argstr='--histogramMatch ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initializeWithDisplacementField=dict( + argstr='--initializeWithDisplacementField %s', ), + initializeWithTransform=dict(argstr='--initializeWithTransform %s', ), + inputPixelType=dict(argstr='--inputPixelType %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', ), + maskProcessingMode=dict(argstr='--maskProcessingMode %s', ), + max_step_length=dict(argstr='--max_step_length %f', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + minimumFixedPyramid=dict( + argstr='--minimumFixedPyramid %s', + sep=',', + ), + minimumMovingPyramid=dict( + argstr='--minimumMovingPyramid %s', + sep=',', + ), + movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', ), + movingVolume=dict(argstr='--movingVolume %s', ), + neighborhoodForBOBF=dict( + argstr='--neighborhoodForBOBF %s', + sep=',', + ), + numberOfBCHApproximationTerms=dict( + argstr='--numberOfBCHApproximationTerms %d', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputCheckerboardVolume=dict( + argstr='--outputCheckerboardVolume %s', + hash_files=False, + ), + outputDebug=dict(argstr='--outputDebug ', ), + outputDisplacementFieldPrefix=dict( + argstr='--outputDisplacementFieldPrefix %s', ), + outputDisplacementFieldVolume=dict( + argstr='--outputDisplacementFieldVolume %s', + hash_files=False, + ), + outputNormalized=dict(argstr='--outputNormalized ', ), + outputPixelType=dict(argstr='--outputPixelType %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + promptUser=dict(argstr='--promptUser ', ), + registrationFilterType=dict(argstr='--registrationFilterType %s', ), + seedForBOBF=dict( + argstr='--seedForBOBF %s', + sep=',', + ), + smoothDisplacementFieldSigma=dict( + argstr='--smoothDisplacementFieldSigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', ), + upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', ), + use_vanilla_dem=dict(argstr='--use_vanilla_dem ', ), ) inputs = BRAINSDemonWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSDemonWarp_outputs(): - output_map = dict(outputCheckerboardVolume=dict(), - outputDisplacementFieldVolume=dict(), - outputVolume=dict(), + output_map = dict( + outputCheckerboardVolume=dict(), + outputDisplacementFieldVolume=dict(), + outputVolume=dict(), ) outputs = BRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py index 943629d5cc..970f335d21 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py @@ -4,169 +4,145 @@ def test_BRAINSFit_inputs(): - input_map = dict(NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00=dict(argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 ', - ), - NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01=dict(argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 ', - ), - NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02=dict(argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 ', - ), - ROIAutoClosingSize=dict(argstr='--ROIAutoClosingSize %f', - ), - ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', - ), - args=dict(argstr='%s', - ), - backgroundFillValue=dict(argstr='--backgroundFillValue %f', - ), - bsplineTransform=dict(argstr='--bsplineTransform %s', - hash_files=False, - ), - costFunctionConvergenceFactor=dict(argstr='--costFunctionConvergenceFactor %f', - ), - costMetric=dict(argstr='--costMetric %s', - ), - debugLevel=dict(argstr='--debugLevel %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - failureExitCode=dict(argstr='--failureExitCode %d', - ), - fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', - ), - fixedVolume=dict(argstr='--fixedVolume %s', - ), - fixedVolumeTimeIndex=dict(argstr='--fixedVolumeTimeIndex %d', - ), - forceMINumberOfThreads=dict(argstr='--forceMINumberOfThreads %d', - ), - gui=dict(argstr='--gui ', - ), - histogramMatch=dict(argstr='--histogramMatch ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initialTransform=dict(argstr='--initialTransform %s', - ), - initializeTransformMode=dict(argstr='--initializeTransformMode %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - linearTransform=dict(argstr='--linearTransform %s', - hash_files=False, - ), - maskInferiorCutOffFromCenter=dict(argstr='--maskInferiorCutOffFromCenter %f', - ), - maskProcessingMode=dict(argstr='--maskProcessingMode %s', - ), - maxBSplineDisplacement=dict(argstr='--maxBSplineDisplacement %f', - ), - maximumStepLength=dict(argstr='--maximumStepLength %f', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - minimumStepLength=dict(argstr='--minimumStepLength %s', - sep=',', - ), - movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', - ), - movingVolume=dict(argstr='--movingVolume %s', - ), - movingVolumeTimeIndex=dict(argstr='--movingVolumeTimeIndex %d', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfIterations=dict(argstr='--numberOfIterations %s', - sep=',', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - numberOfSamples=dict(argstr='--numberOfSamples %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputFixedVolumeROI=dict(argstr='--outputFixedVolumeROI %s', - hash_files=False, - ), - outputMovingVolumeROI=dict(argstr='--outputMovingVolumeROI %s', - hash_files=False, - ), - outputTransform=dict(argstr='--outputTransform %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', - ), - permitParameterVariation=dict(argstr='--permitParameterVariation %s', - sep=',', - ), - projectedGradientTolerance=dict(argstr='--projectedGradientTolerance %f', - ), - promptUser=dict(argstr='--promptUser ', - ), - relaxationFactor=dict(argstr='--relaxationFactor %f', - ), - removeIntensityOutliers=dict(argstr='--removeIntensityOutliers %f', - ), - reproportionScale=dict(argstr='--reproportionScale %f', - ), - scaleOutputValues=dict(argstr='--scaleOutputValues ', - ), - skewScale=dict(argstr='--skewScale %f', - ), - splineGridSize=dict(argstr='--splineGridSize %s', - sep=',', - ), - strippedOutputTransform=dict(argstr='--strippedOutputTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - sep=',', - ), - translationScale=dict(argstr='--translationScale %f', - ), - useAffine=dict(argstr='--useAffine ', - ), - useBSpline=dict(argstr='--useBSpline ', - ), - useCachingOfBSplineWeightsMode=dict(argstr='--useCachingOfBSplineWeightsMode %s', - ), - useExplicitPDFDerivativesMode=dict(argstr='--useExplicitPDFDerivativesMode %s', - ), - useRigid=dict(argstr='--useRigid ', - ), - useScaleSkewVersor3D=dict(argstr='--useScaleSkewVersor3D ', - ), - useScaleVersor3D=dict(argstr='--useScaleVersor3D ', - ), - writeOutputTransformInFloat=dict(argstr='--writeOutputTransformInFloat ', - ), - writeTransformOnFailure=dict(argstr='--writeTransformOnFailure ', - ), + input_map = dict( + NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00=dict( + argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 ', ), + NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01=dict( + argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 ', ), + NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02=dict( + argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 ', ), + ROIAutoClosingSize=dict(argstr='--ROIAutoClosingSize %f', ), + ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', ), + args=dict(argstr='%s', ), + backgroundFillValue=dict(argstr='--backgroundFillValue %f', ), + bsplineTransform=dict( + argstr='--bsplineTransform %s', + hash_files=False, + ), + costFunctionConvergenceFactor=dict( + argstr='--costFunctionConvergenceFactor %f', ), + costMetric=dict(argstr='--costMetric %s', ), + debugLevel=dict(argstr='--debugLevel %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + failureExitCode=dict(argstr='--failureExitCode %d', ), + fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', ), + fixedVolume=dict(argstr='--fixedVolume %s', ), + fixedVolumeTimeIndex=dict(argstr='--fixedVolumeTimeIndex %d', ), + forceMINumberOfThreads=dict(argstr='--forceMINumberOfThreads %d', ), + gui=dict(argstr='--gui ', ), + histogramMatch=dict(argstr='--histogramMatch ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initialTransform=dict(argstr='--initialTransform %s', ), + initializeTransformMode=dict(argstr='--initializeTransformMode %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + linearTransform=dict( + argstr='--linearTransform %s', + hash_files=False, + ), + maskInferiorCutOffFromCenter=dict( + argstr='--maskInferiorCutOffFromCenter %f', ), + maskProcessingMode=dict(argstr='--maskProcessingMode %s', ), + maxBSplineDisplacement=dict(argstr='--maxBSplineDisplacement %f', ), + maximumStepLength=dict(argstr='--maximumStepLength %f', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + minimumStepLength=dict( + argstr='--minimumStepLength %s', + sep=',', + ), + movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', ), + movingVolume=dict(argstr='--movingVolume %s', ), + movingVolumeTimeIndex=dict(argstr='--movingVolumeTimeIndex %d', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfIterations=dict( + argstr='--numberOfIterations %s', + sep=',', + ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + numberOfSamples=dict(argstr='--numberOfSamples %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputFixedVolumeROI=dict( + argstr='--outputFixedVolumeROI %s', + hash_files=False, + ), + outputMovingVolumeROI=dict( + argstr='--outputMovingVolumeROI %s', + hash_files=False, + ), + outputTransform=dict( + argstr='--outputTransform %s', + hash_files=False, + ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', ), + permitParameterVariation=dict( + argstr='--permitParameterVariation %s', + sep=',', + ), + projectedGradientTolerance=dict( + argstr='--projectedGradientTolerance %f', ), + promptUser=dict(argstr='--promptUser ', ), + relaxationFactor=dict(argstr='--relaxationFactor %f', ), + removeIntensityOutliers=dict(argstr='--removeIntensityOutliers %f', ), + reproportionScale=dict(argstr='--reproportionScale %f', ), + scaleOutputValues=dict(argstr='--scaleOutputValues ', ), + skewScale=dict(argstr='--skewScale %f', ), + splineGridSize=dict( + argstr='--splineGridSize %s', + sep=',', + ), + strippedOutputTransform=dict( + argstr='--strippedOutputTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict( + argstr='--transformType %s', + sep=',', + ), + translationScale=dict(argstr='--translationScale %f', ), + useAffine=dict(argstr='--useAffine ', ), + useBSpline=dict(argstr='--useBSpline ', ), + useCachingOfBSplineWeightsMode=dict( + argstr='--useCachingOfBSplineWeightsMode %s', ), + useExplicitPDFDerivativesMode=dict( + argstr='--useExplicitPDFDerivativesMode %s', ), + useRigid=dict(argstr='--useRigid ', ), + useScaleSkewVersor3D=dict(argstr='--useScaleSkewVersor3D ', ), + useScaleVersor3D=dict(argstr='--useScaleVersor3D ', ), + writeOutputTransformInFloat=dict( + argstr='--writeOutputTransformInFloat ', ), + writeTransformOnFailure=dict(argstr='--writeTransformOnFailure ', ), ) inputs = BRAINSFit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSFit_outputs(): - output_map = dict(bsplineTransform=dict(), - linearTransform=dict(), - outputFixedVolumeROI=dict(), - outputMovingVolumeROI=dict(), - outputTransform=dict(), - outputVolume=dict(), - strippedOutputTransform=dict(), + output_map = dict( + bsplineTransform=dict(), + linearTransform=dict(), + outputFixedVolumeROI=dict(), + outputMovingVolumeROI=dict(), + outputTransform=dict(), + outputVolume=dict(), + strippedOutputTransform=dict(), ) outputs = BRAINSFit.output_spec() diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py index a2444018e2..5a6e0beefe 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py @@ -4,53 +4,46 @@ def test_BRAINSResample_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - defaultValue=dict(argstr='--defaultValue %f', - ), - deformationVolume=dict(argstr='--deformationVolume %s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gridSpacing=dict(argstr='--gridSpacing %s', - sep=',', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - inverseTransform=dict(argstr='--inverseTransform ', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - pixelType=dict(argstr='--pixelType %s', - ), - referenceVolume=dict(argstr='--referenceVolume %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - warpTransform=dict(argstr='--warpTransform %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + defaultValue=dict(argstr='--defaultValue %f', ), + deformationVolume=dict(argstr='--deformationVolume %s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridSpacing=dict( + argstr='--gridSpacing %s', + sep=',', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + inverseTransform=dict(argstr='--inverseTransform ', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + pixelType=dict(argstr='--pixelType %s', ), + referenceVolume=dict(argstr='--referenceVolume %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + warpTransform=dict(argstr='--warpTransform %s', ), ) inputs = BRAINSResample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSResample_outputs(): - output_map = dict(outputVolume=dict(), - ) + output_map = dict(outputVolume=dict(), ) outputs = BRAINSResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py b/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py index 81d4422012..67c009c8c2 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py @@ -4,42 +4,38 @@ def test_FiducialRegistration_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedLandmarks=dict(argstr='--fixedLandmarks %s...', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - movingLandmarks=dict(argstr='--movingLandmarks %s...', - ), - outputMessage=dict(argstr='--outputMessage %s', - ), - rms=dict(argstr='--rms %f', - ), - saveTransform=dict(argstr='--saveTransform %s', - hash_files=False, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transformType=dict(argstr='--transformType %s', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedLandmarks=dict(argstr='--fixedLandmarks %s...', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + movingLandmarks=dict(argstr='--movingLandmarks %s...', ), + outputMessage=dict(argstr='--outputMessage %s', ), + rms=dict(argstr='--rms %f', ), + saveTransform=dict( + argstr='--saveTransform %s', + hash_files=False, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transformType=dict(argstr='--transformType %s', ), ) inputs = FiducialRegistration.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FiducialRegistration_outputs(): - output_map = dict(saveTransform=dict(), - ) + output_map = dict(saveTransform=dict(), ) outputs = FiducialRegistration.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py b/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py index 1fd9c45b34..d4e7c12a7f 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py @@ -4,123 +4,110 @@ def test_VBRAINSDemonWarp_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - arrayOfPyramidLevelIterations=dict(argstr='--arrayOfPyramidLevelIterations %s', - sep=',', - ), - backgroundFillValue=dict(argstr='--backgroundFillValue %d', - ), - checkerboardPatternSubdivisions=dict(argstr='--checkerboardPatternSubdivisions %s', - sep=',', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', - ), - fixedVolume=dict(argstr='--fixedVolume %s...', - ), - gradient_type=dict(argstr='--gradient_type %s', - ), - gui=dict(argstr='--gui ', - ), - histogramMatch=dict(argstr='--histogramMatch ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - initializeWithDisplacementField=dict(argstr='--initializeWithDisplacementField %s', - ), - initializeWithTransform=dict(argstr='--initializeWithTransform %s', - ), - inputPixelType=dict(argstr='--inputPixelType %s', - ), - interpolationMode=dict(argstr='--interpolationMode %s', - ), - lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', - ), - makeBOBF=dict(argstr='--makeBOBF ', - ), - max_step_length=dict(argstr='--max_step_length %f', - ), - medianFilterSize=dict(argstr='--medianFilterSize %s', - sep=',', - ), - minimumFixedPyramid=dict(argstr='--minimumFixedPyramid %s', - sep=',', - ), - minimumMovingPyramid=dict(argstr='--minimumMovingPyramid %s', - sep=',', - ), - movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', - ), - movingVolume=dict(argstr='--movingVolume %s...', - ), - neighborhoodForBOBF=dict(argstr='--neighborhoodForBOBF %s', - sep=',', - ), - numberOfBCHApproximationTerms=dict(argstr='--numberOfBCHApproximationTerms %d', - ), - numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', - ), - numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', - ), - numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - outputCheckerboardVolume=dict(argstr='--outputCheckerboardVolume %s', - hash_files=False, - ), - outputDebug=dict(argstr='--outputDebug ', - ), - outputDisplacementFieldPrefix=dict(argstr='--outputDisplacementFieldPrefix %s', - ), - outputDisplacementFieldVolume=dict(argstr='--outputDisplacementFieldVolume %s', - hash_files=False, - ), - outputNormalized=dict(argstr='--outputNormalized ', - ), - outputPixelType=dict(argstr='--outputPixelType %s', - ), - outputVolume=dict(argstr='--outputVolume %s', - hash_files=False, - ), - promptUser=dict(argstr='--promptUser ', - ), - registrationFilterType=dict(argstr='--registrationFilterType %s', - ), - seedForBOBF=dict(argstr='--seedForBOBF %s', - sep=',', - ), - smoothDisplacementFieldSigma=dict(argstr='--smoothDisplacementFieldSigma %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', - ), - upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', - ), - use_vanilla_dem=dict(argstr='--use_vanilla_dem ', - ), - weightFactors=dict(argstr='--weightFactors %s', - sep=',', - ), + input_map = dict( + args=dict(argstr='%s', ), + arrayOfPyramidLevelIterations=dict( + argstr='--arrayOfPyramidLevelIterations %s', + sep=',', + ), + backgroundFillValue=dict(argstr='--backgroundFillValue %d', ), + checkerboardPatternSubdivisions=dict( + argstr='--checkerboardPatternSubdivisions %s', + sep=',', + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s', ), + fixedVolume=dict(argstr='--fixedVolume %s...', ), + gradient_type=dict(argstr='--gradient_type %s', ), + gui=dict(argstr='--gui ', ), + histogramMatch=dict(argstr='--histogramMatch ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + initializeWithDisplacementField=dict( + argstr='--initializeWithDisplacementField %s', ), + initializeWithTransform=dict(argstr='--initializeWithTransform %s', ), + inputPixelType=dict(argstr='--inputPixelType %s', ), + interpolationMode=dict(argstr='--interpolationMode %s', ), + lowerThresholdForBOBF=dict(argstr='--lowerThresholdForBOBF %d', ), + makeBOBF=dict(argstr='--makeBOBF ', ), + max_step_length=dict(argstr='--max_step_length %f', ), + medianFilterSize=dict( + argstr='--medianFilterSize %s', + sep=',', + ), + minimumFixedPyramid=dict( + argstr='--minimumFixedPyramid %s', + sep=',', + ), + minimumMovingPyramid=dict( + argstr='--minimumMovingPyramid %s', + sep=',', + ), + movingBinaryVolume=dict(argstr='--movingBinaryVolume %s', ), + movingVolume=dict(argstr='--movingVolume %s...', ), + neighborhoodForBOBF=dict( + argstr='--neighborhoodForBOBF %s', + sep=',', + ), + numberOfBCHApproximationTerms=dict( + argstr='--numberOfBCHApproximationTerms %d', ), + numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d', ), + numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), + numberOfPyramidLevels=dict(argstr='--numberOfPyramidLevels %d', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + outputCheckerboardVolume=dict( + argstr='--outputCheckerboardVolume %s', + hash_files=False, + ), + outputDebug=dict(argstr='--outputDebug ', ), + outputDisplacementFieldPrefix=dict( + argstr='--outputDisplacementFieldPrefix %s', ), + outputDisplacementFieldVolume=dict( + argstr='--outputDisplacementFieldVolume %s', + hash_files=False, + ), + outputNormalized=dict(argstr='--outputNormalized ', ), + outputPixelType=dict(argstr='--outputPixelType %s', ), + outputVolume=dict( + argstr='--outputVolume %s', + hash_files=False, + ), + promptUser=dict(argstr='--promptUser ', ), + registrationFilterType=dict(argstr='--registrationFilterType %s', ), + seedForBOBF=dict( + argstr='--seedForBOBF %s', + sep=',', + ), + smoothDisplacementFieldSigma=dict( + argstr='--smoothDisplacementFieldSigma %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + upFieldSmoothing=dict(argstr='--upFieldSmoothing %f', ), + upperThresholdForBOBF=dict(argstr='--upperThresholdForBOBF %d', ), + use_vanilla_dem=dict(argstr='--use_vanilla_dem ', ), + weightFactors=dict( + argstr='--weightFactors %s', + sep=',', + ), ) inputs = VBRAINSDemonWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VBRAINSDemonWarp_outputs(): - output_map = dict(outputCheckerboardVolume=dict(), - outputDisplacementFieldVolume=dict(), - outputVolume=dict(), + output_map = dict( + outputCheckerboardVolume=dict(), + outputDisplacementFieldVolume=dict(), + outputVolume=dict(), ) outputs = VBRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/slicer/segmentation/__init__.py b/nipype/interfaces/slicer/segmentation/__init__.py index d4ebe74d7b..d966f07e27 100644 --- a/nipype/interfaces/slicer/segmentation/__init__.py +++ b/nipype/interfaces/slicer/segmentation/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import -from .specialized import RobustStatisticsSegmenter, EMSegmentCommandLine, BRAINSROIAuto +from .specialized import (RobustStatisticsSegmenter, EMSegmentCommandLine, + BRAINSROIAuto) from .simpleregiongrowingsegmentation import SimpleRegionGrowingSegmentation diff --git a/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py b/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py index 6e444a56a3..d466ccc1ac 100644 --- a/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py +++ b/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py @@ -8,15 +8,41 @@ class SimpleRegionGrowingSegmentationInputSpec(CommandLineInputSpec): - smoothingIterations = traits.Int(desc="Number of smoothing iterations", argstr="--smoothingIterations %d") - timestep = traits.Float(desc="Timestep for curvature flow", argstr="--timestep %f") - iterations = traits.Int(desc="Number of iterations of region growing", argstr="--iterations %d") - multiplier = traits.Float(desc="Number of standard deviations to include in intensity model", argstr="--multiplier %f") - neighborhood = traits.Int(desc="The radius of the neighborhood over which to calculate intensity model", argstr="--neighborhood %d") - labelvalue = traits.Int(desc="The integer value (0-255) to use for the segmentation results. This will determine the color of the segmentation that will be generated by the Region growing algorithm", argstr="--labelvalue %d") - seed = InputMultiPath(traits.List(traits.Float(), minlen=3, maxlen=3), desc="Seed point(s) for region growing", argstr="--seed %s...") - inputVolume = File(position=-2, desc="Input volume to be filtered", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output filtered", argstr="%s") + smoothingIterations = traits.Int( + desc="Number of smoothing iterations", + argstr="--smoothingIterations %d") + timestep = traits.Float( + desc="Timestep for curvature flow", argstr="--timestep %f") + iterations = traits.Int( + desc="Number of iterations of region growing", + argstr="--iterations %d") + multiplier = traits.Float( + desc="Number of standard deviations to include in intensity model", + argstr="--multiplier %f") + neighborhood = traits.Int( + desc= + "The radius of the neighborhood over which to calculate intensity model", + argstr="--neighborhood %d") + labelvalue = traits.Int( + desc= + "The integer value (0-255) to use for the segmentation results. This will determine the color of the segmentation that will be generated by the Region growing algorithm", + argstr="--labelvalue %d") + seed = InputMultiPath( + traits.List(traits.Float(), minlen=3, maxlen=3), + desc="Seed point(s) for region growing", + argstr="--seed %s...") + inputVolume = File( + position=-2, + desc="Input volume to be filtered", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output filtered", + argstr="%s") class SimpleRegionGrowingSegmentationOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/slicer/segmentation/specialized.py b/nipype/interfaces/slicer/segmentation/specialized.py index 2fb6131348..fdfeb74e37 100644 --- a/nipype/interfaces/slicer/segmentation/specialized.py +++ b/nipype/interfaces/slicer/segmentation/specialized.py @@ -8,18 +8,44 @@ class RobustStatisticsSegmenterInputSpec(CommandLineInputSpec): - expectedVolume = traits.Float(desc="The approximate volume of the object, in mL.", argstr="--expectedVolume %f") - intensityHomogeneity = traits.Float(desc="What is the homogeneity of intensity within the object? Given constant intensity at 1.0 score and extreme fluctuating intensity at 0.", argstr="--intensityHomogeneity %f") - curvatureWeight = traits.Float(desc="Given sphere 1.0 score and extreme rough bounday/surface 0 score, what is the expected smoothness of the object?", argstr="--curvatureWeight %f") - labelValue = traits.Int(desc="Label value of the output image", argstr="--labelValue %d") - maxRunningTime = traits.Float(desc="The program will stop if this time is reached.", argstr="--maxRunningTime %f") - originalImageFileName = File(position=-3, desc="Original image to be segmented", exists=True, argstr="%s") - labelImageFileName = File(position=-2, desc="Label image for initialization", exists=True, argstr="%s") - segmentedImageFileName = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Segmented image", argstr="%s") + expectedVolume = traits.Float( + desc="The approximate volume of the object, in mL.", + argstr="--expectedVolume %f") + intensityHomogeneity = traits.Float( + desc= + "What is the homogeneity of intensity within the object? Given constant intensity at 1.0 score and extreme fluctuating intensity at 0.", + argstr="--intensityHomogeneity %f") + curvatureWeight = traits.Float( + desc= + "Given sphere 1.0 score and extreme rough bounday/surface 0 score, what is the expected smoothness of the object?", + argstr="--curvatureWeight %f") + labelValue = traits.Int( + desc="Label value of the output image", argstr="--labelValue %d") + maxRunningTime = traits.Float( + desc="The program will stop if this time is reached.", + argstr="--maxRunningTime %f") + originalImageFileName = File( + position=-3, + desc="Original image to be segmented", + exists=True, + argstr="%s") + labelImageFileName = File( + position=-2, + desc="Label image for initialization", + exists=True, + argstr="%s") + segmentedImageFileName = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Segmented image", + argstr="%s") class RobustStatisticsSegmenterOutputSpec(TraitedSpec): - segmentedImageFileName = File(position=-1, desc="Segmented image", exists=True) + segmentedImageFileName = File( + position=-1, desc="Segmented image", exists=True) class RobustStatisticsSegmenter(SEMLikeCommandLine): @@ -42,37 +68,116 @@ class RobustStatisticsSegmenter(SEMLikeCommandLine): input_spec = RobustStatisticsSegmenterInputSpec output_spec = RobustStatisticsSegmenterOutputSpec _cmd = "RobustStatisticsSegmenter " - _outputs_filenames = {'segmentedImageFileName': 'segmentedImageFileName.nii'} + _outputs_filenames = { + 'segmentedImageFileName': 'segmentedImageFileName.nii' + } class EMSegmentCommandLineInputSpec(CommandLineInputSpec): - mrmlSceneFileName = File(desc="Active MRML scene that contains EMSegment algorithm parameters.", exists=True, argstr="--mrmlSceneFileName %s") - resultVolumeFileName = traits.Either(traits.Bool, File(), hash_files=False, desc="The file name that the segmentation result volume will be written to.", argstr="--resultVolumeFileName %s") - targetVolumeFileNames = InputMultiPath(File(exists=True), desc="File names of target volumes (to be segmented). The number of target images must be equal to the number of target images specified in the parameter set, and these images must be spatially aligned.", argstr="--targetVolumeFileNames %s...") - intermediateResultsDirectory = Directory(desc="Directory where EMSegmenter will write intermediate data (e.g., aligned atlas data).", exists=True, argstr="--intermediateResultsDirectory %s") - parametersMRMLNodeName = traits.Str(desc="The name of the EMSegment parameters node within the active MRML scene. Leave blank for default.", argstr="--parametersMRMLNodeName %s") - disableMultithreading = traits.Int(desc="Disable multithreading for the EMSegmenter algorithm only! Preprocessing might still run in multi-threaded mode. -1: Do not overwrite default value. 0: Disable. 1: Enable.", argstr="--disableMultithreading %d") - dontUpdateIntermediateData = traits.Int(desc="Disable update of intermediate results. -1: Do not overwrite default value. 0: Disable. 1: Enable.", argstr="--dontUpdateIntermediateData %d") + mrmlSceneFileName = File( + desc="Active MRML scene that contains EMSegment algorithm parameters.", + exists=True, + argstr="--mrmlSceneFileName %s") + resultVolumeFileName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "The file name that the segmentation result volume will be written to.", + argstr="--resultVolumeFileName %s") + targetVolumeFileNames = InputMultiPath( + File(exists=True), + desc= + "File names of target volumes (to be segmented). The number of target images must be equal to the number of target images specified in the parameter set, and these images must be spatially aligned.", + argstr="--targetVolumeFileNames %s...") + intermediateResultsDirectory = Directory( + desc= + "Directory where EMSegmenter will write intermediate data (e.g., aligned atlas data).", + exists=True, + argstr="--intermediateResultsDirectory %s") + parametersMRMLNodeName = traits.Str( + desc= + "The name of the EMSegment parameters node within the active MRML scene. Leave blank for default.", + argstr="--parametersMRMLNodeName %s") + disableMultithreading = traits.Int( + desc= + "Disable multithreading for the EMSegmenter algorithm only! Preprocessing might still run in multi-threaded mode. -1: Do not overwrite default value. 0: Disable. 1: Enable.", + argstr="--disableMultithreading %d") + dontUpdateIntermediateData = traits.Int( + desc= + "Disable update of intermediate results. -1: Do not overwrite default value. 0: Disable. 1: Enable.", + argstr="--dontUpdateIntermediateData %d") verbose = traits.Bool(desc="Enable verbose output.", argstr="--verbose ") - loadTargetCentered = traits.Bool(desc="Read target files centered.", argstr="--loadTargetCentered ") - loadAtlasNonCentered = traits.Bool(desc="Read atlas files non-centered.", argstr="--loadAtlasNonCentered ") - taskPreProcessingSetting = traits.Str(desc="Specifies the different task parameter. Leave blank for default.", argstr="--taskPreProcessingSetting %s") - keepTempFiles = traits.Bool(desc="If flag is set then at the end of command the temporary files are not removed", argstr="--keepTempFiles ") - resultStandardVolumeFileName = File(desc="Used for testing. Compare segmentation results to this image and return EXIT_FAILURE if they do not match.", exists=True, argstr="--resultStandardVolumeFileName %s") - dontWriteResults = traits.Bool(desc="Used for testing. Don't actually write the resulting labelmap to disk.", argstr="--dontWriteResults ") - generateEmptyMRMLSceneAndQuit = traits.Either(traits.Bool, File(), hash_files=False, desc="Used for testing. Only write a scene with default mrml parameters.", argstr="--generateEmptyMRMLSceneAndQuit %s") - resultMRMLSceneFileName = traits.Either(traits.Bool, File(), hash_files=False, desc="Write out the MRML scene after command line substitutions have been made.", argstr="--resultMRMLSceneFileName %s") - disableCompression = traits.Bool(desc="Don't use compression when writing result image to disk.", argstr="--disableCompression ") - atlasVolumeFileNames = InputMultiPath(File(exists=True), desc="Use an alternative atlas to the one that is specified by the mrml file - note the order matters ! ", argstr="--atlasVolumeFileNames %s...") - registrationPackage = traits.Str(desc="specify the registration package for preprocessing (CMTK or BRAINS or PLASTIMATCH or DEMONS)", argstr="--registrationPackage %s") - registrationAffineType = traits.Int(desc="specify the accuracy of the affine registration. -2: Do not overwrite default, -1: Test, 0: Disable, 1: Fast, 2: Accurate", argstr="--registrationAffineType %d") - registrationDeformableType = traits.Int(desc="specify the accuracy of the deformable registration. -2: Do not overwrite default, -1: Test, 0: Disable, 1: Fast, 2: Accurate", argstr="--registrationDeformableType %d") + loadTargetCentered = traits.Bool( + desc="Read target files centered.", argstr="--loadTargetCentered ") + loadAtlasNonCentered = traits.Bool( + desc="Read atlas files non-centered.", + argstr="--loadAtlasNonCentered ") + taskPreProcessingSetting = traits.Str( + desc="Specifies the different task parameter. Leave blank for default.", + argstr="--taskPreProcessingSetting %s") + keepTempFiles = traits.Bool( + desc= + "If flag is set then at the end of command the temporary files are not removed", + argstr="--keepTempFiles ") + resultStandardVolumeFileName = File( + desc= + "Used for testing. Compare segmentation results to this image and return EXIT_FAILURE if they do not match.", + exists=True, + argstr="--resultStandardVolumeFileName %s") + dontWriteResults = traits.Bool( + desc= + "Used for testing. Don't actually write the resulting labelmap to disk.", + argstr="--dontWriteResults ") + generateEmptyMRMLSceneAndQuit = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Used for testing. Only write a scene with default mrml parameters.", + argstr="--generateEmptyMRMLSceneAndQuit %s") + resultMRMLSceneFileName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Write out the MRML scene after command line substitutions have been made.", + argstr="--resultMRMLSceneFileName %s") + disableCompression = traits.Bool( + desc="Don't use compression when writing result image to disk.", + argstr="--disableCompression ") + atlasVolumeFileNames = InputMultiPath( + File(exists=True), + desc= + "Use an alternative atlas to the one that is specified by the mrml file - note the order matters ! ", + argstr="--atlasVolumeFileNames %s...") + registrationPackage = traits.Str( + desc= + "specify the registration package for preprocessing (CMTK or BRAINS or PLASTIMATCH or DEMONS)", + argstr="--registrationPackage %s") + registrationAffineType = traits.Int( + desc= + "specify the accuracy of the affine registration. -2: Do not overwrite default, -1: Test, 0: Disable, 1: Fast, 2: Accurate", + argstr="--registrationAffineType %d") + registrationDeformableType = traits.Int( + desc= + "specify the accuracy of the deformable registration. -2: Do not overwrite default, -1: Test, 0: Disable, 1: Fast, 2: Accurate", + argstr="--registrationDeformableType %d") class EMSegmentCommandLineOutputSpec(TraitedSpec): - resultVolumeFileName = File(desc="The file name that the segmentation result volume will be written to.", exists=True) - generateEmptyMRMLSceneAndQuit = File(desc="Used for testing. Only write a scene with default mrml parameters.", exists=True) - resultMRMLSceneFileName = File(desc="Write out the MRML scene after command line substitutions have been made.", exists=True) + resultVolumeFileName = File( + desc= + "The file name that the segmentation result volume will be written to.", + exists=True) + generateEmptyMRMLSceneAndQuit = File( + desc= + "Used for testing. Only write a scene with default mrml parameters.", + exists=True) + resultMRMLSceneFileName = File( + desc= + "Write out the MRML scene after command line substitutions have been made.", + exists=True) class EMSegmentCommandLine(SEMLikeCommandLine): @@ -100,24 +205,66 @@ class EMSegmentCommandLine(SEMLikeCommandLine): input_spec = EMSegmentCommandLineInputSpec output_spec = EMSegmentCommandLineOutputSpec _cmd = "EMSegmentCommandLine " - _outputs_filenames = {'generateEmptyMRMLSceneAndQuit': 'generateEmptyMRMLSceneAndQuit', 'resultMRMLSceneFileName': 'resultMRMLSceneFileName', 'resultVolumeFileName': 'resultVolumeFileName.mhd'} + _outputs_filenames = { + 'generateEmptyMRMLSceneAndQuit': 'generateEmptyMRMLSceneAndQuit', + 'resultMRMLSceneFileName': 'resultMRMLSceneFileName', + 'resultVolumeFileName': 'resultVolumeFileName.mhd' + } class BRAINSROIAutoInputSpec(CommandLineInputSpec): - inputVolume = File(desc="The input image for finding the largest region filled mask.", exists=True, argstr="--inputVolume %s") - outputROIMaskVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="The ROI automatically found from the input image.", argstr="--outputROIMaskVolume %s") - outputClippedVolumeROI = traits.Either(traits.Bool, File(), hash_files=False, desc="The inputVolume clipped to the region of the brain mask.", argstr="--outputClippedVolumeROI %s") - otsuPercentileThreshold = traits.Float(desc="Parameter to the Otsu threshold algorithm.", argstr="--otsuPercentileThreshold %f") - thresholdCorrectionFactor = traits.Float(desc="A factor to scale the Otsu algorithm's result threshold, in case clipping mangles the image.", argstr="--thresholdCorrectionFactor %f") - closingSize = traits.Float(desc="The Closing Size (in millimeters) for largest connected filled mask. This value is divided by image spacing and rounded to the next largest voxel number.", argstr="--closingSize %f") - ROIAutoDilateSize = traits.Float(desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f") - outputVolumePixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", desc="The output image Pixel Type is the scalar datatype for representation of the Output Volume.", argstr="--outputVolumePixelType %s") - numberOfThreads = traits.Int(desc="Explicitly specify the maximum number of threads to use.", argstr="--numberOfThreads %d") + inputVolume = File( + desc="The input image for finding the largest region filled mask.", + exists=True, + argstr="--inputVolume %s") + outputROIMaskVolume = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The ROI automatically found from the input image.", + argstr="--outputROIMaskVolume %s") + outputClippedVolumeROI = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc="The inputVolume clipped to the region of the brain mask.", + argstr="--outputClippedVolumeROI %s") + otsuPercentileThreshold = traits.Float( + desc="Parameter to the Otsu threshold algorithm.", + argstr="--otsuPercentileThreshold %f") + thresholdCorrectionFactor = traits.Float( + desc= + "A factor to scale the Otsu algorithm's result threshold, in case clipping mangles the image.", + argstr="--thresholdCorrectionFactor %f") + closingSize = traits.Float( + desc= + "The Closing Size (in millimeters) for largest connected filled mask. This value is divided by image spacing and rounded to the next largest voxel number.", + argstr="--closingSize %f") + ROIAutoDilateSize = traits.Float( + desc= + "This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", + argstr="--ROIAutoDilateSize %f") + outputVolumePixelType = traits.Enum( + "float", + "short", + "ushort", + "int", + "uint", + "uchar", + desc= + "The output image Pixel Type is the scalar datatype for representation of the Output Volume.", + argstr="--outputVolumePixelType %s") + numberOfThreads = traits.Int( + desc="Explicitly specify the maximum number of threads to use.", + argstr="--numberOfThreads %d") class BRAINSROIAutoOutputSpec(TraitedSpec): - outputROIMaskVolume = File(desc="The ROI automatically found from the input image.", exists=True) - outputClippedVolumeROI = File(desc="The inputVolume clipped to the region of the brain mask.", exists=True) + outputROIMaskVolume = File( + desc="The ROI automatically found from the input image.", exists=True) + outputClippedVolumeROI = File( + desc="The inputVolume clipped to the region of the brain mask.", + exists=True) class BRAINSROIAuto(SEMLikeCommandLine): @@ -141,4 +288,7 @@ class BRAINSROIAuto(SEMLikeCommandLine): input_spec = BRAINSROIAutoInputSpec output_spec = BRAINSROIAutoOutputSpec _cmd = "BRAINSROIAuto " - _outputs_filenames = {'outputROIMaskVolume': 'outputROIMaskVolume.nii', 'outputClippedVolumeROI': 'outputClippedVolumeROI.nii'} + _outputs_filenames = { + 'outputROIMaskVolume': 'outputROIMaskVolume.nii', + 'outputClippedVolumeROI': 'outputClippedVolumeROI.nii' + } diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py index 5b8a66ba36..50a99b523d 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py @@ -4,49 +4,47 @@ def test_BRAINSROIAuto_inputs(): - input_map = dict(ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', - ), - args=dict(argstr='%s', - ), - closingSize=dict(argstr='--closingSize %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='--inputVolume %s', - ), - numberOfThreads=dict(argstr='--numberOfThreads %d', - ), - otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', - ), - outputClippedVolumeROI=dict(argstr='--outputClippedVolumeROI %s', - hash_files=False, - ), - outputROIMaskVolume=dict(argstr='--outputROIMaskVolume %s', - hash_files=False, - ), - outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - thresholdCorrectionFactor=dict(argstr='--thresholdCorrectionFactor %f', - ), + input_map = dict( + ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f', ), + args=dict(argstr='%s', ), + closingSize=dict(argstr='--closingSize %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict(argstr='--inputVolume %s', ), + numberOfThreads=dict(argstr='--numberOfThreads %d', ), + otsuPercentileThreshold=dict(argstr='--otsuPercentileThreshold %f', ), + outputClippedVolumeROI=dict( + argstr='--outputClippedVolumeROI %s', + hash_files=False, + ), + outputROIMaskVolume=dict( + argstr='--outputROIMaskVolume %s', + hash_files=False, + ), + outputVolumePixelType=dict(argstr='--outputVolumePixelType %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + thresholdCorrectionFactor=dict( + argstr='--thresholdCorrectionFactor %f', ), ) inputs = BRAINSROIAuto.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BRAINSROIAuto_outputs(): - output_map = dict(outputClippedVolumeROI=dict(), - outputROIMaskVolume=dict(), + output_map = dict( + outputClippedVolumeROI=dict(), + outputROIMaskVolume=dict(), ) outputs = BRAINSROIAuto.output_spec() diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py index e09922f0b1..65fba20d24 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py @@ -4,75 +4,67 @@ def test_EMSegmentCommandLine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - atlasVolumeFileNames=dict(argstr='--atlasVolumeFileNames %s...', - ), - disableCompression=dict(argstr='--disableCompression ', - ), - disableMultithreading=dict(argstr='--disableMultithreading %d', - ), - dontUpdateIntermediateData=dict(argstr='--dontUpdateIntermediateData %d', - ), - dontWriteResults=dict(argstr='--dontWriteResults ', - ), - environ=dict(nohash=True, - usedefault=True, - ), - generateEmptyMRMLSceneAndQuit=dict(argstr='--generateEmptyMRMLSceneAndQuit %s', - hash_files=False, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - intermediateResultsDirectory=dict(argstr='--intermediateResultsDirectory %s', - ), - keepTempFiles=dict(argstr='--keepTempFiles ', - ), - loadAtlasNonCentered=dict(argstr='--loadAtlasNonCentered ', - ), - loadTargetCentered=dict(argstr='--loadTargetCentered ', - ), - mrmlSceneFileName=dict(argstr='--mrmlSceneFileName %s', - ), - parametersMRMLNodeName=dict(argstr='--parametersMRMLNodeName %s', - ), - registrationAffineType=dict(argstr='--registrationAffineType %d', - ), - registrationDeformableType=dict(argstr='--registrationDeformableType %d', - ), - registrationPackage=dict(argstr='--registrationPackage %s', - ), - resultMRMLSceneFileName=dict(argstr='--resultMRMLSceneFileName %s', - hash_files=False, - ), - resultStandardVolumeFileName=dict(argstr='--resultStandardVolumeFileName %s', - ), - resultVolumeFileName=dict(argstr='--resultVolumeFileName %s', - hash_files=False, - ), - targetVolumeFileNames=dict(argstr='--targetVolumeFileNames %s...', - ), - taskPreProcessingSetting=dict(argstr='--taskPreProcessingSetting %s', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='--verbose ', - ), + input_map = dict( + args=dict(argstr='%s', ), + atlasVolumeFileNames=dict(argstr='--atlasVolumeFileNames %s...', ), + disableCompression=dict(argstr='--disableCompression ', ), + disableMultithreading=dict(argstr='--disableMultithreading %d', ), + dontUpdateIntermediateData=dict( + argstr='--dontUpdateIntermediateData %d', ), + dontWriteResults=dict(argstr='--dontWriteResults ', ), + environ=dict( + nohash=True, + usedefault=True, + ), + generateEmptyMRMLSceneAndQuit=dict( + argstr='--generateEmptyMRMLSceneAndQuit %s', + hash_files=False, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + intermediateResultsDirectory=dict( + argstr='--intermediateResultsDirectory %s', ), + keepTempFiles=dict(argstr='--keepTempFiles ', ), + loadAtlasNonCentered=dict(argstr='--loadAtlasNonCentered ', ), + loadTargetCentered=dict(argstr='--loadTargetCentered ', ), + mrmlSceneFileName=dict(argstr='--mrmlSceneFileName %s', ), + parametersMRMLNodeName=dict(argstr='--parametersMRMLNodeName %s', ), + registrationAffineType=dict(argstr='--registrationAffineType %d', ), + registrationDeformableType=dict( + argstr='--registrationDeformableType %d', ), + registrationPackage=dict(argstr='--registrationPackage %s', ), + resultMRMLSceneFileName=dict( + argstr='--resultMRMLSceneFileName %s', + hash_files=False, + ), + resultStandardVolumeFileName=dict( + argstr='--resultStandardVolumeFileName %s', ), + resultVolumeFileName=dict( + argstr='--resultVolumeFileName %s', + hash_files=False, + ), + targetVolumeFileNames=dict(argstr='--targetVolumeFileNames %s...', ), + taskPreProcessingSetting=dict( + argstr='--taskPreProcessingSetting %s', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict(argstr='--verbose ', ), ) inputs = EMSegmentCommandLine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EMSegmentCommandLine_outputs(): - output_map = dict(generateEmptyMRMLSceneAndQuit=dict(), - resultMRMLSceneFileName=dict(), - resultVolumeFileName=dict(), + output_map = dict( + generateEmptyMRMLSceneAndQuit=dict(), + resultMRMLSceneFileName=dict(), + resultVolumeFileName=dict(), ) outputs = EMSegmentCommandLine.output_spec() diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py index 4bd8a64f94..1e0afc9dad 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py @@ -4,50 +4,47 @@ def test_RobustStatisticsSegmenter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - curvatureWeight=dict(argstr='--curvatureWeight %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - expectedVolume=dict(argstr='--expectedVolume %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - intensityHomogeneity=dict(argstr='--intensityHomogeneity %f', - ), - labelImageFileName=dict(argstr='%s', - position=-2, - ), - labelValue=dict(argstr='--labelValue %d', - ), - maxRunningTime=dict(argstr='--maxRunningTime %f', - ), - originalImageFileName=dict(argstr='%s', - position=-3, - ), - segmentedImageFileName=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + curvatureWeight=dict(argstr='--curvatureWeight %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + expectedVolume=dict(argstr='--expectedVolume %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + intensityHomogeneity=dict(argstr='--intensityHomogeneity %f', ), + labelImageFileName=dict( + argstr='%s', + position=-2, + ), + labelValue=dict(argstr='--labelValue %d', ), + maxRunningTime=dict(argstr='--maxRunningTime %f', ), + originalImageFileName=dict( + argstr='%s', + position=-3, + ), + segmentedImageFileName=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = RobustStatisticsSegmenter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_RobustStatisticsSegmenter_outputs(): - output_map = dict(segmentedImageFileName=dict(position=-1, - ), - ) + output_map = dict(segmentedImageFileName=dict(position=-1, ), ) outputs = RobustStatisticsSegmenter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py index 03eba8a580..0eb6b1b5a9 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py @@ -4,51 +4,45 @@ def test_SimpleRegionGrowingSegmentation_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - iterations=dict(argstr='--iterations %d', - ), - labelvalue=dict(argstr='--labelvalue %d', - ), - multiplier=dict(argstr='--multiplier %f', - ), - neighborhood=dict(argstr='--neighborhood %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - seed=dict(argstr='--seed %s...', - ), - smoothingIterations=dict(argstr='--smoothingIterations %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - timestep=dict(argstr='--timestep %f', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + iterations=dict(argstr='--iterations %d', ), + labelvalue=dict(argstr='--labelvalue %d', ), + multiplier=dict(argstr='--multiplier %f', ), + neighborhood=dict(argstr='--neighborhood %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + seed=dict(argstr='--seed %s...', ), + smoothingIterations=dict(argstr='--smoothingIterations %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + timestep=dict(argstr='--timestep %f', ), ) inputs = SimpleRegionGrowingSegmentation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SimpleRegionGrowingSegmentation_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = SimpleRegionGrowingSegmentation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/surface.py b/nipype/interfaces/slicer/surface.py index 774b76eba0..6a1dfe2cc0 100644 --- a/nipype/interfaces/slicer/surface.py +++ b/nipype/interfaces/slicer/surface.py @@ -10,7 +10,13 @@ class MergeModelsInputSpec(CommandLineInputSpec): Model1 = File(position=-3, desc="Model", exists=True, argstr="%s") Model2 = File(position=-2, desc="Model", exists=True, argstr="%s") - ModelOutput = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Model", argstr="%s") + ModelOutput = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Model", + argstr="%s") class MergeModelsOutputSpec(TraitedSpec): @@ -42,9 +48,16 @@ class MergeModels(SEMLikeCommandLine): class ModelToLabelMapInputSpec(CommandLineInputSpec): distance = traits.Float(desc="Sample distance", argstr="--distance %f") - InputVolume = File(position=-3, desc="Input volume", exists=True, argstr="%s") + InputVolume = File( + position=-3, desc="Input volume", exists=True, argstr="%s") surface = File(position=-2, desc="Model", exists=True, argstr="%s") - OutputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="The label volume", argstr="%s") + OutputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="The label volume", + argstr="%s") class ModelToLabelMapOutputSpec(TraitedSpec): @@ -75,18 +88,43 @@ class ModelToLabelMap(SEMLikeCommandLine): class GrayscaleModelMakerInputSpec(CommandLineInputSpec): - InputVolume = File(position=-2, desc="Volume containing the input grayscale data.", exists=True, argstr="%s") - OutputGeometry = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output that contains geometry model.", argstr="%s") - threshold = traits.Float(desc="Grayscale threshold of isosurface. The resulting surface of triangles separates the volume into voxels that lie above (inside) and below (outside) the threshold.", argstr="--threshold %f") + InputVolume = File( + position=-2, + desc="Volume containing the input grayscale data.", + exists=True, + argstr="%s") + OutputGeometry = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output that contains geometry model.", + argstr="%s") + threshold = traits.Float( + desc= + "Grayscale threshold of isosurface. The resulting surface of triangles separates the volume into voxels that lie above (inside) and below (outside) the threshold.", + argstr="--threshold %f") name = traits.Str(desc="Name to use for this model.", argstr="--name %s") - smooth = traits.Int(desc="Number of smoothing iterations. If 0, no smoothing will be done.", argstr="--smooth %d") - decimate = traits.Float(desc="Target reduction during decimation, as a decimal percentage reduction in the number of polygons. If 0, no decimation will be done.", argstr="--decimate %f") - splitnormals = traits.Bool(desc="Splitting normals is useful for visualizing sharp features. However it creates holes in surfaces which affect measurements", argstr="--splitnormals ") - pointnormals = traits.Bool(desc="Calculate the point normals? Calculated point normals make the surface appear smooth. Without point normals, the surface will appear faceted.", argstr="--pointnormals ") + smooth = traits.Int( + desc="Number of smoothing iterations. If 0, no smoothing will be done.", + argstr="--smooth %d") + decimate = traits.Float( + desc= + "Target reduction during decimation, as a decimal percentage reduction in the number of polygons. If 0, no decimation will be done.", + argstr="--decimate %f") + splitnormals = traits.Bool( + desc= + "Splitting normals is useful for visualizing sharp features. However it creates holes in surfaces which affect measurements", + argstr="--splitnormals ") + pointnormals = traits.Bool( + desc= + "Calculate the point normals? Calculated point normals make the surface appear smooth. Without point normals, the surface will appear faceted.", + argstr="--pointnormals ") class GrayscaleModelMakerOutputSpec(TraitedSpec): - OutputGeometry = File(position=-1, desc="Output that contains geometry model.", exists=True) + OutputGeometry = File( + position=-1, desc="Output that contains geometry model.", exists=True) class GrayscaleModelMaker(SEMLikeCommandLine): @@ -115,9 +153,20 @@ class GrayscaleModelMaker(SEMLikeCommandLine): class ProbeVolumeWithModelInputSpec(CommandLineInputSpec): - InputVolume = File(position=-3, desc="Volume to use to 'paint' the model", exists=True, argstr="%s") - InputModel = File(position=-2, desc="Input model", exists=True, argstr="%s") - OutputModel = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Output 'painted' model", argstr="%s") + InputVolume = File( + position=-3, + desc="Volume to use to 'paint' the model", + exists=True, + argstr="%s") + InputModel = File( + position=-2, desc="Input model", exists=True, argstr="%s") + OutputModel = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Output 'painted' model", + argstr="%s") class ProbeVolumeWithModelOutputSpec(TraitedSpec): @@ -148,12 +197,30 @@ class ProbeVolumeWithModel(SEMLikeCommandLine): class LabelMapSmoothingInputSpec(CommandLineInputSpec): - labelToSmooth = traits.Int(desc="The label to smooth. All others will be ignored. If no label is selected by the user, the maximum label in the image is chosen by default.", argstr="--labelToSmooth %d") - numberOfIterations = traits.Int(desc="The number of iterations of the level set AntiAliasing algorithm", argstr="--numberOfIterations %d") - maxRMSError = traits.Float(desc="The maximum RMS error.", argstr="--maxRMSError %f") - gaussianSigma = traits.Float(desc="The standard deviation of the Gaussian kernel", argstr="--gaussianSigma %f") - inputVolume = File(position=-2, desc="Input label map to smooth", exists=True, argstr="%s") - outputVolume = traits.Either(traits.Bool, File(), position=-1, hash_files=False, desc="Smoothed label map", argstr="%s") + labelToSmooth = traits.Int( + desc= + "The label to smooth. All others will be ignored. If no label is selected by the user, the maximum label in the image is chosen by default.", + argstr="--labelToSmooth %d") + numberOfIterations = traits.Int( + desc="The number of iterations of the level set AntiAliasing algorithm", + argstr="--numberOfIterations %d") + maxRMSError = traits.Float( + desc="The maximum RMS error.", argstr="--maxRMSError %f") + gaussianSigma = traits.Float( + desc="The standard deviation of the Gaussian kernel", + argstr="--gaussianSigma %f") + inputVolume = File( + position=-2, + desc="Input label map to smooth", + exists=True, + argstr="%s") + outputVolume = traits.Either( + traits.Bool, + File(), + position=-1, + hash_files=False, + desc="Smoothed label map", + argstr="%s") class LabelMapSmoothingOutputSpec(TraitedSpec): @@ -184,28 +251,95 @@ class LabelMapSmoothing(SEMLikeCommandLine): class ModelMakerInputSpec(CommandLineInputSpec): - InputVolume = File(position=-1, desc="Input label map. The Input Volume drop down menu is populated with the label map volumes that are present in the scene, select one from which to generate models.", exists=True, argstr="%s") - color = File(desc="Color table to make labels to colors and objects", exists=True, argstr="--color %s") - modelSceneFile = traits.Either(traits.Bool, InputMultiPath(File(), ), hash_files=False, desc="Generated models, under a model hierarchy node. Models are imported into Slicer under a model hierarchy node, and their colors are set by the color table associated with the input label map volume. The model hierarchy node must be created before running the model maker, by selecting Create New ModelHierarchy from the Models drop down menu. If you're running from the command line, a model hierarchy node in a new mrml scene will be created for you.", argstr="--modelSceneFile %s...") - name = traits.Str(desc="Name to use for this model. Any text entered in the entry box will be the starting string for the created model file names. The label number and the color name will also be part of the file name. If making multiple models, use this as a prefix to the label and color name.", argstr="--name %s") - generateAll = traits.Bool(desc="Generate models for all labels in the input volume. select this option if you want to create all models that correspond to all values in a labelmap volume (using the Joint Smoothing option below is useful with this option). Ignores Labels, Start Label, End Label settings. Skips label 0.", argstr="--generateAll ") - labels = InputMultiPath(traits.Int, desc="A comma separated list of label values from which to make models. f you specify a list of Labels, it will override any start/end label settings. If you click Generate All Models it will override the list of labels and any start/end label settings.", sep=",", argstr="--labels %s") - start = traits.Int(desc="If you want to specify a continuous range of labels from which to generate models, enter the lower label here. Voxel value from which to start making models. Used instead of the label list to specify a range (make sure the label list is empty or it will over ride this).", argstr="--start %d") - end = traits.Int(desc="If you want to specify a continuous range of labels from which to generate models, enter the higher label here. Voxel value up to which to continue making models. Skip any values with zero voxels.", argstr="--end %d") - skipUnNamed = traits.Bool(desc="Select this to not generate models from labels that do not have names defined in the color look up table associated with the input label map. If true, only models which have an entry in the color table will be generated. If false, generate all models that exist within the label range.", argstr="--skipUnNamed ") - jointsmooth = traits.Bool(desc="This will ensure that all resulting models fit together smoothly, like jigsaw puzzle pieces. Otherwise the models will be smoothed independently and may overlap.", argstr="--jointsmooth ") - smooth = traits.Int(desc="Here you can set the number of smoothing iterations for Laplacian smoothing, or the degree of the polynomial approximating the windowed Sinc function. Use 0 if you wish no smoothing. ", argstr="--smooth %d") - filtertype = traits.Enum("Sinc", "Laplacian", desc="You can control the type of smoothing done on the models by selecting a filter type of either Sinc or Laplacian.", argstr="--filtertype %s") - decimate = traits.Float(desc="Chose the target reduction in number of polygons as a decimal percentage (between 0 and 1) of the number of polygons. Specifies the percentage of triangles to be removed. For example, 0.1 means 10% reduction and 0.9 means 90% reduction.", argstr="--decimate %f") - splitnormals = traits.Bool(desc="Splitting normals is useful for visualizing sharp features. However it creates holes in surfaces which affects measurements.", argstr="--splitnormals ") - pointnormals = traits.Bool(desc="Turn this flag on if you wish to calculate the normal vectors for the points.", argstr="--pointnormals ") - pad = traits.Bool(desc="Pad the input volume with zero value voxels on all 6 faces in order to ensure the production of closed surfaces. Sets the origin translation and extent translation so that the models still line up with the unpadded input volume.", argstr="--pad ") - saveIntermediateModels = traits.Bool(desc="You can save a copy of the models after each of the intermediate steps (marching cubes, smoothing, and decimation if not joint smoothing, otherwise just after decimation). These intermediate models are not saved in the mrml file, you have to load them manually after turning off deleting temporary files in they python console (View ->Python Interactor) using the following command slicer.modules.modelmaker.cliModuleLogic().DeleteTemporaryFilesOff().", argstr="--saveIntermediateModels ") - debug = traits.Bool(desc="turn this flag on in order to see debugging output (look in the Error Log window that is accessed via the View menu)", argstr="--debug ") + InputVolume = File( + position=-1, + desc= + "Input label map. The Input Volume drop down menu is populated with the label map volumes that are present in the scene, select one from which to generate models.", + exists=True, + argstr="%s") + color = File( + desc="Color table to make labels to colors and objects", + exists=True, + argstr="--color %s") + modelSceneFile = traits.Either( + traits.Bool, + InputMultiPath(File(), ), + hash_files=False, + desc= + "Generated models, under a model hierarchy node. Models are imported into Slicer under a model hierarchy node, and their colors are set by the color table associated with the input label map volume. The model hierarchy node must be created before running the model maker, by selecting Create New ModelHierarchy from the Models drop down menu. If you're running from the command line, a model hierarchy node in a new mrml scene will be created for you.", + argstr="--modelSceneFile %s...") + name = traits.Str( + desc= + "Name to use for this model. Any text entered in the entry box will be the starting string for the created model file names. The label number and the color name will also be part of the file name. If making multiple models, use this as a prefix to the label and color name.", + argstr="--name %s") + generateAll = traits.Bool( + desc= + "Generate models for all labels in the input volume. select this option if you want to create all models that correspond to all values in a labelmap volume (using the Joint Smoothing option below is useful with this option). Ignores Labels, Start Label, End Label settings. Skips label 0.", + argstr="--generateAll ") + labels = InputMultiPath( + traits.Int, + desc= + "A comma separated list of label values from which to make models. f you specify a list of Labels, it will override any start/end label settings. If you click Generate All Models it will override the list of labels and any start/end label settings.", + sep=",", + argstr="--labels %s") + start = traits.Int( + desc= + "If you want to specify a continuous range of labels from which to generate models, enter the lower label here. Voxel value from which to start making models. Used instead of the label list to specify a range (make sure the label list is empty or it will over ride this).", + argstr="--start %d") + end = traits.Int( + desc= + "If you want to specify a continuous range of labels from which to generate models, enter the higher label here. Voxel value up to which to continue making models. Skip any values with zero voxels.", + argstr="--end %d") + skipUnNamed = traits.Bool( + desc= + "Select this to not generate models from labels that do not have names defined in the color look up table associated with the input label map. If true, only models which have an entry in the color table will be generated. If false, generate all models that exist within the label range.", + argstr="--skipUnNamed ") + jointsmooth = traits.Bool( + desc= + "This will ensure that all resulting models fit together smoothly, like jigsaw puzzle pieces. Otherwise the models will be smoothed independently and may overlap.", + argstr="--jointsmooth ") + smooth = traits.Int( + desc= + "Here you can set the number of smoothing iterations for Laplacian smoothing, or the degree of the polynomial approximating the windowed Sinc function. Use 0 if you wish no smoothing. ", + argstr="--smooth %d") + filtertype = traits.Enum( + "Sinc", + "Laplacian", + desc= + "You can control the type of smoothing done on the models by selecting a filter type of either Sinc or Laplacian.", + argstr="--filtertype %s") + decimate = traits.Float( + desc= + "Chose the target reduction in number of polygons as a decimal percentage (between 0 and 1) of the number of polygons. Specifies the percentage of triangles to be removed. For example, 0.1 means 10% reduction and 0.9 means 90% reduction.", + argstr="--decimate %f") + splitnormals = traits.Bool( + desc= + "Splitting normals is useful for visualizing sharp features. However it creates holes in surfaces which affects measurements.", + argstr="--splitnormals ") + pointnormals = traits.Bool( + desc= + "Turn this flag on if you wish to calculate the normal vectors for the points.", + argstr="--pointnormals ") + pad = traits.Bool( + desc= + "Pad the input volume with zero value voxels on all 6 faces in order to ensure the production of closed surfaces. Sets the origin translation and extent translation so that the models still line up with the unpadded input volume.", + argstr="--pad ") + saveIntermediateModels = traits.Bool( + desc= + "You can save a copy of the models after each of the intermediate steps (marching cubes, smoothing, and decimation if not joint smoothing, otherwise just after decimation). These intermediate models are not saved in the mrml file, you have to load them manually after turning off deleting temporary files in they python console (View ->Python Interactor) using the following command slicer.modules.modelmaker.cliModuleLogic().DeleteTemporaryFilesOff().", + argstr="--saveIntermediateModels ") + debug = traits.Bool( + desc= + "turn this flag on in order to see debugging output (look in the Error Log window that is accessed via the View menu)", + argstr="--debug ") class ModelMakerOutputSpec(TraitedSpec): - modelSceneFile = OutputMultiPath(File(exists=True), desc="Generated models, under a model hierarchy node. Models are imported into Slicer under a model hierarchy node, and their colors are set by the color table associated with the input label map volume. The model hierarchy node must be created before running the model maker, by selecting Create New ModelHierarchy from the Models drop down menu. If you're running from the command line, a model hierarchy node in a new mrml scene will be created for you.") + modelSceneFile = OutputMultiPath( + File(exists=True), + desc= + "Generated models, under a model hierarchy node. Models are imported into Slicer under a model hierarchy node, and their colors are set by the color table associated with the input label map volume. The model hierarchy node must be created before running the model maker, by selecting Create New ModelHierarchy from the Models drop down menu. If you're running from the command line, a model hierarchy node in a new mrml scene will be created for you." + ) class ModelMaker(SEMLikeCommandLine): diff --git a/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py b/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py index 425541245c..6b1e441720 100644 --- a/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py +++ b/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py @@ -4,44 +4,42 @@ def test_DicomToNrrdConverter_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputDicomDirectory=dict(argstr='--inputDicomDirectory %s', - ), - outputDirectory=dict(argstr='--outputDirectory %s', - hash_files=False, - ), - outputVolume=dict(argstr='--outputVolume %s', - ), - smallGradientThreshold=dict(argstr='--smallGradientThreshold %f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - useBMatrixGradientDirections=dict(argstr='--useBMatrixGradientDirections ', - ), - useIdentityMeaseurementFrame=dict(argstr='--useIdentityMeaseurementFrame ', - ), - writeProtocolGradientsFile=dict(argstr='--writeProtocolGradientsFile ', - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputDicomDirectory=dict(argstr='--inputDicomDirectory %s', ), + outputDirectory=dict( + argstr='--outputDirectory %s', + hash_files=False, + ), + outputVolume=dict(argstr='--outputVolume %s', ), + smallGradientThreshold=dict(argstr='--smallGradientThreshold %f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + useBMatrixGradientDirections=dict( + argstr='--useBMatrixGradientDirections ', ), + useIdentityMeaseurementFrame=dict( + argstr='--useIdentityMeaseurementFrame ', ), + writeProtocolGradientsFile=dict( + argstr='--writeProtocolGradientsFile ', ), ) inputs = DicomToNrrdConverter.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DicomToNrrdConverter_outputs(): - output_map = dict(outputDirectory=dict(), - ) + output_map = dict(outputDirectory=dict(), ) outputs = DicomToNrrdConverter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py b/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py index 5e83f5f935..196d0606d8 100644 --- a/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py +++ b/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py @@ -4,36 +4,35 @@ def test_EMSegmentTransformToNewFormat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputMRMLFileName=dict(argstr='--inputMRMLFileName %s', - ), - outputMRMLFileName=dict(argstr='--outputMRMLFileName %s', - hash_files=False, - ), - templateFlag=dict(argstr='--templateFlag ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputMRMLFileName=dict(argstr='--inputMRMLFileName %s', ), + outputMRMLFileName=dict( + argstr='--outputMRMLFileName %s', + hash_files=False, + ), + templateFlag=dict(argstr='--templateFlag ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = EMSegmentTransformToNewFormat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EMSegmentTransformToNewFormat_outputs(): - output_map = dict(outputMRMLFileName=dict(), - ) + output_map = dict(outputMRMLFileName=dict(), ) outputs = EMSegmentTransformToNewFormat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py b/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py index 2b2f1ad0ee..77019093c4 100644 --- a/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py +++ b/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py @@ -4,49 +4,44 @@ def test_GrayscaleModelMaker_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-2, - ), - OutputGeometry=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - decimate=dict(argstr='--decimate %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - name=dict(argstr='--name %s', - ), - pointnormals=dict(argstr='--pointnormals ', - ), - smooth=dict(argstr='--smooth %d', - ), - splitnormals=dict(argstr='--splitnormals ', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - threshold=dict(argstr='--threshold %f', - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-2, + ), + OutputGeometry=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + decimate=dict(argstr='--decimate %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + name=dict(argstr='--name %s', ), + pointnormals=dict(argstr='--pointnormals ', ), + smooth=dict(argstr='--smooth %d', ), + splitnormals=dict(argstr='--splitnormals ', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + threshold=dict(argstr='--threshold %f', ), ) inputs = GrayscaleModelMaker.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GrayscaleModelMaker_outputs(): - output_map = dict(OutputGeometry=dict(position=-1, - ), - ) + output_map = dict(OutputGeometry=dict(position=-1, ), ) outputs = GrayscaleModelMaker.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py b/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py index ded9cbe0be..a3e863d165 100644 --- a/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py +++ b/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py @@ -4,45 +4,42 @@ def test_LabelMapSmoothing_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - gaussianSigma=dict(argstr='--gaussianSigma %f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume=dict(argstr='%s', - position=-2, - ), - labelToSmooth=dict(argstr='--labelToSmooth %d', - ), - maxRMSError=dict(argstr='--maxRMSError %f', - ), - numberOfIterations=dict(argstr='--numberOfIterations %d', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + gaussianSigma=dict(argstr='--gaussianSigma %f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr='%s', + position=-2, + ), + labelToSmooth=dict(argstr='--labelToSmooth %d', ), + maxRMSError=dict(argstr='--maxRMSError %f', ), + numberOfIterations=dict(argstr='--numberOfIterations %d', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = LabelMapSmoothing.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LabelMapSmoothing_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = LabelMapSmoothing.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_MergeModels.py b/nipype/interfaces/slicer/tests/test_auto_MergeModels.py index 4ba0f98458..6b2cee1e65 100644 --- a/nipype/interfaces/slicer/tests/test_auto_MergeModels.py +++ b/nipype/interfaces/slicer/tests/test_auto_MergeModels.py @@ -4,40 +4,42 @@ def test_MergeModels_inputs(): - input_map = dict(Model1=dict(argstr='%s', - position=-3, - ), - Model2=dict(argstr='%s', - position=-2, - ), - ModelOutput=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + Model1=dict( + argstr='%s', + position=-3, + ), + Model2=dict( + argstr='%s', + position=-2, + ), + ModelOutput=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = MergeModels.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MergeModels_outputs(): - output_map = dict(ModelOutput=dict(position=-1, - ), - ) + output_map = dict(ModelOutput=dict(position=-1, ), ) outputs = MergeModels.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py b/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py index c779eb3238..008e70bc31 100644 --- a/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py +++ b/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py @@ -4,68 +4,56 @@ def test_ModelMaker_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-1, - ), - args=dict(argstr='%s', - ), - color=dict(argstr='--color %s', - ), - debug=dict(argstr='--debug ', - ), - decimate=dict(argstr='--decimate %f', - ), - end=dict(argstr='--end %d', - ), - environ=dict(nohash=True, - usedefault=True, - ), - filtertype=dict(argstr='--filtertype %s', - ), - generateAll=dict(argstr='--generateAll ', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - jointsmooth=dict(argstr='--jointsmooth ', - ), - labels=dict(argstr='--labels %s', - sep=',', - ), - modelSceneFile=dict(argstr='--modelSceneFile %s...', - hash_files=False, - ), - name=dict(argstr='--name %s', - ), - pad=dict(argstr='--pad ', - ), - pointnormals=dict(argstr='--pointnormals ', - ), - saveIntermediateModels=dict(argstr='--saveIntermediateModels ', - ), - skipUnNamed=dict(argstr='--skipUnNamed ', - ), - smooth=dict(argstr='--smooth %d', - ), - splitnormals=dict(argstr='--splitnormals ', - ), - start=dict(argstr='--start %d', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-1, + ), + args=dict(argstr='%s', ), + color=dict(argstr='--color %s', ), + debug=dict(argstr='--debug ', ), + decimate=dict(argstr='--decimate %f', ), + end=dict(argstr='--end %d', ), + environ=dict( + nohash=True, + usedefault=True, + ), + filtertype=dict(argstr='--filtertype %s', ), + generateAll=dict(argstr='--generateAll ', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + jointsmooth=dict(argstr='--jointsmooth ', ), + labels=dict( + argstr='--labels %s', + sep=',', + ), + modelSceneFile=dict( + argstr='--modelSceneFile %s...', + hash_files=False, + ), + name=dict(argstr='--name %s', ), + pad=dict(argstr='--pad ', ), + pointnormals=dict(argstr='--pointnormals ', ), + saveIntermediateModels=dict(argstr='--saveIntermediateModels ', ), + skipUnNamed=dict(argstr='--skipUnNamed ', ), + smooth=dict(argstr='--smooth %d', ), + splitnormals=dict(argstr='--splitnormals ', ), + start=dict(argstr='--start %d', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ModelMaker.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ModelMaker_outputs(): - output_map = dict(modelSceneFile=dict(), - ) + output_map = dict(modelSceneFile=dict(), ) outputs = ModelMaker.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py b/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py index a54ee1fea6..5537cc559f 100644 --- a/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py +++ b/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py @@ -4,42 +4,43 @@ def test_ModelToLabelMap_inputs(): - input_map = dict(InputVolume=dict(argstr='%s', - position=-3, - ), - OutputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - distance=dict(argstr='--distance %f', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - surface=dict(argstr='%s', - position=-2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + InputVolume=dict( + argstr='%s', + position=-3, + ), + OutputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + distance=dict(argstr='--distance %f', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + surface=dict( + argstr='%s', + position=-2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ModelToLabelMap.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ModelToLabelMap_outputs(): - output_map = dict(OutputVolume=dict(position=-1, - ), - ) + output_map = dict(OutputVolume=dict(position=-1, ), ) outputs = ModelToLabelMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py b/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py index dd0a987239..62db6e57e2 100644 --- a/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py +++ b/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py @@ -4,39 +4,39 @@ def test_OrientScalarVolume_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inputVolume1=dict(argstr='%s', - position=-2, - ), - orientation=dict(argstr='--orientation %s', - ), - outputVolume=dict(argstr='%s', - hash_files=False, - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr='%s', + position=-2, + ), + orientation=dict(argstr='--orientation %s', ), + outputVolume=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = OrientScalarVolume.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_OrientScalarVolume_outputs(): - output_map = dict(outputVolume=dict(position=-1, - ), - ) + output_map = dict(outputVolume=dict(position=-1, ), ) outputs = OrientScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py b/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py index 48b75608c8..f15fda4e9a 100644 --- a/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py +++ b/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py @@ -4,40 +4,42 @@ def test_ProbeVolumeWithModel_inputs(): - input_map = dict(InputModel=dict(argstr='%s', - position=-2, - ), - InputVolume=dict(argstr='%s', - position=-3, - ), - OutputModel=dict(argstr='%s', - hash_files=False, - position=-1, - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + InputModel=dict( + argstr='%s', + position=-2, + ), + InputVolume=dict( + argstr='%s', + position=-3, + ), + OutputModel=dict( + argstr='%s', + hash_files=False, + position=-1, + ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = ProbeVolumeWithModel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ProbeVolumeWithModel_outputs(): - output_map = dict(OutputModel=dict(position=-1, - ), - ) + output_map = dict(OutputModel=dict(position=-1, ), ) outputs = ProbeVolumeWithModel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py b/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py index 369a25b77d..3f29a03307 100644 --- a/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py +++ b/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py @@ -4,22 +4,24 @@ def test_SlicerCommandLine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SlicerCommandLine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/slicer/utilities.py b/nipype/interfaces/slicer/utilities.py index 7e3d690d68..5faf640570 100644 --- a/nipype/interfaces/slicer/utilities.py +++ b/nipype/interfaces/slicer/utilities.py @@ -8,13 +8,29 @@ class EMSegmentTransformToNewFormatInputSpec(CommandLineInputSpec): - inputMRMLFileName = File(desc="Active MRML scene that contains EMSegment algorithm parameters in the format before 3.6.3 - please include absolute file name in path.", exists=True, argstr="--inputMRMLFileName %s") - outputMRMLFileName = traits.Either(traits.Bool, File(), hash_files=False, desc="Write out the MRML scene after transformation to format 3.6.3 has been made. - has to be in the same directory as the input MRML file due to Slicer Core bug - please include absolute file name in path ", argstr="--outputMRMLFileName %s") - templateFlag = traits.Bool(desc="Set to true if the transformed mrml file should be used as template file ", argstr="--templateFlag ") + inputMRMLFileName = File( + desc= + "Active MRML scene that contains EMSegment algorithm parameters in the format before 3.6.3 - please include absolute file name in path.", + exists=True, + argstr="--inputMRMLFileName %s") + outputMRMLFileName = traits.Either( + traits.Bool, + File(), + hash_files=False, + desc= + "Write out the MRML scene after transformation to format 3.6.3 has been made. - has to be in the same directory as the input MRML file due to Slicer Core bug - please include absolute file name in path ", + argstr="--outputMRMLFileName %s") + templateFlag = traits.Bool( + desc= + "Set to true if the transformed mrml file should be used as template file ", + argstr="--templateFlag ") class EMSegmentTransformToNewFormatOutputSpec(TraitedSpec): - outputMRMLFileName = File(desc="Write out the MRML scene after transformation to format 3.6.3 has been made. - has to be in the same directory as the input MRML file due to Slicer Core bug - please include absolute file name in path ", exists=True) + outputMRMLFileName = File( + desc= + "Write out the MRML scene after transformation to format 3.6.3 has been made. - has to be in the same directory as the input MRML file due to Slicer Core bug - please include absolute file name in path ", + exists=True) class EMSegmentTransformToNewFormat(SEMLikeCommandLine): diff --git a/nipype/interfaces/spm/base.py b/nipype/interfaces/spm/base.py index 7882fa1280..cb0416392a 100644 --- a/nipype/interfaces/spm/base.py +++ b/nipype/interfaces/spm/base.py @@ -14,7 +14,8 @@ spm.SPMCommand().version """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, object, str, bytes # Standard library imports @@ -29,15 +30,12 @@ # Local imports from ... import logging from ...utils import spm_docs as sd, NUMPY_MMAP -from ..base import ( - BaseInterface, traits, isdefined, InputMultiPath, - BaseInterfaceInputSpec, Directory, Undefined, - ImageFile, PackageInfo -) +from ..base import (BaseInterface, traits, isdefined, InputMultiPath, + BaseInterfaceInputSpec, Directory, Undefined, ImageFile, + PackageInfo) from ..matlab import MatlabCommand from ...external.due import due, Doi, BibTeX - __docformat__ = 'restructuredtext' logger = logging.getLogger('interface') @@ -72,16 +70,16 @@ def scans_for_fname(fname): """ if isinstance(fname, list): - scans = np.zeros((len(fname),), dtype=object) + scans = np.zeros((len(fname), ), dtype=object) for sno, f in enumerate(fname): scans[sno] = '%s,1' % f return scans img = load(fname, mmap=NUMPY_MMAP) if len(img.shape) == 3: - return np.array(('%s,1' % fname,), dtype=object) + return np.array(('%s,1' % fname, ), dtype=object) else: n_scans = img.shape[3] - scans = np.zeros((n_scans,), dtype=object) + scans = np.zeros((n_scans, ), dtype=object) for sno in range(n_scans): scans[sno] = '%s,%d' % (fname, sno + 1) return scans @@ -104,7 +102,7 @@ def scans_for_fnames(fnames, keep4d=False, separate_sessions=False): if func_is_3d(fnames[0]): fnames = [fnames] if separate_sessions or keep4d: - flist = np.zeros((len(fnames),), dtype=object) + flist = np.zeros((len(fnames), ), dtype=object) for i, f in enumerate(fnames): if separate_sessions: if keep4d: @@ -188,12 +186,10 @@ def getinfo(klass, matlab_cmd=None, paths=None, use_mcr=None): } use_mcr = use_mcr or 'FORCE_SPMMCR' in os.environ - matlab_cmd = ( - (use_mcr and os.getenv('SPMMCRCMD')) or - os.getenv('MATLABCMD', 'matlab -nodesktop -nosplash')) + matlab_cmd = ((use_mcr and os.getenv('SPMMCRCMD')) + or os.getenv('MATLABCMD', 'matlab -nodesktop -nosplash')) - mlab = MatlabCommand(matlab_cmd=matlab_cmd, - resource_monitor=False) + mlab = MatlabCommand(matlab_cmd=matlab_cmd, resource_monitor=False) mlab.inputs.mfile = False if paths: mlab.inputs.paths = paths @@ -246,13 +242,14 @@ def no_spm(): class SPMCommandInputSpec(BaseInterfaceInputSpec): matlab_cmd = traits.Str(desc='matlab command to use') paths = InputMultiPath(Directory(), desc='Paths to add to matlabpath') - mfile = traits.Bool(True, desc='Run m-code using m-file', - usedefault=True) + mfile = traits.Bool(True, desc='Run m-code using m-file', usedefault=True) use_mcr = traits.Bool(desc='Run m-code using SPM MCR') - use_v8struct = traits.Bool(True, min_ver='8', usedefault=True, - desc=('Generate SPM8 and higher ' - 'compatible jobs') - ) + use_v8struct = traits.Bool( + True, + min_ver='8', + usedefault=True, + desc=('Generate SPM8 and higher ' + 'compatible jobs')) class SPMCommand(BaseInterface): @@ -270,23 +267,26 @@ class SPMCommand(BaseInterface): _paths = None _use_mcr = None - references_ = [{'entry': BibTeX("@book{FrackowiakFristonFrithDolanMazziotta1997," - "author={R.S.J. Frackowiak, K.J. Friston, C.D. Frith, R.J. Dolan, and J.C. Mazziotta}," - "title={Human Brain Function}," - "publisher={Academic Press USA}," - "year={1997}," - "}"), - 'description': 'The fundamental text on Statistical Parametric Mapping (SPM)', - # 'path': "nipype.interfaces.spm", - 'tags': ['implementation'], - }] + references_ = [{ + 'entry': + BibTeX( + "@book{FrackowiakFristonFrithDolanMazziotta1997," + "author={R.S.J. Frackowiak, K.J. Friston, C.D. Frith, R.J. Dolan, and J.C. Mazziotta}," + "title={Human Brain Function}," + "publisher={Academic Press USA}," + "year={1997}," + "}"), + 'description': + 'The fundamental text on Statistical Parametric Mapping (SPM)', + # 'path': "nipype.interfaces.spm", + 'tags': ['implementation'], + }] def __init__(self, **inputs): super(SPMCommand, self).__init__(**inputs) - self.inputs.on_trait_change(self._matlab_cmd_update, ['matlab_cmd', - 'mfile', - 'paths', - 'use_mcr']) + self.inputs.on_trait_change( + self._matlab_cmd_update, + ['matlab_cmd', 'mfile', 'paths', 'use_mcr']) self._find_mlab_cmd_defaults() self._check_mlab_inputs() self._matlab_cmd_update() @@ -312,10 +312,11 @@ def _matlab_cmd_update(self): # MatlabCommand has to be created here, # because matlab_cmd is not a proper input # and can be set only during init - self.mlab = MatlabCommand(matlab_cmd=self.inputs.matlab_cmd, - mfile=self.inputs.mfile, - paths=self.inputs.paths, - resource_monitor=False) + self.mlab = MatlabCommand( + matlab_cmd=self.inputs.matlab_cmd, + mfile=self.inputs.mfile, + paths=self.inputs.paths, + resource_monitor=False) self.mlab.inputs.script_file = 'pyscript_%s.m' % \ self.__class__.__name__.split('.')[-1].lower() if isdefined(self.inputs.use_mcr) and self.inputs.use_mcr: @@ -330,12 +331,10 @@ def version(self): info_dict = Info.getinfo( matlab_cmd=self.inputs.matlab_cmd, paths=self.inputs.paths, - use_mcr=self.inputs.use_mcr - ) + use_mcr=self.inputs.use_mcr) if info_dict: - return '%s.%s' % ( - info_dict['name'].split('SPM')[-1], - info_dict['release']) + return '%s.%s' % (info_dict['name'].split('SPM')[-1], + info_dict['release']) @property def jobtype(self): @@ -467,13 +466,15 @@ def _generate_job(self, prefix='', contents=None): jobstring += "{...\n" for i, val in enumerate(contents): if isinstance(val, np.ndarray): - jobstring += self._generate_job(prefix=None, - contents=val) + jobstring += self._generate_job( + prefix=None, contents=val) elif isinstance(val, list): items_format = [] for el in val: - items_format += ['{}' if not isinstance(el, (str, bytes)) - else '\'{}\''] + items_format += [ + '{}' if not isinstance(el, (str, bytes)) else + '\'{}\'' + ] val_format = ', '.join(items_format).format jobstring += '[{}];...\n'.format(val_format(*val)) elif isinstance(val, (str, bytes)): @@ -488,8 +489,7 @@ def _generate_job(self, prefix='', contents=None): newprefix = "%s(%d).%s" % (prefix, i + 1, field) else: newprefix = "(%d).%s" % (i + 1, field) - jobstring += self._generate_job(newprefix, - val[field]) + jobstring += self._generate_job(newprefix, val[field]) return jobstring if isinstance(contents, (str, bytes)): jobstring += "%s = '%s';\n" % (prefix, contents) @@ -532,29 +532,34 @@ def _make_matlab_command(self, contents, postscript=None): end\n """ if self.mlab.inputs.mfile: - if (isdefined(self.inputs.use_v8struct) and - self.inputs.use_v8struct): + if (isdefined(self.inputs.use_v8struct) + and self.inputs.use_v8struct): mscript += self._generate_job('jobs{1}.spm.%s.%s' % - (self.jobtype, self.jobname), - contents[0]) + (self.jobtype, + self.jobname), contents[0]) else: - if self.jobname in ['st', 'smooth', 'preproc', 'preproc8', - 'fmri_spec', 'fmri_est', - 'factorial_design', 'defs']: + if self.jobname in [ + 'st', 'smooth', 'preproc', 'preproc8', 'fmri_spec', + 'fmri_est', 'factorial_design', 'defs' + ]: # parentheses mscript += self._generate_job('jobs{1}.%s{1}.%s(1)' % - (self.jobtype, self.jobname), - contents[0]) + (self.jobtype, + self.jobname), contents[0]) else: # curly brackets mscript += self._generate_job('jobs{1}.%s{1}.%s{1}' % - (self.jobtype, self.jobname), - contents[0]) + (self.jobtype, + self.jobname), contents[0]) else: - jobdef = {'jobs': [{self.jobtype: - [{self.jobname: - self.reformat_dict_for_savemat(contents[0])}] - }]} + jobdef = { + 'jobs': [{ + self.jobtype: [{ + self.jobname: + self.reformat_dict_for_savemat(contents[0]) + }] + }] + } savemat(os.path.join(cwd, 'pyjobs_%s.mat' % self.jobname), jobdef) mscript += "load pyjobs_%s;\n\n" % self.jobname mscript += """ @@ -570,14 +575,21 @@ def _make_matlab_command(self, contents, postscript=None): mscript += postscript return mscript + class ImageFileSPM(ImageFile): """ Defines an ImageFile trait specific to SPM interfaces. """ - def __init__(self, value='', filter=None, auto_set=False, entries=0, - exists=False, types=['nifti1', 'nifti2'], - allow_compressed=False, **metadata): + def __init__(self, + value='', + filter=None, + auto_set=False, + entries=0, + exists=False, + types=['nifti1', 'nifti2'], + allow_compressed=False, + **metadata): """ Trait handles neuroimaging files. Parameters @@ -589,6 +601,6 @@ def __init__(self, value='', filter=None, auto_set=False, entries=0, """ self.types = types self.allow_compressed = allow_compressed - super(ImageFileSPM, self).__init__(value, filter, auto_set, entries, - exists, types, allow_compressed, - **metadata) + super(ImageFileSPM, + self).__init__(value, filter, auto_set, entries, exists, types, + allow_compressed, **metadata) diff --git a/nipype/interfaces/spm/model.py b/nipype/interfaces/spm/model.py index 8ddc06a9b0..f7df523587 100644 --- a/nipype/interfaces/spm/model.py +++ b/nipype/interfaces/spm/model.py @@ -11,7 +11,8 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, bytes # Standard library imports @@ -28,38 +29,46 @@ split_filename) from ..base import (Bunch, traits, TraitedSpec, File, Directory, OutputMultiPath, InputMultiPath, isdefined) -from .base import (SPMCommand, SPMCommandInputSpec, - scans_for_fnames, ImageFileSPM) +from .base import (SPMCommand, SPMCommandInputSpec, scans_for_fnames, + ImageFileSPM) __docformat__ = 'restructuredtext' iflogger = logging.getLogger('interface') class Level1DesignInputSpec(SPMCommandInputSpec): - spm_mat_dir = Directory(exists=True, field='dir', - desc='directory to store SPM.mat file (opt)') - timing_units = traits.Enum('secs', 'scans', field='timing.units', - desc='units for specification of onsets', - mandatory=True) - interscan_interval = traits.Float(field='timing.RT', - desc='Interscan interval in secs', - mandatory=True) - microtime_resolution = traits.Int(field='timing.fmri_t', - desc=('Number of time-bins per scan ' - 'in secs (opt)')) - microtime_onset = traits.Float(field='timing.fmri_t0', - desc=('The onset/time-bin in seconds for ' - 'alignment (opt)')) - session_info = traits.Any(field='sess', - desc=('Session specific information generated ' - 'by ``modelgen.SpecifyModel``'), - mandatory=True) - factor_info = traits.List(traits.Dict(traits.Enum('name', 'levels')), - field='fact', - desc=('Factor specific information ' - 'file (opt)')) - bases = traits.Dict(traits.Enum('hrf', 'fourier', 'fourier_han', - 'gamma', 'fir'), field='bases', desc=""" + spm_mat_dir = Directory( + exists=True, field='dir', desc='directory to store SPM.mat file (opt)') + timing_units = traits.Enum( + 'secs', + 'scans', + field='timing.units', + desc='units for specification of onsets', + mandatory=True) + interscan_interval = traits.Float( + field='timing.RT', desc='Interscan interval in secs', mandatory=True) + microtime_resolution = traits.Int( + field='timing.fmri_t', + desc=('Number of time-bins per scan ' + 'in secs (opt)')) + microtime_onset = traits.Float( + field='timing.fmri_t0', + desc=('The onset/time-bin in seconds for ' + 'alignment (opt)')) + session_info = traits.Any( + field='sess', + desc=('Session specific information generated ' + 'by ``modelgen.SpecifyModel``'), + mandatory=True) + factor_info = traits.List( + traits.Dict(traits.Enum('name', 'levels')), + field='fact', + desc=('Factor specific information ' + 'file (opt)')) + bases = traits.Dict( + traits.Enum('hrf', 'fourier', 'fourier_han', 'gamma', 'fir'), + field='bases', + desc=""" dict {'name':{'basesparam1':val,...}} name : string Name of basis function (hrf, fourier, fourier_han, @@ -75,25 +84,36 @@ class Level1DesignInputSpec(SPMCommandInputSpec): Post-stimulus window length (in seconds) order : int Number of basis functions -""", mandatory=True) - volterra_expansion_order = traits.Enum(1, 2, field='volt', - desc=('Model interactions - ' - 'yes:1, no:2')) - global_intensity_normalization = traits.Enum('none', 'scaling', - field='global', - desc=('Global intensity ' - 'normalization - ' - 'scaling or none')) - mask_image = File(exists=True, field='mask', - desc='Image for explicitly masking the analysis') - mask_threshold = traits.Either(traits.Enum('-Inf'), traits.Float(), - desc="Thresholding for the mask", - default='-Inf', usedefault=True) - model_serial_correlations = traits.Enum('AR(1)', 'FAST', 'none', - field='cvi', - desc=('Model serial correlations ' - 'AR(1), FAST or none. FAST ' - 'is available in SPM12')) +""", + mandatory=True) + volterra_expansion_order = traits.Enum( + 1, 2, field='volt', desc=('Model interactions - ' + 'yes:1, no:2')) + global_intensity_normalization = traits.Enum( + 'none', + 'scaling', + field='global', + desc=('Global intensity ' + 'normalization - ' + 'scaling or none')) + mask_image = File( + exists=True, + field='mask', + desc='Image for explicitly masking the analysis') + mask_threshold = traits.Either( + traits.Enum('-Inf'), + traits.Float(), + desc="Thresholding for the mask", + default='-Inf', + usedefault=True) + model_serial_correlations = traits.Enum( + 'AR(1)', + 'FAST', + 'none', + field='cvi', + desc=('Model serial correlations ' + 'AR(1), FAST or none. FAST ' + 'is available in SPM12')) class Level1DesignOutputSpec(TraitedSpec): @@ -138,8 +158,8 @@ def _format_arg(self, opt, spec, val): def _parse_inputs(self): """validate spm realign options if set to None ignore """ - einputs = super(Level1Design, self)._parse_inputs( - skip=('mask_threshold')) + einputs = super(Level1Design, + self)._parse_inputs(skip=('mask_threshold')) for sessinfo in einputs[0]['sess']: sessinfo['scans'] = scans_for_fnames( filename_to_list(sessinfo['scans']), keep4d=False) @@ -156,12 +176,12 @@ def _make_matlab_command(self, content): # SPM doesn't handle explicit masking properly, especially # when you want to use the entire mask image postscript = "load SPM;\n" - postscript += ("SPM.xM.VM = spm_vol('%s');\n" - % list_to_filename(self.inputs.mask_image)) + postscript += ("SPM.xM.VM = spm_vol('%s');\n" % list_to_filename( + self.inputs.mask_image)) postscript += "SPM.xM.I = 0;\n" postscript += "SPM.xM.T = [];\n" - postscript += ("SPM.xM.TH = ones(size(SPM.xM.TH))*(%s);\n" - % self.inputs.mask_threshold) + postscript += ("SPM.xM.TH = ones(size(SPM.xM.TH))*(%s);\n" % + self.inputs.mask_threshold) postscript += ("SPM.xM.xs = struct('Masking', " "'explicit masking only');\n") postscript += "save SPM SPM;\n" @@ -178,38 +198,45 @@ def _list_outputs(self): class EstimateModelInputSpec(SPMCommandInputSpec): - spm_mat_file = File(exists=True, field='spmmat', - copyfile=True, mandatory=True, + spm_mat_file = File( + exists=True, + field='spmmat', + copyfile=True, + mandatory=True, desc='Absolute path to SPM.mat') estimation_method = traits.Dict( traits.Enum('Classical', 'Bayesian2', 'Bayesian'), - field='method', mandatory=True, + field='method', + mandatory=True, desc=('Dictionary of either Classical: 1, Bayesian: 1, ' 'or Bayesian2: 1 (dict)')) - write_residuals = traits.Bool(field='write_residuals', - desc="Write individual residual images") + write_residuals = traits.Bool( + field='write_residuals', desc="Write individual residual images") flags = traits.Dict(desc='Additional arguments') class EstimateModelOutputSpec(TraitedSpec): - mask_image = ImageFileSPM(exists=True, - desc='binary mask to constrain estimation') - beta_images = OutputMultiPath(ImageFileSPM(exists=True), - desc='design parameter estimates') - residual_image = ImageFileSPM(exists=True, - desc='Mean-squared image of the residuals') - residual_images = OutputMultiPath(ImageFileSPM(exists=True), + mask_image = ImageFileSPM( + exists=True, desc='binary mask to constrain estimation') + beta_images = OutputMultiPath( + ImageFileSPM(exists=True), desc='design parameter estimates') + residual_image = ImageFileSPM( + exists=True, desc='Mean-squared image of the residuals') + residual_images = OutputMultiPath( + ImageFileSPM(exists=True), desc="individual residual images (requires `write_residuals`") RPVimage = ImageFileSPM(exists=True, desc='Resels per voxel image') spm_mat_file = File(exists=True, desc='Updated SPM mat file') labels = ImageFileSPM(exists=True, desc="label file") - SDerror = OutputMultiPath(ImageFileSPM(exists=True), + SDerror = OutputMultiPath( + ImageFileSPM(exists=True), desc="Images of the standard deviation of the error") - ARcoef = OutputMultiPath(ImageFileSPM(exists=True), - desc="Images of the AR coefficient") - Cbetas = OutputMultiPath(ImageFileSPM(exists=True), - desc="Images of the parameter posteriors") - SDbetas = OutputMultiPath(ImageFileSPM(exists=True), + ARcoef = OutputMultiPath( + ImageFileSPM(exists=True), desc="Images of the AR coefficient") + Cbetas = OutputMultiPath( + ImageFileSPM(exists=True), desc="Images of the parameter posteriors") + SDbetas = OutputMultiPath( + ImageFileSPM(exists=True), desc="Images of the standard deviation of parameter posteriors") @@ -247,8 +274,9 @@ def _parse_inputs(self): """ einputs = super(EstimateModel, self)._parse_inputs(skip=('flags')) if isdefined(self.inputs.flags): - einputs[0].update({flag: val for (flag, val) in - self.inputs.flags.items()}) + einputs[0].update( + {flag: val + for (flag, val) in self.inputs.flags.items()}) return einputs def _list_outputs(self): @@ -258,93 +286,90 @@ def _list_outputs(self): spm = sio.loadmat(self.inputs.spm_mat_file, struct_as_record=False) betas = [vbeta.fname[0] for vbeta in spm['SPM'][0, 0].Vbeta[0]] - if ('Bayesian' in self.inputs.estimation_method.keys() or - 'Bayesian2' in self.inputs.estimation_method.keys()): - outputs['labels'] = os.path.join(pth, - 'labels.{}'.format(outtype)) + if ('Bayesian' in self.inputs.estimation_method.keys() + or 'Bayesian2' in self.inputs.estimation_method.keys()): + outputs['labels'] = os.path.join(pth, 'labels.{}'.format(outtype)) outputs['SDerror'] = glob(os.path.join(pth, 'Sess*_SDerror*')) outputs['ARcoef'] = glob(os.path.join(pth, 'Sess*_AR_*')) if betas: - outputs['Cbetas'] = [os.path.join(pth, 'C{}'.format(beta)) - for beta in betas] - outputs['SDbetas'] = [os.path.join(pth, 'SD{}'.format(beta)) - for beta in betas] + outputs['Cbetas'] = [ + os.path.join(pth, 'C{}'.format(beta)) for beta in betas + ] + outputs['SDbetas'] = [ + os.path.join(pth, 'SD{}'.format(beta)) for beta in betas + ] if 'Classical' in self.inputs.estimation_method.keys(): - outputs['residual_image'] = os.path.join(pth, - 'ResMS.{}'.format(outtype)) - outputs['RPVimage'] = os.path.join(pth, - 'RPV.{}'.format(outtype)) + outputs['residual_image'] = os.path.join( + pth, 'ResMS.{}'.format(outtype)) + outputs['RPVimage'] = os.path.join(pth, 'RPV.{}'.format(outtype)) if self.inputs.write_residuals: outputs['residual_images'] = glob(os.path.join(pth, 'Res_*')) if betas: - outputs['beta_images'] = [os.path.join(pth, beta) - for beta in betas] + outputs['beta_images'] = [ + os.path.join(pth, beta) for beta in betas + ] - outputs['mask_image'] = os.path.join(pth, - 'mask.{}'.format(outtype)) + outputs['mask_image'] = os.path.join(pth, 'mask.{}'.format(outtype)) outputs['spm_mat_file'] = os.path.join(pth, 'SPM.mat') return outputs class EstimateContrastInputSpec(SPMCommandInputSpec): - spm_mat_file = File(exists=True, field='spmmat', - desc='Absolute path to SPM.mat', - copyfile=True, - mandatory=True) + spm_mat_file = File( + exists=True, + field='spmmat', + desc='Absolute path to SPM.mat', + copyfile=True, + mandatory=True) contrasts = traits.List( - traits.Either(traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('F'), - traits.List(traits.Either( - traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float)), - traits.Tuple(traits.Str, - traits.Enum('T'), - traits.List(traits.Str), - traits.List(traits.Float), - traits.List( - traits.Float)))))), + traits.Either( + traits.Tuple(traits.Str, traits.Enum('T'), traits.List(traits.Str), + traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('T'), traits.List(traits.Str), + traits.List(traits.Float), traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('F'), + traits.List( + traits.Either( + traits.Tuple(traits.Str, traits.Enum('T'), + traits.List(traits.Str), + traits.List(traits.Float)), + traits.Tuple(traits.Str, traits.Enum('T'), + traits.List(traits.Str), + traits.List(traits.Float), + traits.List(traits.Float)))))), desc="""List of contrasts with each contrast being a list of the form: [('name', 'stat', [condition list], [weight list], [session list])] If session list is None or not provided, all sessions are used. For F contrasts, the condition list should contain previously defined T-contrasts.""", mandatory=True) - beta_images = InputMultiPath(File(exists=True), - desc=('Parameter estimates of the ' - 'design matrix'), - copyfile=False, - mandatory=True) - residual_image = File(exists=True, - desc='Mean-squared image of the residuals', - copyfile=False, - mandatory=True) - use_derivs = traits.Bool(desc='use derivatives for estimation', - xor=['group_contrast']) - group_contrast = traits.Bool(desc='higher level contrast', - xor=['use_derivs']) + beta_images = InputMultiPath( + File(exists=True), + desc=('Parameter estimates of the ' + 'design matrix'), + copyfile=False, + mandatory=True) + residual_image = File( + exists=True, + desc='Mean-squared image of the residuals', + copyfile=False, + mandatory=True) + use_derivs = traits.Bool( + desc='use derivatives for estimation', xor=['group_contrast']) + group_contrast = traits.Bool( + desc='higher level contrast', xor=['use_derivs']) class EstimateContrastOutputSpec(TraitedSpec): - con_images = OutputMultiPath(File(exists=True), - desc='contrast images from a t-contrast') - spmT_images = OutputMultiPath(File(exists=True), - desc='stat images from a t-contrast') - ess_images = OutputMultiPath(File(exists=True), - desc='contrast images from an F-contrast') - spmF_images = OutputMultiPath(File(exists=True), - desc='stat images from an F-contrast') + con_images = OutputMultiPath( + File(exists=True), desc='contrast images from a t-contrast') + spmT_images = OutputMultiPath( + File(exists=True), desc='stat images from a t-contrast') + ess_images = OutputMultiPath( + File(exists=True), desc='contrast images from an F-contrast') + spmF_images = OutputMultiPath( + File(exists=True), desc='stat images from an F-contrast') spm_mat_file = File(exists=True, desc='Updated SPM mat file') @@ -376,26 +401,28 @@ def _make_matlab_command(self, _): cname = [] for i, cont in enumerate(self.inputs.contrasts): cname.insert(i, cont[0]) - contrasts.insert(i, Bunch(name=cont[0], - stat=cont[1], - conditions=cont[2], - weights=None, - sessions=None)) + contrasts.insert(i, + Bunch( + name=cont[0], + stat=cont[1], + conditions=cont[2], + weights=None, + sessions=None)) if len(cont) >= 4: contrasts[i].weights = cont[3] if len(cont) >= 5: contrasts[i].sessions = cont[4] script = "% generated by nipype.interfaces.spm\n" script += "spm_defaults;\n" - script += ("jobs{1}.stats{1}.con.spmmat = {'%s'};\n" - % self.inputs.spm_mat_file) + script += ("jobs{1}.stats{1}.con.spmmat = {'%s'};\n" % + self.inputs.spm_mat_file) script += "load(jobs{1}.stats{1}.con.spmmat{:});\n" script += "SPM.swd = '%s';\n" % os.getcwd() script += "save(jobs{1}.stats{1}.con.spmmat{:},'SPM');\n" script += "names = SPM.xX.name;\n" # get names for columns - if (isdefined(self.inputs.group_contrast) and - self.inputs.group_contrast): + if (isdefined(self.inputs.group_contrast) + and self.inputs.group_contrast): script += "condnames=names;\n" else: if self.inputs.use_derivs: @@ -413,30 +440,31 @@ def _make_matlab_command(self, _): # BUILD CONTRAST SESSION STRUCTURE for i, contrast in enumerate(contrasts): if contrast.stat == 'T': - script += ("consess{%d}.tcon.name = '%s';\n" - % (i + 1, contrast.name)) - script += ("consess{%d}.tcon.convec = zeros(1,numel(names));\n" - % (i + 1)) + script += ("consess{%d}.tcon.name = '%s';\n" % + (i + 1, contrast.name)) + script += ( + "consess{%d}.tcon.convec = zeros(1,numel(names));\n" % + (i + 1)) for c0, cond in enumerate(contrast.conditions): - script += ("idx = strmatch('%s',condnames,'exact');\n" - % (cond)) + script += ("idx = strmatch('%s',condnames,'exact');\n" % + (cond)) script += (("if isempty(idx), throw(MException(" "'CondName:Chk', sprintf('Condition %%s not " "found in design','%s'))); end;\n") % cond) if contrast.sessions: for sno, sw in enumerate(contrast.sessions): - script += ("sidx = find(condsess(idx)==%d);\n" - % (sno + 1)) + script += ("sidx = find(condsess(idx)==%d);\n" % + (sno + 1)) script += (("consess{%d}.tcon.convec(idx(sidx)) " - "= %f;\n") - % (i + 1, sw * contrast.weights[c0])) + "= %f;\n") % + (i + 1, sw * contrast.weights[c0])) else: - script += ("consess{%d}.tcon.convec(idx) = %f;\n" - % (i + 1, contrast.weights[c0])) + script += ("consess{%d}.tcon.convec(idx) = %f;\n" % + (i + 1, contrast.weights[c0])) for i, contrast in enumerate(contrasts): if contrast.stat == 'F': - script += ("consess{%d}.fcon.name = '%s';\n" - % (i + 1, contrast.name)) + script += ("consess{%d}.fcon.name = '%s';\n" % + (i + 1, contrast.name)) for cl0, fcont in enumerate(contrast.conditions): try: tidx = cname.index(fcont[0]) @@ -445,8 +473,8 @@ def _make_matlab_command(self, _): " T contrast. probably not defined prior " "to the F contrasts") script += (("consess{%d}.fcon.convec{%d} = " - "consess{%d}.tcon.convec;\n") - % (i + 1, cl0 + 1, tidx + 1)) + "consess{%d}.tcon.convec;\n") % + (i + 1, cl0 + 1, tidx + 1)) script += "jobs{1}.stats{1}.con.consess = consess;\n" script += ("if strcmp(spm('ver'),'SPM8'), spm_jobman('initcfg');" "jobs=spm_jobman('spm5tospm8',{jobs});end\n") @@ -483,37 +511,53 @@ def _list_outputs(self): class ThresholdInputSpec(SPMCommandInputSpec): - spm_mat_file = File(exists=True, desc='absolute path to SPM.mat', - copyfile=True, mandatory=True) - stat_image = File(exists=True, desc='stat image', - copyfile=False, mandatory=True) - contrast_index = traits.Int(mandatory=True, - desc='which contrast in the SPM.mat to use') - use_fwe_correction = traits.Bool(True, usedefault=True, - desc=('whether to use FWE (Bonferroni) ' - 'correction for initial threshold ' - '(height_threshold_type has to be ' - 'set to p-value)')) - use_topo_fdr = traits.Bool(True, usedefault=True, - desc=('whether to use FDR over cluster extent ' - 'probabilities')) - height_threshold = traits.Float(0.05, usedefault=True, - desc=('value for initial thresholding ' - '(defining clusters)')) - height_threshold_type = traits.Enum('p-value', 'stat', usedefault=True, - desc=('Is the cluster forming ' - 'threshold a stat value or ' - 'p-value?')) - extent_fdr_p_threshold = traits.Float(0.05, usedefault=True, - desc=('p threshold on FDR corrected ' - 'cluster size probabilities')) - extent_threshold = traits.Int(0, usedefault=True, - desc='Minimum cluster size in voxels') - force_activation = traits.Bool(False, usedefault=True, - desc=('In case no clusters survive the ' - 'topological inference step this ' - 'will pick a culster with the highes ' - 'sum of t-values. Use with care.')) + spm_mat_file = File( + exists=True, + desc='absolute path to SPM.mat', + copyfile=True, + mandatory=True) + stat_image = File( + exists=True, desc='stat image', copyfile=False, mandatory=True) + contrast_index = traits.Int( + mandatory=True, desc='which contrast in the SPM.mat to use') + use_fwe_correction = traits.Bool( + True, + usedefault=True, + desc=('whether to use FWE (Bonferroni) ' + 'correction for initial threshold ' + '(height_threshold_type has to be ' + 'set to p-value)')) + use_topo_fdr = traits.Bool( + True, + usedefault=True, + desc=('whether to use FDR over cluster extent ' + 'probabilities')) + height_threshold = traits.Float( + 0.05, + usedefault=True, + desc=('value for initial thresholding ' + '(defining clusters)')) + height_threshold_type = traits.Enum( + 'p-value', + 'stat', + usedefault=True, + desc=('Is the cluster forming ' + 'threshold a stat value or ' + 'p-value?')) + extent_fdr_p_threshold = traits.Float( + 0.05, + usedefault=True, + desc=('p threshold on FDR corrected ' + 'cluster size probabilities')) + extent_threshold = traits.Int( + 0, usedefault=True, desc='Minimum cluster size in voxels') + force_activation = traits.Bool( + False, + usedefault=True, + desc=('In case no clusters survive the ' + 'topological inference step this ' + 'will pick a culster with the highes ' + 'sum of t-values. Use with care.')) class ThresholdOutputSpec(TraitedSpec): @@ -568,11 +612,11 @@ def _make_matlab_command(self, _): script += "force_activation = 1;\n" else: script += "force_activation = 0;\n" - script += ("cluster_extent_p_fdr_thr = %f;\n" - % self.inputs.extent_fdr_p_threshold) + script += ("cluster_extent_p_fdr_thr = %f;\n" % + self.inputs.extent_fdr_p_threshold) script += "stat_filename = '%s';\n" % self.inputs.stat_image - script += ("height_threshold_type = '%s';\n" - % self.inputs.height_threshold_type) + script += ("height_threshold_type = '%s';\n" % + self.inputs.height_threshold_type) script += "extent_threshold = %d;\n" % self.inputs.extent_threshold script += "load %s;\n" % self.inputs.spm_mat_file @@ -606,8 +650,8 @@ def _make_matlab_command(self, _): """ script += (("spm_write_filtered(Zth,XYZth,stat_map_vol.dim'," - "stat_map_vol.mat,'thresholded map', '%s');\n") - % self._gen_pre_topo_map_filename()) + "stat_map_vol.mat,'thresholded map', '%s');\n") % + self._gen_pre_topo_map_filename()) script += """ max_size = 0; max_size_index = 0; @@ -699,17 +743,21 @@ def _list_outputs(self): class ThresholdStatisticsInputSpec(SPMCommandInputSpec): - spm_mat_file = File(exists=True, desc='absolute path to SPM.mat', - copyfile=True, mandatory=True) - stat_image = File(exists=True, desc='stat image', - copyfile=False, mandatory=True) - contrast_index = traits.Int(mandatory=True, - desc='which contrast in the SPM.mat to use') - height_threshold = traits.Float(desc=('stat value for initial ' - 'thresholding (defining clusters)'), - mandatory=True) - extent_threshold = traits.Int(0, usedefault=True, - desc="Minimum cluster size in voxels") + spm_mat_file = File( + exists=True, + desc='absolute path to SPM.mat', + copyfile=True, + mandatory=True) + stat_image = File( + exists=True, desc='stat image', copyfile=False, mandatory=True) + contrast_index = traits.Int( + mandatory=True, desc='which contrast in the SPM.mat to use') + height_threshold = traits.Float( + desc=('stat value for initial ' + 'thresholding (defining clusters)'), + mandatory=True) + extent_threshold = traits.Int( + 0, usedefault=True, desc="Minimum cluster size in voxels") class ThresholdStatisticsOutputSpec(TraitedSpec): @@ -800,11 +848,11 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): setattr(outputs, cur_output, float(line)) cur_output = "" continue - if (len(line.split()) != 0 and - line.split()[0] in ["clusterwise_P_FDR", - "clusterwise_P_RF", "voxelwise_P_Bonf", - "voxelwise_P_FDR", "voxelwise_P_RF", - "voxelwise_P_uncor"]): + if (len(line.split()) != 0 and line.split()[0] in [ + "clusterwise_P_FDR", "clusterwise_P_RF", + "voxelwise_P_Bonf", "voxelwise_P_FDR", "voxelwise_P_RF", + "voxelwise_P_uncor" + ]): cur_output = line.split()[0] continue @@ -812,52 +860,61 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): class FactorialDesignInputSpec(SPMCommandInputSpec): - spm_mat_dir = Directory(exists=True, field='dir', - desc='directory to store SPM.mat file (opt)') + spm_mat_dir = Directory( + exists=True, field='dir', desc='directory to store SPM.mat file (opt)') # Need to make an alias of InputMultiPath; the inputs below are not Path - covariates = InputMultiPath(traits.Dict( - key_trait=traits.Enum('vector', 'name', 'interaction', 'centering')), - field='cov', - desc=('covariate dictionary {vector, name, ' - 'interaction, centering}')) - threshold_mask_none = traits.Bool(field='masking.tm.tm_none', - xor=['threshold_mask_absolute', - 'threshold_mask_relative'], - desc='do not use threshold masking') - threshold_mask_absolute = traits.Float(field='masking.tm.tma.athresh', - xor=['threshold_mask_none', - 'threshold_mask_relative'], - desc='use an absolute threshold') - threshold_mask_relative = traits.Float(field='masking.tm.tmr.rthresh', - xor=['threshold_mask_absolute', - 'threshold_mask_none'], - desc=('threshold using a ' - 'proportion of the global ' - 'value')) - use_implicit_threshold = traits.Bool(field='masking.im', - desc=('use implicit mask NaNs or ' - 'zeros to threshold')) - explicit_mask_file = File(field='masking.em', # requires cell - desc='use an implicit mask file to threshold') - global_calc_omit = traits.Bool(field='globalc.g_omit', - xor=['global_calc_mean', - 'global_calc_values'], - desc='omit global calculation') - global_calc_mean = traits.Bool(field='globalc.g_mean', - xor=['global_calc_omit', - 'global_calc_values'], - desc='use mean for global calculation') - global_calc_values = traits.List(traits.Float, - field='globalc.g_user.global_uval', - xor=['global_calc_mean', - 'global_calc_omit'], - desc='omit global calculation') - no_grand_mean_scaling = traits.Bool(field='globalm.gmsca.gmsca_no', - desc=('do not perform grand mean ' - 'scaling')) - global_normalization = traits.Enum(1, 2, 3, field='globalm.glonorm', - desc=('global normalization None-1, ' - 'Proportional-2, ANCOVA-3')) + covariates = InputMultiPath( + traits.Dict( + key_trait=traits.Enum('vector', 'name', 'interaction', + 'centering')), + field='cov', + desc=('covariate dictionary {vector, name, ' + 'interaction, centering}')) + threshold_mask_none = traits.Bool( + field='masking.tm.tm_none', + xor=['threshold_mask_absolute', 'threshold_mask_relative'], + desc='do not use threshold masking') + threshold_mask_absolute = traits.Float( + field='masking.tm.tma.athresh', + xor=['threshold_mask_none', 'threshold_mask_relative'], + desc='use an absolute threshold') + threshold_mask_relative = traits.Float( + field='masking.tm.tmr.rthresh', + xor=['threshold_mask_absolute', 'threshold_mask_none'], + desc=('threshold using a ' + 'proportion of the global ' + 'value')) + use_implicit_threshold = traits.Bool( + field='masking.im', + desc=('use implicit mask NaNs or ' + 'zeros to threshold')) + explicit_mask_file = File( + field='masking.em', # requires cell + desc='use an implicit mask file to threshold') + global_calc_omit = traits.Bool( + field='globalc.g_omit', + xor=['global_calc_mean', 'global_calc_values'], + desc='omit global calculation') + global_calc_mean = traits.Bool( + field='globalc.g_mean', + xor=['global_calc_omit', 'global_calc_values'], + desc='use mean for global calculation') + global_calc_values = traits.List( + traits.Float, + field='globalc.g_user.global_uval', + xor=['global_calc_mean', 'global_calc_omit'], + desc='omit global calculation') + no_grand_mean_scaling = traits.Bool( + field='globalm.gmsca.gmsca_no', + desc=('do not perform grand mean ' + 'scaling')) + global_normalization = traits.Enum( + 1, + 2, + 3, + field='globalm.glonorm', + desc=('global normalization None-1, ' + 'Proportional-2, ANCOVA-3')) class FactorialDesignOutputSpec(TraitedSpec): @@ -883,9 +940,12 @@ def _format_arg(self, opt, spec, val): return np.array([str(val)], dtype=object) if opt in ['covariates']: outlist = [] - mapping = {'name': 'cname', 'vector': 'c', - 'interaction': 'iCFI', - 'centering': 'iCC'} + mapping = { + 'name': 'cname', + 'vector': 'c', + 'interaction': 'iCFI', + 'centering': 'iCC' + } for dictitem in val: outdict = {} for key, keyval in list(dictitem.items()): @@ -910,9 +970,12 @@ def _list_outputs(self): class OneSampleTTestDesignInputSpec(FactorialDesignInputSpec): - in_files = traits.List(File(exists=True), field='des.t1.scans', - mandatory=True, minlen=2, - desc='input files') + in_files = traits.List( + File(exists=True), + field='des.t1.scans', + mandatory=True, + minlen=2, + desc='input files') class OneSampleTTestDesign(FactorialDesign): @@ -939,18 +1002,26 @@ def _format_arg(self, opt, spec, val): class TwoSampleTTestDesignInputSpec(FactorialDesignInputSpec): # very unlikely that you will have a single image in one group, so setting # parameters to require at least two files in each group [SG] - group1_files = traits.List(File(exists=True), field='des.t2.scans1', - mandatory=True, minlen=2, - desc='Group 1 input files') - group2_files = traits.List(File(exists=True), field='des.t2.scans2', - mandatory=True, minlen=2, - desc='Group 2 input files') - dependent = traits.Bool(field='des.t2.dept', - desc=('Are the measurements dependent between ' - 'levels')) - unequal_variance = traits.Bool(field='des.t2.variance', - desc=('Are the variances equal or unequal ' - 'between groups')) + group1_files = traits.List( + File(exists=True), + field='des.t2.scans1', + mandatory=True, + minlen=2, + desc='Group 1 input files') + group2_files = traits.List( + File(exists=True), + field='des.t2.scans2', + mandatory=True, + minlen=2, + desc='Group 2 input files') + dependent = traits.Bool( + field='des.t2.dept', + desc=('Are the measurements dependent between ' + 'levels')) + unequal_variance = traits.Bool( + field='des.t2.variance', + desc=('Are the variances equal or unequal ' + 'between groups')) class TwoSampleTTestDesign(FactorialDesign): @@ -976,15 +1047,16 @@ def _format_arg(self, opt, spec, val): class PairedTTestDesignInputSpec(FactorialDesignInputSpec): - paired_files = traits.List(traits.List(File(exists=True), - minlen=2, maxlen=2), - field='des.pt.pair', - mandatory=True, minlen=2, - desc='List of paired files') - grand_mean_scaling = traits.Bool(field='des.pt.gmsca', - desc='Perform grand mean scaling') - ancova = traits.Bool(field='des.pt.ancova', - desc='Specify ancova-by-factor regressors') + paired_files = traits.List( + traits.List(File(exists=True), minlen=2, maxlen=2), + field='des.pt.pair', + mandatory=True, + minlen=2, + desc='List of paired files') + grand_mean_scaling = traits.Bool( + field='des.pt.gmsca', desc='Perform grand mean scaling') + ancova = traits.Bool( + field='des.pt.ancova', desc='Specify ancova-by-factor regressors') class PairedTTestDesign(FactorialDesign): @@ -1009,18 +1081,22 @@ def _format_arg(self, opt, spec, val): class MultipleRegressionDesignInputSpec(FactorialDesignInputSpec): - in_files = traits.List(File(exists=True), - field='des.mreg.scans', - mandatory=True, minlen=2, - desc='List of files') - include_intercept = traits.Bool(True, field='des.mreg.incint', - usedefault=True, - desc='Include intercept in design') - user_covariates = InputMultiPath(traits.Dict( - key_trait=traits.Enum('vector', 'name', 'centering')), - field='des.mreg.mcov', - desc=('covariate dictionary {vector, ' - 'name, centering}')) + in_files = traits.List( + File(exists=True), + field='des.mreg.scans', + mandatory=True, + minlen=2, + desc='List of files') + include_intercept = traits.Bool( + True, + field='des.mreg.incint', + usedefault=True, + desc='Include intercept in design') + user_covariates = InputMultiPath( + traits.Dict(key_trait=traits.Enum('vector', 'name', 'centering')), + field='des.mreg.mcov', + desc=('covariate dictionary {vector, ' + 'name, centering}')) class MultipleRegressionDesign(FactorialDesign): @@ -1043,13 +1119,12 @@ def _format_arg(self, opt, spec, val): return np.array(val, dtype=object) if opt in ['user_covariates']: outlist = [] - mapping = {'name': 'cname', 'vector': 'c', - 'centering': 'iCC'} + mapping = {'name': 'cname', 'vector': 'c', 'centering': 'iCC'} for dictitem in val: outdict = {} for key, keyval in list(dictitem.items()): outdict[mapping[key]] = keyval outlist.append(outdict) return outlist - return (super(MultipleRegressionDesign, self) - ._format_arg(opt, spec, val)) + return (super(MultipleRegressionDesign, self)._format_arg( + opt, spec, val)) diff --git a/nipype/interfaces/spm/preprocess.py b/nipype/interfaces/spm/preprocess.py index 0eebf3c6b8..7dd47ef46f 100644 --- a/nipype/interfaces/spm/preprocess.py +++ b/nipype/interfaces/spm/preprocess.py @@ -9,10 +9,10 @@ >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range - import os from copy import deepcopy @@ -22,44 +22,48 @@ # Local imports from ...utils.filemanip import (fname_presuffix, filename_to_list, list_to_filename, split_filename) -from ..base import (OutputMultiPath, TraitedSpec, isdefined, - traits, InputMultiPath, File) -from .base import (SPMCommand, scans_for_fname, func_is_3d, - scans_for_fnames, SPMCommandInputSpec, ImageFileSPM) +from ..base import (OutputMultiPath, TraitedSpec, isdefined, traits, + InputMultiPath, File) +from .base import (SPMCommand, scans_for_fname, func_is_3d, scans_for_fnames, + SPMCommandInputSpec, ImageFileSPM) __docformat__ = 'restructuredtext' - class SliceTimingInputSpec(SPMCommandInputSpec): - in_files = InputMultiPath(traits.Either(traits.List(ImageFileSPM( - exists=True)), - ImageFileSPM(exists=True)), - field='scans', - desc='list of filenames to apply slice timing', - mandatory=True, copyfile=False) - num_slices = traits.Int(field='nslices', - desc='number of slices in a volume', - mandatory=True) - time_repetition = traits.Float(field='tr', - desc=('time between volume acquisitions' - '(start to start time)'), - mandatory=True) - time_acquisition = traits.Float(field='ta', - desc=('time of volume acquisition. usually' - 'calculated as TR-(TR/num_slices)'), - mandatory=True) - slice_order = traits.List(traits.Float(), field='so', - desc=('1-based order or onset (in ms) in which ' - 'slices are acquired'), - mandatory=True) - ref_slice = traits.Int(field='refslice', - desc='1-based Number of the reference slice or ' - 'reference time point if slice_order is in ' - 'onsets (ms)', - mandatory=True) - out_prefix = traits.String('a', field='prefix', usedefault=True, - desc='slicetimed output prefix') + in_files = InputMultiPath( + traits.Either( + traits.List(ImageFileSPM(exists=True)), ImageFileSPM(exists=True)), + field='scans', + desc='list of filenames to apply slice timing', + mandatory=True, + copyfile=False) + num_slices = traits.Int( + field='nslices', desc='number of slices in a volume', mandatory=True) + time_repetition = traits.Float( + field='tr', + desc=('time between volume acquisitions' + '(start to start time)'), + mandatory=True) + time_acquisition = traits.Float( + field='ta', + desc=('time of volume acquisition. usually' + 'calculated as TR-(TR/num_slices)'), + mandatory=True) + slice_order = traits.List( + traits.Float(), + field='so', + desc=('1-based order or onset (in ms) in which ' + 'slices are acquired'), + mandatory=True) + ref_slice = traits.Int( + field='refslice', + desc='1-based Number of the reference slice or ' + 'reference time point if slice_order is in ' + 'onsets (ms)', + mandatory=True) + out_prefix = traits.String( + 'a', field='prefix', usedefault=True, desc='slicetimed output prefix') class SliceTimingOutputSpec(TraitedSpec): @@ -98,9 +102,8 @@ def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'in_files': - return scans_for_fnames(filename_to_list(val), - keep4d=False, - separate_sessions=True) + return scans_for_fnames( + filename_to_list(val), keep4d=False, separate_sessions=True) return super(SliceTiming, self)._format_arg(opt, spec, val) def _list_outputs(self): @@ -110,8 +113,10 @@ def _list_outputs(self): filelist = filename_to_list(self.inputs.in_files) for f in filelist: if isinstance(f, list): - run = [fname_presuffix(in_f, prefix=self.inputs.out_prefix) - for in_f in f] + run = [ + fname_presuffix(in_f, prefix=self.inputs.out_prefix) + for in_f in f + ] else: run = fname_presuffix(f, prefix=self.inputs.out_prefix) outputs['timecorrected_files'].append(run) @@ -119,67 +124,98 @@ def _list_outputs(self): class RealignInputSpec(SPMCommandInputSpec): - in_files = InputMultiPath(traits.Either(traits.List( - ImageFileSPM(exists=True)), - ImageFileSPM(exists=True)), field='data', - mandatory=True, copyfile=True, - desc='list of filenames to realign') - jobtype = traits.Enum('estwrite', 'estimate', 'write', - desc='one of: estimate, write, estwrite', - usedefault=True) - quality = traits.Range(low=0.0, high=1.0, field='eoptions.quality', - desc='0.1 = fast, 1.0 = precise') - fwhm = traits.Range(low=0.0, field='eoptions.fwhm', - desc='gaussian smoothing kernel width') - separation = traits.Range(low=0.0, field='eoptions.sep', - desc='sampling separation in mm') - register_to_mean = traits.Bool(field='eoptions.rtm', - desc=('Indicate whether realignment is ' - 'done to the mean image')) - weight_img = File(exists=True, field='eoptions.weight', - desc='filename of weighting image') - interp = traits.Range(low=0, high=7, field='eoptions.interp', - desc='degree of b-spline used for interpolation') - wrap = traits.List(traits.Int(), minlen=3, maxlen=3, - field='eoptions.wrap', - desc='Check if interpolation should wrap in [x,y,z]') - write_which = traits.ListInt([2, 1], field='roptions.which', - minlen=2, maxlen=2, usedefault=True, - desc='determines which images to reslice') - write_interp = traits.Range(low=0, high=7, field='roptions.interp', - desc=('degree of b-spline used for ' - 'interpolation')) - write_wrap = traits.List(traits.Int(), minlen=3, maxlen=3, - field='roptions.wrap', - desc=('Check if interpolation should wrap in ' - '[x,y,z]')) - write_mask = traits.Bool(field='roptions.mask', - desc='True/False mask output image') - out_prefix = traits.String('r', field='roptions.prefix', usedefault=True, - desc='realigned output prefix') + in_files = InputMultiPath( + traits.Either( + traits.List(ImageFileSPM(exists=True)), ImageFileSPM(exists=True)), + field='data', + mandatory=True, + copyfile=True, + desc='list of filenames to realign') + jobtype = traits.Enum( + 'estwrite', + 'estimate', + 'write', + desc='one of: estimate, write, estwrite', + usedefault=True) + quality = traits.Range( + low=0.0, + high=1.0, + field='eoptions.quality', + desc='0.1 = fast, 1.0 = precise') + fwhm = traits.Range( + low=0.0, field='eoptions.fwhm', desc='gaussian smoothing kernel width') + separation = traits.Range( + low=0.0, field='eoptions.sep', desc='sampling separation in mm') + register_to_mean = traits.Bool( + field='eoptions.rtm', + desc=('Indicate whether realignment is ' + 'done to the mean image')) + weight_img = File( + exists=True, + field='eoptions.weight', + desc='filename of weighting image') + interp = traits.Range( + low=0, + high=7, + field='eoptions.interp', + desc='degree of b-spline used for interpolation') + wrap = traits.List( + traits.Int(), + minlen=3, + maxlen=3, + field='eoptions.wrap', + desc='Check if interpolation should wrap in [x,y,z]') + write_which = traits.ListInt( + [2, 1], + field='roptions.which', + minlen=2, + maxlen=2, + usedefault=True, + desc='determines which images to reslice') + write_interp = traits.Range( + low=0, + high=7, + field='roptions.interp', + desc=('degree of b-spline used for ' + 'interpolation')) + write_wrap = traits.List( + traits.Int(), + minlen=3, + maxlen=3, + field='roptions.wrap', + desc=('Check if interpolation should wrap in ' + '[x,y,z]')) + write_mask = traits.Bool( + field='roptions.mask', desc='True/False mask output image') + out_prefix = traits.String( + 'r', + field='roptions.prefix', + usedefault=True, + desc='realigned output prefix') class RealignOutputSpec(TraitedSpec): mean_image = File(exists=True, desc='Mean image file from the realignment') - modified_in_files = OutputMultiPath(traits.Either( - traits.List(File(exists=True)), File(exists=True)), - desc=('Copies of all files passed to ' - 'in_files. Headers will have ' - 'been modified to align all ' - 'images with the first, or ' - 'optionally to first do that, ' - 'extract a mean image, and ' - 're-align to that mean image.')) - realigned_files = OutputMultiPath(traits.Either( - traits.List(File(exists=True)), File(exists=True)), - desc=('If jobtype is write or estwrite, ' - 'these will be the resliced files.' - ' Otherwise, they will be copies ' - 'of in_files that have had their ' - 'headers rewritten.')) - realignment_parameters = OutputMultiPath(File(exists=True), - desc=('Estimated translation and ' - 'rotation parameters')) + modified_in_files = OutputMultiPath( + traits.Either(traits.List(File(exists=True)), File(exists=True)), + desc=('Copies of all files passed to ' + 'in_files. Headers will have ' + 'been modified to align all ' + 'images with the first, or ' + 'optionally to first do that, ' + 'extract a mean image, and ' + 're-align to that mean image.')) + realigned_files = OutputMultiPath( + traits.Either(traits.List(File(exists=True)), File(exists=True)), + desc=('If jobtype is write or estwrite, ' + 'these will be the resliced files.' + ' Otherwise, they will be copies ' + 'of in_files that have had their ' + 'headers rewritten.')) + realignment_parameters = OutputMultiPath( + File(exists=True), + desc=('Estimated translation and ' + 'rotation parameters')) class Realign(SPMCommand): @@ -212,9 +248,8 @@ def _format_arg(self, opt, spec, val): separate_sessions = False else: separate_sessions = True - return scans_for_fnames(val, - keep4d=False, - separate_sessions=separate_sessions) + return scans_for_fnames( + val, keep4d=False, separate_sessions=separate_sessions) return super(Realign, self)._format_arg(opt, spec, val) def _parse_inputs(self): @@ -237,14 +272,14 @@ def _list_outputs(self): else: tmp_imgf = imgf outputs['realignment_parameters'].append( - fname_presuffix(tmp_imgf, prefix='rp_', suffix='.txt', - use_ext=False)) + fname_presuffix( + tmp_imgf, prefix='rp_', suffix='.txt', use_ext=False)) if not isinstance(imgf, list) and func_is_3d(imgf): break if self.inputs.jobtype == "estimate": outputs['realigned_files'] = self.inputs.in_files - if (self.inputs.jobtype == "estimate" or - self.inputs.jobtype == "estwrite"): + if (self.inputs.jobtype == "estimate" + or self.inputs.jobtype == "estwrite"): outputs['modified_in_files'] = self.inputs.in_files if self.inputs.jobtype == "write" or self.inputs.jobtype == "estwrite": if isinstance(self.inputs.in_files[0], list): @@ -253,13 +288,13 @@ def _list_outputs(self): first_image = self.inputs.in_files[0] if resliced_mean: - outputs['mean_image'] = fname_presuffix(first_image, - prefix='mean') + outputs['mean_image'] = fname_presuffix( + first_image, prefix='mean') if resliced_all: outputs['realigned_files'] = [] for idx, imgf in enumerate( - filename_to_list(self.inputs.in_files)): + filename_to_list(self.inputs.in_files)): realigned_run = [] if isinstance(imgf, list): for i, inner_imgf in enumerate(filename_to_list(imgf)): @@ -274,50 +309,79 @@ def _list_outputs(self): class CoregisterInputSpec(SPMCommandInputSpec): - target = ImageFileSPM(exists=True, mandatory=True, - field='ref', desc='reference file to register to', - copyfile=False) - source = InputMultiPath(ImageFileSPM(exists=True), - field='source', desc='file to register to target', - copyfile=True, mandatory=True) - jobtype = traits.Enum('estwrite', 'estimate', 'write', - desc='one of: estimate, write, estwrite', - usedefault=True) - apply_to_files = InputMultiPath(File(exists=True), field='other', - desc='files to apply transformation to', - copyfile=True) - cost_function = traits.Enum('mi', 'nmi', 'ecc', 'ncc', - field='eoptions.cost_fun', - desc="""cost function, one of: + target = ImageFileSPM( + exists=True, + mandatory=True, + field='ref', + desc='reference file to register to', + copyfile=False) + source = InputMultiPath( + ImageFileSPM(exists=True), + field='source', + desc='file to register to target', + copyfile=True, + mandatory=True) + jobtype = traits.Enum( + 'estwrite', + 'estimate', + 'write', + desc='one of: estimate, write, estwrite', + usedefault=True) + apply_to_files = InputMultiPath( + File(exists=True), + field='other', + desc='files to apply transformation to', + copyfile=True) + cost_function = traits.Enum( + 'mi', + 'nmi', + 'ecc', + 'ncc', + field='eoptions.cost_fun', + desc="""cost function, one of: 'mi' - Mutual Information, 'nmi' - Normalised Mutual Information, 'ecc' - Entropy Correlation Coefficient, 'ncc' - Normalised Cross Correlation""") - fwhm = traits.List(traits.Float(), minlen=2, maxlen=2, - field='eoptions.fwhm', - desc='gaussian smoothing kernel width (mm)') - separation = traits.List(traits.Float(), field='eoptions.sep', - desc='sampling separation in mm') - tolerance = traits.List(traits.Float(), field='eoptions.tol', - desc='acceptable tolerance for each of 12 params') - write_interp = traits.Range(low=0, high=7, field='roptions.interp', - desc=('degree of b-spline used for ' - 'interpolation')) - write_wrap = traits.List(traits.Int(), minlen=3, maxlen=3, - field='roptions.wrap', - desc=('Check if interpolation should wrap in ' - '[x,y,z]')) - write_mask = traits.Bool(field='roptions.mask', - desc='True/False mask output image') - out_prefix = traits.String('r', field='roptions.prefix', usedefault=True, - desc='coregistered output prefix') + fwhm = traits.List( + traits.Float(), + minlen=2, + maxlen=2, + field='eoptions.fwhm', + desc='gaussian smoothing kernel width (mm)') + separation = traits.List( + traits.Float(), field='eoptions.sep', desc='sampling separation in mm') + tolerance = traits.List( + traits.Float(), + field='eoptions.tol', + desc='acceptable tolerance for each of 12 params') + write_interp = traits.Range( + low=0, + high=7, + field='roptions.interp', + desc=('degree of b-spline used for ' + 'interpolation')) + write_wrap = traits.List( + traits.Int(), + minlen=3, + maxlen=3, + field='roptions.wrap', + desc=('Check if interpolation should wrap in ' + '[x,y,z]')) + write_mask = traits.Bool( + field='roptions.mask', desc='True/False mask output image') + out_prefix = traits.String( + 'r', + field='roptions.prefix', + usedefault=True, + desc='coregistered output prefix') class CoregisterOutputSpec(TraitedSpec): - coregistered_source = OutputMultiPath(File(exists=True), - desc='Coregistered source files') - coregistered_files = OutputMultiPath(File(exists=True), - desc='Coregistered other files') + coregistered_source = OutputMultiPath( + File(exists=True), desc='Coregistered source files') + coregistered_files = OutputMultiPath( + File(exists=True), desc='Coregistered other files') class Coregister(SPMCommand): @@ -344,10 +408,9 @@ class Coregister(SPMCommand): def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ - if (opt == 'target' or - (opt == 'source' and self.inputs.jobtype != "write")): - return scans_for_fnames(filename_to_list(val), - keep4d=True) + if (opt == 'target' + or (opt == 'source' and self.inputs.jobtype != "write")): + return scans_for_fnames(filename_to_list(val), keep4d=True) if opt == 'apply_to_files': return np.array(filename_to_list(val), dtype=object) if opt == 'source' and self.inputs.jobtype == "write": @@ -375,94 +438,127 @@ def _list_outputs(self): if isdefined(self.inputs.apply_to_files): outputs['coregistered_files'] = self.inputs.apply_to_files outputs['coregistered_source'] = self.inputs.source - elif (self.inputs.jobtype == "write" or - self.inputs.jobtype == "estwrite"): + elif (self.inputs.jobtype == "write" + or self.inputs.jobtype == "estwrite"): if isdefined(self.inputs.apply_to_files): outputs['coregistered_files'] = [] for imgf in filename_to_list(self.inputs.apply_to_files): - (outputs['coregistered_files'] - .append(fname_presuffix(imgf, - prefix=self.inputs.out_prefix))) + (outputs['coregistered_files'].append( + fname_presuffix(imgf, prefix=self.inputs.out_prefix))) outputs['coregistered_source'] = [] for imgf in filename_to_list(self.inputs.source): - (outputs['coregistered_source'] - .append(fname_presuffix(imgf, prefix=self.inputs.out_prefix))) + (outputs['coregistered_source'].append( + fname_presuffix(imgf, prefix=self.inputs.out_prefix))) return outputs class NormalizeInputSpec(SPMCommandInputSpec): - template = File(exists=True, field='eoptions.template', - desc='template file to normalize to', - mandatory=True, xor=['parameter_file'], - copyfile=False) - source = InputMultiPath(ImageFileSPM(exists=True), - field='subj.source', xor=['parameter_file'], - desc='file to normalize to template', - mandatory=True, copyfile=True) - jobtype = traits.Enum('estwrite', 'est', 'write', usedefault=True, - desc='Estimate, Write or do both') + template = File( + exists=True, + field='eoptions.template', + desc='template file to normalize to', + mandatory=True, + xor=['parameter_file'], + copyfile=False) + source = InputMultiPath( + ImageFileSPM(exists=True), + field='subj.source', + xor=['parameter_file'], + desc='file to normalize to template', + mandatory=True, + copyfile=True) + jobtype = traits.Enum( + 'estwrite', + 'est', + 'write', + usedefault=True, + desc='Estimate, Write or do both') apply_to_files = InputMultiPath( traits.Either(File(exists=True), traits.List(File(exists=True))), field='subj.resample', desc='files to apply transformation to', copyfile=True) - parameter_file = File(field='subj.matname', mandatory=True, - xor=['source', 'template'], - desc='normalization parameter file*_sn.mat', - copyfile=False) - source_weight = File(field='subj.wtsrc', - desc='name of weighting image for source', - copyfile=False) - template_weight = File(field='eoptions.weight', - desc='name of weighting image for template', - copyfile=False) - source_image_smoothing = traits.Float(field='eoptions.smosrc', - desc='source smoothing') - template_image_smoothing = traits.Float(field='eoptions.smoref', - desc='template smoothing') - affine_regularization_type = traits.Enum('mni', 'size', 'none', - field='eoptions.regtype', - desc='mni, size, none') - DCT_period_cutoff = traits.Float(field='eoptions.cutoff', - desc='Cutoff of for DCT bases') - nonlinear_iterations = traits.Int(field='eoptions.nits', - desc=('Number of iterations of ' - 'nonlinear warping')) - nonlinear_regularization = traits.Float(field='eoptions.reg', - desc=('the amount of the ' - 'regularization for the ' - 'nonlinear part of the ' - 'normalization')) - write_preserve = traits.Bool(field='roptions.preserve', - desc='True/False warped images are modulated') - write_bounding_box = traits.List(traits.List(traits.Float(), minlen=3, - maxlen=3), - field='roptions.bb', minlen=2, maxlen=2, - desc='3x2-element list of lists') - write_voxel_sizes = traits.List(traits.Float(), field='roptions.vox', - minlen=3, maxlen=3, - desc='3-element list') - write_interp = traits.Range(low=0, high=7, field='roptions.interp', - desc=('degree of b-spline used for ' - 'interpolation')) - write_wrap = traits.List(traits.Int(), field='roptions.wrap', - desc=('Check if interpolation should wrap in ' - '[x,y,z] - list of bools')) - out_prefix = traits.String('w', field='roptions.prefix', usedefault=True, - desc='normalized output prefix') + parameter_file = File( + field='subj.matname', + mandatory=True, + xor=['source', 'template'], + desc='normalization parameter file*_sn.mat', + copyfile=False) + source_weight = File( + field='subj.wtsrc', + desc='name of weighting image for source', + copyfile=False) + template_weight = File( + field='eoptions.weight', + desc='name of weighting image for template', + copyfile=False) + source_image_smoothing = traits.Float( + field='eoptions.smosrc', desc='source smoothing') + template_image_smoothing = traits.Float( + field='eoptions.smoref', desc='template smoothing') + affine_regularization_type = traits.Enum( + 'mni', + 'size', + 'none', + field='eoptions.regtype', + desc='mni, size, none') + DCT_period_cutoff = traits.Float( + field='eoptions.cutoff', desc='Cutoff of for DCT bases') + nonlinear_iterations = traits.Int( + field='eoptions.nits', + desc=('Number of iterations of ' + 'nonlinear warping')) + nonlinear_regularization = traits.Float( + field='eoptions.reg', + desc=('the amount of the ' + 'regularization for the ' + 'nonlinear part of the ' + 'normalization')) + write_preserve = traits.Bool( + field='roptions.preserve', + desc='True/False warped images are modulated') + write_bounding_box = traits.List( + traits.List(traits.Float(), minlen=3, maxlen=3), + field='roptions.bb', + minlen=2, + maxlen=2, + desc='3x2-element list of lists') + write_voxel_sizes = traits.List( + traits.Float(), + field='roptions.vox', + minlen=3, + maxlen=3, + desc='3-element list') + write_interp = traits.Range( + low=0, + high=7, + field='roptions.interp', + desc=('degree of b-spline used for ' + 'interpolation')) + write_wrap = traits.List( + traits.Int(), + field='roptions.wrap', + desc=('Check if interpolation should wrap in ' + '[x,y,z] - list of bools')) + out_prefix = traits.String( + 'w', + field='roptions.prefix', + usedefault=True, + desc='normalized output prefix') class NormalizeOutputSpec(TraitedSpec): - normalization_parameters = OutputMultiPath(File(exists=True), - desc=('MAT files containing ' - 'the normalization ' - 'parameters')) - normalized_source = OutputMultiPath(File(exists=True), - desc='Normalized source files') - normalized_files = OutputMultiPath(File(exists=True), - desc='Normalized other files') + normalization_parameters = OutputMultiPath( + File(exists=True), + desc=('MAT files containing ' + 'the normalization ' + 'parameters')) + normalized_source = OutputMultiPath( + File(exists=True), desc='Normalized source files') + normalized_files = OutputMultiPath( + File(exists=True), desc='Normalized other files') class Normalize(SPMCommand): @@ -503,8 +599,8 @@ def _format_arg(self, opt, spec, val): def _parse_inputs(self): """Validate spm normalize options if set to None ignore """ - einputs = super(Normalize, self)._parse_inputs(skip=('jobtype', - 'apply_to_files')) + einputs = super( + Normalize, self)._parse_inputs(skip=('jobtype', 'apply_to_files')) if isdefined(self.inputs.apply_to_files): inputfiles = deepcopy(self.inputs.apply_to_files) if isdefined(self.inputs.source): @@ -535,8 +631,8 @@ def _list_outputs(self): outputs['normalized_files'] = self.inputs.apply_to_files outputs['normalized_source'] = self.inputs.source elif 'write' in self.inputs.jobtype: - if (isdefined(self.inputs.write_preserve) and - self.inputs.write_preserve): + if (isdefined(self.inputs.write_preserve) + and self.inputs.write_preserve): prefixNorm = ''.join(['m', self.inputs.out_prefix]) else: prefixNorm = self.inputs.out_prefix @@ -545,8 +641,10 @@ def _list_outputs(self): filelist = filename_to_list(self.inputs.apply_to_files) for f in filelist: if isinstance(f, list): - run = [fname_presuffix(in_f, prefix=prefixNorm) - for in_f in f] + run = [ + fname_presuffix(in_f, prefix=prefixNorm) + for in_f in f + ] else: run = [fname_presuffix(f, prefix=prefixNorm)] outputs['normalized_files'].extend(run) @@ -560,77 +658,128 @@ def _list_outputs(self): class Normalize12InputSpec(SPMCommandInputSpec): - image_to_align = ImageFileSPM(exists=True, field='subj.vol', - desc=('file to estimate normalization parameters ' - 'with'), - xor=['deformation_file'], - mandatory=True, copyfile=True) + image_to_align = ImageFileSPM( + exists=True, + field='subj.vol', + desc=('file to estimate normalization parameters ' + 'with'), + xor=['deformation_file'], + mandatory=True, + copyfile=True) apply_to_files = InputMultiPath( - traits.Either(ImageFileSPM(exists=True), - traits.List(ImageFileSPM(exists=True))), + traits.Either( + ImageFileSPM(exists=True), traits.List(ImageFileSPM(exists=True))), field='subj.resample', desc='files to apply transformation to', copyfile=True) - deformation_file = ImageFileSPM(field='subj.def', mandatory=True, - xor=['image_to_align', 'tpm'], copyfile=False, - desc=('file y_*.nii containing 3 deformation ' - 'fields for the deformation in x, y and z ' - 'dimension')) - jobtype = traits.Enum('estwrite', 'est', 'write', usedefault=True, - desc='Estimate, Write or do Both') - bias_regularization = traits.Enum(0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, - 10, field='eoptions.biasreg', - desc='no(0) - extremely heavy (10)') - bias_fwhm = traits.Enum(30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, - 140, 150, 'Inf', field='eoptions.biasfwhm', - desc='FWHM of Gaussian smoothness of bias') - tpm = File(exists=True, field='eoptions.tpm', - desc=('template in form of tissue probablitiy maps to ' - 'normalize to'), - xor=['deformation_file'], - copyfile=False) - affine_regularization_type = traits.Enum('mni', 'size', 'none', - field='eoptions.affreg', - desc='mni, size, none') - warping_regularization = traits.List(traits.Float(), field='eoptions.reg', - minlen=5, maxlen=5, - desc=('controls balance between ' - 'parameters and data')) - smoothness = traits.Float(field='eoptions.fwhm', - desc=('value (in mm) to smooth the data before ' - 'normalization')) - sampling_distance = traits.Float(field='eoptions.samp', - desc=('Sampling distance on data for ' - 'parameter estimation')) - write_bounding_box = traits.List(traits.List(traits.Float(), - minlen=3, maxlen=3), - field='woptions.bb', minlen=2, maxlen=2, - desc=('3x2-element list of lists ' - 'representing the bounding box ' - '(in mm) to be written')) - write_voxel_sizes = traits.List(traits.Float(), field='woptions.vox', - minlen=3, maxlen=3, - desc=('3-element list representing the ' - 'voxel sizes (in mm) of the written ' - 'normalised images')) - write_interp = traits.Range(low=0, high=7, field='woptions.interp', - desc=('degree of b-spline used for ' - 'interpolation')) - out_prefix = traits.String('w', field='woptions.prefix', usedefault=True, - desc='Normalized output prefix') + deformation_file = ImageFileSPM( + field='subj.def', + mandatory=True, + xor=['image_to_align', 'tpm'], + copyfile=False, + desc=('file y_*.nii containing 3 deformation ' + 'fields for the deformation in x, y and z ' + 'dimension')) + jobtype = traits.Enum( + 'estwrite', + 'est', + 'write', + usedefault=True, + desc='Estimate, Write or do Both') + bias_regularization = traits.Enum( + 0, + 0.00001, + 0.0001, + 0.001, + 0.01, + 0.1, + 1, + 10, + field='eoptions.biasreg', + desc='no(0) - extremely heavy (10)') + bias_fwhm = traits.Enum( + 30, + 40, + 50, + 60, + 70, + 80, + 90, + 100, + 110, + 120, + 130, + 140, + 150, + 'Inf', + field='eoptions.biasfwhm', + desc='FWHM of Gaussian smoothness of bias') + tpm = File( + exists=True, + field='eoptions.tpm', + desc=('template in form of tissue probablitiy maps to ' + 'normalize to'), + xor=['deformation_file'], + copyfile=False) + affine_regularization_type = traits.Enum( + 'mni', 'size', 'none', field='eoptions.affreg', desc='mni, size, none') + warping_regularization = traits.List( + traits.Float(), + field='eoptions.reg', + minlen=5, + maxlen=5, + desc=('controls balance between ' + 'parameters and data')) + smoothness = traits.Float( + field='eoptions.fwhm', + desc=('value (in mm) to smooth the data before ' + 'normalization')) + sampling_distance = traits.Float( + field='eoptions.samp', + desc=('Sampling distance on data for ' + 'parameter estimation')) + write_bounding_box = traits.List( + traits.List(traits.Float(), minlen=3, maxlen=3), + field='woptions.bb', + minlen=2, + maxlen=2, + desc=('3x2-element list of lists ' + 'representing the bounding box ' + '(in mm) to be written')) + write_voxel_sizes = traits.List( + traits.Float(), + field='woptions.vox', + minlen=3, + maxlen=3, + desc=('3-element list representing the ' + 'voxel sizes (in mm) of the written ' + 'normalised images')) + write_interp = traits.Range( + low=0, + high=7, + field='woptions.interp', + desc=('degree of b-spline used for ' + 'interpolation')) + out_prefix = traits.String( + 'w', + field='woptions.prefix', + usedefault=True, + desc='Normalized output prefix') class Normalize12OutputSpec(TraitedSpec): - deformation_field = OutputMultiPath(File(exists=True), - desc=('NIfTI file containing 3 ' - 'deformation fields for the ' - 'deformation in x, y and z ' - 'dimension')) - normalized_image = OutputMultiPath(File(exists=True), - desc=('Normalized file that needed to ' - 'be aligned')) - normalized_files = OutputMultiPath(File(exists=True), - desc='Normalized other files') + deformation_field = OutputMultiPath( + File(exists=True), + desc=('NIfTI file containing 3 ' + 'deformation fields for the ' + 'deformation in x, y and z ' + 'dimension')) + normalized_image = OutputMultiPath( + File(exists=True), + desc=('Normalized file that needed to ' + 'be aligned')) + normalized_files = OutputMultiPath( + File(exists=True), desc='Normalized other files') class Normalize12(SPMCommand): @@ -676,8 +825,9 @@ def _format_arg(self, opt, spec, val): def _parse_inputs(self, skip=()): """validate spm normalize options if set to None ignore """ - einputs = super(Normalize12, self)._parse_inputs( - skip=('jobtype', 'apply_to_files')) + einputs = super( + Normalize12, + self)._parse_inputs(skip=('jobtype', 'apply_to_files')) if isdefined(self.inputs.apply_to_files): inputfiles = deepcopy(self.inputs.apply_to_files) if isdefined(self.inputs.image_to_align): @@ -726,12 +876,19 @@ def _list_outputs(self): class SegmentInputSpec(SPMCommandInputSpec): - data = InputMultiPath(ImageFileSPM(exists=True), field='data', - desc='one scan per subject', - copyfile=False, mandatory=True) - gm_output_type = traits.List(traits.Bool(), minlen=3, maxlen=3, - field='output.GM', - desc="""Options to produce grey matter images: c1*.img, wc1*.img and mwc1*.img. + data = InputMultiPath( + ImageFileSPM(exists=True), + field='data', + desc='one scan per subject', + copyfile=False, + mandatory=True) + gm_output_type = traits.List( + traits.Bool(), + minlen=3, + maxlen=3, + field='output.GM', + desc= + """Options to produce grey matter images: c1*.img, wc1*.img and mwc1*.img. None: [False,False,False], Native Space: [False,False,True], Unmodulated Normalised: [False,True,False], @@ -740,9 +897,12 @@ class SegmentInputSpec(SPMCommandInputSpec): Native + Modulated Normalised: [True,False,True], Native + Modulated + Unmodulated: [True,True,True], Modulated + Unmodulated Normalised: [True,True,False]""") - wm_output_type = traits.List(traits.Bool(), minlen=3, maxlen=3, - field='output.WM', - desc=""" + wm_output_type = traits.List( + traits.Bool(), + minlen=3, + maxlen=3, + field='output.WM', + desc=""" Options to produce white matter images: c2*.img, wc2*.img and mwc2*.img. None: [False,False,False], Native Space: [False,False,True], @@ -752,9 +912,12 @@ class SegmentInputSpec(SPMCommandInputSpec): Native + Modulated Normalised: [True,False,True], Native + Modulated + Unmodulated: [True,True,True], Modulated + Unmodulated Normalised: [True,True,False]""") - csf_output_type = traits.List(traits.Bool(), minlen=3, maxlen=3, - field='output.CSF', - desc=""" + csf_output_type = traits.List( + traits.Bool(), + minlen=3, + maxlen=3, + field='output.CSF', + desc=""" Options to produce CSF images: c3*.img, wc3*.img and mwc3*.img. None: [False,False,False], Native Space: [False,False,True], @@ -764,63 +927,104 @@ class SegmentInputSpec(SPMCommandInputSpec): Native + Modulated Normalised: [True,False,True], Native + Modulated + Unmodulated: [True,True,True], Modulated + Unmodulated Normalised: [True,True,False]""") - save_bias_corrected = traits.Bool(field='output.biascor', - desc=('True/False produce a bias ' - 'corrected image')) - clean_masks = traits.Enum('no', 'light', 'thorough', - field='output.cleanup', - desc=("clean using estimated brain mask " - "('no','light','thorough')")) - tissue_prob_maps = traits.List(File(exists=True), field='opts.tpm', - desc=('list of gray, white & csf prob. ' - '(opt,)')) - gaussians_per_class = traits.List(traits.Int(), field='opts.ngaus', - desc=('num Gaussians capture intensity ' - 'distribution')) - affine_regularization = traits.Enum('mni', 'eastern', 'subj', 'none', '', - field='opts.regtype', - desc=('Possible options: "mni", ' - '"eastern", "subj", "none" ' - '(no reguralisation), "" ' - '(no affine registration)')) - warping_regularization = traits.Float(field='opts.warpreg', - desc=('Controls balance between ' - 'parameters and data')) - warp_frequency_cutoff = traits.Float(field='opts.warpco', - desc='Cutoff of DCT bases') - bias_regularization = traits.Enum(0, 0.00001, 0.0001, 0.001, - 0.01, 0.1, 1, 10, field='opts.biasreg', - desc='no(0) - extremely heavy (10)') - bias_fwhm = traits.Enum(30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, - 'Inf', field='opts.biasfwhm', - desc='FWHM of Gaussian smoothness of bias') - sampling_distance = traits.Float(field='opts.samp', - desc=('Sampling distance on data for ' - 'parameter estimation')) - mask_image = File(exists=True, field='opts.msk', - desc='Binary image to restrict parameter estimation ') + save_bias_corrected = traits.Bool( + field='output.biascor', + desc=('True/False produce a bias ' + 'corrected image')) + clean_masks = traits.Enum( + 'no', + 'light', + 'thorough', + field='output.cleanup', + desc=("clean using estimated brain mask " + "('no','light','thorough')")) + tissue_prob_maps = traits.List( + File(exists=True), + field='opts.tpm', + desc=('list of gray, white & csf prob. ' + '(opt,)')) + gaussians_per_class = traits.List( + traits.Int(), + field='opts.ngaus', + desc=('num Gaussians capture intensity ' + 'distribution')) + affine_regularization = traits.Enum( + 'mni', + 'eastern', + 'subj', + 'none', + '', + field='opts.regtype', + desc=('Possible options: "mni", ' + '"eastern", "subj", "none" ' + '(no reguralisation), "" ' + '(no affine registration)')) + warping_regularization = traits.Float( + field='opts.warpreg', + desc=('Controls balance between ' + 'parameters and data')) + warp_frequency_cutoff = traits.Float( + field='opts.warpco', desc='Cutoff of DCT bases') + bias_regularization = traits.Enum( + 0, + 0.00001, + 0.0001, + 0.001, + 0.01, + 0.1, + 1, + 10, + field='opts.biasreg', + desc='no(0) - extremely heavy (10)') + bias_fwhm = traits.Enum( + 30, + 40, + 50, + 60, + 70, + 80, + 90, + 100, + 110, + 120, + 130, + 'Inf', + field='opts.biasfwhm', + desc='FWHM of Gaussian smoothness of bias') + sampling_distance = traits.Float( + field='opts.samp', + desc=('Sampling distance on data for ' + 'parameter estimation')) + mask_image = File( + exists=True, + field='opts.msk', + desc='Binary image to restrict parameter estimation ') class SegmentOutputSpec(TraitedSpec): native_gm_image = File(desc='native space grey probability map') - normalized_gm_image = File(desc='normalized grey probability map',) - modulated_gm_image = File(desc=('modulated, normalized grey ' - 'probability map')) + normalized_gm_image = File(desc='normalized grey probability map', ) + modulated_gm_image = File( + desc=('modulated, normalized grey ' + 'probability map')) native_wm_image = File(desc='native space white probability map') normalized_wm_image = File(desc='normalized white probability map') - modulated_wm_image = File(desc=('modulated, normalized white ' - 'probability map')) + modulated_wm_image = File( + desc=('modulated, normalized white ' + 'probability map')) native_csf_image = File(desc='native space csf probability map') normalized_csf_image = File(desc='normalized csf probability map') - modulated_csf_image = File(desc=('modulated, normalized csf ' - 'probability map')) - modulated_input_image = File(deprecated='0.10', - new_name='bias_corrected_image', - desc='bias-corrected version of input image') + modulated_csf_image = File( + desc=('modulated, normalized csf ' + 'probability map')) + modulated_input_image = File( + deprecated='0.10', + new_name='bias_corrected_image', + desc='bias-corrected version of input image') bias_corrected_image = File(desc='bias-corrected version of input image') transformation_mat = File(exists=True, desc='Normalization transformation') - inverse_transformation_mat = File(exists=True, - desc='Inverse normalization info') + inverse_transformation_mat = File( + exists=True, desc='Inverse normalization info') class Segment(SPMCommand): @@ -878,14 +1082,14 @@ def _list_outputs(self): outtype = '%s_output_type' % tissue if isdefined(getattr(self.inputs, outtype)): for idx, (image, prefix) in enumerate([('modulated', 'mw'), - ('normalized', 'w'), - ('native', '')]): + ('normalized', + 'w'), ('native', '')]): if getattr(self.inputs, outtype)[idx]: outfield = '%s_%s_image' % (image, tissue) outputs[outfield] = fname_presuffix( f, prefix='%sc%d' % (prefix, tidx + 1)) - if (isdefined(self.inputs.save_bias_corrected) and - self.inputs.save_bias_corrected): + if (isdefined(self.inputs.save_bias_corrected) + and self.inputs.save_bias_corrected): outputs['bias_corrected_image'] = fname_presuffix(f, prefix='m') t_mat = fname_presuffix(f, suffix='_seg_sn.mat', use_ext=False) outputs['transformation_mat'] = t_mat @@ -895,63 +1099,78 @@ def _list_outputs(self): class NewSegmentInputSpec(SPMCommandInputSpec): - channel_files = InputMultiPath(ImageFileSPM(exists=True), mandatory=True, - desc="A list of files to be segmented", - field='channel', copyfile=False) - channel_info = traits.Tuple(traits.Float(), traits.Float(), - traits.Tuple(traits.Bool, traits.Bool), - desc="""A tuple with the following fields: + channel_files = InputMultiPath( + ImageFileSPM(exists=True), + mandatory=True, + desc="A list of files to be segmented", + field='channel', + copyfile=False) + channel_info = traits.Tuple( + traits.Float(), + traits.Float(), + traits.Tuple(traits.Bool, traits.Bool), + desc="""A tuple with the following fields: - bias reguralisation (0-10) - FWHM of Gaussian smoothness of bias - which maps to save (Corrected, Field) - a tuple of two boolean values""", - field='channel') + field='channel') tissues = traits.List( - traits.Tuple(traits.Tuple(ImageFileSPM(exists=True),traits.Int()), - traits.Int(), traits.Tuple(traits.Bool, traits.Bool), - traits.Tuple(traits.Bool, traits.Bool)), + traits.Tuple( + traits.Tuple(ImageFileSPM(exists=True), traits.Int()), + traits.Int(), traits.Tuple(traits.Bool, traits.Bool), + traits.Tuple(traits.Bool, traits.Bool)), desc="""A list of tuples (one per tissue) with the following fields: - tissue probability map (4D), 1-based index to frame - number of gaussians - which maps to save [Native, DARTEL] - a tuple of two boolean values - which maps to save [Unmodulated, Modulated] - a tuple of two boolean values""", field='tissue') - affine_regularization = traits.Enum('mni', 'eastern', 'subj', 'none', - field='warp.affreg', - desc='mni, eastern, subj, none ') - warping_regularization = traits.Either(traits.List(traits.Float(), - minlen=5, maxlen=5), - traits.Float(), - field='warp.reg', - desc=('Warping regularization ' - 'parameter(s). Accepts float ' - 'or list of floats (the ' - 'latter is required by ' - 'SPM12)')) - sampling_distance = traits.Float(field='warp.samp', - desc=('Sampling distance on data for ' - 'parameter estimation')) - write_deformation_fields = traits.List(traits.Bool(), minlen=2, maxlen=2, - field='warp.write', - desc=("Which deformation fields to " - "write:[Inverse, Forward]")) + affine_regularization = traits.Enum( + 'mni', + 'eastern', + 'subj', + 'none', + field='warp.affreg', + desc='mni, eastern, subj, none ') + warping_regularization = traits.Either( + traits.List(traits.Float(), minlen=5, maxlen=5), + traits.Float(), + field='warp.reg', + desc=('Warping regularization ' + 'parameter(s). Accepts float ' + 'or list of floats (the ' + 'latter is required by ' + 'SPM12)')) + sampling_distance = traits.Float( + field='warp.samp', + desc=('Sampling distance on data for ' + 'parameter estimation')) + write_deformation_fields = traits.List( + traits.Bool(), + minlen=2, + maxlen=2, + field='warp.write', + desc=("Which deformation fields to " + "write:[Inverse, Forward]")) class NewSegmentOutputSpec(TraitedSpec): - native_class_images = traits.List(traits.List(File(exists=True)), - desc='native space probability maps') - dartel_input_images = traits.List(traits.List(File(exists=True)), - desc='dartel imported class images') - normalized_class_images = traits.List(traits.List(File(exists=True)), - desc='normalized class images') - modulated_class_images = traits.List(traits.List(File(exists=True)), - desc=('modulated+normalized class ' - 'images')) - transformation_mat = OutputMultiPath(File(exists=True), - desc='Normalization transformation') - bias_corrected_images = OutputMultiPath(File(exists=True), - desc='bias corrected images') - bias_field_images = OutputMultiPath(File(exists=True), - desc='bias field images') + native_class_images = traits.List( + traits.List(File(exists=True)), desc='native space probability maps') + dartel_input_images = traits.List( + traits.List(File(exists=True)), desc='dartel imported class images') + normalized_class_images = traits.List( + traits.List(File(exists=True)), desc='normalized class images') + modulated_class_images = traits.List( + traits.List(File(exists=True)), + desc=('modulated+normalized class ' + 'images')) + transformation_mat = OutputMultiPath( + File(exists=True), desc='Normalization transformation') + bias_corrected_images = OutputMultiPath( + File(exists=True), desc='bias corrected images') + bias_field_images = OutputMultiPath( + File(exists=True), desc='bias field images') forward_deformation_field = OutputMultiPath(File(exists=True)) inverse_deformation_field = OutputMultiPath(File(exists=True)) @@ -1019,18 +1238,17 @@ def _format_arg(self, opt, spec, val): new_tissues = [] for tissue in val: new_tissue = {} - new_tissue['tpm'] = np.array([','.join([tissue[0][0], - str(tissue[0][1])])], - dtype=object) + new_tissue['tpm'] = np.array( + [','.join([tissue[0][0], str(tissue[0][1])])], + dtype=object) new_tissue['ngaus'] = tissue[1] new_tissue['native'] = [int(tissue[2][0]), int(tissue[2][1])] new_tissue['warped'] = [int(tissue[3][0]), int(tissue[3][1])] new_tissues.append(new_tissue) return new_tissues elif opt == 'write_deformation_fields': - return super(NewSegment, self)._format_arg(opt, spec, - [int(val[0]), - int(val[1])]) + return super(NewSegment, self)._format_arg( + opt, spec, [int(val[0]), int(val[1])]) else: return super(NewSegment, self)._format_arg(opt, spec, val) @@ -1097,19 +1315,24 @@ def _list_outputs(self): class SmoothInputSpec(SPMCommandInputSpec): - in_files = InputMultiPath(ImageFileSPM(exists=True), - field='data', desc='list of files to smooth', - mandatory=True, copyfile=False) - fwhm = traits.Either(traits.List(traits.Float(), minlen=3, maxlen=3), - traits.Float(), field='fwhm', - desc='3-list of fwhm for each dimension') - data_type = traits.Int(field='dtype', - desc='Data type of the output images') - implicit_masking = traits.Bool(field='im', - desc=('A mask implied by a particular' - 'voxel value')) - out_prefix = traits.String('s', field='prefix', usedefault=True, - desc='smoothed output prefix') + in_files = InputMultiPath( + ImageFileSPM(exists=True), + field='data', + desc='list of files to smooth', + mandatory=True, + copyfile=False) + fwhm = traits.Either( + traits.List(traits.Float(), minlen=3, maxlen=3), + traits.Float(), + field='fwhm', + desc='3-list of fwhm for each dimension') + data_type = traits.Int( + field='dtype', desc='Data type of the output images') + implicit_masking = traits.Bool( + field='im', desc=('A mask implied by a particular' + 'voxel value')) + out_prefix = traits.String( + 's', field='prefix', usedefault=True, desc='smoothed output prefix') class SmoothOutputSpec(TraitedSpec): @@ -1160,39 +1383,45 @@ def _list_outputs(self): class DARTELInputSpec(SPMCommandInputSpec): - image_files = traits.List(traits.List(ImageFileSPM(exists=True)), - desc="A list of files to be segmented", - field='warp.images', copyfile=False, - mandatory=True) - template_prefix = traits.Str('Template', usedefault=True, - field='warp.settings.template', - desc='Prefix for template') - regularization_form = traits.Enum('Linear', 'Membrane', 'Bending', - field='warp.settings.rform', - desc=('Form of regularization energy ' - 'term')) - iteration_parameters = traits.List(traits.Tuple(traits.Range(1, 10), - traits.Tuple(traits.Float, - traits.Float, - traits.Float), - traits.Enum(1, 2, 4, 8, 16, - 32, 64, 128, - 256, 512), - traits.Enum(0, 0.5, 1, 2, - 4, 8, 16, 32)), - minlen=3, - maxlen=12, - field='warp.settings.param', - desc="""List of tuples for each iteration + image_files = traits.List( + traits.List(ImageFileSPM(exists=True)), + desc="A list of files to be segmented", + field='warp.images', + copyfile=False, + mandatory=True) + template_prefix = traits.Str( + 'Template', + usedefault=True, + field='warp.settings.template', + desc='Prefix for template') + regularization_form = traits.Enum( + 'Linear', + 'Membrane', + 'Bending', + field='warp.settings.rform', + desc=('Form of regularization energy ' + 'term')) + iteration_parameters = traits.List( + traits.Tuple( + traits.Range(1, 10), + traits.Tuple(traits.Float, traits.Float, traits.Float), + traits.Enum(1, 2, 4, 8, 16, 32, 64, 128, 256, 512), + traits.Enum(0, 0.5, 1, 2, 4, 8, 16, 32)), + minlen=3, + maxlen=12, + field='warp.settings.param', + desc="""List of tuples for each iteration - Inner iterations - Regularization parameters - Time points for deformation model - smoothing parameter """) - optimization_parameters = traits.Tuple(traits.Float, traits.Range(1, 8), - traits.Range(1, 8), - field='warp.settings.optim', - desc=""" + optimization_parameters = traits.Tuple( + traits.Float, + traits.Range(1, 8), + traits.Range(1, 8), + field='warp.settings.optim', + desc=""" Optimization settings a tuple - LM regularization - cycles of multigrid solver @@ -1202,11 +1431,12 @@ class DARTELInputSpec(SPMCommandInputSpec): class DARTELOutputSpec(TraitedSpec): final_template_file = File(exists=True, desc='final DARTEL template') - template_files = traits.List(File(exists=True), - desc=('Templates from different stages of ' - 'iteration')) - dartel_flow_fields = traits.List(File(exists=True), - desc='DARTEL flow fields') + template_files = traits.List( + File(exists=True), + desc=('Templates from different stages of ' + 'iteration')) + dartel_flow_fields = traits.List( + File(exists=True), desc='DARTEL flow fields') class DARTEL(SPMCommand): @@ -1261,51 +1491,69 @@ def _list_outputs(self): outputs['template_files'] = [] for i in range(6): outputs['template_files'].append( - os.path.realpath( - '%s_%d.nii' % (self.inputs.template_prefix, i + 1))) + os.path.realpath('%s_%d.nii' % (self.inputs.template_prefix, + i + 1))) outputs['final_template_file'] = os.path.realpath( '%s_6.nii' % self.inputs.template_prefix) outputs['dartel_flow_fields'] = [] for filename in self.inputs.image_files[0]: pth, base, ext = split_filename(filename) outputs['dartel_flow_fields'].append( - os.path.realpath('u_%s_%s%s' % (base, - self.inputs.template_prefix, - ext))) + os.path.realpath('u_%s_%s%s' % + (base, self.inputs.template_prefix, ext))) return outputs class DARTELNorm2MNIInputSpec(SPMCommandInputSpec): - template_file = ImageFileSPM(exists=True, copyfile=False, mandatory=True, - desc="DARTEL template", field='mni_norm.template') - flowfield_files = InputMultiPath(ImageFileSPM(exists=True), mandatory=True, - desc="DARTEL flow fields u_rc1*", - field='mni_norm.data.subjs.flowfields') - apply_to_files = InputMultiPath(ImageFileSPM(exists=True), - desc="Files to apply the transform to", - field='mni_norm.data.subjs.images', - mandatory=True, copyfile=False) - voxel_size = traits.Tuple(traits.Float, traits.Float, traits.Float, - desc="Voxel sizes for output file", - field='mni_norm.vox') - bounding_box = traits.Tuple(traits.Float, traits.Float, traits.Float, - traits.Float, traits.Float, traits.Float, - desc="Voxel sizes for output file", - field='mni_norm.bb') - modulate = traits.Bool(field='mni_norm.preserve', - desc=("Modulate out images - no modulation " - "preserves concentrations")) - fwhm = traits.Either(traits.List(traits.Float(), minlen=3, maxlen=3), - traits.Float(), field='mni_norm.fwhm', - desc='3-list of fwhm for each dimension') + template_file = ImageFileSPM( + exists=True, + copyfile=False, + mandatory=True, + desc="DARTEL template", + field='mni_norm.template') + flowfield_files = InputMultiPath( + ImageFileSPM(exists=True), + mandatory=True, + desc="DARTEL flow fields u_rc1*", + field='mni_norm.data.subjs.flowfields') + apply_to_files = InputMultiPath( + ImageFileSPM(exists=True), + desc="Files to apply the transform to", + field='mni_norm.data.subjs.images', + mandatory=True, + copyfile=False) + voxel_size = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + desc="Voxel sizes for output file", + field='mni_norm.vox') + bounding_box = traits.Tuple( + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + traits.Float, + desc="Voxel sizes for output file", + field='mni_norm.bb') + modulate = traits.Bool( + field='mni_norm.preserve', + desc=("Modulate out images - no modulation " + "preserves concentrations")) + fwhm = traits.Either( + traits.List(traits.Float(), minlen=3, maxlen=3), + traits.Float(), + field='mni_norm.fwhm', + desc='3-list of fwhm for each dimension') class DARTELNorm2MNIOutputSpec(TraitedSpec): - normalized_files = OutputMultiPath(File(exists=True), - desc='Normalized files in MNI space') - normalization_parameter_file = File(exists=True, - desc=('Transform parameters to MNI ' - 'space')) + normalized_files = OutputMultiPath( + File(exists=True), desc='Normalized files in MNI space') + normalization_parameter_file = File( + exists=True, desc=('Transform parameters to MNI ' + 'space')) class DARTELNorm2MNI(SPMCommand): @@ -1371,21 +1619,31 @@ def _list_outputs(self): class CreateWarpedInputSpec(SPMCommandInputSpec): - image_files = InputMultiPath(ImageFileSPM(exists=True), mandatory=True, - desc="A list of files to be warped", - field='crt_warped.images', copyfile=False) - flowfield_files = InputMultiPath(ImageFileSPM(exists=True), copyfile=False, - desc="DARTEL flow fields u_rc1*", - field='crt_warped.flowfields', - mandatory=True) - iterations = traits.Range(low=0, high=9, - desc=("The number of iterations: log2(number of " - "time steps)"), - field='crt_warped.K') - interp = traits.Range(low=0, high=7, field='crt_warped.interp', - desc='degree of b-spline used for interpolation') - modulate = traits.Bool(field='crt_warped.jactransf', - desc="Modulate images") + image_files = InputMultiPath( + ImageFileSPM(exists=True), + mandatory=True, + desc="A list of files to be warped", + field='crt_warped.images', + copyfile=False) + flowfield_files = InputMultiPath( + ImageFileSPM(exists=True), + copyfile=False, + desc="DARTEL flow fields u_rc1*", + field='crt_warped.flowfields', + mandatory=True) + iterations = traits.Range( + low=0, + high=9, + desc=("The number of iterations: log2(number of " + "time steps)"), + field='crt_warped.K') + interp = traits.Range( + low=0, + high=7, + field='crt_warped.interp', + desc='degree of b-spline used for interpolation') + modulate = traits.Bool( + field='crt_warped.jactransf', desc="Modulate images") class CreateWarpedOutputSpec(TraitedSpec): @@ -1417,8 +1675,7 @@ def _format_arg(self, opt, spec, val): """ if opt in ['image_files']: - return scans_for_fnames(val, keep4d=True, - separate_sessions=True) + return scans_for_fnames(val, keep4d=True, separate_sessions=True) if opt in ['flowfield_files']: return scans_for_fnames(val, keep4d=True) else: @@ -1439,13 +1696,16 @@ def _list_outputs(self): class ApplyDeformationFieldInputSpec(SPMCommandInputSpec): - in_files = InputMultiPath(ImageFileSPM(exists=True), - mandatory=True, field='fnames') + in_files = InputMultiPath( + ImageFileSPM(exists=True), mandatory=True, field='fnames') deformation_field = File(exists=True, mandatory=True, field='comp{1}.def') - reference_volume = ImageFileSPM(exists=True, mandatory=True, - field='comp{2}.id.space') - interp = traits.Range(low=0, high=7, field='interp', - desc='degree of b-spline used for interpolation') + reference_volume = ImageFileSPM( + exists=True, mandatory=True, field='comp{2}.id.space') + interp = traits.Range( + low=0, + high=7, + field='interp', + desc='degree of b-spline used for interpolation') class ApplyDeformationFieldOutputSpec(TraitedSpec): @@ -1487,126 +1747,197 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): in_files = InputMultiPath( ImageFileSPM(exists=True), desc="A list of files to be segmented", - field='estwrite.data', copyfile=False, mandatory=True) + field='estwrite.data', + copyfile=False, + mandatory=True) tissues = ImageFileSPM( exists=True, field='estwrite.tpm', desc='tissue probability map') gaussians_per_class = traits.Tuple( - (2, 2, 2, 3, 4, 2), *([traits.Int()] * 6), + (2, 2, 2, 3, 4, 2), + *([traits.Int()] * 6), usedefault=True, desc='number of gaussians for each tissue class') bias_regularization = traits.Enum( - 0.0001, - (0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10), - field='estwrite.opts.biasreg', usedefault=True, + 0.0001, (0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10), + field='estwrite.opts.biasreg', + usedefault=True, desc='no(0) - extremely heavy (10)') bias_fwhm = traits.Enum( - 60, - (30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 'Inf'), + 60, (30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 'Inf'), field='estwrite.opts.biasfwhm', usedefault=True, desc='FWHM of Gaussian smoothness of bias') sampling_distance = traits.Float( - 3, usedefault=True, field='estwrite.opts.samp', + 3, + usedefault=True, + field='estwrite.opts.samp', desc='Sampling distance on data for parameter estimation') warping_regularization = traits.Float( - 4, usedefault=True, field='estwrite.opts.warpreg', + 4, + usedefault=True, + field='estwrite.opts.warpreg', desc='Controls balance between parameters and data') spatial_normalization = traits.Enum( - 'high', 'low', usedefault=True,) + 'high', + 'low', + usedefault=True, + ) dartel_template = ImageFileSPM( - exists=True, - field='estwrite.extopts.dartelwarp.normhigh.darteltpm') + exists=True, field='estwrite.extopts.dartelwarp.normhigh.darteltpm') use_sanlm_denoising_filter = traits.Range( - 0, 2, 2, usedefault=True, field='estwrite.extopts.sanlm', + 0, + 2, + 2, + usedefault=True, + field='estwrite.extopts.sanlm', desc="0=No denoising, 1=denoising,2=denoising multi-threaded") mrf_weighting = traits.Float( 0.15, usedefault=True, field='estwrite.extopts.mrf') cleanup_partitions = traits.Int( - 1, usedefault=True, field='estwrite.extopts.cleanup', + 1, + usedefault=True, + field='estwrite.extopts.cleanup', desc="0=None,1=light,2=thorough") display_results = traits.Bool( True, usedefault=True, field='estwrite.extopts.print') gm_native = traits.Bool( - False, usedefault=True, field='estwrite.output.GM.native',) + False, + usedefault=True, + field='estwrite.output.GM.native', + ) gm_normalized = traits.Bool( - False, usedefault=True, field='estwrite.output.GM.warped',) + False, + usedefault=True, + field='estwrite.output.GM.warped', + ) gm_modulated_normalized = traits.Range( - 0, 2, 2, usedefault=True, field='estwrite.output.GM.modulated', + 0, + 2, + 2, + usedefault=True, + field='estwrite.output.GM.modulated', desc='0=none,1=affine+non-linear(SPM8 default),2=non-linear only') gm_dartel = traits.Range( - 0, 2, 0, usedefault=True, field='estwrite.output.GM.dartel', + 0, + 2, + 0, + usedefault=True, + field='estwrite.output.GM.dartel', desc="0=None,1=rigid(SPM8 default),2=affine") wm_native = traits.Bool( - False, usedefault=True, field='estwrite.output.WM.native',) + False, + usedefault=True, + field='estwrite.output.WM.native', + ) wm_normalized = traits.Bool( - False, usedefault=True, field='estwrite.output.WM.warped',) + False, + usedefault=True, + field='estwrite.output.WM.warped', + ) wm_modulated_normalized = traits.Range( - 0, 2, 2, usedefault=True, field='estwrite.output.WM.modulated', + 0, + 2, + 2, + usedefault=True, + field='estwrite.output.WM.modulated', desc='0=none,1=affine+non-linear(SPM8 default),2=non-linear only') wm_dartel = traits.Range( - 0, 2, 0, usedefault=True, field='estwrite.output.WM.dartel', + 0, + 2, + 0, + usedefault=True, + field='estwrite.output.WM.dartel', desc="0=None,1=rigid(SPM8 default),2=affine") csf_native = traits.Bool( - False, usedefault=True, field='estwrite.output.CSF.native',) + False, + usedefault=True, + field='estwrite.output.CSF.native', + ) csf_normalized = traits.Bool( - False, usedefault=True, field='estwrite.output.CSF.warped',) + False, + usedefault=True, + field='estwrite.output.CSF.warped', + ) csf_modulated_normalized = traits.Range( - 0, 2, 2, usedefault=True, field='estwrite.output.CSF.modulated', + 0, + 2, + 2, + usedefault=True, + field='estwrite.output.CSF.modulated', desc='0=none,1=affine+non-linear(SPM8 default),2=non-linear only') csf_dartel = traits.Range( - 0, 2, 0, usedefault=True, field='estwrite.output.CSF.dartel', + 0, + 2, + 0, + usedefault=True, + field='estwrite.output.CSF.dartel', desc="0=None,1=rigid(SPM8 default),2=affine") bias_corrected_native = traits.Bool( - False, usedefault=True, field='estwrite.output.bias.native',) + False, + usedefault=True, + field='estwrite.output.bias.native', + ) bias_corrected_normalized = traits.Bool( - True, usedefault=True, field='estwrite.output.bias.warped',) + True, + usedefault=True, + field='estwrite.output.bias.warped', + ) bias_corrected_affine = traits.Bool( - False, usedefault=True, field='estwrite.output.bias.affine',) + False, + usedefault=True, + field='estwrite.output.bias.affine', + ) pve_label_native = traits.Bool( False, usedefault=True, field='estwrite.output.label.native') pve_label_normalized = traits.Bool( False, usedefault=True, field='estwrite.output.label.warped') pve_label_dartel = traits.Range( - 0, 2, 0, usedefault=True, field='estwrite.output.label.dartel', + 0, + 2, + 0, + usedefault=True, + field='estwrite.output.label.dartel', desc="0=None,1=rigid(SPM8 default),2=affine") jacobian_determinant = traits.Bool( False, usedefault=True, field='estwrite.jacobian.warped') deformation_field = traits.Tuple( - (0, 0), traits.Bool, traits.Bool, usedefault=True, + (0, 0), + traits.Bool, + traits.Bool, + usedefault=True, field='estwrite.output.warps', desc='forward and inverse field') class VBMSegmentOuputSpec(TraitedSpec): - native_class_images = traits.List(traits.List(File(exists=True)), - desc='native space probability maps') - dartel_input_images = traits.List(traits.List(File(exists=True)), - desc='dartel imported class images') - normalized_class_images = traits.List(traits.List(File(exists=True)), - desc='normalized class images') - modulated_class_images = traits.List(traits.List(File(exists=True)), - desc=('modulated+normalized class ' - 'images')) - transformation_mat = OutputMultiPath(File(exists=True), - desc='Normalization transformation') + native_class_images = traits.List( + traits.List(File(exists=True)), desc='native space probability maps') + dartel_input_images = traits.List( + traits.List(File(exists=True)), desc='dartel imported class images') + normalized_class_images = traits.List( + traits.List(File(exists=True)), desc='normalized class images') + modulated_class_images = traits.List( + traits.List(File(exists=True)), + desc=('modulated+normalized class ' + 'images')) + transformation_mat = OutputMultiPath( + File(exists=True), desc='Normalization transformation') bias_corrected_images = OutputMultiPath( - File(exists=True), - desc='bias corrected images') + File(exists=True), desc='bias corrected images') normalized_bias_corrected_images = OutputMultiPath( - File(exists=True), - desc='bias corrected images') + File(exists=True), desc='bias corrected images') pve_label_native_images = OutputMultiPath(File(exists=True)) pve_label_normalized_images = OutputMultiPath(File(exists=True)) @@ -1619,7 +1950,6 @@ class VBMSegmentOuputSpec(TraitedSpec): class VBMSegment(SPMCommand): - """Use VBM8 toolbox to separate structural images into different tissue classes. @@ -1692,17 +2022,18 @@ def _list_outputs(self): # normalized space if getattr(self.inputs, '%s_normalized' % tis): outputs['normalized_class_images'][i].append( - os.path.join(pth, - "w%sp%d%s.nii" % (dartel_px, - i + 1, base))) + os.path.join(pth, "w%sp%d%s.nii" % (dartel_px, i + 1, + base))) if getattr(self.inputs, '%s_modulated_normalized' % tis) == 1: - outputs['modulated_class_images'][i].append(os.path.join( - pth, "mw%sp%d%s.nii" % (dartel_px, i + 1, base))) + outputs['modulated_class_images'][i].append( + os.path.join(pth, "mw%sp%d%s.nii" % (dartel_px, i + 1, + base))) elif getattr(self.inputs, '%s_modulated_normalized' % tis) == 2: - outputs['normalized_class_images'][i].append(os.path.join( - pth, "m0w%sp%d%s.nii" % (dartel_px, i + 1, base))) + outputs['normalized_class_images'][i].append( + os.path.join(pth, "m0w%sp%d%s.nii" % (dartel_px, i + 1, + base))) if self.inputs.pve_label_native: outputs['pve_label_native_images'].append( @@ -1759,5 +2090,5 @@ def _parse_inputs(self): einputs[0]['estwrite']['extopts']['dartelwarp'] = {'normlow': 1} return einputs else: - return super(VBMSegment, self)._parse_inputs( - skip=('spatial_normalization')) + return super(VBMSegment, + self)._parse_inputs(skip=('spatial_normalization')) diff --git a/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py b/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py index dfcfe7744c..18dc844d9e 100644 --- a/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py +++ b/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py @@ -4,42 +4,43 @@ def test_Analyze2nii_inputs(): - input_map = dict(analyze_file=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + analyze_file=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = Analyze2nii.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Analyze2nii_outputs(): - output_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - nifti_file=dict(), - paths=dict(), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + output_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + nifti_file=dict(), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) outputs = Analyze2nii.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py b/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py index 36f32cc0c2..07e957ae3f 100644 --- a/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py +++ b/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py @@ -4,40 +4,41 @@ def test_ApplyDeformations_inputs(): - input_map = dict(deformation_field=dict(field='comp{1}.def', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(field='fnames', - mandatory=True, - ), - interp=dict(field='interp', - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - reference_volume=dict(field='comp{2}.id.space', - mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + deformation_field=dict( + field='comp{1}.def', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + field='fnames', + mandatory=True, + ), + interp=dict(field='interp', ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + reference_volume=dict( + field='comp{2}.id.space', + mandatory=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = ApplyDeformations.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyDeformations_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = ApplyDeformations.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py b/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py index ffe254c824..ba0f7d9065 100644 --- a/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py +++ b/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py @@ -4,46 +4,44 @@ def test_ApplyInverseDeformation_inputs(): - input_map = dict(bounding_box=dict(field='comp{1}.inv.comp{1}.sn2def.bb', - ), - deformation=dict(field='comp{1}.inv.comp{1}.sn2def.matname', - xor=['deformation_field'], - ), - deformation_field=dict(field='comp{1}.inv.comp{1}.def', - xor=['deformation'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(field='fnames', - mandatory=True, - ), - interpolation=dict(field='interp', - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - target=dict(field='comp{1}.inv.space', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - voxel_sizes=dict(field='comp{1}.inv.comp{1}.sn2def.vox', - ), + input_map = dict( + bounding_box=dict(field='comp{1}.inv.comp{1}.sn2def.bb', ), + deformation=dict( + field='comp{1}.inv.comp{1}.sn2def.matname', + xor=['deformation_field'], + ), + deformation_field=dict( + field='comp{1}.inv.comp{1}.def', + xor=['deformation'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + field='fnames', + mandatory=True, + ), + interpolation=dict(field='interp', ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + target=dict(field='comp{1}.inv.space', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + voxel_sizes=dict(field='comp{1}.inv.comp{1}.sn2def.vox', ), ) inputs = ApplyInverseDeformation.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyInverseDeformation_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = ApplyInverseDeformation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py b/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py index b1fc483046..1cec8743e8 100644 --- a/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py +++ b/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py @@ -4,36 +4,34 @@ def test_ApplyTransform_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(copyfile=True, - mandatory=True, - ), - mat=dict(mandatory=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - out_file=dict(genfile=True, - ), - paths=dict(), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + copyfile=True, + mandatory=True, + ), + mat=dict(mandatory=True, ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + out_file=dict(genfile=True, ), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = ApplyTransform.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ApplyTransform_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = ApplyTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py b/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py index 46caa23009..80d05cf65e 100644 --- a/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py +++ b/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py @@ -4,36 +4,37 @@ def test_CalcCoregAffine_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - invmat=dict(), - mat=dict(), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - moving=dict(copyfile=False, - mandatory=True, - ), - paths=dict(), - target=dict(mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + invmat=dict(), + mat=dict(), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + moving=dict( + copyfile=False, + mandatory=True, + ), + paths=dict(), + target=dict(mandatory=True, ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = CalcCoregAffine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CalcCoregAffine_outputs(): - output_map = dict(invmat=dict(), - mat=dict(), + output_map = dict( + invmat=dict(), + mat=dict(), ) outputs = CalcCoregAffine.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_Coregister.py b/nipype/interfaces/spm/tests/test_auto_Coregister.py index 3c1ab4b50c..0323ee1223 100644 --- a/nipype/interfaces/spm/tests/test_auto_Coregister.py +++ b/nipype/interfaces/spm/tests/test_auto_Coregister.py @@ -4,59 +4,56 @@ def test_Coregister_inputs(): - input_map = dict(apply_to_files=dict(copyfile=True, - field='other', - ), - cost_function=dict(field='eoptions.cost_fun', - ), - fwhm=dict(field='eoptions.fwhm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - jobtype=dict(usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - out_prefix=dict(field='roptions.prefix', - usedefault=True, - ), - paths=dict(), - separation=dict(field='eoptions.sep', - ), - source=dict(copyfile=True, - field='source', - mandatory=True, - ), - target=dict(copyfile=False, - field='ref', - mandatory=True, - ), - tolerance=dict(field='eoptions.tol', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - write_interp=dict(field='roptions.interp', - ), - write_mask=dict(field='roptions.mask', - ), - write_wrap=dict(field='roptions.wrap', - ), + input_map = dict( + apply_to_files=dict( + copyfile=True, + field='other', + ), + cost_function=dict(field='eoptions.cost_fun', ), + fwhm=dict(field='eoptions.fwhm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + jobtype=dict(usedefault=True, ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + out_prefix=dict( + field='roptions.prefix', + usedefault=True, + ), + paths=dict(), + separation=dict(field='eoptions.sep', ), + source=dict( + copyfile=True, + field='source', + mandatory=True, + ), + target=dict( + copyfile=False, + field='ref', + mandatory=True, + ), + tolerance=dict(field='eoptions.tol', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + write_interp=dict(field='roptions.interp', ), + write_mask=dict(field='roptions.mask', ), + write_wrap=dict(field='roptions.wrap', ), ) inputs = Coregister.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Coregister_outputs(): - output_map = dict(coregistered_files=dict(), - coregistered_source=dict(), + output_map = dict( + coregistered_files=dict(), + coregistered_source=dict(), ) outputs = Coregister.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_CreateWarped.py b/nipype/interfaces/spm/tests/test_auto_CreateWarped.py index f188d42e9e..33e7136635 100644 --- a/nipype/interfaces/spm/tests/test_auto_CreateWarped.py +++ b/nipype/interfaces/spm/tests/test_auto_CreateWarped.py @@ -4,43 +4,41 @@ def test_CreateWarped_inputs(): - input_map = dict(flowfield_files=dict(copyfile=False, - field='crt_warped.flowfields', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_files=dict(copyfile=False, - field='crt_warped.images', - mandatory=True, - ), - interp=dict(field='crt_warped.interp', - ), - iterations=dict(field='crt_warped.K', - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - modulate=dict(field='crt_warped.jactransf', - ), - paths=dict(), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + flowfield_files=dict( + copyfile=False, + field='crt_warped.flowfields', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_files=dict( + copyfile=False, + field='crt_warped.images', + mandatory=True, + ), + interp=dict(field='crt_warped.interp', ), + iterations=dict(field='crt_warped.K', ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + modulate=dict(field='crt_warped.jactransf', ), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = CreateWarped.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CreateWarped_outputs(): - output_map = dict(warped_files=dict(), - ) + output_map = dict(warped_files=dict(), ) outputs = CreateWarped.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_DARTEL.py b/nipype/interfaces/spm/tests/test_auto_DARTEL.py index 345c2b0b8c..b5b6ef1c28 100644 --- a/nipype/interfaces/spm/tests/test_auto_DARTEL.py +++ b/nipype/interfaces/spm/tests/test_auto_DARTEL.py @@ -4,43 +4,43 @@ def test_DARTEL_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_files=dict(copyfile=False, - field='warp.images', - mandatory=True, - ), - iteration_parameters=dict(field='warp.settings.param', - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - optimization_parameters=dict(field='warp.settings.optim', - ), - paths=dict(), - regularization_form=dict(field='warp.settings.rform', - ), - template_prefix=dict(field='warp.settings.template', - usedefault=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_files=dict( + copyfile=False, + field='warp.images', + mandatory=True, + ), + iteration_parameters=dict(field='warp.settings.param', ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + optimization_parameters=dict(field='warp.settings.optim', ), + paths=dict(), + regularization_form=dict(field='warp.settings.rform', ), + template_prefix=dict( + field='warp.settings.template', + usedefault=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = DARTEL.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DARTEL_outputs(): - output_map = dict(dartel_flow_fields=dict(), - final_template_file=dict(), - template_files=dict(), + output_map = dict( + dartel_flow_fields=dict(), + final_template_file=dict(), + template_files=dict(), ) outputs = DARTEL.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py b/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py index 1743a5d791..66d77ce30a 100644 --- a/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py +++ b/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py @@ -4,48 +4,48 @@ def test_DARTELNorm2MNI_inputs(): - input_map = dict(apply_to_files=dict(copyfile=False, - field='mni_norm.data.subjs.images', - mandatory=True, - ), - bounding_box=dict(field='mni_norm.bb', - ), - flowfield_files=dict(field='mni_norm.data.subjs.flowfields', - mandatory=True, - ), - fwhm=dict(field='mni_norm.fwhm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - modulate=dict(field='mni_norm.preserve', - ), - paths=dict(), - template_file=dict(copyfile=False, - field='mni_norm.template', - mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - voxel_size=dict(field='mni_norm.vox', - ), + input_map = dict( + apply_to_files=dict( + copyfile=False, + field='mni_norm.data.subjs.images', + mandatory=True, + ), + bounding_box=dict(field='mni_norm.bb', ), + flowfield_files=dict( + field='mni_norm.data.subjs.flowfields', + mandatory=True, + ), + fwhm=dict(field='mni_norm.fwhm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + modulate=dict(field='mni_norm.preserve', ), + paths=dict(), + template_file=dict( + copyfile=False, + field='mni_norm.template', + mandatory=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + voxel_size=dict(field='mni_norm.vox', ), ) inputs = DARTELNorm2MNI.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DARTELNorm2MNI_outputs(): - output_map = dict(normalization_parameter_file=dict(), - normalized_files=dict(), + output_map = dict( + normalization_parameter_file=dict(), + normalized_files=dict(), ) outputs = DARTELNorm2MNI.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_DicomImport.py b/nipype/interfaces/spm/tests/test_auto_DicomImport.py index 48abb3c646..81e3aa5c21 100644 --- a/nipype/interfaces/spm/tests/test_auto_DicomImport.py +++ b/nipype/interfaces/spm/tests/test_auto_DicomImport.py @@ -4,44 +4,48 @@ def test_DicomImport_inputs(): - input_map = dict(format=dict(field='convopts.format', - usedefault=True, - ), - icedims=dict(field='convopts.icedims', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(field='data', - mandatory=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - output_dir=dict(field='outdir', - usedefault=True, - ), - output_dir_struct=dict(field='root', - usedefault=True, - ), - paths=dict(), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + format=dict( + field='convopts.format', + usedefault=True, + ), + icedims=dict( + field='convopts.icedims', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + field='data', + mandatory=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + output_dir=dict( + field='outdir', + usedefault=True, + ), + output_dir_struct=dict( + field='root', + usedefault=True, + ), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = DicomImport.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DicomImport_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = DicomImport.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py b/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py index de1ac9ca63..a7fc4a897c 100644 --- a/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py +++ b/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py @@ -4,48 +4,49 @@ def test_EstimateContrast_inputs(): - input_map = dict(beta_images=dict(copyfile=False, - mandatory=True, - ), - contrasts=dict(mandatory=True, - ), - group_contrast=dict(xor=['use_derivs'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - residual_image=dict(copyfile=False, - mandatory=True, - ), - spm_mat_file=dict(copyfile=True, - field='spmmat', - mandatory=True, - ), - use_derivs=dict(xor=['group_contrast'], - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + beta_images=dict( + copyfile=False, + mandatory=True, + ), + contrasts=dict(mandatory=True, ), + group_contrast=dict(xor=['use_derivs'], ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + residual_image=dict( + copyfile=False, + mandatory=True, + ), + spm_mat_file=dict( + copyfile=True, + field='spmmat', + mandatory=True, + ), + use_derivs=dict(xor=['group_contrast'], ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = EstimateContrast.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EstimateContrast_outputs(): - output_map = dict(con_images=dict(), - ess_images=dict(), - spmF_images=dict(), - spmT_images=dict(), - spm_mat_file=dict(), + output_map = dict( + con_images=dict(), + ess_images=dict(), + spmF_images=dict(), + spmT_images=dict(), + spm_mat_file=dict(), ) outputs = EstimateContrast.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_EstimateModel.py b/nipype/interfaces/spm/tests/test_auto_EstimateModel.py index b9636e44ed..7d27d5454a 100644 --- a/nipype/interfaces/spm/tests/test_auto_EstimateModel.py +++ b/nipype/interfaces/spm/tests/test_auto_EstimateModel.py @@ -4,48 +4,50 @@ def test_EstimateModel_inputs(): - input_map = dict(estimation_method=dict(field='method', - mandatory=True, - ), - flags=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - spm_mat_file=dict(copyfile=True, - field='spmmat', - mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - write_residuals=dict(field='write_residuals', - ), + input_map = dict( + estimation_method=dict( + field='method', + mandatory=True, + ), + flags=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + spm_mat_file=dict( + copyfile=True, + field='spmmat', + mandatory=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + write_residuals=dict(field='write_residuals', ), ) inputs = EstimateModel.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_EstimateModel_outputs(): - output_map = dict(ARcoef=dict(), - Cbetas=dict(), - RPVimage=dict(), - SDbetas=dict(), - SDerror=dict(), - beta_images=dict(), - labels=dict(), - mask_image=dict(), - residual_image=dict(), - residual_images=dict(), - spm_mat_file=dict(), + output_map = dict( + ARcoef=dict(), + Cbetas=dict(), + RPVimage=dict(), + SDbetas=dict(), + SDerror=dict(), + beta_images=dict(), + labels=dict(), + mask_image=dict(), + residual_image=dict(), + residual_images=dict(), + spm_mat_file=dict(), ) outputs = EstimateModel.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py b/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py index 34de3b2efe..66e282b97e 100644 --- a/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py @@ -4,59 +4,58 @@ def test_FactorialDesign_inputs(): - input_map = dict(covariates=dict(field='cov', - ), - explicit_mask_file=dict(field='masking.em', - ), - global_calc_mean=dict(field='globalc.g_mean', - xor=['global_calc_omit', 'global_calc_values'], - ), - global_calc_omit=dict(field='globalc.g_omit', - xor=['global_calc_mean', 'global_calc_values'], - ), - global_calc_values=dict(field='globalc.g_user.global_uval', - xor=['global_calc_mean', 'global_calc_omit'], - ), - global_normalization=dict(field='globalm.glonorm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', - ), - paths=dict(), - spm_mat_dir=dict(field='dir', - ), - threshold_mask_absolute=dict(field='masking.tm.tma.athresh', - xor=['threshold_mask_none', 'threshold_mask_relative'], - ), - threshold_mask_none=dict(field='masking.tm.tm_none', - xor=['threshold_mask_absolute', 'threshold_mask_relative'], - ), - threshold_mask_relative=dict(field='masking.tm.tmr.rthresh', - xor=['threshold_mask_absolute', 'threshold_mask_none'], - ), - use_implicit_threshold=dict(field='masking.im', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + covariates=dict(field='cov', ), + explicit_mask_file=dict(field='masking.em', ), + global_calc_mean=dict( + field='globalc.g_mean', + xor=['global_calc_omit', 'global_calc_values'], + ), + global_calc_omit=dict( + field='globalc.g_omit', + xor=['global_calc_mean', 'global_calc_values'], + ), + global_calc_values=dict( + field='globalc.g_user.global_uval', + xor=['global_calc_mean', 'global_calc_omit'], + ), + global_normalization=dict(field='globalm.glonorm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', ), + paths=dict(), + spm_mat_dir=dict(field='dir', ), + threshold_mask_absolute=dict( + field='masking.tm.tma.athresh', + xor=['threshold_mask_none', 'threshold_mask_relative'], + ), + threshold_mask_none=dict( + field='masking.tm.tm_none', + xor=['threshold_mask_absolute', 'threshold_mask_relative'], + ), + threshold_mask_relative=dict( + field='masking.tm.tmr.rthresh', + xor=['threshold_mask_absolute', 'threshold_mask_none'], + ), + use_implicit_threshold=dict(field='masking.im', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = FactorialDesign.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FactorialDesign_outputs(): - output_map = dict(spm_mat_file=dict(), - ) + output_map = dict(spm_mat_file=dict(), ) outputs = FactorialDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Level1Design.py b/nipype/interfaces/spm/tests/test_auto_Level1Design.py index 5d0a14f5c5..75ca24a3cc 100644 --- a/nipype/interfaces/spm/tests/test_auto_Level1Design.py +++ b/nipype/interfaces/spm/tests/test_auto_Level1Design.py @@ -4,59 +4,53 @@ def test_Level1Design_inputs(): - input_map = dict(bases=dict(field='bases', - mandatory=True, - ), - factor_info=dict(field='fact', - ), - global_intensity_normalization=dict(field='global', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - interscan_interval=dict(field='timing.RT', - mandatory=True, - ), - mask_image=dict(field='mask', - ), - mask_threshold=dict(usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - microtime_onset=dict(field='timing.fmri_t0', - ), - microtime_resolution=dict(field='timing.fmri_t', - ), - model_serial_correlations=dict(field='cvi', - ), - paths=dict(), - session_info=dict(field='sess', - mandatory=True, - ), - spm_mat_dir=dict(field='dir', - ), - timing_units=dict(field='timing.units', - mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - volterra_expansion_order=dict(field='volt', - ), + input_map = dict( + bases=dict( + field='bases', + mandatory=True, + ), + factor_info=dict(field='fact', ), + global_intensity_normalization=dict(field='global', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + interscan_interval=dict( + field='timing.RT', + mandatory=True, + ), + mask_image=dict(field='mask', ), + mask_threshold=dict(usedefault=True, ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + microtime_onset=dict(field='timing.fmri_t0', ), + microtime_resolution=dict(field='timing.fmri_t', ), + model_serial_correlations=dict(field='cvi', ), + paths=dict(), + session_info=dict( + field='sess', + mandatory=True, + ), + spm_mat_dir=dict(field='dir', ), + timing_units=dict( + field='timing.units', + mandatory=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + volterra_expansion_order=dict(field='volt', ), ) inputs = Level1Design.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Level1Design_outputs(): - output_map = dict(spm_mat_file=dict(), - ) + output_map = dict(spm_mat_file=dict(), ) outputs = Level1Design.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py b/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py index 6c8a465865..f16dcd7e64 100644 --- a/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py @@ -4,67 +4,67 @@ def test_MultipleRegressionDesign_inputs(): - input_map = dict(covariates=dict(field='cov', - ), - explicit_mask_file=dict(field='masking.em', - ), - global_calc_mean=dict(field='globalc.g_mean', - xor=['global_calc_omit', 'global_calc_values'], - ), - global_calc_omit=dict(field='globalc.g_omit', - xor=['global_calc_mean', 'global_calc_values'], - ), - global_calc_values=dict(field='globalc.g_user.global_uval', - xor=['global_calc_mean', 'global_calc_omit'], - ), - global_normalization=dict(field='globalm.glonorm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(field='des.mreg.scans', - mandatory=True, - ), - include_intercept=dict(field='des.mreg.incint', - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', - ), - paths=dict(), - spm_mat_dir=dict(field='dir', - ), - threshold_mask_absolute=dict(field='masking.tm.tma.athresh', - xor=['threshold_mask_none', 'threshold_mask_relative'], - ), - threshold_mask_none=dict(field='masking.tm.tm_none', - xor=['threshold_mask_absolute', 'threshold_mask_relative'], - ), - threshold_mask_relative=dict(field='masking.tm.tmr.rthresh', - xor=['threshold_mask_absolute', 'threshold_mask_none'], - ), - use_implicit_threshold=dict(field='masking.im', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - user_covariates=dict(field='des.mreg.mcov', - ), + input_map = dict( + covariates=dict(field='cov', ), + explicit_mask_file=dict(field='masking.em', ), + global_calc_mean=dict( + field='globalc.g_mean', + xor=['global_calc_omit', 'global_calc_values'], + ), + global_calc_omit=dict( + field='globalc.g_omit', + xor=['global_calc_mean', 'global_calc_values'], + ), + global_calc_values=dict( + field='globalc.g_user.global_uval', + xor=['global_calc_mean', 'global_calc_omit'], + ), + global_normalization=dict(field='globalm.glonorm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + field='des.mreg.scans', + mandatory=True, + ), + include_intercept=dict( + field='des.mreg.incint', + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', ), + paths=dict(), + spm_mat_dir=dict(field='dir', ), + threshold_mask_absolute=dict( + field='masking.tm.tma.athresh', + xor=['threshold_mask_none', 'threshold_mask_relative'], + ), + threshold_mask_none=dict( + field='masking.tm.tm_none', + xor=['threshold_mask_absolute', 'threshold_mask_relative'], + ), + threshold_mask_relative=dict( + field='masking.tm.tmr.rthresh', + xor=['threshold_mask_absolute', 'threshold_mask_none'], + ), + use_implicit_threshold=dict(field='masking.im', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + user_covariates=dict(field='des.mreg.mcov', ), ) inputs = MultipleRegressionDesign.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MultipleRegressionDesign_outputs(): - output_map = dict(spm_mat_file=dict(), - ) + output_map = dict(spm_mat_file=dict(), ) outputs = MultipleRegressionDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_NewSegment.py b/nipype/interfaces/spm/tests/test_auto_NewSegment.py index 6a2b9e1334..eead9de915 100644 --- a/nipype/interfaces/spm/tests/test_auto_NewSegment.py +++ b/nipype/interfaces/spm/tests/test_auto_NewSegment.py @@ -4,52 +4,48 @@ def test_NewSegment_inputs(): - input_map = dict(affine_regularization=dict(field='warp.affreg', - ), - channel_files=dict(copyfile=False, - field='channel', - mandatory=True, - ), - channel_info=dict(field='channel', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - sampling_distance=dict(field='warp.samp', - ), - tissues=dict(field='tissue', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - warping_regularization=dict(field='warp.reg', - ), - write_deformation_fields=dict(field='warp.write', - ), + input_map = dict( + affine_regularization=dict(field='warp.affreg', ), + channel_files=dict( + copyfile=False, + field='channel', + mandatory=True, + ), + channel_info=dict(field='channel', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + sampling_distance=dict(field='warp.samp', ), + tissues=dict(field='tissue', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + warping_regularization=dict(field='warp.reg', ), + write_deformation_fields=dict(field='warp.write', ), ) inputs = NewSegment.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_NewSegment_outputs(): - output_map = dict(bias_corrected_images=dict(), - bias_field_images=dict(), - dartel_input_images=dict(), - forward_deformation_field=dict(), - inverse_deformation_field=dict(), - modulated_class_images=dict(), - native_class_images=dict(), - normalized_class_images=dict(), - transformation_mat=dict(), + output_map = dict( + bias_corrected_images=dict(), + bias_field_images=dict(), + dartel_input_images=dict(), + forward_deformation_field=dict(), + inverse_deformation_field=dict(), + modulated_class_images=dict(), + native_class_images=dict(), + normalized_class_images=dict(), + transformation_mat=dict(), ) outputs = NewSegment.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_Normalize.py b/nipype/interfaces/spm/tests/test_auto_Normalize.py index 7aa7949a11..0d98c9bae7 100644 --- a/nipype/interfaces/spm/tests/test_auto_Normalize.py +++ b/nipype/interfaces/spm/tests/test_auto_Normalize.py @@ -4,81 +4,77 @@ def test_Normalize_inputs(): - input_map = dict(DCT_period_cutoff=dict(field='eoptions.cutoff', - ), - affine_regularization_type=dict(field='eoptions.regtype', - ), - apply_to_files=dict(copyfile=True, - field='subj.resample', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - jobtype=dict(usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - nonlinear_iterations=dict(field='eoptions.nits', - ), - nonlinear_regularization=dict(field='eoptions.reg', - ), - out_prefix=dict(field='roptions.prefix', - usedefault=True, - ), - parameter_file=dict(copyfile=False, - field='subj.matname', - mandatory=True, - xor=['source', 'template'], - ), - paths=dict(), - source=dict(copyfile=True, - field='subj.source', - mandatory=True, - xor=['parameter_file'], - ), - source_image_smoothing=dict(field='eoptions.smosrc', - ), - source_weight=dict(copyfile=False, - field='subj.wtsrc', - ), - template=dict(copyfile=False, - field='eoptions.template', - mandatory=True, - xor=['parameter_file'], - ), - template_image_smoothing=dict(field='eoptions.smoref', - ), - template_weight=dict(copyfile=False, - field='eoptions.weight', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - write_bounding_box=dict(field='roptions.bb', - ), - write_interp=dict(field='roptions.interp', - ), - write_preserve=dict(field='roptions.preserve', - ), - write_voxel_sizes=dict(field='roptions.vox', - ), - write_wrap=dict(field='roptions.wrap', - ), + input_map = dict( + DCT_period_cutoff=dict(field='eoptions.cutoff', ), + affine_regularization_type=dict(field='eoptions.regtype', ), + apply_to_files=dict( + copyfile=True, + field='subj.resample', + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + jobtype=dict(usedefault=True, ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + nonlinear_iterations=dict(field='eoptions.nits', ), + nonlinear_regularization=dict(field='eoptions.reg', ), + out_prefix=dict( + field='roptions.prefix', + usedefault=True, + ), + parameter_file=dict( + copyfile=False, + field='subj.matname', + mandatory=True, + xor=['source', 'template'], + ), + paths=dict(), + source=dict( + copyfile=True, + field='subj.source', + mandatory=True, + xor=['parameter_file'], + ), + source_image_smoothing=dict(field='eoptions.smosrc', ), + source_weight=dict( + copyfile=False, + field='subj.wtsrc', + ), + template=dict( + copyfile=False, + field='eoptions.template', + mandatory=True, + xor=['parameter_file'], + ), + template_image_smoothing=dict(field='eoptions.smoref', ), + template_weight=dict( + copyfile=False, + field='eoptions.weight', + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + write_bounding_box=dict(field='roptions.bb', ), + write_interp=dict(field='roptions.interp', ), + write_preserve=dict(field='roptions.preserve', ), + write_voxel_sizes=dict(field='roptions.vox', ), + write_wrap=dict(field='roptions.wrap', ), ) inputs = Normalize.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Normalize_outputs(): - output_map = dict(normalization_parameters=dict(), - normalized_files=dict(), - normalized_source=dict(), + output_map = dict( + normalization_parameters=dict(), + normalized_files=dict(), + normalized_source=dict(), ) outputs = Normalize.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_Normalize12.py b/nipype/interfaces/spm/tests/test_auto_Normalize12.py index 74bf60132a..d56b9c4c2a 100644 --- a/nipype/interfaces/spm/tests/test_auto_Normalize12.py +++ b/nipype/interfaces/spm/tests/test_auto_Normalize12.py @@ -4,70 +4,66 @@ def test_Normalize12_inputs(): - input_map = dict(affine_regularization_type=dict(field='eoptions.affreg', - ), - apply_to_files=dict(copyfile=True, - field='subj.resample', - ), - bias_fwhm=dict(field='eoptions.biasfwhm', - ), - bias_regularization=dict(field='eoptions.biasreg', - ), - deformation_file=dict(copyfile=False, - field='subj.def', - mandatory=True, - xor=['image_to_align', 'tpm'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - image_to_align=dict(copyfile=True, - field='subj.vol', - mandatory=True, - xor=['deformation_file'], - ), - jobtype=dict(usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - out_prefix=dict(field='woptions.prefix', - usedefault=True, - ), - paths=dict(), - sampling_distance=dict(field='eoptions.samp', - ), - smoothness=dict(field='eoptions.fwhm', - ), - tpm=dict(copyfile=False, - field='eoptions.tpm', - xor=['deformation_file'], - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - warping_regularization=dict(field='eoptions.reg', - ), - write_bounding_box=dict(field='woptions.bb', - ), - write_interp=dict(field='woptions.interp', - ), - write_voxel_sizes=dict(field='woptions.vox', - ), + input_map = dict( + affine_regularization_type=dict(field='eoptions.affreg', ), + apply_to_files=dict( + copyfile=True, + field='subj.resample', + ), + bias_fwhm=dict(field='eoptions.biasfwhm', ), + bias_regularization=dict(field='eoptions.biasreg', ), + deformation_file=dict( + copyfile=False, + field='subj.def', + mandatory=True, + xor=['image_to_align', 'tpm'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + image_to_align=dict( + copyfile=True, + field='subj.vol', + mandatory=True, + xor=['deformation_file'], + ), + jobtype=dict(usedefault=True, ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + out_prefix=dict( + field='woptions.prefix', + usedefault=True, + ), + paths=dict(), + sampling_distance=dict(field='eoptions.samp', ), + smoothness=dict(field='eoptions.fwhm', ), + tpm=dict( + copyfile=False, + field='eoptions.tpm', + xor=['deformation_file'], + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + warping_regularization=dict(field='eoptions.reg', ), + write_bounding_box=dict(field='woptions.bb', ), + write_interp=dict(field='woptions.interp', ), + write_voxel_sizes=dict(field='woptions.vox', ), ) inputs = Normalize12.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Normalize12_outputs(): - output_map = dict(deformation_field=dict(), - normalized_files=dict(), - normalized_image=dict(), + output_map = dict( + deformation_field=dict(), + normalized_files=dict(), + normalized_image=dict(), ) outputs = Normalize12.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py b/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py index 323660a95d..41ba89895c 100644 --- a/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py @@ -4,62 +4,62 @@ def test_OneSampleTTestDesign_inputs(): - input_map = dict(covariates=dict(field='cov', - ), - explicit_mask_file=dict(field='masking.em', - ), - global_calc_mean=dict(field='globalc.g_mean', - xor=['global_calc_omit', 'global_calc_values'], - ), - global_calc_omit=dict(field='globalc.g_omit', - xor=['global_calc_mean', 'global_calc_values'], - ), - global_calc_values=dict(field='globalc.g_user.global_uval', - xor=['global_calc_mean', 'global_calc_omit'], - ), - global_normalization=dict(field='globalm.glonorm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(field='des.t1.scans', - mandatory=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', - ), - paths=dict(), - spm_mat_dir=dict(field='dir', - ), - threshold_mask_absolute=dict(field='masking.tm.tma.athresh', - xor=['threshold_mask_none', 'threshold_mask_relative'], - ), - threshold_mask_none=dict(field='masking.tm.tm_none', - xor=['threshold_mask_absolute', 'threshold_mask_relative'], - ), - threshold_mask_relative=dict(field='masking.tm.tmr.rthresh', - xor=['threshold_mask_absolute', 'threshold_mask_none'], - ), - use_implicit_threshold=dict(field='masking.im', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + covariates=dict(field='cov', ), + explicit_mask_file=dict(field='masking.em', ), + global_calc_mean=dict( + field='globalc.g_mean', + xor=['global_calc_omit', 'global_calc_values'], + ), + global_calc_omit=dict( + field='globalc.g_omit', + xor=['global_calc_mean', 'global_calc_values'], + ), + global_calc_values=dict( + field='globalc.g_user.global_uval', + xor=['global_calc_mean', 'global_calc_omit'], + ), + global_normalization=dict(field='globalm.glonorm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + field='des.t1.scans', + mandatory=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', ), + paths=dict(), + spm_mat_dir=dict(field='dir', ), + threshold_mask_absolute=dict( + field='masking.tm.tma.athresh', + xor=['threshold_mask_none', 'threshold_mask_relative'], + ), + threshold_mask_none=dict( + field='masking.tm.tm_none', + xor=['threshold_mask_absolute', 'threshold_mask_relative'], + ), + threshold_mask_relative=dict( + field='masking.tm.tmr.rthresh', + xor=['threshold_mask_absolute', 'threshold_mask_none'], + ), + use_implicit_threshold=dict(field='masking.im', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = OneSampleTTestDesign.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_OneSampleTTestDesign_outputs(): - output_map = dict(spm_mat_file=dict(), - ) + output_map = dict(spm_mat_file=dict(), ) outputs = OneSampleTTestDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py b/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py index d2ab89aed8..8a6d68fc20 100644 --- a/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py @@ -4,66 +4,64 @@ def test_PairedTTestDesign_inputs(): - input_map = dict(ancova=dict(field='des.pt.ancova', - ), - covariates=dict(field='cov', - ), - explicit_mask_file=dict(field='masking.em', - ), - global_calc_mean=dict(field='globalc.g_mean', - xor=['global_calc_omit', 'global_calc_values'], - ), - global_calc_omit=dict(field='globalc.g_omit', - xor=['global_calc_mean', 'global_calc_values'], - ), - global_calc_values=dict(field='globalc.g_user.global_uval', - xor=['global_calc_mean', 'global_calc_omit'], - ), - global_normalization=dict(field='globalm.glonorm', - ), - grand_mean_scaling=dict(field='des.pt.gmsca', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', - ), - paired_files=dict(field='des.pt.pair', - mandatory=True, - ), - paths=dict(), - spm_mat_dir=dict(field='dir', - ), - threshold_mask_absolute=dict(field='masking.tm.tma.athresh', - xor=['threshold_mask_none', 'threshold_mask_relative'], - ), - threshold_mask_none=dict(field='masking.tm.tm_none', - xor=['threshold_mask_absolute', 'threshold_mask_relative'], - ), - threshold_mask_relative=dict(field='masking.tm.tmr.rthresh', - xor=['threshold_mask_absolute', 'threshold_mask_none'], - ), - use_implicit_threshold=dict(field='masking.im', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + ancova=dict(field='des.pt.ancova', ), + covariates=dict(field='cov', ), + explicit_mask_file=dict(field='masking.em', ), + global_calc_mean=dict( + field='globalc.g_mean', + xor=['global_calc_omit', 'global_calc_values'], + ), + global_calc_omit=dict( + field='globalc.g_omit', + xor=['global_calc_mean', 'global_calc_values'], + ), + global_calc_values=dict( + field='globalc.g_user.global_uval', + xor=['global_calc_mean', 'global_calc_omit'], + ), + global_normalization=dict(field='globalm.glonorm', ), + grand_mean_scaling=dict(field='des.pt.gmsca', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', ), + paired_files=dict( + field='des.pt.pair', + mandatory=True, + ), + paths=dict(), + spm_mat_dir=dict(field='dir', ), + threshold_mask_absolute=dict( + field='masking.tm.tma.athresh', + xor=['threshold_mask_none', 'threshold_mask_relative'], + ), + threshold_mask_none=dict( + field='masking.tm.tm_none', + xor=['threshold_mask_absolute', 'threshold_mask_relative'], + ), + threshold_mask_relative=dict( + field='masking.tm.tmr.rthresh', + xor=['threshold_mask_absolute', 'threshold_mask_none'], + ), + use_implicit_threshold=dict(field='masking.im', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = PairedTTestDesign.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PairedTTestDesign_outputs(): - output_map = dict(spm_mat_file=dict(), - ) + output_map = dict(spm_mat_file=dict(), ) outputs = PairedTTestDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Realign.py b/nipype/interfaces/spm/tests/test_auto_Realign.py index ef1989bc19..2c9cd7bb42 100644 --- a/nipype/interfaces/spm/tests/test_auto_Realign.py +++ b/nipype/interfaces/spm/tests/test_auto_Realign.py @@ -4,65 +4,58 @@ def test_Realign_inputs(): - input_map = dict(fwhm=dict(field='eoptions.fwhm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(copyfile=True, - field='data', - mandatory=True, - ), - interp=dict(field='eoptions.interp', - ), - jobtype=dict(usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - out_prefix=dict(field='roptions.prefix', - usedefault=True, - ), - paths=dict(), - quality=dict(field='eoptions.quality', - ), - register_to_mean=dict(field='eoptions.rtm', - ), - separation=dict(field='eoptions.sep', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - weight_img=dict(field='eoptions.weight', - ), - wrap=dict(field='eoptions.wrap', - ), - write_interp=dict(field='roptions.interp', - ), - write_mask=dict(field='roptions.mask', - ), - write_which=dict(field='roptions.which', - maxlen=2, - minlen=2, - usedefault=True, - ), - write_wrap=dict(field='roptions.wrap', - ), + input_map = dict( + fwhm=dict(field='eoptions.fwhm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + copyfile=True, + field='data', + mandatory=True, + ), + interp=dict(field='eoptions.interp', ), + jobtype=dict(usedefault=True, ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + out_prefix=dict( + field='roptions.prefix', + usedefault=True, + ), + paths=dict(), + quality=dict(field='eoptions.quality', ), + register_to_mean=dict(field='eoptions.rtm', ), + separation=dict(field='eoptions.sep', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + weight_img=dict(field='eoptions.weight', ), + wrap=dict(field='eoptions.wrap', ), + write_interp=dict(field='roptions.interp', ), + write_mask=dict(field='roptions.mask', ), + write_which=dict( + field='roptions.which', + maxlen=2, + minlen=2, + usedefault=True, + ), + write_wrap=dict(field='roptions.wrap', ), ) inputs = Realign.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Realign_outputs(): - output_map = dict(mean_image=dict(), - modified_in_files=dict(), - realigned_files=dict(), - realignment_parameters=dict(), + output_map = dict( + mean_image=dict(), + modified_in_files=dict(), + realigned_files=dict(), + realignment_parameters=dict(), ) outputs = Realign.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_Reslice.py b/nipype/interfaces/spm/tests/test_auto_Reslice.py index a2f10d727c..6fd7f02c51 100644 --- a/nipype/interfaces/spm/tests/test_auto_Reslice.py +++ b/nipype/interfaces/spm/tests/test_auto_Reslice.py @@ -4,36 +4,32 @@ def test_Reslice_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - interp=dict(usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - out_file=dict(), - paths=dict(), - space_defining=dict(mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + interp=dict(usedefault=True, ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + out_file=dict(), + paths=dict(), + space_defining=dict(mandatory=True, ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = Reslice.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Reslice_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Reslice.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py b/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py index 4bca83c6cf..48704de37b 100644 --- a/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py +++ b/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py @@ -4,40 +4,36 @@ def test_ResliceToReference_inputs(): - input_map = dict(bounding_box=dict(field='comp{2}.idbbvox.bb', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(field='fnames', - mandatory=True, - ), - interpolation=dict(field='interp', - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - target=dict(field='comp{1}.id.space', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - voxel_sizes=dict(field='comp{2}.idbbvox.vox', - ), + input_map = dict( + bounding_box=dict(field='comp{2}.idbbvox.bb', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + field='fnames', + mandatory=True, + ), + interpolation=dict(field='interp', ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + target=dict(field='comp{1}.id.space', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + voxel_sizes=dict(field='comp{2}.idbbvox.vox', ), ) inputs = ResliceToReference.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ResliceToReference_outputs(): - output_map = dict(out_files=dict(), - ) + output_map = dict(out_files=dict(), ) outputs = ResliceToReference.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_SPMCommand.py b/nipype/interfaces/spm/tests/test_auto_SPMCommand.py index 0f36f719d7..2adf53dead 100644 --- a/nipype/interfaces/spm/tests/test_auto_SPMCommand.py +++ b/nipype/interfaces/spm/tests/test_auto_SPMCommand.py @@ -4,22 +4,23 @@ def test_SPMCommand_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = SPMCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/spm/tests/test_auto_Segment.py b/nipype/interfaces/spm/tests/test_auto_Segment.py index b18f405de1..61021c9599 100644 --- a/nipype/interfaces/spm/tests/test_auto_Segment.py +++ b/nipype/interfaces/spm/tests/test_auto_Segment.py @@ -4,74 +4,63 @@ def test_Segment_inputs(): - input_map = dict(affine_regularization=dict(field='opts.regtype', - ), - bias_fwhm=dict(field='opts.biasfwhm', - ), - bias_regularization=dict(field='opts.biasreg', - ), - clean_masks=dict(field='output.cleanup', - ), - csf_output_type=dict(field='output.CSF', - ), - data=dict(copyfile=False, - field='data', - mandatory=True, - ), - gaussians_per_class=dict(field='opts.ngaus', - ), - gm_output_type=dict(field='output.GM', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - mask_image=dict(field='opts.msk', - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - sampling_distance=dict(field='opts.samp', - ), - save_bias_corrected=dict(field='output.biascor', - ), - tissue_prob_maps=dict(field='opts.tpm', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - warp_frequency_cutoff=dict(field='opts.warpco', - ), - warping_regularization=dict(field='opts.warpreg', - ), - wm_output_type=dict(field='output.WM', - ), + input_map = dict( + affine_regularization=dict(field='opts.regtype', ), + bias_fwhm=dict(field='opts.biasfwhm', ), + bias_regularization=dict(field='opts.biasreg', ), + clean_masks=dict(field='output.cleanup', ), + csf_output_type=dict(field='output.CSF', ), + data=dict( + copyfile=False, + field='data', + mandatory=True, + ), + gaussians_per_class=dict(field='opts.ngaus', ), + gm_output_type=dict(field='output.GM', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + mask_image=dict(field='opts.msk', ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + sampling_distance=dict(field='opts.samp', ), + save_bias_corrected=dict(field='output.biascor', ), + tissue_prob_maps=dict(field='opts.tpm', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + warp_frequency_cutoff=dict(field='opts.warpco', ), + warping_regularization=dict(field='opts.warpreg', ), + wm_output_type=dict(field='output.WM', ), ) inputs = Segment.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Segment_outputs(): - output_map = dict(bias_corrected_image=dict(), - inverse_transformation_mat=dict(), - modulated_csf_image=dict(), - modulated_gm_image=dict(), - modulated_input_image=dict(deprecated='0.10', - new_name='bias_corrected_image', - ), - modulated_wm_image=dict(), - native_csf_image=dict(), - native_gm_image=dict(), - native_wm_image=dict(), - normalized_csf_image=dict(), - normalized_gm_image=dict(), - normalized_wm_image=dict(), - transformation_mat=dict(), + output_map = dict( + bias_corrected_image=dict(), + inverse_transformation_mat=dict(), + modulated_csf_image=dict(), + modulated_gm_image=dict(), + modulated_input_image=dict( + deprecated='0.10', + new_name='bias_corrected_image', + ), + modulated_wm_image=dict(), + native_csf_image=dict(), + native_gm_image=dict(), + native_wm_image=dict(), + normalized_csf_image=dict(), + normalized_gm_image=dict(), + normalized_wm_image=dict(), + transformation_mat=dict(), ) outputs = Segment.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_SliceTiming.py b/nipype/interfaces/spm/tests/test_auto_SliceTiming.py index 357096a402..575c6c0cca 100644 --- a/nipype/interfaces/spm/tests/test_auto_SliceTiming.py +++ b/nipype/interfaces/spm/tests/test_auto_SliceTiming.py @@ -4,51 +4,57 @@ def test_SliceTiming_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(copyfile=False, - field='scans', - mandatory=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - num_slices=dict(field='nslices', - mandatory=True, - ), - out_prefix=dict(field='prefix', - usedefault=True, - ), - paths=dict(), - ref_slice=dict(field='refslice', - mandatory=True, - ), - slice_order=dict(field='so', - mandatory=True, - ), - time_acquisition=dict(field='ta', - mandatory=True, - ), - time_repetition=dict(field='tr', - mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + copyfile=False, + field='scans', + mandatory=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + num_slices=dict( + field='nslices', + mandatory=True, + ), + out_prefix=dict( + field='prefix', + usedefault=True, + ), + paths=dict(), + ref_slice=dict( + field='refslice', + mandatory=True, + ), + slice_order=dict( + field='so', + mandatory=True, + ), + time_acquisition=dict( + field='ta', + mandatory=True, + ), + time_repetition=dict( + field='tr', + mandatory=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = SliceTiming.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SliceTiming_outputs(): - output_map = dict(timecorrected_files=dict(), - ) + output_map = dict(timecorrected_files=dict(), ) outputs = SliceTiming.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Smooth.py b/nipype/interfaces/spm/tests/test_auto_Smooth.py index 3f0426abb0..28e44f2ed3 100644 --- a/nipype/interfaces/spm/tests/test_auto_Smooth.py +++ b/nipype/interfaces/spm/tests/test_auto_Smooth.py @@ -4,42 +4,40 @@ def test_Smooth_inputs(): - input_map = dict(data_type=dict(field='dtype', - ), - fwhm=dict(field='fwhm', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - implicit_masking=dict(field='im', - ), - in_files=dict(copyfile=False, - field='data', - mandatory=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - out_prefix=dict(field='prefix', - usedefault=True, - ), - paths=dict(), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + data_type=dict(field='dtype', ), + fwhm=dict(field='fwhm', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + implicit_masking=dict(field='im', ), + in_files=dict( + copyfile=False, + field='data', + mandatory=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + out_prefix=dict( + field='prefix', + usedefault=True, + ), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = Smooth.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Smooth_outputs(): - output_map = dict(smoothed_files=dict(), - ) + output_map = dict(smoothed_files=dict(), ) outputs = Smooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Threshold.py b/nipype/interfaces/spm/tests/test_auto_Threshold.py index 017b1c5325..4a97ee3c14 100644 --- a/nipype/interfaces/spm/tests/test_auto_Threshold.py +++ b/nipype/interfaces/spm/tests/test_auto_Threshold.py @@ -4,55 +4,50 @@ def test_Threshold_inputs(): - input_map = dict(contrast_index=dict(mandatory=True, - ), - extent_fdr_p_threshold=dict(usedefault=True, - ), - extent_threshold=dict(usedefault=True, - ), - force_activation=dict(usedefault=True, - ), - height_threshold=dict(usedefault=True, - ), - height_threshold_type=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - spm_mat_file=dict(copyfile=True, - mandatory=True, - ), - stat_image=dict(copyfile=False, - mandatory=True, - ), - use_fwe_correction=dict(usedefault=True, - ), - use_mcr=dict(), - use_topo_fdr=dict(usedefault=True, - ), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + contrast_index=dict(mandatory=True, ), + extent_fdr_p_threshold=dict(usedefault=True, ), + extent_threshold=dict(usedefault=True, ), + force_activation=dict(usedefault=True, ), + height_threshold=dict(usedefault=True, ), + height_threshold_type=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + spm_mat_file=dict( + copyfile=True, + mandatory=True, + ), + stat_image=dict( + copyfile=False, + mandatory=True, + ), + use_fwe_correction=dict(usedefault=True, ), + use_mcr=dict(), + use_topo_fdr=dict(usedefault=True, ), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = Threshold.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Threshold_outputs(): - output_map = dict(activation_forced=dict(), - cluster_forming_thr=dict(), - n_clusters=dict(), - pre_topo_fdr_map=dict(), - pre_topo_n_clusters=dict(), - thresholded_map=dict(), + output_map = dict( + activation_forced=dict(), + cluster_forming_thr=dict(), + n_clusters=dict(), + pre_topo_fdr_map=dict(), + pre_topo_n_clusters=dict(), + thresholded_map=dict(), ) outputs = Threshold.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py b/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py index 7cd496ce94..93eb42db58 100644 --- a/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py +++ b/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py @@ -4,45 +4,45 @@ def test_ThresholdStatistics_inputs(): - input_map = dict(contrast_index=dict(mandatory=True, - ), - extent_threshold=dict(usedefault=True, - ), - height_threshold=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - paths=dict(), - spm_mat_file=dict(copyfile=True, - mandatory=True, - ), - stat_image=dict(copyfile=False, - mandatory=True, - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + contrast_index=dict(mandatory=True, ), + extent_threshold=dict(usedefault=True, ), + height_threshold=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + paths=dict(), + spm_mat_file=dict( + copyfile=True, + mandatory=True, + ), + stat_image=dict( + copyfile=False, + mandatory=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = ThresholdStatistics.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_ThresholdStatistics_outputs(): - output_map = dict(clusterwise_P_FDR=dict(), - clusterwise_P_RF=dict(), - voxelwise_P_Bonf=dict(), - voxelwise_P_FDR=dict(), - voxelwise_P_RF=dict(), - voxelwise_P_uncor=dict(), + output_map = dict( + clusterwise_P_FDR=dict(), + clusterwise_P_RF=dict(), + voxelwise_P_Bonf=dict(), + voxelwise_P_FDR=dict(), + voxelwise_P_RF=dict(), + voxelwise_P_uncor=dict(), ) outputs = ThresholdStatistics.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py b/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py index f38f8023be..e2d82629d6 100644 --- a/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py @@ -4,69 +4,68 @@ def test_TwoSampleTTestDesign_inputs(): - input_map = dict(covariates=dict(field='cov', - ), - dependent=dict(field='des.t2.dept', - ), - explicit_mask_file=dict(field='masking.em', - ), - global_calc_mean=dict(field='globalc.g_mean', - xor=['global_calc_omit', 'global_calc_values'], - ), - global_calc_omit=dict(field='globalc.g_omit', - xor=['global_calc_mean', 'global_calc_values'], - ), - global_calc_values=dict(field='globalc.g_user.global_uval', - xor=['global_calc_mean', 'global_calc_omit'], - ), - global_normalization=dict(field='globalm.glonorm', - ), - group1_files=dict(field='des.t2.scans1', - mandatory=True, - ), - group2_files=dict(field='des.t2.scans2', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', - ), - paths=dict(), - spm_mat_dir=dict(field='dir', - ), - threshold_mask_absolute=dict(field='masking.tm.tma.athresh', - xor=['threshold_mask_none', 'threshold_mask_relative'], - ), - threshold_mask_none=dict(field='masking.tm.tm_none', - xor=['threshold_mask_absolute', 'threshold_mask_relative'], - ), - threshold_mask_relative=dict(field='masking.tm.tmr.rthresh', - xor=['threshold_mask_absolute', 'threshold_mask_none'], - ), - unequal_variance=dict(field='des.t2.variance', - ), - use_implicit_threshold=dict(field='masking.im', - ), - use_mcr=dict(), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), + input_map = dict( + covariates=dict(field='cov', ), + dependent=dict(field='des.t2.dept', ), + explicit_mask_file=dict(field='masking.em', ), + global_calc_mean=dict( + field='globalc.g_mean', + xor=['global_calc_omit', 'global_calc_values'], + ), + global_calc_omit=dict( + field='globalc.g_omit', + xor=['global_calc_mean', 'global_calc_values'], + ), + global_calc_values=dict( + field='globalc.g_user.global_uval', + xor=['global_calc_mean', 'global_calc_omit'], + ), + global_normalization=dict(field='globalm.glonorm', ), + group1_files=dict( + field='des.t2.scans1', + mandatory=True, + ), + group2_files=dict( + field='des.t2.scans2', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + no_grand_mean_scaling=dict(field='globalm.gmsca.gmsca_no', ), + paths=dict(), + spm_mat_dir=dict(field='dir', ), + threshold_mask_absolute=dict( + field='masking.tm.tma.athresh', + xor=['threshold_mask_none', 'threshold_mask_relative'], + ), + threshold_mask_none=dict( + field='masking.tm.tm_none', + xor=['threshold_mask_absolute', 'threshold_mask_relative'], + ), + threshold_mask_relative=dict( + field='masking.tm.tmr.rthresh', + xor=['threshold_mask_absolute', 'threshold_mask_none'], + ), + unequal_variance=dict(field='des.t2.variance', ), + use_implicit_threshold=dict(field='masking.im', ), + use_mcr=dict(), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), ) inputs = TwoSampleTTestDesign.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_TwoSampleTTestDesign_outputs(): - output_map = dict(spm_mat_file=dict(), - ) + output_map = dict(spm_mat_file=dict(), ) outputs = TwoSampleTTestDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_VBMSegment.py b/nipype/interfaces/spm/tests/test_auto_VBMSegment.py index d61f7c623f..6ef35124f3 100644 --- a/nipype/interfaces/spm/tests/test_auto_VBMSegment.py +++ b/nipype/interfaces/spm/tests/test_auto_VBMSegment.py @@ -4,136 +4,163 @@ def test_VBMSegment_inputs(): - input_map = dict(bias_corrected_affine=dict(field='estwrite.output.bias.affine', - usedefault=True, - ), - bias_corrected_native=dict(field='estwrite.output.bias.native', - usedefault=True, - ), - bias_corrected_normalized=dict(field='estwrite.output.bias.warped', - usedefault=True, - ), - bias_fwhm=dict(field='estwrite.opts.biasfwhm', - usedefault=True, - ), - bias_regularization=dict(field='estwrite.opts.biasreg', - usedefault=True, - ), - cleanup_partitions=dict(field='estwrite.extopts.cleanup', - usedefault=True, - ), - csf_dartel=dict(field='estwrite.output.CSF.dartel', - usedefault=True, - ), - csf_modulated_normalized=dict(field='estwrite.output.CSF.modulated', - usedefault=True, - ), - csf_native=dict(field='estwrite.output.CSF.native', - usedefault=True, - ), - csf_normalized=dict(field='estwrite.output.CSF.warped', - usedefault=True, - ), - dartel_template=dict(field='estwrite.extopts.dartelwarp.normhigh.darteltpm', - ), - deformation_field=dict(field='estwrite.output.warps', - usedefault=True, - ), - display_results=dict(field='estwrite.extopts.print', - usedefault=True, - ), - gaussians_per_class=dict(usedefault=True, - ), - gm_dartel=dict(field='estwrite.output.GM.dartel', - usedefault=True, - ), - gm_modulated_normalized=dict(field='estwrite.output.GM.modulated', - usedefault=True, - ), - gm_native=dict(field='estwrite.output.GM.native', - usedefault=True, - ), - gm_normalized=dict(field='estwrite.output.GM.warped', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_files=dict(copyfile=False, - field='estwrite.data', - mandatory=True, - ), - jacobian_determinant=dict(field='estwrite.jacobian.warped', - usedefault=True, - ), - matlab_cmd=dict(), - mfile=dict(usedefault=True, - ), - mrf_weighting=dict(field='estwrite.extopts.mrf', - usedefault=True, - ), - paths=dict(), - pve_label_dartel=dict(field='estwrite.output.label.dartel', - usedefault=True, - ), - pve_label_native=dict(field='estwrite.output.label.native', - usedefault=True, - ), - pve_label_normalized=dict(field='estwrite.output.label.warped', - usedefault=True, - ), - sampling_distance=dict(field='estwrite.opts.samp', - usedefault=True, - ), - spatial_normalization=dict(usedefault=True, - ), - tissues=dict(field='estwrite.tpm', - ), - use_mcr=dict(), - use_sanlm_denoising_filter=dict(field='estwrite.extopts.sanlm', - usedefault=True, - ), - use_v8struct=dict(min_ver='8', - usedefault=True, - ), - warping_regularization=dict(field='estwrite.opts.warpreg', - usedefault=True, - ), - wm_dartel=dict(field='estwrite.output.WM.dartel', - usedefault=True, - ), - wm_modulated_normalized=dict(field='estwrite.output.WM.modulated', - usedefault=True, - ), - wm_native=dict(field='estwrite.output.WM.native', - usedefault=True, - ), - wm_normalized=dict(field='estwrite.output.WM.warped', - usedefault=True, - ), + input_map = dict( + bias_corrected_affine=dict( + field='estwrite.output.bias.affine', + usedefault=True, + ), + bias_corrected_native=dict( + field='estwrite.output.bias.native', + usedefault=True, + ), + bias_corrected_normalized=dict( + field='estwrite.output.bias.warped', + usedefault=True, + ), + bias_fwhm=dict( + field='estwrite.opts.biasfwhm', + usedefault=True, + ), + bias_regularization=dict( + field='estwrite.opts.biasreg', + usedefault=True, + ), + cleanup_partitions=dict( + field='estwrite.extopts.cleanup', + usedefault=True, + ), + csf_dartel=dict( + field='estwrite.output.CSF.dartel', + usedefault=True, + ), + csf_modulated_normalized=dict( + field='estwrite.output.CSF.modulated', + usedefault=True, + ), + csf_native=dict( + field='estwrite.output.CSF.native', + usedefault=True, + ), + csf_normalized=dict( + field='estwrite.output.CSF.warped', + usedefault=True, + ), + dartel_template=dict( + field='estwrite.extopts.dartelwarp.normhigh.darteltpm', ), + deformation_field=dict( + field='estwrite.output.warps', + usedefault=True, + ), + display_results=dict( + field='estwrite.extopts.print', + usedefault=True, + ), + gaussians_per_class=dict(usedefault=True, ), + gm_dartel=dict( + field='estwrite.output.GM.dartel', + usedefault=True, + ), + gm_modulated_normalized=dict( + field='estwrite.output.GM.modulated', + usedefault=True, + ), + gm_native=dict( + field='estwrite.output.GM.native', + usedefault=True, + ), + gm_normalized=dict( + field='estwrite.output.GM.warped', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_files=dict( + copyfile=False, + field='estwrite.data', + mandatory=True, + ), + jacobian_determinant=dict( + field='estwrite.jacobian.warped', + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, ), + mrf_weighting=dict( + field='estwrite.extopts.mrf', + usedefault=True, + ), + paths=dict(), + pve_label_dartel=dict( + field='estwrite.output.label.dartel', + usedefault=True, + ), + pve_label_native=dict( + field='estwrite.output.label.native', + usedefault=True, + ), + pve_label_normalized=dict( + field='estwrite.output.label.warped', + usedefault=True, + ), + sampling_distance=dict( + field='estwrite.opts.samp', + usedefault=True, + ), + spatial_normalization=dict(usedefault=True, ), + tissues=dict(field='estwrite.tpm', ), + use_mcr=dict(), + use_sanlm_denoising_filter=dict( + field='estwrite.extopts.sanlm', + usedefault=True, + ), + use_v8struct=dict( + min_ver='8', + usedefault=True, + ), + warping_regularization=dict( + field='estwrite.opts.warpreg', + usedefault=True, + ), + wm_dartel=dict( + field='estwrite.output.WM.dartel', + usedefault=True, + ), + wm_modulated_normalized=dict( + field='estwrite.output.WM.modulated', + usedefault=True, + ), + wm_native=dict( + field='estwrite.output.WM.native', + usedefault=True, + ), + wm_normalized=dict( + field='estwrite.output.WM.warped', + usedefault=True, + ), ) inputs = VBMSegment.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VBMSegment_outputs(): - output_map = dict(bias_corrected_images=dict(), - dartel_input_images=dict(), - forward_deformation_field=dict(), - inverse_deformation_field=dict(), - jacobian_determinant_images=dict(), - modulated_class_images=dict(), - native_class_images=dict(), - normalized_bias_corrected_images=dict(), - normalized_class_images=dict(), - pve_label_native_images=dict(), - pve_label_normalized_images=dict(), - pve_label_registered_images=dict(), - transformation_mat=dict(), + output_map = dict( + bias_corrected_images=dict(), + dartel_input_images=dict(), + forward_deformation_field=dict(), + inverse_deformation_field=dict(), + jacobian_determinant_images=dict(), + modulated_class_images=dict(), + native_class_images=dict(), + normalized_bias_corrected_images=dict(), + normalized_class_images=dict(), + pve_label_native_images=dict(), + pve_label_normalized_images=dict(), + pve_label_registered_images=dict(), + transformation_mat=dict(), ) outputs = VBMSegment.output_spec() diff --git a/nipype/interfaces/spm/tests/test_base.py b/nipype/interfaces/spm/tests/test_base.py index 57d0d88c21..a8a23e8def 100644 --- a/nipype/interfaces/spm/tests/test_base.py +++ b/nipype/interfaces/spm/tests/test_base.py @@ -16,8 +16,7 @@ from nipype.interfaces.spm.base import SPMCommandInputSpec from nipype.interfaces.base import traits -mlab.MatlabCommand.set_default_matlab_cmd( - os.getenv('MATLABCMD', 'matlab')) +mlab.MatlabCommand.set_default_matlab_cmd(os.getenv('MATLABCMD', 'matlab')) def test_scan_for_fnames(create_files_in_directory): @@ -29,6 +28,7 @@ def test_scan_for_fnames(create_files_in_directory): save_time = False if not save_time: + @pytest.mark.skipif(no_spm(), reason="spm is not installed") def test_spm_path(): spm_path = spm.Info.path() @@ -40,6 +40,7 @@ def test_spm_path(): def test_use_mfile(): class TestClass(spm.SPMCommand): input_spec = spm.SPMCommandInputSpec + dc = TestClass() # dc = derived_class assert dc.inputs.mfile @@ -49,6 +50,7 @@ def test_find_mlab_cmd_defaults(): class TestClass(spm.SPMCommand): pass + # test without FORCE_SPMMCR, SPMMCRCMD set for varname in ['FORCE_SPMMCR', 'SPMMCRCMD']: try: @@ -56,17 +58,17 @@ class TestClass(spm.SPMCommand): except KeyError: pass dc = TestClass() - assert dc._use_mcr == None - assert dc._matlab_cmd == None + assert dc._use_mcr is None + assert dc._matlab_cmd is None # test with only FORCE_SPMMCR set os.environ['FORCE_SPMMCR'] = '1' dc = TestClass() - assert dc._use_mcr == True - assert dc._matlab_cmd == None + assert dc._use_mcr + assert dc._matlab_cmd is None # test with both, FORCE_SPMMCR and SPMMCRCMD set os.environ['SPMMCRCMD'] = 'spmcmd' dc = TestClass() - assert dc._use_mcr == True + assert dc._use_mcr assert dc._matlab_cmd == 'spmcmd' # restore environment os.environ.clear() @@ -77,6 +79,7 @@ class TestClass(spm.SPMCommand): def test_cmd_update(): class TestClass(spm.SPMCommand): input_spec = spm.SPMCommandInputSpec + dc = TestClass() # dc = derived_class dc.inputs.matlab_cmd = 'foo' assert dc.mlab._cmd == 'foo' @@ -87,6 +90,7 @@ class TestClass(spm.SPMCommand): _jobtype = 'jobtype' _jobname = 'jobname' input_spec = spm.SPMCommandInputSpec + dc = TestClass() # dc = derived_class assert dc.jobtype == 'jobtype' assert dc.jobname == 'jobname' @@ -95,6 +99,7 @@ class TestClass(spm.SPMCommand): def test_reformat_dict_for_savemat(): class TestClass(spm.SPMCommand): input_spec = spm.SPMCommandInputSpec + dc = TestClass() # dc = derived_class out = dc._reformat_dict_for_savemat({'a': {'b': {'c': []}}}) assert out == [{'a': [{'b': [{'c': []}]}]}] @@ -103,6 +108,7 @@ class TestClass(spm.SPMCommand): def test_generate_job(create_files_in_directory): class TestClass(spm.SPMCommand): input_spec = spm.SPMCommandInputSpec + dc = TestClass() # dc = derived_class out = dc._generate_job() assert out == '' @@ -122,7 +128,7 @@ class TestClass(spm.SPMCommand): out = dc._generate_job(prefix='test', contents=contents) assert out == "test = 'foo';\n" # cell array of vectors - contents = {'onsets': np.array((1,), dtype=object)} + contents = {'onsets': np.array((1, ), dtype=object)} contents['onsets'][0] = [1, 2, 3, 4] out = dc._generate_job(prefix='test', contents=contents) assert out == 'test.onsets = {...\n[1, 2, 3, 4];...\n};\n' @@ -136,6 +142,7 @@ class TestClass(spm.SPMCommand): input_spec = TestClassInputSpec _jobtype = 'jobtype' _jobname = 'jobname' + dc = TestClass() # dc = derived_class dc.inputs.test_in = True out = dc._make_matlab_command(dc._parse_inputs()) @@ -150,6 +157,7 @@ class TestClass(spm.SPMCommand): _jobtype = 'jobtype' _jobname = 'jobname' input_spec = spm.SPMCommandInputSpec + dc = TestClass() # dc = derived_class filelist, outdir = create_files_in_directory contents = {'contents': [1, 2, 3, 4]} diff --git a/nipype/interfaces/spm/tests/test_model.py b/nipype/interfaces/spm/tests/test_model.py index 307c4f1786..a9cb957944 100644 --- a/nipype/interfaces/spm/tests/test_model.py +++ b/nipype/interfaces/spm/tests/test_model.py @@ -6,8 +6,7 @@ import nipype.interfaces.spm.model as spm import nipype.interfaces.matlab as mlab -mlab.MatlabCommand.set_default_matlab_cmd( - os.getenv('MATLABCMD', 'matlab')) +mlab.MatlabCommand.set_default_matlab_cmd(os.getenv('MATLABCMD', 'matlab')) def test_level1design(): diff --git a/nipype/interfaces/spm/tests/test_preprocess.py b/nipype/interfaces/spm/tests/test_preprocess.py index f167ad521a..2b70b7bb54 100644 --- a/nipype/interfaces/spm/tests/test_preprocess.py +++ b/nipype/interfaces/spm/tests/test_preprocess.py @@ -10,8 +10,7 @@ from nipype.interfaces.spm import no_spm import nipype.interfaces.matlab as mlab -mlab.MatlabCommand.set_default_matlab_cmd( - os.getenv('MATLABCMD', 'matlab')) +mlab.MatlabCommand.set_default_matlab_cmd(os.getenv('MATLABCMD', 'matlab')) def test_slicetiming(): @@ -77,8 +76,8 @@ def test_normalize12_list_outputs(create_files_in_directory): filelist, outdir = create_files_in_directory norm12 = spm.Normalize12(image_to_align=filelist[0]) assert norm12._list_outputs()['normalized_image'][0].startswith('w') - norm12 = spm.Normalize12(image_to_align=filelist[0], - apply_to_files=filelist[1]) + norm12 = spm.Normalize12( + image_to_align=filelist[0], apply_to_files=filelist[1]) assert norm12._list_outputs()['normalized_files'][0].startswith('w') diff --git a/nipype/interfaces/spm/tests/test_utils.py b/nipype/interfaces/spm/tests/test_utils.py index 7d8106f80c..a574fb90a7 100644 --- a/nipype/interfaces/spm/tests/test_utils.py +++ b/nipype/interfaces/spm/tests/test_utils.py @@ -18,7 +18,7 @@ def test_coreg(): coreg.inputs.target = target assert coreg.inputs.matlab_cmd == 'mymatlab' coreg.inputs.moving = moving - assert isdefined(coreg.inputs.mat) == False + assert not isdefined(coreg.inputs.mat) pth, mov, _ = split_filename(moving) _, tgt, _ = split_filename(target) mat = os.path.join(pth, '%s_to_%s.mat' % (mov, tgt)) @@ -50,8 +50,10 @@ def test_reslice(): reslice.inputs.in_file = moving reslice.inputs.space_defining = space_defining assert reslice.inputs.interp == 0 - with pytest.raises(TraitError): reslice.inputs.trait_set(interp='nearest') - with pytest.raises(TraitError): reslice.inputs.trait_set(interp=10) + with pytest.raises(TraitError): + reslice.inputs.trait_set(interp='nearest') + with pytest.raises(TraitError): + reslice.inputs.trait_set(interp=10) reslice.inputs.interp = 1 script = reslice._make_matlab_command(None) outfile = fname_presuffix(moving, prefix='r') @@ -70,9 +72,12 @@ def test_dicom_import(): assert di.inputs.output_dir_struct == 'flat' assert di.inputs.output_dir == './converted_dicom' assert di.inputs.format == 'nii' - assert di.inputs.icedims == False - with pytest.raises(TraitError): di.inputs.trait_set(output_dir_struct='wrong') - with pytest.raises(TraitError): di.inputs.trait_set(format='FAT') - with pytest.raises(TraitError): di.inputs.trait_set(in_files=['does_sfd_not_32fn_exist.dcm']) + assert not di.inputs.icedims + with pytest.raises(TraitError): + di.inputs.trait_set(output_dir_struct='wrong') + with pytest.raises(TraitError): + di.inputs.trait_set(format='FAT') + with pytest.raises(TraitError): + di.inputs.trait_set(in_files=['does_sfd_not_32fn_exist.dcm']) di.inputs.in_files = [dicom] assert di.inputs.in_files == [dicom] diff --git a/nipype/interfaces/spm/utils.py b/nipype/interfaces/spm/utils.py index 5c91e1313b..5dd6c05e4d 100644 --- a/nipype/interfaces/spm/utils.py +++ b/nipype/interfaces/spm/utils.py @@ -1,14 +1,18 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import numpy as np -from ...utils.filemanip import split_filename, fname_presuffix, filename_to_list, list_to_filename -from ..base import TraitedSpec, isdefined, File, traits, OutputMultiPath, InputMultiPath -from .base import SPMCommandInputSpec, SPMCommand, scans_for_fnames, scans_for_fname +from ...utils.filemanip import (split_filename, fname_presuffix, + filename_to_list, list_to_filename) +from ..base import (TraitedSpec, isdefined, File, traits, OutputMultiPath, + InputMultiPath) +from .base import (SPMCommandInputSpec, SPMCommand, scans_for_fnames, + scans_for_fname) class Analyze2niiInputSpec(SPMCommandInputSpec): @@ -41,11 +45,16 @@ def _list_outputs(self): class CalcCoregAffineInputSpec(SPMCommandInputSpec): - target = File(exists=True, mandatory=True, - desc='target for generating affine transform') - moving = File(exists=True, mandatory=True, copyfile=False, - desc=('volume transform can be applied to register with ' - 'target')) + target = File( + exists=True, + mandatory=True, + desc='target for generating affine transform') + moving = File( + exists=True, + mandatory=True, + copyfile=False, + desc=('volume transform can be applied to register with ' + 'target')) mat = File(desc='Filename used to store affine matrix') invmat = File(desc='Filename used to store inverse affine matrix') @@ -109,9 +118,7 @@ def _make_matlab_command(self, _): save('%s' , 'M' ); M = inv(M); save('%s','M') - """ % (self.inputs.target, - self.inputs.moving, - self.inputs.mat, + """ % (self.inputs.target, self.inputs.moving, self.inputs.mat, self.inputs.invmat) return script @@ -123,12 +130,14 @@ def _list_outputs(self): class ApplyTransformInputSpec(SPMCommandInputSpec): - in_file = File(exists=True, mandatory=True, copyfile=True, - desc='file to apply transform to, (only updates header)') - mat = File(exists=True, mandatory=True, - desc='file holding transform to apply') - out_file = File(desc="output file name for transformed data", - genfile=True) + in_file = File( + exists=True, + mandatory=True, + copyfile=True, + desc='file to apply transform to, (only updates header)') + mat = File( + exists=True, mandatory=True, desc='file holding transform to apply') + out_file = File(desc="output file name for transformed data", genfile=True) class ApplyTransformOutputSpec(TraitedSpec): @@ -167,9 +176,7 @@ def _make_matlab_command(self, _): V.fname = fullfile(outfile); spm_write_vol(V,X); - """ % (self.inputs.in_file, - self.inputs.out_file, - self.inputs.mat) + """ % (self.inputs.in_file, self.inputs.out_file, self.inputs.mat) # img_space = spm_get_space(infile); # spm_get_space(infile, transform.M * img_space); return script @@ -188,14 +195,21 @@ def _gen_outfilename(self): class ResliceInputSpec(SPMCommandInputSpec): - in_file = File(exists=True, mandatory=True, - desc='file to apply transform to, (only updates header)') - space_defining = File(exists=True, mandatory=True, - desc='Volume defining space to slice in_file into') + in_file = File( + exists=True, + mandatory=True, + desc='file to apply transform to, (only updates header)') + space_defining = File( + exists=True, + mandatory=True, + desc='Volume defining space to slice in_file into') - interp = traits.Range(low=0, high=7, usedefault=True, - desc='degree of b-spline used for interpolation' - '0 is nearest neighbor (default)') + interp = traits.Range( + low=0, + high=7, + usedefault=True, + desc='degree of b-spline used for interpolation' + '0 is nearest neighbor (default)') out_file = File(desc='Optional file to save resliced volume') @@ -213,8 +227,8 @@ class Reslice(SPMCommand): def _make_matlab_command(self, _): """ generates script""" if not isdefined(self.inputs.out_file): - self.inputs.out_file = fname_presuffix(self.inputs.in_file, - prefix='r') + self.inputs.out_file = fname_presuffix( + self.inputs.in_file, prefix='r') script = """ flags.mean = 0; flags.which = 1; @@ -223,8 +237,7 @@ def _make_matlab_command(self, _): infiles = strvcat(\'%s\', \'%s\'); invols = spm_vol(infiles); spm_reslice(invols, flags); - """ % (self.inputs.interp, - self.inputs.space_defining, + """ % (self.inputs.interp, self.inputs.space_defining, self.inputs.in_file) return script @@ -236,7 +249,9 @@ def _list_outputs(self): class ApplyInverseDeformationInput(SPMCommandInputSpec): in_files = InputMultiPath( - File(exists=True), mandatory=True, field='fnames', + File(exists=True), + mandatory=True, + field='fnames', desc='Files on which deformation is applied') target = File( exists=True, @@ -253,24 +268,27 @@ class ApplyInverseDeformationInput(SPMCommandInputSpec): desc='SN SPM deformation file', xor=['deformation']) interpolation = traits.Range( - low=0, high=7, field='interp', + low=0, + high=7, + field='interp', desc='degree of b-spline used for interpolation') bounding_box = traits.List( traits.Float(), field='comp{1}.inv.comp{1}.sn2def.bb', - minlen=6, maxlen=6, + minlen=6, + maxlen=6, desc='6-element list (opt)') voxel_sizes = traits.List( traits.Float(), field='comp{1}.inv.comp{1}.sn2def.vox', - minlen=3, maxlen=3, + minlen=3, + maxlen=3, desc='3-element list (opt)') class ApplyInverseDeformationOutput(TraitedSpec): - out_files = OutputMultiPath(File(exists=True), - desc='Transformed files') + out_files = OutputMultiPath(File(exists=True), desc='Transformed files') class ApplyInverseDeformation(SPMCommand): @@ -318,31 +336,36 @@ def _list_outputs(self): class ResliceToReferenceInput(SPMCommandInputSpec): in_files = InputMultiPath( - File(exists=True), mandatory=True, field='fnames', + File(exists=True), + mandatory=True, + field='fnames', desc='Files on which deformation is applied') target = File( exists=True, field='comp{1}.id.space', desc='File defining target space') interpolation = traits.Range( - low=0, high=7, field='interp', + low=0, + high=7, + field='interp', desc='degree of b-spline used for interpolation') bounding_box = traits.List( traits.Float(), field='comp{2}.idbbvox.bb', - minlen=6, maxlen=6, + minlen=6, + maxlen=6, desc='6-element list (opt)') voxel_sizes = traits.List( traits.Float(), field='comp{2}.idbbvox.vox', - minlen=3, maxlen=3, + minlen=3, + maxlen=3, desc='3-element list (opt)') class ResliceToReferenceOutput(TraitedSpec): - out_files = OutputMultiPath(File(exists=True), - desc='Transformed files') + out_files = OutputMultiPath(File(exists=True), desc='Transformed files') class ResliceToReference(SPMCommand): @@ -394,32 +417,39 @@ class DicomImportInputSpec(SPMCommandInputSpec): field='data', desc='dicom files to be converted') output_dir_struct = traits.Enum( - 'flat', 'series', 'patname', 'patid_date', 'patid', 'date_time', + 'flat', + 'series', + 'patname', + 'patid_date', + 'patid', + 'date_time', field='root', usedefault=True, desc='directory structure for the output.') - output_dir = traits.Str('./converted_dicom', - field='outdir', - usedefault=True, - desc='output directory.') + output_dir = traits.Str( + './converted_dicom', + field='outdir', + usedefault=True, + desc='output directory.') format = traits.Enum( - 'nii', 'img', + 'nii', + 'img', field='convopts.format', usedefault=True, desc='output format.') - icedims = traits.Bool(False, - field='convopts.icedims', - usedefault=True, - desc=('If image sorting fails, one can try using ' - 'the additional SIEMENS ICEDims information ' - 'to create unique filenames. Use this only if ' - 'there would be multiple volumes with exactly ' - 'the same file names.')) + icedims = traits.Bool( + False, + field='convopts.icedims', + usedefault=True, + desc=('If image sorting fails, one can try using ' + 'the additional SIEMENS ICEDims information ' + 'to create unique filenames. Use this only if ' + 'there would be multiple volumes with exactly ' + 'the same file names.')) class DicomImportOutputSpec(TraitedSpec): - out_files = OutputMultiPath(File(exists=True), - desc='converted files') + out_files = OutputMultiPath(File(exists=True), desc='converted files') class DicomImport(SPMCommand): @@ -472,8 +502,9 @@ def _list_outputs(self): elif self.inputs.output_dir_struct == 'series': outputs['out_files'] = glob( os.path.join(od, os.path.join('*', '*.%s' % ext))) - elif (self.inputs.output_dir_struct in - ['patid', 'date_time', 'patname']): + elif (self.inputs.output_dir_struct in [ + 'patid', 'date_time', 'patname' + ]): outputs['out_files'] = glob( os.path.join(od, os.path.join('*', '*', '*.%s' % ext))) elif self.inputs.output_dir_struct == 'patid_date': diff --git a/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py b/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py index 36d02d5fe9..da594a7365 100644 --- a/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py +++ b/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py @@ -4,21 +4,17 @@ def test_BIDSDataGrabber_inputs(): - input_map = dict(base_dir=dict(mandatory=True, - ), - output_query=dict(), - raise_on_empty=dict(usedefault=True, - ), - return_type=dict(usedefault=True, - ), + input_map = dict( + base_dir=dict(mandatory=True, ), + output_query=dict(), + raise_on_empty=dict(usedefault=True, ), + return_type=dict(usedefault=True, ), ) inputs = BIDSDataGrabber.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_BIDSDataGrabber_outputs(): output_map = dict() outputs = BIDSDataGrabber.output_spec() diff --git a/nipype/interfaces/tests/test_auto_Bru2.py b/nipype/interfaces/tests/test_auto_Bru2.py index ec4151cc8f..5a33f26ecf 100644 --- a/nipype/interfaces/tests/test_auto_Bru2.py +++ b/nipype/interfaces/tests/test_auto_Bru2.py @@ -4,42 +4,41 @@ def test_Bru2_inputs(): - input_map = dict(actual_size=dict(argstr='-a', - ), - append_protocol_name=dict(argstr='-p', - ), - args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - force_conversion=dict(argstr='-f', - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - input_dir=dict(argstr='%s', - mandatory=True, - position=-1, - ), - output_filename=dict(argstr='-o %s', - genfile=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + actual_size=dict(argstr='-a', ), + append_protocol_name=dict(argstr='-p', ), + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_conversion=dict(argstr='-f', ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + input_dir=dict( + argstr='%s', + mandatory=True, + position=-1, + ), + output_filename=dict( + argstr='-o %s', + genfile=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Bru2.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Bru2_outputs(): - output_map = dict(nii_file=dict(), - ) + output_map = dict(nii_file=dict(), ) outputs = Bru2.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_C3dAffineTool.py b/nipype/interfaces/tests/test_auto_C3dAffineTool.py index 3abbf26110..17304e1252 100644 --- a/nipype/interfaces/tests/test_auto_C3dAffineTool.py +++ b/nipype/interfaces/tests/test_auto_C3dAffineTool.py @@ -4,45 +4,50 @@ def test_C3dAffineTool_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - fsl2ras=dict(argstr='-fsl2ras', - position=4, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - itk_transform=dict(argstr='-oitk %s', - hash_files=False, - position=5, - ), - reference_file=dict(argstr='-ref %s', - position=1, - ), - source_file=dict(argstr='-src %s', - position=2, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - transform_file=dict(argstr='%s', - position=3, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + fsl2ras=dict( + argstr='-fsl2ras', + position=4, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + itk_transform=dict( + argstr='-oitk %s', + hash_files=False, + position=5, + ), + reference_file=dict( + argstr='-ref %s', + position=1, + ), + source_file=dict( + argstr='-src %s', + position=2, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + transform_file=dict( + argstr='%s', + position=3, + ), ) inputs = C3dAffineTool.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_C3dAffineTool_outputs(): - output_map = dict(itk_transform=dict(), - ) + output_map = dict(itk_transform=dict(), ) outputs = C3dAffineTool.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_CopyMeta.py b/nipype/interfaces/tests/test_auto_CopyMeta.py index d80611ccf1..012edfa886 100644 --- a/nipype/interfaces/tests/test_auto_CopyMeta.py +++ b/nipype/interfaces/tests/test_auto_CopyMeta.py @@ -4,23 +4,19 @@ def test_CopyMeta_inputs(): - input_map = dict(dest_file=dict(mandatory=True, - ), - exclude_classes=dict(), - include_classes=dict(), - src_file=dict(mandatory=True, - ), + input_map = dict( + dest_file=dict(mandatory=True, ), + exclude_classes=dict(), + include_classes=dict(), + src_file=dict(mandatory=True, ), ) inputs = CopyMeta.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CopyMeta_outputs(): - output_map = dict(dest_file=dict(), - ) + output_map = dict(dest_file=dict(), ) outputs = CopyMeta.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_DataFinder.py b/nipype/interfaces/tests/test_auto_DataFinder.py index 82b74b6017..c186db9e00 100644 --- a/nipype/interfaces/tests/test_auto_DataFinder.py +++ b/nipype/interfaces/tests/test_auto_DataFinder.py @@ -4,27 +4,24 @@ def test_DataFinder_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ignore_regexes=dict(), - match_regex=dict(usedefault=True, - ), - max_depth=dict(), - min_depth=dict(), - root_paths=dict(mandatory=True, - ), - unpack_single=dict(usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + ignore_regexes=dict(), + match_regex=dict(usedefault=True, ), + max_depth=dict(), + min_depth=dict(), + root_paths=dict(mandatory=True, ), + unpack_single=dict(usedefault=True, ), ) inputs = DataFinder.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DataFinder_outputs(): output_map = dict() outputs = DataFinder.output_spec() diff --git a/nipype/interfaces/tests/test_auto_DataGrabber.py b/nipype/interfaces/tests/test_auto_DataGrabber.py index 8d95bf9637..e9717fafd5 100644 --- a/nipype/interfaces/tests/test_auto_DataGrabber.py +++ b/nipype/interfaces/tests/test_auto_DataGrabber.py @@ -4,26 +4,23 @@ def test_DataGrabber_inputs(): - input_map = dict(base_directory=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - raise_on_empty=dict(usedefault=True, - ), - sort_filelist=dict(mandatory=True, - ), - template=dict(mandatory=True, - ), - template_args=dict(), + input_map = dict( + base_directory=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + raise_on_empty=dict(usedefault=True, ), + sort_filelist=dict(mandatory=True, ), + template=dict(mandatory=True, ), + template_args=dict(), ) inputs = DataGrabber.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DataGrabber_outputs(): output_map = dict() outputs = DataGrabber.output_spec() diff --git a/nipype/interfaces/tests/test_auto_DataSink.py b/nipype/interfaces/tests/test_auto_DataSink.py index 7c739969a7..fec7475737 100644 --- a/nipype/interfaces/tests/test_auto_DataSink.py +++ b/nipype/interfaces/tests/test_auto_DataSink.py @@ -4,36 +4,32 @@ def test_DataSink_inputs(): - input_map = dict(_outputs=dict(usedefault=True, - ), - base_directory=dict(), - bucket=dict(), - container=dict(), - creds_path=dict(), - encrypt_bucket_keys=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - local_copy=dict(), - parameterization=dict(usedefault=True, - ), - regexp_substitutions=dict(), - remove_dest_dir=dict(usedefault=True, - ), - strip_dir=dict(), - substitutions=dict(), + input_map = dict( + _outputs=dict(usedefault=True, ), + base_directory=dict(), + bucket=dict(), + container=dict(), + creds_path=dict(), + encrypt_bucket_keys=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + local_copy=dict(), + parameterization=dict(usedefault=True, ), + regexp_substitutions=dict(), + remove_dest_dir=dict(usedefault=True, ), + strip_dir=dict(), + substitutions=dict(), ) inputs = DataSink.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DataSink_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = DataSink.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_Dcm2nii.py b/nipype/interfaces/tests/test_auto_Dcm2nii.py index 20a29004cb..044a0f918b 100644 --- a/nipype/interfaces/tests/test_auto_Dcm2nii.py +++ b/nipype/interfaces/tests/test_auto_Dcm2nii.py @@ -4,87 +4,104 @@ def test_Dcm2nii_inputs(): - input_map = dict(anonymize=dict(argstr='-a', - usedefault=True, - ), - args=dict(argstr='%s', - ), - collapse_folders=dict(argstr='-c', - usedefault=True, - ), - config_file=dict(argstr='-b %s', - genfile=True, - ), - convert_all_pars=dict(argstr='-v', - usedefault=True, - ), - date_in_filename=dict(argstr='-d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - events_in_filename=dict(argstr='-e', - usedefault=True, - ), - gzip_output=dict(argstr='-g', - usedefault=True, - ), - id_in_filename=dict(argstr='-i', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - nii_output=dict(argstr='-n', - usedefault=True, - ), - output_dir=dict(argstr='-o %s', - genfile=True, - ), - protocol_in_filename=dict(argstr='-p', - usedefault=True, - ), - reorient=dict(argstr='-r', - ), - reorient_and_crop=dict(argstr='-x', - usedefault=True, - ), - source_dir=dict(argstr='%s', - mandatory=True, - position=-1, - xor=['source_names'], - ), - source_in_filename=dict(argstr='-f', - usedefault=True, - ), - source_names=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - xor=['source_dir'], - ), - spm_analyze=dict(argstr='-s', - xor=['nii_output'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + anonymize=dict( + argstr='-a', + usedefault=True, + ), + args=dict(argstr='%s', ), + collapse_folders=dict( + argstr='-c', + usedefault=True, + ), + config_file=dict( + argstr='-b %s', + genfile=True, + ), + convert_all_pars=dict( + argstr='-v', + usedefault=True, + ), + date_in_filename=dict( + argstr='-d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + events_in_filename=dict( + argstr='-e', + usedefault=True, + ), + gzip_output=dict( + argstr='-g', + usedefault=True, + ), + id_in_filename=dict( + argstr='-i', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + nii_output=dict( + argstr='-n', + usedefault=True, + ), + output_dir=dict( + argstr='-o %s', + genfile=True, + ), + protocol_in_filename=dict( + argstr='-p', + usedefault=True, + ), + reorient=dict(argstr='-r', ), + reorient_and_crop=dict( + argstr='-x', + usedefault=True, + ), + source_dir=dict( + argstr='%s', + mandatory=True, + position=-1, + xor=['source_names'], + ), + source_in_filename=dict( + argstr='-f', + usedefault=True, + ), + source_names=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + xor=['source_dir'], + ), + spm_analyze=dict( + argstr='-s', + xor=['nii_output'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Dcm2nii.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Dcm2nii_outputs(): - output_map = dict(bvals=dict(), - bvecs=dict(), - converted_files=dict(), - reoriented_and_cropped_files=dict(), - reoriented_files=dict(), + output_map = dict( + bvals=dict(), + bvecs=dict(), + converted_files=dict(), + reoriented_and_cropped_files=dict(), + reoriented_files=dict(), ) outputs = Dcm2nii.output_spec() diff --git a/nipype/interfaces/tests/test_auto_Dcm2niix.py b/nipype/interfaces/tests/test_auto_Dcm2niix.py index 3d496f3aba..ade47ab224 100644 --- a/nipype/interfaces/tests/test_auto_Dcm2niix.py +++ b/nipype/interfaces/tests/test_auto_Dcm2niix.py @@ -4,69 +4,82 @@ def test_Dcm2niix_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - bids_format=dict(argstr='-b', - usedefault=True, - ), - compress=dict(argstr='-z %s', - usedefault=True, - ), - crop=dict(argstr='-x', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - has_private=dict(argstr='-t', - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - merge_imgs=dict(argstr='-m', - usedefault=True, - ), - out_filename=dict(argstr='-f %s', - usedefault=True, - ), - output_dir=dict(argstr='-o %s', - genfile=True, - ), - single_file=dict(argstr='-s', - usedefault=True, - ), - source_dir=dict(argstr='%s', - mandatory=True, - position=-1, - xor=['source_names'], - ), - source_names=dict(argstr='%s', - copyfile=False, - mandatory=True, - position=-1, - xor=['source_dir'], - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - verbose=dict(argstr='-v', - usedefault=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + bids_format=dict( + argstr='-b', + usedefault=True, + ), + compress=dict( + argstr='-z %s', + usedefault=True, + ), + crop=dict( + argstr='-x', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + has_private=dict( + argstr='-t', + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + merge_imgs=dict( + argstr='-m', + usedefault=True, + ), + out_filename=dict( + argstr='-f %s', + usedefault=True, + ), + output_dir=dict( + argstr='-o %s', + genfile=True, + ), + single_file=dict( + argstr='-s', + usedefault=True, + ), + source_dir=dict( + argstr='%s', + mandatory=True, + position=-1, + xor=['source_names'], + ), + source_names=dict( + argstr='%s', + copyfile=False, + mandatory=True, + position=-1, + xor=['source_dir'], + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + verbose=dict( + argstr='-v', + usedefault=True, + ), ) inputs = Dcm2niix.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Dcm2niix_outputs(): - output_map = dict(bids=dict(), - bvals=dict(), - bvecs=dict(), - converted_files=dict(), + output_map = dict( + bids=dict(), + bvals=dict(), + bvecs=dict(), + converted_files=dict(), ) outputs = Dcm2niix.output_spec() diff --git a/nipype/interfaces/tests/test_auto_DcmStack.py b/nipype/interfaces/tests/test_auto_DcmStack.py index ee31e088a2..53a5259af5 100644 --- a/nipype/interfaces/tests/test_auto_DcmStack.py +++ b/nipype/interfaces/tests/test_auto_DcmStack.py @@ -4,28 +4,23 @@ def test_DcmStack_inputs(): - input_map = dict(dicom_files=dict(mandatory=True, - ), - embed_meta=dict(), - exclude_regexes=dict(), - force_read=dict(usedefault=True, - ), - include_regexes=dict(), - out_ext=dict(usedefault=True, - ), - out_format=dict(), - out_path=dict(), + input_map = dict( + dicom_files=dict(mandatory=True, ), + embed_meta=dict(), + exclude_regexes=dict(), + force_read=dict(usedefault=True, ), + include_regexes=dict(), + out_ext=dict(usedefault=True, ), + out_format=dict(), + out_path=dict(), ) inputs = DcmStack.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_DcmStack_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = DcmStack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_FreeSurferSource.py b/nipype/interfaces/tests/test_auto_FreeSurferSource.py index a99ddb9d4f..56e7083143 100644 --- a/nipype/interfaces/tests/test_auto_FreeSurferSource.py +++ b/nipype/interfaces/tests/test_auto_FreeSurferSource.py @@ -4,114 +4,105 @@ def test_FreeSurferSource_inputs(): - input_map = dict(hemi=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - subject_id=dict(mandatory=True, - ), - subjects_dir=dict(mandatory=True, - ), + input_map = dict( + hemi=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + subject_id=dict(mandatory=True, ), + subjects_dir=dict(mandatory=True, ), ) inputs = FreeSurferSource.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_FreeSurferSource_outputs(): - output_map = dict(BA_stats=dict(altkey='BA', - loc='stats', - ), - T1=dict(loc='mri', - ), - annot=dict(altkey='*annot', - loc='label', - ), - aparc_a2009s_stats=dict(altkey='aparc.a2009s', - loc='stats', - ), - aparc_aseg=dict(altkey='aparc*aseg', - loc='mri', - ), - aparc_stats=dict(altkey='aparc', - loc='stats', - ), - area_pial=dict(altkey='area.pial', - loc='surf', - ), - aseg=dict(loc='mri', - ), - aseg_stats=dict(altkey='aseg', - loc='stats', - ), - avg_curv=dict(loc='surf', - ), - brain=dict(loc='mri', - ), - brainmask=dict(loc='mri', - ), - curv=dict(loc='surf', - ), - curv_pial=dict(altkey='curv.pial', - loc='surf', - ), - curv_stats=dict(altkey='curv', - loc='stats', - ), - entorhinal_exvivo_stats=dict(altkey='entorhinal_exvivo', - loc='stats', - ), - filled=dict(loc='mri', - ), - graymid=dict(altkey=['graymid', 'midthickness'], - loc='surf', - ), - inflated=dict(loc='surf', - ), - jacobian_white=dict(loc='surf', - ), - label=dict(altkey='*label', - loc='label', - ), - norm=dict(loc='mri', - ), - nu=dict(loc='mri', - ), - orig=dict(loc='mri', - ), - pial=dict(loc='surf', - ), - rawavg=dict(loc='mri', - ), - ribbon=dict(altkey='*ribbon', - loc='mri', - ), - smoothwm=dict(loc='surf', - ), - sphere=dict(loc='surf', - ), - sphere_reg=dict(altkey='sphere.reg', - loc='surf', - ), - sulc=dict(loc='surf', - ), - thickness=dict(loc='surf', - ), - volume=dict(loc='surf', - ), - white=dict(loc='surf', - ), - wm=dict(loc='mri', - ), - wmparc=dict(loc='mri', - ), - wmparc_stats=dict(altkey='wmparc', - loc='stats', - ), + output_map = dict( + BA_stats=dict( + altkey='BA', + loc='stats', + ), + T1=dict(loc='mri', ), + annot=dict( + altkey='*annot', + loc='label', + ), + aparc_a2009s_stats=dict( + altkey='aparc.a2009s', + loc='stats', + ), + aparc_aseg=dict( + altkey='aparc*aseg', + loc='mri', + ), + aparc_stats=dict( + altkey='aparc', + loc='stats', + ), + area_pial=dict( + altkey='area.pial', + loc='surf', + ), + aseg=dict(loc='mri', ), + aseg_stats=dict( + altkey='aseg', + loc='stats', + ), + avg_curv=dict(loc='surf', ), + brain=dict(loc='mri', ), + brainmask=dict(loc='mri', ), + curv=dict(loc='surf', ), + curv_pial=dict( + altkey='curv.pial', + loc='surf', + ), + curv_stats=dict( + altkey='curv', + loc='stats', + ), + entorhinal_exvivo_stats=dict( + altkey='entorhinal_exvivo', + loc='stats', + ), + filled=dict(loc='mri', ), + graymid=dict( + altkey=['graymid', 'midthickness'], + loc='surf', + ), + inflated=dict(loc='surf', ), + jacobian_white=dict(loc='surf', ), + label=dict( + altkey='*label', + loc='label', + ), + norm=dict(loc='mri', ), + nu=dict(loc='mri', ), + orig=dict(loc='mri', ), + pial=dict(loc='surf', ), + rawavg=dict(loc='mri', ), + ribbon=dict( + altkey='*ribbon', + loc='mri', + ), + smoothwm=dict(loc='surf', ), + sphere=dict(loc='surf', ), + sphere_reg=dict( + altkey='sphere.reg', + loc='surf', + ), + sulc=dict(loc='surf', ), + thickness=dict(loc='surf', ), + volume=dict(loc='surf', ), + white=dict(loc='surf', ), + wm=dict(loc='mri', ), + wmparc=dict(loc='mri', ), + wmparc_stats=dict( + altkey='wmparc', + loc='stats', + ), ) outputs = FreeSurferSource.output_spec() diff --git a/nipype/interfaces/tests/test_auto_GroupAndStack.py b/nipype/interfaces/tests/test_auto_GroupAndStack.py index 208869f667..a8f30e32f9 100644 --- a/nipype/interfaces/tests/test_auto_GroupAndStack.py +++ b/nipype/interfaces/tests/test_auto_GroupAndStack.py @@ -4,28 +4,23 @@ def test_GroupAndStack_inputs(): - input_map = dict(dicom_files=dict(mandatory=True, - ), - embed_meta=dict(), - exclude_regexes=dict(), - force_read=dict(usedefault=True, - ), - include_regexes=dict(), - out_ext=dict(usedefault=True, - ), - out_format=dict(), - out_path=dict(), + input_map = dict( + dicom_files=dict(mandatory=True, ), + embed_meta=dict(), + exclude_regexes=dict(), + force_read=dict(usedefault=True, ), + include_regexes=dict(), + out_ext=dict(usedefault=True, ), + out_format=dict(), + out_path=dict(), ) inputs = GroupAndStack.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_GroupAndStack_outputs(): - output_map = dict(out_list=dict(), - ) + output_map = dict(out_list=dict(), ) outputs = GroupAndStack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_IOBase.py b/nipype/interfaces/tests/test_auto_IOBase.py index d8db29919a..1578f3c62b 100644 --- a/nipype/interfaces/tests/test_auto_IOBase.py +++ b/nipype/interfaces/tests/test_auto_IOBase.py @@ -4,14 +4,14 @@ def test_IOBase_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ) + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = IOBase.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/tests/test_auto_JSONFileGrabber.py b/nipype/interfaces/tests/test_auto_JSONFileGrabber.py index d6458e1e8f..7efb3b70fb 100644 --- a/nipype/interfaces/tests/test_auto_JSONFileGrabber.py +++ b/nipype/interfaces/tests/test_auto_JSONFileGrabber.py @@ -4,20 +4,20 @@ def test_JSONFileGrabber_inputs(): - input_map = dict(defaults=dict(), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(), + input_map = dict( + defaults=dict(), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(), ) inputs = JSONFileGrabber.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JSONFileGrabber_outputs(): output_map = dict() outputs = JSONFileGrabber.output_spec() diff --git a/nipype/interfaces/tests/test_auto_JSONFileSink.py b/nipype/interfaces/tests/test_auto_JSONFileSink.py index 1d569e76d4..116eaed977 100644 --- a/nipype/interfaces/tests/test_auto_JSONFileSink.py +++ b/nipype/interfaces/tests/test_auto_JSONFileSink.py @@ -4,26 +4,23 @@ def test_JSONFileSink_inputs(): - input_map = dict(_outputs=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_dict=dict(usedefault=True, - ), - out_file=dict(), + input_map = dict( + _outputs=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_dict=dict(usedefault=True, ), + out_file=dict(), ) inputs = JSONFileSink.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_JSONFileSink_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = JSONFileSink.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_LookupMeta.py b/nipype/interfaces/tests/test_auto_LookupMeta.py index b1e1f4b447..29100aaef7 100644 --- a/nipype/interfaces/tests/test_auto_LookupMeta.py +++ b/nipype/interfaces/tests/test_auto_LookupMeta.py @@ -4,18 +4,15 @@ def test_LookupMeta_inputs(): - input_map = dict(in_file=dict(mandatory=True, - ), - meta_keys=dict(mandatory=True, - ), + input_map = dict( + in_file=dict(mandatory=True, ), + meta_keys=dict(mandatory=True, ), ) inputs = LookupMeta.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_LookupMeta_outputs(): output_map = dict() outputs = LookupMeta.output_spec() diff --git a/nipype/interfaces/tests/test_auto_MatlabCommand.py b/nipype/interfaces/tests/test_auto_MatlabCommand.py index 71a5587767..2d49dbab4b 100644 --- a/nipype/interfaces/tests/test_auto_MatlabCommand.py +++ b/nipype/interfaces/tests/test_auto_MatlabCommand.py @@ -4,51 +4,53 @@ def test_MatlabCommand_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - logfile=dict(argstr='-logfile %s', - ), - mfile=dict(usedefault=True, - ), - nodesktop=dict(argstr='-nodesktop', - nohash=True, - usedefault=True, - ), - nosplash=dict(argstr='-nosplash', - nohash=True, - usedefault=True, - ), - paths=dict(), - postscript=dict(usedefault=True, - ), - prescript=dict(usedefault=True, - ), - script=dict(argstr='-r "%s;exit"', - mandatory=True, - position=-1, - ), - script_file=dict(usedefault=True, - ), - single_comp_thread=dict(argstr='-singleCompThread', - nohash=True, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uses_mcr=dict(nohash=True, - xor=['nodesktop', 'nosplash', 'single_comp_thread'], - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + logfile=dict(argstr='-logfile %s', ), + mfile=dict(usedefault=True, ), + nodesktop=dict( + argstr='-nodesktop', + nohash=True, + usedefault=True, + ), + nosplash=dict( + argstr='-nosplash', + nohash=True, + usedefault=True, + ), + paths=dict(), + postscript=dict(usedefault=True, ), + prescript=dict(usedefault=True, ), + script=dict( + argstr='-r "%s;exit"', + mandatory=True, + position=-1, + ), + script_file=dict(usedefault=True, ), + single_comp_thread=dict( + argstr='-singleCompThread', + nohash=True, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uses_mcr=dict( + nohash=True, + xor=['nodesktop', 'nosplash', 'single_comp_thread'], + ), ) inputs = MatlabCommand.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/tests/test_auto_MergeNifti.py b/nipype/interfaces/tests/test_auto_MergeNifti.py index 605f829602..9e0a017c60 100644 --- a/nipype/interfaces/tests/test_auto_MergeNifti.py +++ b/nipype/interfaces/tests/test_auto_MergeNifti.py @@ -4,25 +4,21 @@ def test_MergeNifti_inputs(): - input_map = dict(in_files=dict(mandatory=True, - ), - merge_dim=dict(), - out_ext=dict(usedefault=True, - ), - out_format=dict(), - out_path=dict(), - sort_order=dict(), + input_map = dict( + in_files=dict(mandatory=True, ), + merge_dim=dict(), + out_ext=dict(usedefault=True, ), + out_format=dict(), + out_path=dict(), + sort_order=dict(), ) inputs = MergeNifti.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MergeNifti_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = MergeNifti.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_MeshFix.py b/nipype/interfaces/tests/test_auto_MeshFix.py index 04c314e2e2..241f200b86 100644 --- a/nipype/interfaces/tests/test_auto_MeshFix.py +++ b/nipype/interfaces/tests/test_auto_MeshFix.py @@ -4,103 +4,102 @@ def test_MeshFix_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - cut_inner=dict(argstr='--cut-inner %d', - ), - cut_outer=dict(argstr='--cut-outer %d', - ), - decouple_inin=dict(argstr='--decouple-inin %d', - ), - decouple_outin=dict(argstr='--decouple-outin %d', - ), - decouple_outout=dict(argstr='--decouple-outout %d', - ), - dilation=dict(argstr='--dilate %d', - ), - dont_clean=dict(argstr='--no-clean', - ), - environ=dict(nohash=True, - usedefault=True, - ), - epsilon_angle=dict(argstr='-a %f', - ), - finetuning_distance=dict(argstr='%f', - requires=['finetuning_substeps'], - ), - finetuning_inwards=dict(argstr='--fineTuneIn ', - requires=['finetuning_distance', 'finetuning_substeps'], - ), - finetuning_outwards=dict(argstr='--fineTuneIn ', - requires=['finetuning_distance', 'finetuning_substeps'], - xor=['finetuning_inwards'], - ), - finetuning_substeps=dict(argstr='%d', - requires=['finetuning_distance'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file1=dict(argstr='%s', - mandatory=True, - position=1, - ), - in_file2=dict(argstr='%s', - position=2, - ), - join_closest_components=dict(argstr='-jc', - xor=['join_closest_components'], - ), - join_overlapping_largest_components=dict(argstr='-j', - xor=['join_closest_components'], - ), - laplacian_smoothing_steps=dict(argstr='--smooth %d', - ), - number_of_biggest_shells=dict(argstr='--shells %d', - ), - out_filename=dict(argstr='-o %s', - genfile=True, - ), - output_type=dict(usedefault=True, - ), - quiet_mode=dict(argstr='-q', - ), - remove_handles=dict(argstr='--remove-handles', - ), - save_as_freesurfer_mesh=dict(argstr='--fsmesh', - xor=['save_as_vrml', 'save_as_stl'], - ), - save_as_stl=dict(argstr='--stl', - xor=['save_as_vmrl', 'save_as_freesurfer_mesh'], - ), - save_as_vmrl=dict(argstr='--wrl', - xor=['save_as_stl', 'save_as_freesurfer_mesh'], - ), - set_intersections_to_one=dict(argstr='--intersect', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), - uniform_remeshing_steps=dict(argstr='-u %d', - requires=['uniform_remeshing_vertices'], - ), - uniform_remeshing_vertices=dict(argstr='--vertices %d', - requires=['uniform_remeshing_steps'], - ), - x_shift=dict(argstr='--smooth %d', - ), + input_map = dict( + args=dict(argstr='%s', ), + cut_inner=dict(argstr='--cut-inner %d', ), + cut_outer=dict(argstr='--cut-outer %d', ), + decouple_inin=dict(argstr='--decouple-inin %d', ), + decouple_outin=dict(argstr='--decouple-outin %d', ), + decouple_outout=dict(argstr='--decouple-outout %d', ), + dilation=dict(argstr='--dilate %d', ), + dont_clean=dict(argstr='--no-clean', ), + environ=dict( + nohash=True, + usedefault=True, + ), + epsilon_angle=dict(argstr='-a %f', ), + finetuning_distance=dict( + argstr='%f', + requires=['finetuning_substeps'], + ), + finetuning_inwards=dict( + argstr='--fineTuneIn ', + requires=['finetuning_distance', 'finetuning_substeps'], + ), + finetuning_outwards=dict( + argstr='--fineTuneIn ', + requires=['finetuning_distance', 'finetuning_substeps'], + xor=['finetuning_inwards'], + ), + finetuning_substeps=dict( + argstr='%d', + requires=['finetuning_distance'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file1=dict( + argstr='%s', + mandatory=True, + position=1, + ), + in_file2=dict( + argstr='%s', + position=2, + ), + join_closest_components=dict( + argstr='-jc', + xor=['join_closest_components'], + ), + join_overlapping_largest_components=dict( + argstr='-j', + xor=['join_closest_components'], + ), + laplacian_smoothing_steps=dict(argstr='--smooth %d', ), + number_of_biggest_shells=dict(argstr='--shells %d', ), + out_filename=dict( + argstr='-o %s', + genfile=True, + ), + output_type=dict(usedefault=True, ), + quiet_mode=dict(argstr='-q', ), + remove_handles=dict(argstr='--remove-handles', ), + save_as_freesurfer_mesh=dict( + argstr='--fsmesh', + xor=['save_as_vrml', 'save_as_stl'], + ), + save_as_stl=dict( + argstr='--stl', + xor=['save_as_vmrl', 'save_as_freesurfer_mesh'], + ), + save_as_vmrl=dict( + argstr='--wrl', + xor=['save_as_stl', 'save_as_freesurfer_mesh'], + ), + set_intersections_to_one=dict(argstr='--intersect', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), + uniform_remeshing_steps=dict( + argstr='-u %d', + requires=['uniform_remeshing_vertices'], + ), + uniform_remeshing_vertices=dict( + argstr='--vertices %d', + requires=['uniform_remeshing_steps'], + ), + x_shift=dict(argstr='--smooth %d', ), ) inputs = MeshFix.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_MeshFix_outputs(): - output_map = dict(mesh_file=dict(), - ) + output_map = dict(mesh_file=dict(), ) outputs = MeshFix.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_MySQLSink.py b/nipype/interfaces/tests/test_auto_MySQLSink.py index 80bf344e63..3df9e4532f 100644 --- a/nipype/interfaces/tests/test_auto_MySQLSink.py +++ b/nipype/interfaces/tests/test_auto_MySQLSink.py @@ -4,28 +4,29 @@ def test_MySQLSink_inputs(): - input_map = dict(config=dict(mandatory=True, - xor=['host'], - ), - database_name=dict(mandatory=True, - ), - host=dict(mandatory=True, - requires=['username', 'password'], - usedefault=True, - xor=['config'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - password=dict(), - table_name=dict(mandatory=True, - ), - username=dict(), + input_map = dict( + config=dict( + mandatory=True, + xor=['host'], + ), + database_name=dict(mandatory=True, ), + host=dict( + mandatory=True, + requires=['username', 'password'], + usedefault=True, + xor=['config'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + password=dict(), + table_name=dict(mandatory=True, ), + username=dict(), ) inputs = MySQLSink.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/tests/test_auto_NiftiGeneratorBase.py b/nipype/interfaces/tests/test_auto_NiftiGeneratorBase.py index 0846313121..c81cd38afa 100644 --- a/nipype/interfaces/tests/test_auto_NiftiGeneratorBase.py +++ b/nipype/interfaces/tests/test_auto_NiftiGeneratorBase.py @@ -4,14 +4,14 @@ def test_NiftiGeneratorBase_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - ) + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = NiftiGeneratorBase.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/tests/test_auto_PETPVC.py b/nipype/interfaces/tests/test_auto_PETPVC.py index 6dbac76fa2..f08c9b6d44 100644 --- a/nipype/interfaces/tests/test_auto_PETPVC.py +++ b/nipype/interfaces/tests/test_auto_PETPVC.py @@ -4,62 +4,66 @@ def test_PETPVC_inputs(): - input_map = dict(alpha=dict(argstr='-a %.4f', - ), - args=dict(argstr='%s', - ), - debug=dict(argstr='-d', - usedefault=True, - ), - environ=dict(nohash=True, - usedefault=True, - ), - fwhm_x=dict(argstr='-x %.4f', - mandatory=True, - ), - fwhm_y=dict(argstr='-y %.4f', - mandatory=True, - ), - fwhm_z=dict(argstr='-z %.4f', - mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-i %s', - mandatory=True, - ), - mask_file=dict(argstr='-m %s', - mandatory=True, - ), - n_deconv=dict(argstr='-k %d', - ), - n_iter=dict(argstr='-n %d', - ), - out_file=dict(argstr='-o %s', - genfile=True, - hash_files=False, - ), - pvc=dict(argstr='-p %s', - mandatory=True, - ), - stop_crit=dict(argstr='-a %.4f', - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + alpha=dict(argstr='-a %.4f', ), + args=dict(argstr='%s', ), + debug=dict( + argstr='-d', + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm_x=dict( + argstr='-x %.4f', + mandatory=True, + ), + fwhm_y=dict( + argstr='-y %.4f', + mandatory=True, + ), + fwhm_z=dict( + argstr='-z %.4f', + mandatory=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-i %s', + mandatory=True, + ), + mask_file=dict( + argstr='-m %s', + mandatory=True, + ), + n_deconv=dict(argstr='-k %d', ), + n_iter=dict(argstr='-n %d', ), + out_file=dict( + argstr='-o %s', + genfile=True, + hash_files=False, + ), + pvc=dict( + argstr='-p %s', + mandatory=True, + ), + stop_crit=dict(argstr='-a %.4f', ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = PETPVC.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_PETPVC_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = PETPVC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_Quickshear.py b/nipype/interfaces/tests/test_auto_Quickshear.py index e2edaf37c6..a123444790 100644 --- a/nipype/interfaces/tests/test_auto_Quickshear.py +++ b/nipype/interfaces/tests/test_auto_Quickshear.py @@ -4,46 +4,50 @@ def test_Quickshear_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - buff=dict(argstr='%d', - position=4, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='%s', - mandatory=True, - position=1, - ), - mask_file=dict(argstr='%s', - mandatory=True, - position=2, - ), - out_file=dict(argstr='%s', - keep_extension=True, - name_source='in_file', - name_template='%s_defaced', - position=3, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + buff=dict( + argstr='%d', + position=4, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='%s', + mandatory=True, + position=1, + ), + mask_file=dict( + argstr='%s', + mandatory=True, + position=2, + ), + out_file=dict( + argstr='%s', + keep_extension=True, + name_source='in_file', + name_template='%s_defaced', + position=3, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Quickshear.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Quickshear_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Quickshear.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_S3DataGrabber.py b/nipype/interfaces/tests/test_auto_S3DataGrabber.py index d5a2536eb8..6e8cc8d424 100644 --- a/nipype/interfaces/tests/test_auto_S3DataGrabber.py +++ b/nipype/interfaces/tests/test_auto_S3DataGrabber.py @@ -4,34 +4,27 @@ def test_S3DataGrabber_inputs(): - input_map = dict(anon=dict(usedefault=True, - ), - bucket=dict(mandatory=True, - ), - bucket_path=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - local_directory=dict(), - raise_on_empty=dict(usedefault=True, - ), - region=dict(usedefault=True, - ), - sort_filelist=dict(mandatory=True, - ), - template=dict(mandatory=True, - ), - template_args=dict(), + input_map = dict( + anon=dict(usedefault=True, ), + bucket=dict(mandatory=True, ), + bucket_path=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + local_directory=dict(), + raise_on_empty=dict(usedefault=True, ), + region=dict(usedefault=True, ), + sort_filelist=dict(mandatory=True, ), + template=dict(mandatory=True, ), + template_args=dict(), ) inputs = S3DataGrabber.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_S3DataGrabber_outputs(): output_map = dict() outputs = S3DataGrabber.output_spec() diff --git a/nipype/interfaces/tests/test_auto_SQLiteSink.py b/nipype/interfaces/tests/test_auto_SQLiteSink.py index e7319e4d29..a57c72d739 100644 --- a/nipype/interfaces/tests/test_auto_SQLiteSink.py +++ b/nipype/interfaces/tests/test_auto_SQLiteSink.py @@ -4,18 +4,17 @@ def test_SQLiteSink_inputs(): - input_map = dict(database_file=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - table_name=dict(mandatory=True, - ), + input_map = dict( + database_file=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + table_name=dict(mandatory=True, ), ) inputs = SQLiteSink.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/tests/test_auto_SSHDataGrabber.py b/nipype/interfaces/tests/test_auto_SSHDataGrabber.py index 1c350203e6..cef48fa7c6 100644 --- a/nipype/interfaces/tests/test_auto_SSHDataGrabber.py +++ b/nipype/interfaces/tests/test_auto_SSHDataGrabber.py @@ -4,37 +4,29 @@ def test_SSHDataGrabber_inputs(): - input_map = dict(base_directory=dict(mandatory=True, - ), - download_files=dict(usedefault=True, - ), - hostname=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - password=dict(), - raise_on_empty=dict(usedefault=True, - ), - sort_filelist=dict(mandatory=True, - ), - ssh_log_to_file=dict(usedefault=True, - ), - template=dict(mandatory=True, - ), - template_args=dict(), - template_expression=dict(usedefault=True, - ), - username=dict(), + input_map = dict( + base_directory=dict(mandatory=True, ), + download_files=dict(usedefault=True, ), + hostname=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + password=dict(), + raise_on_empty=dict(usedefault=True, ), + sort_filelist=dict(mandatory=True, ), + ssh_log_to_file=dict(usedefault=True, ), + template=dict(mandatory=True, ), + template_args=dict(), + template_expression=dict(usedefault=True, ), + username=dict(), ) inputs = SSHDataGrabber.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SSHDataGrabber_outputs(): output_map = dict() outputs = SSHDataGrabber.output_spec() diff --git a/nipype/interfaces/tests/test_auto_SelectFiles.py b/nipype/interfaces/tests/test_auto_SelectFiles.py index 12ca6ac859..321d853f4a 100644 --- a/nipype/interfaces/tests/test_auto_SelectFiles.py +++ b/nipype/interfaces/tests/test_auto_SelectFiles.py @@ -4,25 +4,22 @@ def test_SelectFiles_inputs(): - input_map = dict(base_directory=dict(), - force_lists=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - raise_on_empty=dict(usedefault=True, - ), - sort_filelist=dict(usedefault=True, - ), + input_map = dict( + base_directory=dict(), + force_lists=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + raise_on_empty=dict(usedefault=True, ), + sort_filelist=dict(usedefault=True, ), ) inputs = SelectFiles.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SelectFiles_outputs(): output_map = dict() outputs = SelectFiles.output_spec() diff --git a/nipype/interfaces/tests/test_auto_SignalExtraction.py b/nipype/interfaces/tests/test_auto_SignalExtraction.py index 6f314f2f11..ce90755994 100644 --- a/nipype/interfaces/tests/test_auto_SignalExtraction.py +++ b/nipype/interfaces/tests/test_auto_SignalExtraction.py @@ -4,35 +4,27 @@ def test_SignalExtraction_inputs(): - input_map = dict(class_labels=dict(mandatory=True, - ), - detrend=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(mandatory=True, - ), - incl_shared_variance=dict(usedefault=True, - ), - include_global=dict(usedefault=True, - ), - label_files=dict(mandatory=True, - ), - out_file=dict(usedefault=True, - ), + input_map = dict( + class_labels=dict(mandatory=True, ), + detrend=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict(mandatory=True, ), + incl_shared_variance=dict(usedefault=True, ), + include_global=dict(usedefault=True, ), + label_files=dict(mandatory=True, ), + out_file=dict(usedefault=True, ), ) inputs = SignalExtraction.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SignalExtraction_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = SignalExtraction.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_SlicerCommandLine.py b/nipype/interfaces/tests/test_auto_SlicerCommandLine.py index 26a4700a0e..0322ba0896 100644 --- a/nipype/interfaces/tests/test_auto_SlicerCommandLine.py +++ b/nipype/interfaces/tests/test_auto_SlicerCommandLine.py @@ -4,27 +4,28 @@ def test_SlicerCommandLine_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - module=dict(), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + module=dict(), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = SlicerCommandLine.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SlicerCommandLine_outputs(): output_map = dict() outputs = SlicerCommandLine.output_spec() diff --git a/nipype/interfaces/tests/test_auto_SplitNifti.py b/nipype/interfaces/tests/test_auto_SplitNifti.py index 087ed1184c..e1f6539fab 100644 --- a/nipype/interfaces/tests/test_auto_SplitNifti.py +++ b/nipype/interfaces/tests/test_auto_SplitNifti.py @@ -4,24 +4,20 @@ def test_SplitNifti_inputs(): - input_map = dict(in_file=dict(mandatory=True, - ), - out_ext=dict(usedefault=True, - ), - out_format=dict(), - out_path=dict(), - split_dim=dict(), + input_map = dict( + in_file=dict(mandatory=True, ), + out_ext=dict(usedefault=True, ), + out_format=dict(), + out_path=dict(), + split_dim=dict(), ) inputs = SplitNifti.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_SplitNifti_outputs(): - output_map = dict(out_list=dict(), - ) + output_map = dict(out_list=dict(), ) outputs = SplitNifti.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_XNATSink.py b/nipype/interfaces/tests/test_auto_XNATSink.py index e4ce926c6e..e10813bc3d 100644 --- a/nipype/interfaces/tests/test_auto_XNATSink.py +++ b/nipype/interfaces/tests/test_auto_XNATSink.py @@ -4,38 +4,34 @@ def test_XNATSink_inputs(): - input_map = dict(_outputs=dict(usedefault=True, - ), - assessor_id=dict(xor=['reconstruction_id'], - ), - cache_dir=dict(), - config=dict(mandatory=True, - xor=['server'], - ), - experiment_id=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - project_id=dict(mandatory=True, - ), - pwd=dict(), - reconstruction_id=dict(xor=['assessor_id'], - ), - server=dict(mandatory=True, - requires=['user', 'pwd'], - xor=['config'], - ), - share=dict(usedefault=True, - ), - subject_id=dict(mandatory=True, - ), - user=dict(), + input_map = dict( + _outputs=dict(usedefault=True, ), + assessor_id=dict(xor=['reconstruction_id'], ), + cache_dir=dict(), + config=dict( + mandatory=True, + xor=['server'], + ), + experiment_id=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + project_id=dict(mandatory=True, ), + pwd=dict(), + reconstruction_id=dict(xor=['assessor_id'], ), + server=dict( + mandatory=True, + requires=['user', 'pwd'], + xor=['config'], + ), + share=dict(usedefault=True, ), + subject_id=dict(mandatory=True, ), + user=dict(), ) inputs = XNATSink.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/tests/test_auto_XNATSource.py b/nipype/interfaces/tests/test_auto_XNATSource.py index afd02e6c9d..c3efc99cbc 100644 --- a/nipype/interfaces/tests/test_auto_XNATSource.py +++ b/nipype/interfaces/tests/test_auto_XNATSource.py @@ -4,32 +4,32 @@ def test_XNATSource_inputs(): - input_map = dict(cache_dir=dict(), - config=dict(mandatory=True, - xor=['server'], - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - pwd=dict(), - query_template=dict(mandatory=True, - ), - query_template_args=dict(usedefault=True, - ), - server=dict(mandatory=True, - requires=['user', 'pwd'], - xor=['config'], - ), - user=dict(), + input_map = dict( + cache_dir=dict(), + config=dict( + mandatory=True, + xor=['server'], + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + pwd=dict(), + query_template=dict(mandatory=True, ), + query_template_args=dict(usedefault=True, ), + server=dict( + mandatory=True, + requires=['user', 'pwd'], + xor=['config'], + ), + user=dict(), ) inputs = XNATSource.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_XNATSource_outputs(): output_map = dict() outputs = XNATSource.output_spec() diff --git a/nipype/interfaces/tests/test_bids.py b/nipype/interfaces/tests/test_bids.py index aa5bc6c359..33ef861e11 100644 --- a/nipype/interfaces/tests/test_bids.py +++ b/nipype/interfaces/tests/test_bids.py @@ -17,12 +17,12 @@ # There are three reasons these tests will be skipped: -@pytest.mark.skipif(not have_pybids, - reason="Pybids is not installed") -@pytest.mark.skipif(sys.version_info < (3, 0), - reason="Pybids no longer supports Python 2") -@pytest.mark.skipif(not dist_is_editable('pybids'), - reason="Pybids is not installed in editable mode") +@pytest.mark.skipif(not have_pybids, reason="Pybids is not installed") +@pytest.mark.skipif( + sys.version_info < (3, 0), reason="Pybids no longer supports Python 2") +@pytest.mark.skipif( + not dist_is_editable('pybids'), + reason="Pybids is not installed in editable mode") def test_bids_grabber(tmpdir): tmpdir.chdir() bg = BIDSDataGrabber() @@ -31,18 +31,18 @@ def test_bids_grabber(tmpdir): results = bg.run() assert os.path.basename(results.outputs.anat[0]) == 'sub-01_T1w.nii.gz' assert os.path.basename(results.outputs.func[0]) == ( - 'sub-01_task-mixedgamblestask_run-01_bold.nii.gz') + 'sub-01_task-mixedgamblestask_run-01_bold.nii.gz') -@pytest.mark.skipif(not have_pybids, - reason="Pybids is not installed") -@pytest.mark.skipif(sys.version_info < (3, 0), - reason="Pybids no longer supports Python 2") -@pytest.mark.skipif(not dist_is_editable('pybids'), - reason="Pybids is not installed in editable mode") +@pytest.mark.skipif(not have_pybids, reason="Pybids is not installed") +@pytest.mark.skipif( + sys.version_info < (3, 0), reason="Pybids no longer supports Python 2") +@pytest.mark.skipif( + not dist_is_editable('pybids'), + reason="Pybids is not installed in editable mode") def test_bids_fields(tmpdir): tmpdir.chdir() - bg = BIDSDataGrabber(infields = ['subject'], outfields = ['dwi']) + bg = BIDSDataGrabber(infields=['subject'], outfields=['dwi']) bg.inputs.base_dir = os.path.join(datadir, 'ds005') bg.inputs.subject = '01' bg.inputs.output_query['dwi'] = dict(modality='dwi') diff --git a/nipype/interfaces/tests/test_io.py b/nipype/interfaces/tests/test_io.py index ff56c9ec9d..a2103eadf2 100644 --- a/nipype/interfaces/tests/test_io.py +++ b/nipype/interfaces/tests/test_io.py @@ -59,29 +59,94 @@ def test_s3datagrabber(): assert dg.inputs.template_args == {'outfiles': []} -templates1 = {"model": "interfaces/{package}/model.py", - "preprocess": "interfaces/{package}/pre*.py"} +templates1 = { + "model": "interfaces/{package}/model.py", + "preprocess": "interfaces/{package}/pre*.py" +} templates2 = {"converter": "interfaces/dcm{to!s}nii.py"} templates3 = {"model": "interfaces/{package.name}/model.py"} -@pytest.mark.parametrize("SF_args, inputs_att, expected", [ - ({"templates":templates1}, {"package":"fsl"}, - {"infields":["package"], "outfields":["model", "preprocess"], "run_output":{"model":op.join(op.dirname(nipype.__file__),"interfaces/fsl/model.py"), "preprocess":op.join(op.dirname(nipype.__file__),"interfaces/fsl/preprocess.py")}, "node_output":["model", "preprocess"]}), - - ({"templates":templates1, "force_lists":True}, {"package":"spm"}, - {"infields":["package"], "outfields":["model", "preprocess"], "run_output":{"model":[op.join(op.dirname(nipype.__file__),"interfaces/spm/model.py")], "preprocess":[op.join(op.dirname(nipype.__file__),"interfaces/spm/preprocess.py")]}, "node_output":["model", "preprocess"]}), - - ({"templates":templates1}, {"package":"fsl", "force_lists":["model"]}, - {"infields":["package"], "outfields":["model", "preprocess"], "run_output":{"model":[op.join(op.dirname(nipype.__file__),"interfaces/fsl/model.py")], "preprocess":op.join(op.dirname(nipype.__file__),"interfaces/fsl/preprocess.py")}, "node_output":["model", "preprocess"]}), - - ({"templates":templates2}, {"to":2}, - {"infields":["to"], "outfields":["converter"], "run_output":{"converter":op.join(op.dirname(nipype.__file__), "interfaces/dcm2nii.py")}, "node_output":["converter"]}), - ({"templates": templates3}, {"package": namedtuple("package", ["name"])("fsl")}, - {"infields": ["package"], "outfields": ["model"], - "run_output": {"model": op.join(op.dirname(nipype.__file__), "interfaces/fsl/model.py")}, - "node_output": ["model"]}), - ]) +@pytest.mark.parametrize("SF_args, inputs_att, expected", [ + ({ + "templates": templates1 + }, { + "package": "fsl" + }, { + "infields": ["package"], + "outfields": ["model", "preprocess"], + "run_output": { + "model": + op.join(op.dirname(nipype.__file__), "interfaces/fsl/model.py"), + "preprocess": + op.join( + op.dirname(nipype.__file__), "interfaces/fsl/preprocess.py") + }, + "node_output": ["model", "preprocess"] + }), + ({ + "templates": templates1, + "force_lists": True + }, { + "package": "spm" + }, { + "infields": ["package"], + "outfields": ["model", "preprocess"], + "run_output": { + "model": + [op.join(op.dirname(nipype.__file__), "interfaces/spm/model.py")], + "preprocess": [ + op.join( + op.dirname(nipype.__file__), + "interfaces/spm/preprocess.py") + ] + }, + "node_output": ["model", "preprocess"] + }), + ({ + "templates": templates1 + }, { + "package": "fsl", + "force_lists": ["model"] + }, { + "infields": ["package"], + "outfields": ["model", "preprocess"], + "run_output": { + "model": + [op.join(op.dirname(nipype.__file__), "interfaces/fsl/model.py")], + "preprocess": + op.join( + op.dirname(nipype.__file__), "interfaces/fsl/preprocess.py") + }, + "node_output": ["model", "preprocess"] + }), + ({ + "templates": templates2 + }, { + "to": 2 + }, { + "infields": ["to"], + "outfields": ["converter"], + "run_output": { + "converter": + op.join(op.dirname(nipype.__file__), "interfaces/dcm2nii.py") + }, + "node_output": ["converter"] + }), + ({ + "templates": templates3 + }, { + "package": namedtuple("package", ["name"])("fsl") + }, { + "infields": ["package"], + "outfields": ["model"], + "run_output": { + "model": + op.join(op.dirname(nipype.__file__), "interfaces/fsl/model.py") + }, + "node_output": ["model"] + }), +]) def test_selectfiles(SF_args, inputs_att, expected): base_dir = op.dirname(nipype.__file__) dg = nio.SelectFiles(base_directory=base_dir, **SF_args) @@ -100,11 +165,13 @@ def test_selectfiles(SF_args, inputs_att, expected): def test_selectfiles_valueerror(): """Test ValueError when force_lists has field that isn't in template.""" base_dir = op.dirname(nipype.__file__) - templates = {"model": "interfaces/{package}/model.py", - "preprocess": "interfaces/{package}/pre*.py"} + templates = { + "model": "interfaces/{package}/model.py", + "preprocess": "interfaces/{package}/pre*.py" + } force_lists = ["model", "preprocess", "registration"] - sf = nio.SelectFiles(templates, base_directory=base_dir, - force_lists=force_lists) + sf = nio.SelectFiles( + templates, base_directory=base_dir, force_lists=force_lists) with pytest.raises(ValueError): sf.run() @@ -119,8 +186,9 @@ def test_s3datagrabber_communication(tmpdir): dg.inputs.local_directory = tmpdir.strpath dg.inputs.sort_filelist = True dg.inputs.template = '*' - dg.inputs.field_template = dict(func='%s/BOLD/task001_%s/bold.nii.gz', - struct='%s/anatomy/highres001_brain.nii.gz') + dg.inputs.field_template = dict( + func='%s/BOLD/task001_%s/bold.nii.gz', + struct='%s/anatomy/highres001_brain.nii.gz') dg.inputs.subj_id = ['sub001', 'sub002'] dg.inputs.run_num = ['run001', 'run003'] dg.inputs.template_args = dict( @@ -130,36 +198,47 @@ def test_s3datagrabber_communication(tmpdir): struct_outfiles = res.outputs.struct # check for all files - assert os.path.join(dg.inputs.local_directory, '/sub001/BOLD/task001_run001/bold.nii.gz') in func_outfiles[0] + assert os.path.join( + dg.inputs.local_directory, + '/sub001/BOLD/task001_run001/bold.nii.gz') in func_outfiles[0] assert os.path.exists(func_outfiles[0]) - assert os.path.join(dg.inputs.local_directory, '/sub001/anatomy/highres001_brain.nii.gz') in struct_outfiles[0] + assert os.path.join( + dg.inputs.local_directory, + '/sub001/anatomy/highres001_brain.nii.gz') in struct_outfiles[0] assert os.path.exists(struct_outfiles[0]) - assert os.path.join(dg.inputs.local_directory, '/sub002/BOLD/task001_run003/bold.nii.gz') in func_outfiles[1] + assert os.path.join( + dg.inputs.local_directory, + '/sub002/BOLD/task001_run003/bold.nii.gz') in func_outfiles[1] assert os.path.exists(func_outfiles[1]) - assert os.path.join(dg.inputs.local_directory, '/sub002/anatomy/highres001_brain.nii.gz') in struct_outfiles[1] + assert os.path.join( + dg.inputs.local_directory, + '/sub002/anatomy/highres001_brain.nii.gz') in struct_outfiles[1] assert os.path.exists(struct_outfiles[1]) def test_datagrabber_order(tmpdir): - for file_name in ['sub002_L1_R1.q', 'sub002_L1_R2.q', 'sub002_L2_R1.q', - 'sub002_L2_R2.qd', 'sub002_L3_R10.q', 'sub002_L3_R2.q']: + for file_name in [ + 'sub002_L1_R1.q', 'sub002_L1_R2.q', 'sub002_L2_R1.q', + 'sub002_L2_R2.qd', 'sub002_L3_R10.q', 'sub002_L3_R2.q' + ]: tmpdir.join(file_name).open('a').close() dg = nio.DataGrabber(infields=['sid']) dg.inputs.base_directory = tmpdir.strpath dg.inputs.template = '%s_L%d_R*.q*' - dg.inputs.template_args = {'outfiles': [['sid', 1], ['sid', 2], - ['sid', 3]]} + dg.inputs.template_args = { + 'outfiles': [['sid', 1], ['sid', 2], ['sid', 3]] + } dg.inputs.sid = 'sub002' dg.inputs.sort_filelist = True res = dg.run() outfiles = res.outputs.outfiles - assert 'sub002_L1_R1' in outfiles[0][0] - assert 'sub002_L1_R2' in outfiles[0][1] - assert 'sub002_L2_R1' in outfiles[1][0] - assert 'sub002_L2_R2' in outfiles[1][1] - assert 'sub002_L3_R2' in outfiles[2][0] + assert 'sub002_L1_R1' in outfiles[0][0] + assert 'sub002_L1_R2' in outfiles[0][1] + assert 'sub002_L2_R1' in outfiles[1][0] + assert 'sub002_L2_R2' in outfiles[1][1] + assert 'sub002_L3_R2' in outfiles[2][0] assert 'sub002_L3_R10' in outfiles[2][1] @@ -185,7 +264,8 @@ def dummy_input(request, tmpdir_factory): ''' # Init variables - input_path = tmpdir_factory.mktemp('input_data').join('datasink_test_s3.txt') + input_path = tmpdir_factory.mktemp('input_data').join( + 'datasink_test_s3.txt') # Create input file input_path.write_binary(b'ABCD1234') @@ -195,7 +275,8 @@ def dummy_input(request, tmpdir_factory): # Test datasink writes to s3 properly -@pytest.mark.skipif(noboto3 or not fakes3, reason="boto3 or fakes3 library is not available") +@pytest.mark.skipif( + noboto3 or not fakes3, reason="boto3 or fakes3 library is not available") def test_datasink_to_s3(dummy_input, tmpdir): ''' This function tests to see if the S3 functionality of a DataSink @@ -212,14 +293,17 @@ def test_datasink_to_s3(dummy_input, tmpdir): input_path = dummy_input # Start up fake-S3 server - proc = Popen(['fakes3', '-r', fakes3_dir, '-p', '4567'], stdout=open(os.devnull, 'wb')) + proc = Popen( + ['fakes3', '-r', fakes3_dir, '-p', '4567'], + stdout=open(os.devnull, 'wb')) # Init boto3 s3 resource to talk with fakes3 - resource = boto3.resource(aws_access_key_id='mykey', - aws_secret_access_key='mysecret', - service_name='s3', - endpoint_url='http://localhost:4567', - use_ssl=False) + resource = boto3.resource( + aws_access_key_id='mykey', + aws_secret_access_key='mysecret', + service_name='s3', + endpoint_url='http://localhost:4567', + use_ssl=False) resource.meta.client.meta.events.unregister('before-sign.s3', fix_s3_host) # Create bucket @@ -248,7 +332,8 @@ def test_datasink_to_s3(dummy_input, tmpdir): # Test AWS creds read from env vars -@pytest.mark.skipif(noboto3 or not fakes3, reason="boto3 or fakes3 library is not available") +@pytest.mark.skipif( + noboto3 or not fakes3, reason="boto3 or fakes3 library is not available") def test_aws_keys_from_env(): ''' Function to ensure the DataSink can successfully read in AWS @@ -327,13 +412,14 @@ def test_datasink_substitutions(tmpdir): # Patterns should be more comprehendable in the real-world usage # cases since paths would be quite more sensible regexp_substitutions=[(r'xABABAB(\w*)\.n$', r'a-\1-b.n'), - ('(.*%s)[-a]([^%s]*)$' % ((os.path.sep,) * 2), + ('(.*%s)[-a]([^%s]*)$' % ((os.path.sep, ) * 2), r'\1!\2')]) setattr(ds.inputs, '@outdir', files) ds.run() assert sorted([os.path.basename(x) for - x in glob.glob(os.path.join(str(outdir), '*'))]) \ - == ['!-yz-b.n', 'ABABAB.n'] # so we got re used 2nd and both patterns + x in glob.glob(os.path.join(str(outdir), '*'))]) \ + == ['!-yz-b.n', 'ABABAB.n'] # so we got re used 2nd and both patterns + @pytest.fixture() def _temp_analyze_files(tmpdir): @@ -350,16 +436,19 @@ def test_datasink_copydir_1(_temp_analyze_files, tmpdir): orig_img, orig_hdr = _temp_analyze_files outdir = tmpdir pth, fname = os.path.split(orig_img) - ds = nio.DataSink(base_directory=outdir.mkdir("basedir").strpath, parameterization=False) + ds = nio.DataSink( + base_directory=outdir.mkdir("basedir").strpath, parameterization=False) setattr(ds.inputs, '@outdir', pth) ds.run() sep = os.path.sep assert tmpdir.join('basedir', pth.split(sep)[-1], fname).check() + def test_datasink_copydir_2(_temp_analyze_files, tmpdir): orig_img, orig_hdr = _temp_analyze_files pth, fname = os.path.split(orig_img) - ds = nio.DataSink(base_directory=tmpdir.mkdir("basedir").strpath, parameterization=False) + ds = nio.DataSink( + base_directory=tmpdir.mkdir("basedir").strpath, parameterization=False) ds.inputs.remove_dest_dir = True setattr(ds.inputs, 'outdir', pth) ds.run() @@ -379,7 +468,9 @@ def test_datafinder_depth(tmpdir): df.inputs.min_depth = min_depth df.inputs.max_depth = max_depth result = df.run() - expected = ['{}'.format(x) for x in range(min_depth, max_depth + 1)] + expected = [ + '{}'.format(x) for x in range(min_depth, max_depth + 1) + ] for path, exp_fname in zip(result.outputs.out_paths, expected): _, fname = os.path.split(path) assert fname == exp_fname @@ -419,10 +510,12 @@ def test_jsonsink_input(): assert 'test' in ds.inputs.copyable_trait_names() -@pytest.mark.parametrize("inputs_attributes", [ - {'new_entry' : 'someValue'}, - {'new_entry' : 'someValue', 'test' : 'testInfields'} -]) +@pytest.mark.parametrize("inputs_attributes", [{ + 'new_entry': 'someValue' +}, { + 'new_entry': 'someValue', + 'test': 'testInfields' +}]) def test_jsonsink(tmpdir, inputs_attributes): tmpdir.chdir() js = nio.JSONFileSink(infields=['test'], in_dict={'foo': 'var'}) @@ -437,6 +530,3 @@ def test_jsonsink(tmpdir, inputs_attributes): data = simplejson.load(f) assert data == expected_data - - - diff --git a/nipype/interfaces/tests/test_matlab.py b/nipype/interfaces/tests/test_matlab.py index 25b5ac964f..2576a379e7 100644 --- a/nipype/interfaces/tests/test_matlab.py +++ b/nipype/interfaces/tests/test_matlab.py @@ -16,7 +16,9 @@ def clean_workspace_and_get_default_script_file(): # Make sure things are clean. default_script_file = mlab.MatlabInputSpec().script_file if os.path.exists(default_script_file): - os.remove(default_script_file) # raise Exception('Default script file needed for tests; please remove %s!' % default_script_file) + os.remove( + default_script_file + ) # raise Exception('Default script file needed for tests; please remove %s!' % default_script_file) return default_script_file @@ -24,8 +26,8 @@ def clean_workspace_and_get_default_script_file(): def test_cmdline(): default_script_file = clean_workspace_and_get_default_script_file() - mi = mlab.MatlabCommand(script='whos', - script_file='testscript', mfile=False) + mi = mlab.MatlabCommand( + script='whos', script_file='testscript', mfile=False) assert mi.cmdline == \ matlab_cmd + (' -nodesktop -nosplash -singleCompThread -r "fprintf(1,' @@ -38,16 +40,20 @@ def test_cmdline(): assert mi.inputs.script == 'whos' assert mi.inputs.script_file == 'testscript' - assert not os.path.exists(mi.inputs.script_file), 'scriptfile should not exist' - assert not os.path.exists(default_script_file), 'default scriptfile should not exist.' + assert not os.path.exists( + mi.inputs.script_file), 'scriptfile should not exist' + assert not os.path.exists( + default_script_file), 'default scriptfile should not exist.' @pytest.mark.skipif(no_matlab, reason="matlab is not available") def test_mlab_inputspec(): default_script_file = clean_workspace_and_get_default_script_file() spec = mlab.MatlabInputSpec() - for k in ['paths', 'script', 'nosplash', 'mfile', 'logfile', 'script_file', - 'nodesktop']: + for k in [ + 'paths', 'script', 'nosplash', 'mfile', 'logfile', 'script_file', + 'nodesktop' + ]: assert k in spec.copyable_trait_names() assert spec.nodesktop assert spec.nosplash @@ -72,15 +78,18 @@ def test_run_interface(tmpdir): default_script_file = clean_workspace_and_get_default_script_file() mc = mlab.MatlabCommand(matlab_cmd='foo_m') - assert not os.path.exists(default_script_file), 'scriptfile should not exist 1.' + assert not os.path.exists( + default_script_file), 'scriptfile should not exist 1.' with pytest.raises(ValueError): mc.run() # script is mandatory - assert not os.path.exists(default_script_file), 'scriptfile should not exist 2.' + assert not os.path.exists( + default_script_file), 'scriptfile should not exist 2.' if os.path.exists(default_script_file): # cleanup os.remove(default_script_file) mc.inputs.script = 'a=1;' - assert not os.path.exists(default_script_file), 'scriptfile should not exist 3.' + assert not os.path.exists( + default_script_file), 'scriptfile should not exist 3.' with pytest.raises(IOError): mc.run() # foo_m is not an executable assert os.path.exists(default_script_file), 'scriptfile should exist 3.' @@ -91,7 +100,8 @@ def test_run_interface(tmpdir): # bypasses ubuntu dash issue mc = mlab.MatlabCommand(script='foo;', paths=[tmpdir.strpath], mfile=True) - assert not os.path.exists(default_script_file), 'scriptfile should not exist 4.' + assert not os.path.exists( + default_script_file), 'scriptfile should not exist 4.' with pytest.raises(RuntimeError): mc.run() assert os.path.exists(default_script_file), 'scriptfile should exist 4.' @@ -99,7 +109,8 @@ def test_run_interface(tmpdir): os.remove(default_script_file) # bypasses ubuntu dash issue - res = mlab.MatlabCommand(script='a=1;', paths=[tmpdir.strpath], mfile=True).run() + res = mlab.MatlabCommand( + script='a=1;', paths=[tmpdir.strpath], mfile=True).run() assert res.runtime.returncode == 0 assert os.path.exists(default_script_file), 'scriptfile should exist 5.' cwd.chdir() @@ -111,6 +122,7 @@ def test_set_matlabcmd(): mi = mlab.MatlabCommand() mi.set_default_matlab_cmd('foo') - assert not os.path.exists(default_script_file), 'scriptfile should not exist.' + assert not os.path.exists( + default_script_file), 'scriptfile should not exist.' assert mi._default_matlab_cmd == 'foo' mi.set_default_matlab_cmd(matlab_cmd) diff --git a/nipype/interfaces/tests/test_nilearn.py b/nipype/interfaces/tests/test_nilearn.py index ce3846a6d3..79432bc180 100644 --- a/nipype/interfaces/tests/test_nilearn.py +++ b/nipype/interfaces/tests/test_nilearn.py @@ -19,6 +19,7 @@ except ImportError: pass + @pytest.mark.skipif(no_nilearn, reason="the nilearn library is not available") class TestSignalExtraction(): @@ -38,58 +39,67 @@ def setup_class(self, tmpdir_factory): utils.save_toy_nii(self.fake_fmri_data, self.filenames['in_file']) utils.save_toy_nii(self.fake_label_data, self.filenames['label_files']) - def test_signal_extract_no_shared(self): # run - iface.SignalExtraction(in_file=self.filenames['in_file'], - label_files=self.filenames['label_files'], - class_labels=self.labels, - incl_shared_variance=False).run() + iface.SignalExtraction( + in_file=self.filenames['in_file'], + label_files=self.filenames['label_files'], + class_labels=self.labels, + incl_shared_variance=False).run() # assert self.assert_expected_output(self.labels, self.base_wanted) - def test_signal_extr_bad_label_list(self): # run with pytest.raises(ValueError): - iface.SignalExtraction(in_file=self.filenames['in_file'], - label_files=self.filenames['label_files'], - class_labels=['bad'], - incl_shared_variance=False).run() + iface.SignalExtraction( + in_file=self.filenames['in_file'], + label_files=self.filenames['label_files'], + class_labels=['bad'], + incl_shared_variance=False).run() def test_signal_extr_equiv_4d_no_shared(self): - self._test_4d_label(self.base_wanted, self.fake_equiv_4d_label_data, - incl_shared_variance=False) + self._test_4d_label( + self.base_wanted, + self.fake_equiv_4d_label_data, + incl_shared_variance=False) def test_signal_extr_4d_no_shared(self): # set up & run & assert - self._test_4d_label(self.fourd_wanted, self.fake_4d_label_data, incl_shared_variance=False) + self._test_4d_label( + self.fourd_wanted, + self.fake_4d_label_data, + incl_shared_variance=False) def test_signal_extr_global_no_shared(self): # set up - wanted_global = [[-4./6], [-1./6], [3./6], [-1./6], [-7./6]] + wanted_global = [[-4. / 6], [-1. / 6], [3. / 6], [-1. / 6], [-7. / 6]] for i, vals in enumerate(self.base_wanted): wanted_global[i].extend(vals) # run - iface.SignalExtraction(in_file=self.filenames['in_file'], - label_files=self.filenames['label_files'], - class_labels=self.labels, - include_global=True, - incl_shared_variance=False).run() + iface.SignalExtraction( + in_file=self.filenames['in_file'], + label_files=self.filenames['label_files'], + class_labels=self.labels, + include_global=True, + incl_shared_variance=False).run() # assert self.assert_expected_output(self.global_labels, wanted_global) def test_signal_extr_4d_global_no_shared(self): # set up - wanted_global = [[3./8], [-3./8], [1./8], [-7./8], [-9./8]] + wanted_global = [[3. / 8], [-3. / 8], [1. / 8], [-7. / 8], [-9. / 8]] for i, vals in enumerate(self.fourd_wanted): wanted_global[i].extend(vals) # run & assert - self._test_4d_label(wanted_global, self.fake_4d_label_data, - include_global=True, incl_shared_variance=False) + self._test_4d_label( + wanted_global, + self.fake_4d_label_data, + include_global=True, + incl_shared_variance=False) def test_signal_extr_shared(self): # set up @@ -99,38 +109,45 @@ def test_signal_extr_shared(self): wanted_row = [] for reg in range(self.fake_4d_label_data.shape[3]): region = self.fake_4d_label_data[:, :, :, reg].flatten() - wanted_row.append((volume*region).sum()/(region*region).sum()) + wanted_row.append( + (volume * region).sum() / (region * region).sum()) wanted.append(wanted_row) # run & assert self._test_4d_label(wanted, self.fake_4d_label_data) - def test_signal_extr_traits_valid(self): ''' Test a node using the SignalExtraction interface. Unlike interface.run(), node.run() checks the traits ''' # run - node = pe.Node(iface.SignalExtraction(in_file=os.path.abspath(self.filenames['in_file']), - label_files=os.path.abspath(self.filenames['label_files']), - class_labels=self.labels, - incl_shared_variance=False), - name='SignalExtraction') + node = pe.Node( + iface.SignalExtraction( + in_file=os.path.abspath(self.filenames['in_file']), + label_files=os.path.abspath(self.filenames['label_files']), + class_labels=self.labels, + incl_shared_variance=False), + name='SignalExtraction') node.run() # assert # just checking that it passes trait validations - def _test_4d_label(self, wanted, fake_labels, include_global=False, incl_shared_variance=True): + def _test_4d_label(self, + wanted, + fake_labels, + include_global=False, + incl_shared_variance=True): # set up utils.save_toy_nii(fake_labels, self.filenames['4d_label_file']) # run - iface.SignalExtraction(in_file=self.filenames['in_file'], - label_files=self.filenames['4d_label_file'], - class_labels=self.labels, - incl_shared_variance=incl_shared_variance, - include_global=include_global).run() + iface.SignalExtraction( + in_file=self.filenames['in_file'], + label_files=self.filenames['4d_label_file'], + class_labels=self.labels, + incl_shared_variance=incl_shared_variance, + include_global=include_global).run() wanted_labels = self.global_labels if include_global else self.labels @@ -140,9 +157,10 @@ def _test_4d_label(self, wanted, fake_labels, include_global=False, incl_shared_ def assert_expected_output(self, labels, wanted): with open(self.filenames['out_file'], 'r') as output: got = [line.split() for line in output] - labels_got = got.pop(0) # remove header + labels_got = got.pop(0) # remove header assert labels_got == labels - assert len(got) == self.fake_fmri_data.shape[3],'num rows and num volumes' + assert len(got) == self.fake_fmri_data.shape[ + 3], 'num rows and num volumes' # convert from string to float got = [[float(num) for num in row] for row in got] for i, time in enumerate(got): @@ -150,60 +168,33 @@ def assert_expected_output(self, labels, wanted): for j, segment in enumerate(time): npt.assert_almost_equal(segment, wanted[i][j], decimal=1) -#dj: self doesnt have orig_dir at this point, not sure how to change it. should work without it + +# dj: self doesnt have orig_dir at this point, not sure how to change it. +# should work without it # def teardown_class(self): # self.orig_dir.chdir() + fake_fmri_data = np.array([[[[2, -1, 4, -2, 3], [4, -2, -5, -1, 0]], + [[-2, 0, 1, 4, 4], [-5, 3, -3, 1, -5]]], + [[[2, -2, -1, -2, -5], [3, 0, 3, -5, -2]], + [[-4, -2, -2, 1, -2], [3, 1, 4, -3, -2]]]]) - fake_fmri_data = np.array([[[[2, -1, 4, -2, 3], - [4, -2, -5, -1, 0]], - - [[-2, 0, 1, 4, 4], - [-5, 3, -3, 1, -5]]], - - - [[[2, -2, -1, -2, -5], - [3, 0, 3, -5, -2]], - - [[-4, -2, -2, 1, -2], - [3, 1, 4, -3, -2]]]]) - - fake_label_data = np.array([[[1, 0], - [3, 1]], - - [[2, 0], - [1, 3]]]) - - fake_equiv_4d_label_data = np.array([[[[1., 0., 0.], - [0., 0., 0.]], - [[0., 0., 1.], - [1., 0., 0.]]], - [[[0., 1., 0.], - [0., 0., 0.]], - [[1., 0., 0.], - [0., 0., 1.]]]]) - - base_wanted = [[-2.33333, 2, .5], - [0, -2, .5], - [-.3333333, -1, 2.5], - [0, -2, .5], - [-1.3333333, -5, 1]] - - fake_4d_label_data = np.array([[[[0.2, 0.3, 0.5], - [0.1, 0.1, 0.8]], - - [[0.1, 0.3, 0.6], - [0.3, 0.4, 0.3]]], + fake_label_data = np.array([[[1, 0], [3, 1]], [[2, 0], [1, 3]]]) - [[[0.2, 0.2, 0.6], - [0., 0.3, 0.7]], + fake_equiv_4d_label_data = np.array( + [[[[1., 0., 0.], [0., 0., 0.]], [[0., 0., 1.], [1., 0., 0.]]], + [[[0., 1., 0.], [0., 0., 0.]], [[1., 0., 0.], [0., 0., 1.]]]]) - [[0.3, 0.3, 0.4], - [0.3, 0.4, 0.3]]]]) + base_wanted = [[-2.33333, 2, .5], [0, -2, .5], [-.3333333, -1, 2.5], + [0, -2, .5], [-1.3333333, -5, 1]] + fake_4d_label_data = np.array([[[[0.2, 0.3, 0.5], [0.1, 0.1, 0.8]], + [[0.1, 0.3, 0.6], [0.3, 0.4, 0.3]]], + [[[0.2, 0.2, 0.6], [0., 0.3, 0.7]], + [[0.3, 0.3, 0.4], [0.3, 0.4, 0.3]]]]) - fourd_wanted = [[-5.0652173913, -5.44565217391, 5.50543478261], - [-7.02173913043, 11.1847826087, -4.33152173913], - [-19.0869565217, 21.2391304348, -4.57608695652], - [5.19565217391, -3.66304347826, -1.51630434783], + fourd_wanted = [[-5.0652173913, -5.44565217391, 5.50543478261], [ + -7.02173913043, 11.1847826087, -4.33152173913 + ], [-19.0869565217, 21.2391304348, + -4.57608695652], [5.19565217391, -3.66304347826, -1.51630434783], [-12.0, 3., 0.5]] diff --git a/nipype/interfaces/utility/base.py b/nipype/interfaces/utility/base.py index ec744d9fce..87eb51e61b 100644 --- a/nipype/interfaces/utility/base.py +++ b/nipype/interfaces/utility/base.py @@ -6,7 +6,8 @@ >>> tmp = getfixture('tmpdir') >>> old = tmp.chdir() """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range from future import standard_library @@ -17,9 +18,9 @@ import numpy as np import nibabel as nb -from ..base import (traits, TraitedSpec, DynamicTraitedSpec, File, - Undefined, isdefined, OutputMultiPath, InputMultiPath, - BaseInterface, BaseInterfaceInputSpec, Str) +from ..base import (traits, TraitedSpec, DynamicTraitedSpec, File, Undefined, + isdefined, OutputMultiPath, InputMultiPath, BaseInterface, + BaseInterfaceInputSpec, Str) from ..io import IOBase, add_traits from ...utils.filemanip import filename_to_list, copyfile, split_filename @@ -55,11 +56,14 @@ class IdentityInterface(IOBase): def __init__(self, fields=None, mandatory_inputs=True, **inputs): super(IdentityInterface, self).__init__(**inputs) if fields is None or not fields: - raise ValueError('Identity Interface fields must be a non-empty list') + raise ValueError( + 'Identity Interface fields must be a non-empty list') # Each input must be in the fields. for in_field in inputs: if in_field not in fields: - raise ValueError('Identity Interface input is not in the fields: %s' % in_field) + raise ValueError( + 'Identity Interface input is not in the fields: %s' % + in_field) self._fields = fields self._mandatory_inputs = mandatory_inputs add_traits(self.inputs, fields) @@ -78,7 +82,7 @@ def _list_outputs(self): value = getattr(self.inputs, key) if not isdefined(value): msg = "%s requires a value for input '%s' because it was listed in 'fields'. \ - You can turn off mandatory inputs checking by passing mandatory_inputs = False to the constructor." % \ + You can turn off mandatory inputs checking by passing mandatory_inputs = False to the constructor." % \ (self.__class__.__name__, key) raise ValueError(msg) @@ -91,12 +95,19 @@ def _list_outputs(self): class MergeInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - axis = traits.Enum('vstack', 'hstack', usedefault=True, - desc='direction in which to merge, hstack requires same number of elements in each input') - no_flatten = traits.Bool(False, usedefault=True, - desc='append to outlist instead of extending in vstack mode') - ravel_inputs = traits.Bool(False, usedefault=True, - desc='ravel inputs when no_flatten is False') + axis = traits.Enum( + 'vstack', + 'hstack', + usedefault=True, + desc= + 'direction in which to merge, hstack requires same number of elements in each input' + ) + no_flatten = traits.Bool( + False, + usedefault=True, + desc='append to outlist instead of extending in vstack mode') + ravel_inputs = traits.Bool( + False, usedefault=True, desc='ravel inputs when no_flatten is False') class MergeOutputSpec(TraitedSpec): @@ -173,14 +184,16 @@ def _list_outputs(self): return outputs else: getval = lambda idx: getattr(self.inputs, 'in%d' % (idx + 1)) - values = [getval(idx) for idx in range(self._numinputs) - if isdefined(getval(idx))] + values = [ + getval(idx) for idx in range(self._numinputs) + if isdefined(getval(idx)) + ] if self.inputs.axis == 'vstack': for value in values: if isinstance(value, list) and not self.inputs.no_flatten: - out.extend(_ravel(value) if self.inputs.ravel_inputs else - value) + out.extend( + _ravel(value) if self.inputs.ravel_inputs else value) else: out.append(value) else: @@ -193,19 +206,21 @@ def _list_outputs(self): class RenameInputSpec(DynamicTraitedSpec): in_file = File(exists=True, mandatory=True, desc="file to rename") - keep_ext = traits.Bool(desc=("Keep in_file extension, replace " - "non-extension component of name")) - format_string = Str(mandatory=True, - desc="Python formatting string for output template") + keep_ext = traits.Bool( + desc=("Keep in_file extension, replace " + "non-extension component of name")) + format_string = Str( + mandatory=True, desc="Python formatting string for output template") parse_string = Str(desc="Python regexp parse string to define " - "replacement inputs") - use_fullpath = traits.Bool(False, usedefault=True, - desc="Use full path as input to regex parser") + "replacement inputs") + use_fullpath = traits.Bool( + False, usedefault=True, desc="Use full path as input to regex parser") class RenameOutputSpec(TraitedSpec): - out_file = traits.File(exists=True, desc="softlink to original file with new name") + out_file = traits.File( + exists=True, desc="softlink to original file with new name") class Rename(IOBase): @@ -265,9 +280,9 @@ def __init__(self, format_string=None, **inputs): def _rename(self): fmt_dict = dict() if isdefined(self.inputs.parse_string): - if isdefined(self.inputs.use_fullpath) and self.inputs.use_fullpath: - m = re.search(self.inputs.parse_string, - self.inputs.in_file) + if isdefined( + self.inputs.use_fullpath) and self.inputs.use_fullpath: + m = re.search(self.inputs.parse_string, self.inputs.in_file) else: m = re.search(self.inputs.parse_string, os.path.split(self.inputs.in_file)[1]) @@ -278,16 +293,18 @@ def _rename(self): if isdefined(val): fmt_dict[field] = getattr(self.inputs, field) if self.inputs.keep_ext: - fmt_string = "".join([self.inputs.format_string, - split_filename(self.inputs.in_file)[2]]) + fmt_string = "".join([ + self.inputs.format_string, + split_filename(self.inputs.in_file)[2] + ]) else: fmt_string = self.inputs.format_string return fmt_string % fmt_dict def _run_interface(self, runtime): runtime.returncode = 0 - _ = copyfile(self.inputs.in_file, os.path.join(os.getcwd(), - self._rename())) + _ = copyfile(self.inputs.in_file, + os.path.join(os.getcwd(), self._rename())) return runtime def _list_outputs(self): @@ -297,12 +314,17 @@ def _list_outputs(self): class SplitInputSpec(BaseInterfaceInputSpec): - inlist = traits.List(traits.Any, mandatory=True, - desc='list of values to split') - splits = traits.List(traits.Int, mandatory=True, - desc='Number of outputs in each split - should add to number of inputs') - squeeze = traits.Bool(False, usedefault=True, - desc='unfold one-element splits removing the list') + inlist = traits.List( + traits.Any, mandatory=True, desc='list of values to split') + splits = traits.List( + traits.Int, + mandatory=True, + desc='Number of outputs in each split - should add to number of inputs' + ) + squeeze = traits.Bool( + False, + usedefault=True, + desc='unfold one-element splits removing the list') class Split(IOBase): @@ -341,7 +363,8 @@ def _list_outputs(self): splits.extend(self.inputs.splits) splits = np.cumsum(splits) for i in range(len(splits) - 1): - val = np.array(self.inputs.inlist)[splits[i]:splits[i + 1]].tolist() + val = np.array( + self.inputs.inlist)[splits[i]:splits[i + 1]].tolist() if self.inputs.squeeze and len(val) == 1: val = val[0] outputs['out%d' % (i + 1)] = val @@ -349,10 +372,10 @@ def _list_outputs(self): class SelectInputSpec(BaseInterfaceInputSpec): - inlist = InputMultiPath(traits.Any, mandatory=True, - desc='list of values to choose from') - index = InputMultiPath(traits.Int, mandatory=True, - desc='0-based indices of values to choose') + inlist = InputMultiPath( + traits.Any, mandatory=True, desc='list of values to choose from') + index = InputMultiPath( + traits.Int, mandatory=True, desc='0-based indices of values to choose') class SelectOutputSpec(TraitedSpec): @@ -384,7 +407,8 @@ class Select(IOBase): def _list_outputs(self): outputs = self._outputs().get() - out = np.array(self.inputs.inlist)[np.array(self.inputs.index)].tolist() + out = np.array(self.inputs.inlist)[np.array( + self.inputs.index)].tolist() outputs['out'] = out return outputs diff --git a/nipype/interfaces/utility/csv.py b/nipype/interfaces/utility/csv.py index 0529a184a6..54fbe91ba9 100644 --- a/nipype/interfaces/utility/csv.py +++ b/nipype/interfaces/utility/csv.py @@ -11,19 +11,27 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import zip, range, str, open from future import standard_library standard_library.install_aliases() -from ..base import traits, TraitedSpec, DynamicTraitedSpec, File, BaseInterface +from ..base import (traits, TraitedSpec, DynamicTraitedSpec, File, + BaseInterface) from ..io import add_traits class CSVReaderInputSpec(DynamicTraitedSpec, TraitedSpec): - in_file = File(exists=True, mandatory=True, desc='Input comma-seperated value (CSV) file') - header = traits.Bool(False, usedefault=True, desc='True if the first line is a column header') + in_file = File( + exists=True, + mandatory=True, + desc='Input comma-seperated value (CSV) file') + header = traits.Bool( + False, + usedefault=True, + desc='True if the first line is a column header') class CSVReader(BaseInterface): @@ -73,7 +81,8 @@ def _get_outfields(self): if self.inputs.header: self._outfields = tuple(entry) else: - self._outfields = tuple(['column_' + str(x) for x in range(len(entry))]) + self._outfields = tuple( + ['column_' + str(x) for x in range(len(entry))]) return self._outfields def _run_interface(self, runtime): diff --git a/nipype/interfaces/utility/tests/test_auto_AssertEqual.py b/nipype/interfaces/utility/tests/test_auto_AssertEqual.py index 0b561d9702..e447523715 100644 --- a/nipype/interfaces/utility/tests/test_auto_AssertEqual.py +++ b/nipype/interfaces/utility/tests/test_auto_AssertEqual.py @@ -4,18 +4,17 @@ def test_AssertEqual_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - volume1=dict(mandatory=True, - ), - volume2=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + volume1=dict(mandatory=True, ), + volume2=dict(mandatory=True, ), ) inputs = AssertEqual.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - diff --git a/nipype/interfaces/utility/tests/test_auto_CSVReader.py b/nipype/interfaces/utility/tests/test_auto_CSVReader.py index 29457328a9..8a51ca4170 100644 --- a/nipype/interfaces/utility/tests/test_auto_CSVReader.py +++ b/nipype/interfaces/utility/tests/test_auto_CSVReader.py @@ -4,18 +4,15 @@ def test_CSVReader_inputs(): - input_map = dict(header=dict(usedefault=True, - ), - in_file=dict(mandatory=True, - ), + input_map = dict( + header=dict(usedefault=True, ), + in_file=dict(mandatory=True, ), ) inputs = CSVReader.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_CSVReader_outputs(): output_map = dict() outputs = CSVReader.output_spec() diff --git a/nipype/interfaces/utility/tests/test_auto_Function.py b/nipype/interfaces/utility/tests/test_auto_Function.py index 1831728c04..f63294f396 100644 --- a/nipype/interfaces/utility/tests/test_auto_Function.py +++ b/nipype/interfaces/utility/tests/test_auto_Function.py @@ -4,20 +4,19 @@ def test_Function_inputs(): - input_map = dict(function_str=dict(mandatory=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), + input_map = dict( + function_str=dict(mandatory=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), ) inputs = Function.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Function_outputs(): output_map = dict() outputs = Function.output_spec() diff --git a/nipype/interfaces/utility/tests/test_auto_IdentityInterface.py b/nipype/interfaces/utility/tests/test_auto_IdentityInterface.py index 13ad3d6c04..97523d0b86 100644 --- a/nipype/interfaces/utility/tests/test_auto_IdentityInterface.py +++ b/nipype/interfaces/utility/tests/test_auto_IdentityInterface.py @@ -10,8 +10,6 @@ def test_IdentityInterface_inputs(): for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_IdentityInterface_outputs(): output_map = dict() outputs = IdentityInterface.output_spec() diff --git a/nipype/interfaces/utility/tests/test_auto_Merge.py b/nipype/interfaces/utility/tests/test_auto_Merge.py index 07f5b60962..5a66b82e92 100644 --- a/nipype/interfaces/utility/tests/test_auto_Merge.py +++ b/nipype/interfaces/utility/tests/test_auto_Merge.py @@ -4,27 +4,23 @@ def test_Merge_inputs(): - input_map = dict(axis=dict(usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - no_flatten=dict(usedefault=True, - ), - ravel_inputs=dict(usedefault=True, - ), + input_map = dict( + axis=dict(usedefault=True, ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + no_flatten=dict(usedefault=True, ), + ravel_inputs=dict(usedefault=True, ), ) inputs = Merge.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Merge_outputs(): - output_map = dict(out=dict(), - ) + output_map = dict(out=dict(), ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/utility/tests/test_auto_Rename.py b/nipype/interfaces/utility/tests/test_auto_Rename.py index d74f2ea7d1..1e6e1cab34 100644 --- a/nipype/interfaces/utility/tests/test_auto_Rename.py +++ b/nipype/interfaces/utility/tests/test_auto_Rename.py @@ -4,25 +4,20 @@ def test_Rename_inputs(): - input_map = dict(format_string=dict(mandatory=True, - ), - in_file=dict(mandatory=True, - ), - keep_ext=dict(), - parse_string=dict(), - use_fullpath=dict(usedefault=True, - ), + input_map = dict( + format_string=dict(mandatory=True, ), + in_file=dict(mandatory=True, ), + keep_ext=dict(), + parse_string=dict(), + use_fullpath=dict(usedefault=True, ), ) inputs = Rename.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Rename_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Rename.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/utility/tests/test_auto_Select.py b/nipype/interfaces/utility/tests/test_auto_Select.py index 7889366b76..5af07e1493 100644 --- a/nipype/interfaces/utility/tests/test_auto_Select.py +++ b/nipype/interfaces/utility/tests/test_auto_Select.py @@ -4,25 +4,22 @@ def test_Select_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - index=dict(mandatory=True, - ), - inlist=dict(mandatory=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + index=dict(mandatory=True, ), + inlist=dict(mandatory=True, ), ) inputs = Select.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Select_outputs(): - output_map = dict(out=dict(), - ) + output_map = dict(out=dict(), ) outputs = Select.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/utility/tests/test_auto_Split.py b/nipype/interfaces/utility/tests/test_auto_Split.py index a0e02af267..7b2e16a2d3 100644 --- a/nipype/interfaces/utility/tests/test_auto_Split.py +++ b/nipype/interfaces/utility/tests/test_auto_Split.py @@ -4,24 +4,21 @@ def test_Split_inputs(): - input_map = dict(ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - inlist=dict(mandatory=True, - ), - splits=dict(mandatory=True, - ), - squeeze=dict(usedefault=True, - ), + input_map = dict( + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + inlist=dict(mandatory=True, ), + splits=dict(mandatory=True, ), + squeeze=dict(usedefault=True, ), ) inputs = Split.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Split_outputs(): output_map = dict() outputs = Split.output_spec() diff --git a/nipype/interfaces/utility/tests/test_base.py b/nipype/interfaces/utility/tests/test_base.py index 3e66f827d2..159454a7fc 100644 --- a/nipype/interfaces/utility/tests/test_base.py +++ b/nipype/interfaces/utility/tests/test_base.py @@ -22,7 +22,10 @@ def test_rename(tmpdir): assert os.path.exists(outfile) # Now a string-formatting version - rn = utility.Rename(in_file="file.txt", format_string="%(field1)s_file%(field2)d", keep_ext=True) + rn = utility.Rename( + in_file="file.txt", + format_string="%(field1)s_file%(field2)d", + keep_ext=True) # Test .input field creation assert hasattr(rn.inputs, "field1") assert hasattr(rn.inputs, "field2") @@ -36,33 +39,36 @@ def test_rename(tmpdir): assert os.path.exists(outfile) -@pytest.mark.parametrize("args, expected", [ - ({} , ([0], [1,2,3])), - ({"squeeze" : True}, (0 , [1,2,3])) - ]) +@pytest.mark.parametrize("args, expected", [({}, ([0], [1, 2, 3])), + ({ + "squeeze": True + }, (0, [1, 2, 3]))]) def test_split(tmpdir, args, expected): tmpdir.chdir() - node = pe.Node(utility.Split(inlist=list(range(4)), - splits=[1, 3], - **args), - name='split_squeeze') + node = pe.Node( + utility.Split(inlist=list(range(4)), splits=[1, 3], **args), + name='split_squeeze') res = node.run() assert res.outputs.out1 == expected[0] assert res.outputs.out2 == expected[1] @pytest.mark.parametrize("args, kwargs, in_lists, expected", [ - ([3], {}, [0, [1, 2], [3, 4, 5]], [0, 1, 2, 3, 4, 5]), - ([0], {}, None, None), - ([], {}, [], []), - ([], {}, [0, [1, 2], [3, 4, 5]], [0, [1, 2], [3, 4, 5]]), - ([3], {'axis': 'hstack'}, [[0], [1, 2], [3, 4, 5]], [[0, 1, 3]]), - ([3], {'axis': 'hstack'}, [[0, 1], [2, 3], [4, 5]], - [[0, 2, 4], [1, 3, 5]]), - ([3], {'axis': 'hstack'}, [[0, 1], [2, 3], [4, 5]], - [[0, 2, 4], [1, 3, 5]]), - ]) + ([3], {}, [0, [1, 2], [3, 4, 5]], [0, 1, 2, 3, 4, 5]), + ([0], {}, None, None), + ([], {}, [], []), + ([], {}, [0, [1, 2], [3, 4, 5]], [0, [1, 2], [3, 4, 5]]), + ([3], { + 'axis': 'hstack' + }, [[0], [1, 2], [3, 4, 5]], [[0, 1, 3]]), + ([3], { + 'axis': 'hstack' + }, [[0, 1], [2, 3], [4, 5]], [[0, 2, 4], [1, 3, 5]]), + ([3], { + 'axis': 'hstack' + }, [[0, 1], [2, 3], [4, 5]], [[0, 2, 4], [1, 3, 5]]), +]) def test_merge(tmpdir, args, kwargs, in_lists, expected): tmpdir.chdir() diff --git a/nipype/interfaces/utility/tests/test_csv.py b/nipype/interfaces/utility/tests/test_csv.py index f0101b4da7..a5c678153e 100644 --- a/nipype/interfaces/utility/tests/test_csv.py +++ b/nipype/interfaces/utility/tests/test_csv.py @@ -8,9 +8,7 @@ def test_csvReader(tmpdir): header = "files,labels,erosion\n" - lines = ["foo,hello,300.1\n", - "bar,world,5\n", - "baz,goodbye,0.3\n"] + lines = ["foo,hello,300.1\n", "bar,world,5\n", "baz,goodbye,0.3\n"] for x in range(2): name = tmpdir.join("testfile.csv").strpath with open(name, 'w') as fid: diff --git a/nipype/interfaces/utility/tests/test_wrappers.py b/nipype/interfaces/utility/tests/test_wrappers.py index b995dc27ad..392ae094b0 100644 --- a/nipype/interfaces/utility/tests/test_wrappers.py +++ b/nipype/interfaces/utility/tests/test_wrappers.py @@ -15,6 +15,7 @@ def concat_sort(in_arrays): return np.sort(all_vals) """ + def test_function(tmpdir): tmpdir.chdir() @@ -22,7 +23,13 @@ def gen_random_array(size): import numpy as np return np.random.rand(size, size) - f1 = pe.MapNode(utility.Function(input_names=['size'], output_names=['random_array'], function=gen_random_array), name='random_array', iterfield=['size']) + f1 = pe.MapNode( + utility.Function( + input_names=['size'], + output_names=['random_array'], + function=gen_random_array), + name='random_array', + iterfield=['size']) f1.inputs.size = [2, 3, 5] wf = pe.Workflow(name="test_workflow") @@ -30,13 +37,14 @@ def gen_random_array(size): def increment_array(in_array): return in_array + 1 - f2 = pe.MapNode(utility.Function(function=increment_array), name='increment_array', iterfield=['in_array']) + f2 = pe.MapNode( + utility.Function(function=increment_array), + name='increment_array', + iterfield=['in_array']) wf.connect(f1, 'random_array', f2, 'in_array') - f3 = pe.Node( - utility.Function(function=concat_sort), - name="concat_sort") + f3 = pe.Node(utility.Function(function=concat_sort), name="concat_sort") wf.connect(f2, 'out', f3, 'in_arrays') wf.run() @@ -49,10 +57,12 @@ def make_random_array(size): def should_fail(tmp): tmp.chdir() - node = pe.Node(utility.Function(input_names=["size"], - output_names=["random_array"], - function=make_random_array), - name="should_fail") + node = pe.Node( + utility.Function( + input_names=["size"], + output_names=["random_array"], + function=make_random_array), + name="should_fail") node.inputs.size = 10 node.run() @@ -65,11 +75,13 @@ def test_should_fail(tmpdir): def test_function_with_imports(tmpdir): tmpdir.chdir() - node = pe.Node(utility.Function(input_names=["size"], - output_names=["random_array"], - function=make_random_array, - imports=["import numpy as np"]), - name="should_not_fail") + node = pe.Node( + utility.Function( + input_names=["size"], + output_names=["random_array"], + function=make_random_array, + imports=["import numpy as np"]), + name="should_not_fail") print(node.inputs.function_str) node.inputs.size = 10 node.run() @@ -84,39 +96,43 @@ def test_aux_connect_function(tmpdir): wf = pe.Workflow(name="test_workflow") def _gen_tuple(size): - return [1, ] * size + return [ + 1, + ] * size def _sum_and_sub_mul(a, b, c): - return (a+b)*c, (a-b)*c + return (a + b) * c, (a - b) * c def _inc(x): return x + 1 - params = pe.Node(utility.IdentityInterface(fields=['size', 'num']), name='params') - params.inputs.num = 42 + params = pe.Node( + utility.IdentityInterface(fields=['size', 'num']), name='params') + params.inputs.num = 42 params.inputs.size = 1 - gen_tuple = pe.Node(utility.Function(input_names=['size'], - output_names=['tuple'], - function=_gen_tuple), - name='gen_tuple') + gen_tuple = pe.Node( + utility.Function( + input_names=['size'], output_names=['tuple'], function=_gen_tuple), + name='gen_tuple') - ssm = pe.Node(utility.Function(input_names=['a', 'b', 'c'], - output_names=['sum', 'sub'], - function=_sum_and_sub_mul), - name='sum_and_sub_mul') + ssm = pe.Node( + utility.Function( + input_names=['a', 'b', 'c'], + output_names=['sum', 'sub'], + function=_sum_and_sub_mul), + name='sum_and_sub_mul') - split = pe.Node(utility.Split(splits=[1, 1], - squeeze=True), - name='split') + split = pe.Node(utility.Split(splits=[1, 1], squeeze=True), name='split') wf.connect([ - (params, gen_tuple, [(("size", _inc), "size")]), - (params, ssm, [(("num", _inc), "c")]), - (gen_tuple, split, [("tuple", "inlist")]), - (split, ssm, [(("out1", _inc), "a"), - ("out2", "b"), - ]), - ]) + (params, gen_tuple, [(("size", _inc), "size")]), + (params, ssm, [(("num", _inc), "c")]), + (gen_tuple, split, [("tuple", "inlist")]), + (split, ssm, [ + (("out1", _inc), "a"), + ("out2", "b"), + ]), + ]) wf.run() diff --git a/nipype/interfaces/utility/wrappers.py b/nipype/interfaces/utility/wrappers.py index 9999c4af6a..204daac484 100644 --- a/nipype/interfaces/utility/wrappers.py +++ b/nipype/interfaces/utility/wrappers.py @@ -7,7 +7,8 @@ >>> old = tmp.chdir() """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from future import standard_library standard_library.install_aliases() @@ -23,6 +24,7 @@ iflogger = logging.getLogger('interface') + class FunctionInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): function_str = traits.Str(mandatory=True, desc='code for function') @@ -45,8 +47,12 @@ class Function(IOBase): input_spec = FunctionInputSpec output_spec = DynamicTraitedSpec - def __init__(self, input_names=None, output_names='out', function=None, - imports=None, **inputs): + def __init__(self, + input_names=None, + output_names='out', + function=None, + imports=None, + **inputs): """ Parameters @@ -82,14 +88,13 @@ def __init__(self, input_names=None, output_names='out', function=None, elif isinstance(function, (str, bytes)): self.inputs.function_str = function if input_names is None: - fninfo = create_function_from_source( - function, imports).__code__ + fninfo = create_function_from_source(function, + imports).__code__ else: raise Exception('Unknown type of function') if input_names is None: input_names = fninfo.co_varnames[:fninfo.co_argcount] - self.inputs.on_trait_change(self._set_function_string, - 'function_str') + self.inputs.on_trait_change(self._set_function_string, 'function_str') self._input_names = filename_to_list(input_names) self._output_names = filename_to_list(output_names) add_traits(self.inputs, [name for name in self._input_names]) @@ -105,10 +110,12 @@ def _set_function_string(self, obj, name, old, new): fninfo = new.__code__ elif isinstance(new, (str, bytes)): function_source = new - fninfo = create_function_from_source( - new, self.imports).__code__ - self.inputs.trait_set(trait_change_notify=False, - **{'%s' % name: function_source}) + fninfo = create_function_from_source(new, + self.imports).__code__ + self.inputs.trait_set( + trait_change_notify=False, **{ + '%s' % name: function_source + }) # Update input traits input_names = fninfo.co_varnames[:fninfo.co_argcount] new_names = set(input_names) - set(self._input_names) @@ -138,7 +145,8 @@ def _run_interface(self, runtime): if len(self._output_names) == 1: self._out[self._output_names[0]] = out else: - if isinstance(out, tuple) and (len(out) != len(self._output_names)): + if isinstance(out, tuple) and \ + (len(out) != len(self._output_names)): raise RuntimeError('Mismatch in number of expected outputs') else: diff --git a/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py b/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py index 83bd21b7bf..166f4eb19e 100644 --- a/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py +++ b/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py @@ -4,43 +4,46 @@ def test_Vnifti2Image_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - attributes=dict(argstr='-attr %s', - position=2, - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - position=1, - ), - out_file=dict(argstr='-out %s', - hash_files=False, - keep_extension=False, - name_source=['in_file'], - name_template='%s.v', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + attributes=dict( + argstr='-attr %s', + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + position=1, + ), + out_file=dict( + argstr='-out %s', + hash_files=False, + keep_extension=False, + name_source=['in_file'], + name_template='%s.v', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = Vnifti2Image.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_Vnifti2Image_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = Vnifti2Image.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/vista/tests/test_auto_VtoMat.py b/nipype/interfaces/vista/tests/test_auto_VtoMat.py index e9e198e90b..6663f43c9a 100644 --- a/nipype/interfaces/vista/tests/test_auto_VtoMat.py +++ b/nipype/interfaces/vista/tests/test_auto_VtoMat.py @@ -4,40 +4,42 @@ def test_VtoMat_inputs(): - input_map = dict(args=dict(argstr='%s', - ), - environ=dict(nohash=True, - usedefault=True, - ), - ignore_exception=dict(deprecated='1.0.0', - nohash=True, - usedefault=True, - ), - in_file=dict(argstr='-in %s', - mandatory=True, - position=1, - ), - out_file=dict(argstr='-out %s', - hash_files=False, - keep_extension=False, - name_source=['in_file'], - name_template='%s.mat', - position=-1, - ), - terminal_output=dict(deprecated='1.0.0', - nohash=True, - ), + input_map = dict( + args=dict(argstr='%s', ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_exception=dict( + deprecated='1.0.0', + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr='-in %s', + mandatory=True, + position=1, + ), + out_file=dict( + argstr='-out %s', + hash_files=False, + keep_extension=False, + name_source=['in_file'], + name_template='%s.mat', + position=-1, + ), + terminal_output=dict( + deprecated='1.0.0', + nohash=True, + ), ) inputs = VtoMat.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value - - def test_VtoMat_outputs(): - output_map = dict(out_file=dict(), - ) + output_map = dict(out_file=dict(), ) outputs = VtoMat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/vista/vista.py b/nipype/interfaces/vista/vista.py index e8928ae24a..729b36aaa0 100644 --- a/nipype/interfaces/vista/vista.py +++ b/nipype/interfaces/vista/vista.py @@ -9,16 +9,29 @@ >>> os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from ..base import CommandLineInputSpec, CommandLine, TraitedSpec, File class Vnifti2ImageInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='-in %s', mandatory=True, position=1, desc='in file') - attributes = File(exists=True, argstr='-attr %s', position=2, desc='attribute file') - out_file = File(name_template="%s.v", keep_extension=False, argstr='-out %s', hash_files=False, - position=-1, desc='output data file', name_source=["in_file"]) + in_file = File( + exists=True, + argstr='-in %s', + mandatory=True, + position=1, + desc='in file') + attributes = File( + exists=True, argstr='-attr %s', position=2, desc='attribute file') + out_file = File( + name_template="%s.v", + keep_extension=False, + argstr='-out %s', + hash_files=False, + position=-1, + desc='output data file', + name_source=["in_file"]) class Vnifti2ImageOutputSpec(TraitedSpec): @@ -45,9 +58,20 @@ class Vnifti2Image(CommandLine): class VtoMatInputSpec(CommandLineInputSpec): - in_file = File(exists=True, argstr='-in %s', mandatory=True, position=1, desc='in file') - out_file = File(name_template="%s.mat", keep_extension=False, argstr='-out %s', hash_files=False, - position=-1, desc='output mat file', name_source=["in_file"]) + in_file = File( + exists=True, + argstr='-in %s', + mandatory=True, + position=1, + desc='in file') + out_file = File( + name_template="%s.mat", + keep_extension=False, + argstr='-out %s', + hash_files=False, + position=-1, + desc='output mat file', + name_source=["in_file"]) class VtoMatOutputSpec(TraitedSpec): diff --git a/nipype/interfaces/vtkbase.py b/nipype/interfaces/vtkbase.py index 458d4fa7b5..c6f6a64305 100644 --- a/nipype/interfaces/vtkbase.py +++ b/nipype/interfaces/vtkbase.py @@ -6,7 +6,8 @@ Code using tvtk should import it through this module """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from .. import logging diff --git a/nipype/pipeline/__init__.py b/nipype/pipeline/__init__.py index f4e865980c..badfda5ba0 100644 --- a/nipype/pipeline/__init__.py +++ b/nipype/pipeline/__init__.py @@ -5,6 +5,7 @@ Package contains modules for generating pipelines using interfaces """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) __docformat__ = 'restructuredtext' from .engine import Node, MapNode, JoinNode, Workflow diff --git a/nipype/pipeline/engine/base.py b/nipype/pipeline/engine/base.py index 0c1d3748c0..07615d4164 100644 --- a/nipype/pipeline/engine/base.py +++ b/nipype/pipeline/engine/base.py @@ -14,7 +14,8 @@ os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object from future import standard_library diff --git a/nipype/pipeline/engine/nodes.py b/nipype/pipeline/engine/nodes.py index ed1fde9d28..c9bbff1f12 100644 --- a/nipype/pipeline/engine/nodes.py +++ b/nipype/pipeline/engine/nodes.py @@ -13,7 +13,8 @@ os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, str, bytes, open from collections import OrderedDict @@ -30,27 +31,19 @@ from ... import config, logging from ...utils.misc import flatten, unflatten, str2bool, dict_diff -from ...utils.filemanip import ( - md5, FileNotFoundError, filename_to_list, list_to_filename, - copyfiles, fnames_presuffix, loadpkl, split_filename, load_json, makedirs, - emptydirs, savepkl, to_str -) - -from ...interfaces.base import ( - traits, InputMultiPath, CommandLine, Undefined, DynamicTraitedSpec, - Bunch, InterfaceResult, Interface, isdefined -) +from ...utils.filemanip import (md5, FileNotFoundError, filename_to_list, + list_to_filename, copyfiles, fnames_presuffix, + loadpkl, split_filename, load_json, makedirs, + emptydirs, savepkl, to_str) + +from ...interfaces.base import (traits, InputMultiPath, CommandLine, Undefined, + DynamicTraitedSpec, Bunch, InterfaceResult, + Interface, isdefined) from .utils import ( - _parameterization_dir, - save_hashfile as _save_hashfile, - load_resultfile as _load_resultfile, - save_resultfile as _save_resultfile, - nodelist_runner as _node_runner, - strip_temp as _strip_temp, - write_report, - clean_working_directory, - merge_dict, evaluate_connect_function -) + _parameterization_dir, save_hashfile as _save_hashfile, load_resultfile as + _load_resultfile, save_resultfile as _save_resultfile, nodelist_runner as + _node_runner, strip_temp as _strip_temp, write_report, + clean_working_directory, merge_dict, evaluate_connect_function) from .base import EngineBase standard_library.install_aliases() @@ -80,9 +73,17 @@ class Node(EngineBase): """ - def __init__(self, interface, name, iterables=None, itersource=None, - synchronize=False, overwrite=None, needed_outputs=None, - run_without_submitting=False, n_procs=None, mem_gb=0.20, + def __init__(self, + interface, + name, + iterables=None, + itersource=None, + synchronize=False, + overwrite=None, + needed_outputs=None, + run_without_submitting=False, + n_procs=None, + mem_gb=0.20, **kwargs): """ Parameters @@ -179,7 +180,8 @@ def __init__(self, interface, name, iterables=None, itersource=None, self._n_procs = n_procs # Downstream n_procs - if hasattr(self._interface.inputs, 'num_threads') and self._n_procs is not None: + if hasattr(self._interface.inputs, + 'num_threads') and self._n_procs is not None: self._interface.inputs.num_threads = self._n_procs # Initialize needed_outputs @@ -212,8 +214,9 @@ def mem_gb(self): """Get estimated memory (GB)""" if hasattr(self._interface, 'estimated_memory_gb'): self._mem_gb = self._interface.estimated_memory_gb - logger.warning('Setting "estimated_memory_gb" on Interfaces has been ' - 'deprecated as of nipype 1.0, please use Node.mem_gb.') + logger.warning( + 'Setting "estimated_memory_gb" on Interfaces has been ' + 'deprecated as of nipype 1.0, please use Node.mem_gb.') return self._mem_gb @@ -222,8 +225,8 @@ def n_procs(self): """Get the estimated number of processes/threads""" if self._n_procs is not None: return self._n_procs - if hasattr(self._interface.inputs, - 'num_threads') and isdefined(self._interface.inputs.num_threads): + if hasattr(self._interface.inputs, 'num_threads') and isdefined( + self._interface.inputs.num_threads): return self._interface.inputs.num_threads return 1 @@ -260,8 +263,8 @@ def output_dir(self): def set_input(self, parameter, val): """Set interface input value""" - logger.debug('[Node] %s - setting input %s = %s', - self.name, parameter, to_str(val)) + logger.debug('[Node] %s - setting input %s = %s', self.name, parameter, + to_str(val)) setattr(self.inputs, parameter, deepcopy(val)) def get_output(self, parameter): @@ -290,7 +293,10 @@ def hash_exists(self, updatehash=False): if op.exists(outdir): # Find previous hashfiles globhashes = glob(op.join(outdir, '_0x*.json')) - unfinished = [path for path in globhashes if path.endswith('_unfinished.json')] + unfinished = [ + path for path in globhashes + if path.endswith('_unfinished.json') + ] hashfiles = list(set(globhashes) - set(unfinished)) if len(hashfiles) > 1: for rmfile in hashfiles: @@ -313,8 +319,9 @@ def hash_exists(self, updatehash=False): # Remove outdated hashfile if hashfiles and hashfiles[0] != hashfile: - logger.info('[Node] Outdated hashfile found for "%s", removing and forcing node ' - 'to rerun.', self.fullname) + logger.info( + '[Node] Outdated hashfile found for "%s", removing and forcing node ' + 'to rerun.', self.fullname) # If logging is more verbose than INFO (20), print diff between hashes loglevel = logger.getEffectiveLevel() @@ -322,13 +329,15 @@ def hash_exists(self, updatehash=False): split_out = split_filename(hashfiles[0]) exp_hash_file_base = split_out[1] exp_hash = exp_hash_file_base[len('_0x'):] - logger.log(loglevel, "[Node] Old/new hashes = %s/%s", exp_hash, hashvalue) + logger.log(loglevel, "[Node] Old/new hashes = %s/%s", + exp_hash, hashvalue) try: prev_inputs = load_json(hashfiles[0]) except Exception: pass else: - logger.log(loglevel, dict_diff(prev_inputs, hashed_inputs, 10)) + logger.log(loglevel, + dict_diff(prev_inputs, hashed_inputs, 10)) os.remove(hashfiles[0]) @@ -339,8 +348,9 @@ def hash_exists(self, updatehash=False): logger.debug( 'updatehash=%s, overwrite=%s, always_run=%s, hash_exists=%s, ' - 'hash_method=%s', updatehash, self.overwrite, self._interface.always_run, - hash_exists, self.config['execution']['hash_method'].lower()) + 'hash_method=%s', updatehash, self.overwrite, + self._interface.always_run, hash_exists, + self.config['execution']['hash_method'].lower()) return hash_exists, hashvalue, hashfile, hashed_inputs def run(self, updatehash=False): @@ -370,7 +380,8 @@ def run(self, updatehash=False): logger.info('[Node] Setting-up "%s" in "%s".', self.fullname, outdir) hash_info = self.hash_exists(updatehash=updatehash) hash_exists, hashvalue, hashfile, hashed_inputs = hash_info - force_run = self.overwrite or (self.overwrite is None and self._interface.always_run) + force_run = self.overwrite or (self.overwrite is None + and self._interface.always_run) # If the node is cached, check on pklz files and finish if hash_exists and (updatehash or not force_run): @@ -393,16 +404,18 @@ def run(self, updatehash=False): # by rerunning we mean only nodes that did finish to run previously if hash_exists and not isinstance(self, MapNode): logger.debug('[Node] Rerunning "%s"', self.fullname) - if not force_run and str2bool(self.config['execution']['stop_on_first_rerun']): - raise Exception('Cannot rerun when "stop_on_first_rerun" is set to True') + if not force_run and str2bool( + self.config['execution']['stop_on_first_rerun']): + raise Exception( + 'Cannot rerun when "stop_on_first_rerun" is set to True') # Remove hashfile if it exists at this point (re-running) if op.exists(hashfile): os.remove(hashfile) # Hashfile while running - hashfile_unfinished = op.join( - outdir, '_0x%s_unfinished.json' % hashvalue) + hashfile_unfinished = op.join(outdir, + '_0x%s_unfinished.json' % hashvalue) # Delete directory contents if this is not a MapNode or can't resume rm_outdir = not isinstance(self, MapNode) and not ( @@ -423,11 +436,10 @@ def run(self, updatehash=False): # Store runtime-hashfile, pre-execution report, the node and the inputs set. _save_hashfile(hashfile_unfinished, hashed_inputs) - write_report(self, report_type='preexec', - is_mapnode=isinstance(self, MapNode)) + write_report( + self, report_type='preexec', is_mapnode=isinstance(self, MapNode)) savepkl(op.join(outdir, '_node.pklz'), self) - savepkl(op.join(outdir, '_inputs.pklz'), - self.inputs.get_traitsfree()) + savepkl(op.join(outdir, '_inputs.pklz'), self.inputs.get_traitsfree()) try: cwd = os.getcwd() @@ -435,8 +447,9 @@ def run(self, updatehash=False): # Changing back to cwd is probably not necessary # but this makes sure there's somewhere to change to. cwd = op.split(outdir)[0] - logger.warning('Current folder "%s" does not exist, changing to "%s" instead.', - os.getenv('PWD', 'unknown'), cwd) + logger.warning( + 'Current folder "%s" does not exist, changing to "%s" instead.', + os.getenv('PWD', 'unknown'), cwd) os.chdir(outdir) try: @@ -451,8 +464,8 @@ def run(self, updatehash=False): # Tear-up after success shutil.move(hashfile_unfinished, hashfile) - write_report(self, report_type='postexec', - is_mapnode=isinstance(self, MapNode)) + write_report( + self, report_type='postexec', is_mapnode=isinstance(self, MapNode)) logger.info('[Node] Finished "%s".', self.fullname) return result @@ -503,12 +516,14 @@ def _get_inputs(self): try: self.set_input(key, deepcopy(output_value)) except traits.TraitError as e: - msg = ['Error setting node input:', - 'Node: %s' % self.name, - 'input: %s' % key, - 'results_file: %s' % results_file, - 'value: %s' % str(output_value)] - e.args = (e.args[0] + "\n" + '\n'.join(msg),) + msg = [ + 'Error setting node input:', + 'Node: %s' % self.name, + 'input: %s' % key, + 'results_file: %s' % results_file, + 'value: %s' % str(output_value) + ] + e.args = (e.args[0] + "\n" + '\n'.join(msg), ) raise # Successfully set inputs @@ -532,10 +547,11 @@ def _load_results(self): self._copyfiles_to_wd(linksonly=True) aggouts = self._interface.aggregate_outputs( needed_outputs=self.needed_outputs) - runtime = Bunch(cwd=cwd, - returncode=0, - environ=dict(os.environ), - hostname=socket.gethostname()) + runtime = Bunch( + cwd=cwd, + returncode=0, + environ=dict(os.environ), + hostname=socket.gethostname()) result = InterfaceResult( interface=self._interface.__class__, runtime=runtime, @@ -557,16 +573,16 @@ def _run_command(self, execute, copyfiles=True): logger.info("[Node] Some of the outputs were not found: " "rerunning node.") copyfiles = False # OE: this was like this before, - execute = True # I'll keep them for safety + execute = True # I'll keep them for safety else: - logger.info( - "[Node] Cached - collecting precomputed outputs") + logger.info("[Node] Cached - collecting precomputed outputs") return result # Run command: either execute is true or load_results failed. - runtime = Bunch(returncode=1, - environ=dict(os.environ), - hostname=socket.gethostname()) + runtime = Bunch( + returncode=1, + environ=dict(os.environ), + hostname=socket.gethostname()) result = InterfaceResult( interface=self._interface.__class__, runtime=runtime, @@ -605,12 +621,12 @@ def _run_command(self, execute, copyfiles=True): dirs2keep = [op.join(outdir, 'mapflow')] result.outputs = clean_working_directory( - result.outputs, outdir, + result.outputs, + outdir, self._interface.inputs, self.needed_outputs, self.config, - dirs2keep=dirs2keep - ) + dirs2keep=dirs2keep) _save_resultfile(result, outdir, self.name) return result @@ -621,8 +637,8 @@ def _copyfiles_to_wd(self, execute=True, linksonly=False): # Nothing to be done return - logger.debug('copying files to wd [execute=%s, linksonly=%s]', - execute, linksonly) + logger.debug('copying files to wd [execute=%s, linksonly=%s]', execute, + linksonly) outdir = self.output_dir() if execute and linksonly: @@ -639,21 +655,18 @@ def _copyfiles_to_wd(self, execute=True, linksonly=False): if execute: if linksonly: if not info['copy']: - newfiles = copyfiles(infiles, - [outdir], - copy=info['copy'], - create_new=True) + newfiles = copyfiles( + infiles, [outdir], + copy=info['copy'], + create_new=True) else: - newfiles = fnames_presuffix(infiles, - newpath=outdir) - newfiles = _strip_temp( - newfiles, - op.abspath(olddir).split(op.sep)[-1]) + newfiles = fnames_presuffix(infiles, newpath=outdir) + newfiles = _strip_temp(newfiles, + op.abspath(olddir).split( + op.sep)[-1]) else: - newfiles = copyfiles(infiles, - [outdir], - copy=info['copy'], - create_new=True) + newfiles = copyfiles( + infiles, [outdir], copy=info['copy'], create_new=True) else: newfiles = fnames_presuffix(infiles, newpath=outdir) if not isinstance(files, list): @@ -696,8 +709,13 @@ class JoinNode(Node): """ - def __init__(self, interface, name, joinsource, joinfield=None, - unique=False, **kwargs): + def __init__(self, + interface, + name, + joinsource, + joinfield=None, + unique=False, + **kwargs): """ Parameters @@ -849,8 +867,10 @@ def _collate_join_field_inputs(self): try: setattr(self._interface.inputs, field, val) except Exception as e: - raise ValueError(">>JN %s %s %s %s %s: %s" % ( - self, field, val, self.inputs.copyable_trait_names(), self.joinfield, e)) + raise ValueError(">>JN %s %s %s %s %s: %s" % + (self, field, val, + self.inputs.copyable_trait_names(), + self.joinfield, e)) elif hasattr(self._interface.inputs, field): # copy the non-join field val = getattr(self._inputs, field) @@ -871,8 +891,10 @@ def _collate_input_value(self, field): the iterables order. If the ``unique`` flag is set, then duplicate values are removed but the iterables order is preserved. """ - val = [self._slot_value(field, idx) - for idx in range(self._next_slot_index)] + val = [ + self._slot_value(field, idx) + for idx in range(self._next_slot_index) + ] basetrait = self._interface.inputs.trait(field) if isinstance(basetrait.trait_type, traits.Set): return set(val) @@ -887,9 +909,10 @@ def _slot_value(self, field, index): try: return getattr(self._inputs, slot_field) except AttributeError as e: - raise AttributeError("The join node %s does not have a slot field %s" - " to hold the %s value at index %d: %s" - % (self, slot_field, field, index, e)) + raise AttributeError( + "The join node %s does not have a slot field %s" + " to hold the %s value at index %d: %s" % (self, slot_field, + field, index, e)) class MapNode(Node): @@ -908,7 +931,13 @@ class MapNode(Node): """ - def __init__(self, interface, iterfield, name, serial=False, nested=False, **kwargs): + def __init__(self, + interface, + iterfield, + name, + serial=False, + nested=False, + **kwargs): """ Parameters @@ -938,8 +967,8 @@ def __init__(self, interface, iterfield, name, serial=False, nested=False, **kwa iterfield = [iterfield] self.iterfield = iterfield self.nested = nested - self._inputs = self._create_dynamic_traits(self._interface.inputs, - fields=self.iterfield) + self._inputs = self._create_dynamic_traits( + self._interface.inputs, fields=self.iterfield) self._inputs.on_trait_change(self._set_mapnode_input) self._got_inputs = False self._serial = serial @@ -971,13 +1000,13 @@ def set_input(self, parameter, val): Set interface input value or nodewrapper attribute Priority goes to interface. """ - logger.debug('setting nodelevel(%s) input %s = %s', - to_str(self), parameter, to_str(val)) + logger.debug('setting nodelevel(%s) input %s = %s', to_str(self), + parameter, to_str(val)) self._set_mapnode_input(parameter, deepcopy(val)) def _set_mapnode_input(self, name, newvalue): - logger.debug('setting mapnode(%s) input: %s -> %s', - to_str(self), name, to_str(newvalue)) + logger.debug('setting mapnode(%s) input: %s -> %s', to_str(self), name, + to_str(newvalue)) if name in self.iterfield: setattr(self._inputs, name, newvalue) else: @@ -994,8 +1023,8 @@ def _get_hashval(self): name, InputMultiPath( self._interface.inputs.traits()[name].trait_type)) - logger.debug('setting hashinput %s-> %s', - name, getattr(self._inputs, name)) + logger.debug('setting hashinput %s-> %s', name, + getattr(self._inputs, name)) if self.nested: setattr(hashinputs, name, flatten(getattr(self._inputs, name))) else: @@ -1025,26 +1054,31 @@ def _make_nodes(self, cwd=None): if cwd is None: cwd = self.output_dir() if self.nested: - nitems = len(flatten(filename_to_list(getattr(self.inputs, self.iterfield[0])))) + nitems = len( + flatten( + filename_to_list(getattr(self.inputs, self.iterfield[0])))) else: - nitems = len(filename_to_list(getattr(self.inputs, self.iterfield[0]))) + nitems = len( + filename_to_list(getattr(self.inputs, self.iterfield[0]))) for i in range(nitems): nodename = '_%s%d' % (self.name, i) - node = Node(deepcopy(self._interface), - n_procs=self._n_procs, - mem_gb=self._mem_gb, - overwrite=self.overwrite, - needed_outputs=self.needed_outputs, - run_without_submitting=self.run_without_submitting, - base_dir=op.join(cwd, 'mapflow'), - name=nodename) + node = Node( + deepcopy(self._interface), + n_procs=self._n_procs, + mem_gb=self._mem_gb, + overwrite=self.overwrite, + needed_outputs=self.needed_outputs, + run_without_submitting=self.run_without_submitting, + base_dir=op.join(cwd, 'mapflow'), + name=nodename) node.plugin_args = self.plugin_args node.interface.inputs.trait_set( **deepcopy(self._interface.inputs.get())) node.interface.resource_monitor = self._interface.resource_monitor for field in self.iterfield: if self.nested: - fieldvals = flatten(filename_to_list(getattr(self.inputs, field))) + fieldvals = flatten( + filename_to_list(getattr(self.inputs, field))) else: fieldvals = filename_to_list(getattr(self.inputs, field)) logger.debug('setting input %d %s %s', i, field, fieldvals[i]) @@ -1054,7 +1088,10 @@ def _make_nodes(self, cwd=None): def _collate_results(self, nodes): finalresult = InterfaceResult( - interface=[], runtime=[], provenance=[], inputs=[], + interface=[], + runtime=[], + provenance=[], + inputs=[], outputs=self.outputs) returncode = [] for i, nresult, err in nodes: @@ -1071,8 +1108,8 @@ def _collate_results(self, nodes): if self.outputs: for key, _ in list(self.outputs.items()): - rm_extra = (self.config['execution'] - ['remove_unnecessary_outputs']) + rm_extra = ( + self.config['execution']['remove_unnecessary_outputs']) if str2bool(rm_extra) and self.needed_outputs: if key not in self.needed_outputs: continue @@ -1091,8 +1128,10 @@ def _collate_results(self, nodes): for key, _ in list(self.outputs.items()): values = getattr(finalresult.outputs, key) if isdefined(values): - values = unflatten(values, filename_to_list( - getattr(self.inputs, self.iterfield[0]))) + values = unflatten(values, + filename_to_list( + getattr(self.inputs, + self.iterfield[0]))) setattr(finalresult.outputs, key, values) if returncode and any([code is not None for code in returncode]): @@ -1120,13 +1159,15 @@ def num_subnodes(self): if self._serial: return 1 if self.nested: - return len(filename_to_list(flatten(getattr(self.inputs, self.iterfield[0])))) + return len( + filename_to_list( + flatten(getattr(self.inputs, self.iterfield[0])))) return len(filename_to_list(getattr(self.inputs, self.iterfield[0]))) def _get_inputs(self): old_inputs = self._inputs.get() - self._inputs = self._create_dynamic_traits(self._interface.inputs, - fields=self.iterfield) + self._inputs = self._create_dynamic_traits( + self._interface.inputs, fields=self.iterfield) self._inputs.trait_set(**old_inputs) super(MapNode, self)._get_inputs() @@ -1141,14 +1182,14 @@ def _check_iterfield(self): raise ValueError(("Input %s was not set but it is listed " "in iterfields.") % iterfield) if len(self.iterfield) > 1: - first_len = len(filename_to_list(getattr(self.inputs, - self.iterfield[0]))) + first_len = len( + filename_to_list(getattr(self.inputs, self.iterfield[0]))) for iterfield in self.iterfield[1:]: - if first_len != len(filename_to_list(getattr(self.inputs, - iterfield))): - raise ValueError(("All iterfields of a MapNode have to " - "have the same length. %s") % - str(self.inputs)) + if first_len != len( + filename_to_list(getattr(self.inputs, iterfield))): + raise ValueError( + ("All iterfields of a MapNode have to " + "have the same length. %s") % str(self.inputs)) def _run_interface(self, execute=True, updatehash=False): """Run the mapnode interface @@ -1163,20 +1204,22 @@ def _run_interface(self, execute=True, updatehash=False): # Set up mapnode folder names if self.nested: - nitems = len(filename_to_list(flatten(getattr(self.inputs, - self.iterfield[0])))) + nitems = len( + filename_to_list( + flatten(getattr(self.inputs, self.iterfield[0])))) else: - nitems = len(filename_to_list(getattr(self.inputs, - self.iterfield[0]))) + nitems = len( + filename_to_list(getattr(self.inputs, self.iterfield[0]))) nnametpl = '_%s{}' % self.name nodenames = [nnametpl.format(i) for i in range(nitems)] # Run mapnode - result = self._collate_results(_node_runner( - self._make_nodes(cwd), - updatehash=updatehash, - stop_first=str2bool(self.config['execution']['stop_on_first_crash']) - )) + result = self._collate_results( + _node_runner( + self._make_nodes(cwd), + updatehash=updatehash, + stop_first=str2bool( + self.config['execution']['stop_on_first_crash']))) # And store results _save_resultfile(result, cwd, self.name) # remove any node directories no longer required @@ -1186,7 +1229,7 @@ def _run_interface(self, execute=True, updatehash=False): if path.split(op.sep)[-1] not in nodenames: dirs2remove.append(path) for path in dirs2remove: - logger.debug('[MapNode] Removing folder "%s".' , path) + logger.debug('[MapNode] Removing folder "%s".', path) shutil.rmtree(path) return result diff --git a/nipype/pipeline/engine/tests/test_engine.py b/nipype/pipeline/engine/tests/test_engine.py index 034174758a..49b9f46852 100644 --- a/nipype/pipeline/engine/tests/test_engine.py +++ b/nipype/pipeline/engine/tests/test_engine.py @@ -10,7 +10,8 @@ from builtins import open from copy import deepcopy from glob import glob -import os, sys +import os +import sys import networkx as nx @@ -24,6 +25,7 @@ class InputSpec(nib.TraitedSpec): input2 = nib.traits.Int(desc='a random int') input_file = nib.traits.File(desc='Random File') + class OutputSpec(nib.TraitedSpec): output1 = nib.traits.List(nib.traits.Int, desc='outputs') @@ -43,7 +45,8 @@ def _list_outputs(self): def test_init(): - with pytest.raises(TypeError): pe.Workflow() + with pytest.raises(TypeError): + pe.Workflow() pipe = pe.Workflow(name='pipe') assert type(pipe._graph) == nx.DiGraph @@ -56,7 +59,9 @@ def test_connect(): assert mod1 in pipe._graph.nodes() assert mod2 in pipe._graph.nodes() - assert pipe._graph.get_edge_data(mod1, mod2) == {'connect': [('output1', 'input1')]} + assert pipe._graph.get_edge_data(mod1, mod2) == { + 'connect': [('output1', 'input1')] + } def test_add_nodes(): @@ -68,15 +73,23 @@ def test_add_nodes(): assert mod1 in pipe._graph.nodes() assert mod2 in pipe._graph.nodes() + # Test graph expansion. The following set tests the building blocks # of the graph expansion routine. # XXX - SG I'll create a graphical version of these tests and actually # ensure that all connections are tested later -@pytest.mark.parametrize("iterables, expected", [ - ({"1": None}, (1,0)), #test1 - ({"1": dict(input1=lambda: [1, 2], input2=lambda: [1, 2])}, (4,0)) #test2 - ]) + +@pytest.mark.parametrize( + "iterables, expected", + [ + ({ + "1": None + }, (1, 0)), # test1 + ({ + "1": dict(input1=lambda: [1, 2], input2=lambda: [1, 2]) + }, (4, 0)) # test2 + ]) def test_1mod(iterables, expected): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=EngineTestInterface(), name='mod1') @@ -88,17 +101,28 @@ def test_1mod(iterables, expected): assert len(pipe._execgraph.edges()) == expected[1] -@pytest.mark.parametrize("iterables, expected", [ - ({"1": {}, "2": dict(input1=lambda: [1, 2])}, (3,2)), #test3 - ({"1": dict(input1=lambda: [1, 2]), "2": {}}, (4,2)), #test4 - ({"1": dict(input1=lambda: [1, 2]), "2": dict(input1=lambda: [1, 2])}, (6,4)) #test5 - ]) +@pytest.mark.parametrize( + "iterables, expected", + [ + ({ + "1": {}, + "2": dict(input1=lambda: [1, 2]) + }, (3, 2)), # test3 + ({ + "1": dict(input1=lambda: [1, 2]), + "2": {} + }, (4, 2)), # test4 + ({ + "1": dict(input1=lambda: [1, 2]), + "2": dict(input1=lambda: [1, 2]) + }, (6, 4)) # test5 + ]) def test_2mods(iterables, expected): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=EngineTestInterface(), name='mod1') mod2 = pe.Node(interface=EngineTestInterface(), name='mod2') for nr in ["1", "2"]: - setattr(eval("mod"+nr), "iterables", iterables[nr]) + setattr(eval("mod" + nr), "iterables", iterables[nr]) pipe.connect([(mod1, mod2, [('output1', 'input2')])]) pipe._flatgraph = pipe._create_flat_graph() pipe._execgraph = pe.generate_expanded_graph(deepcopy(pipe._flatgraph)) @@ -106,27 +130,41 @@ def test_2mods(iterables, expected): assert len(pipe._execgraph.edges()) == expected[1] -@pytest.mark.parametrize("iterables, expected, connect", [ - ({"1": {}, "2": dict(input1=lambda: [1, 2]), "3": {}}, (5,4), ("1-2","2-3")), #test6 - ({"1": dict(input1=lambda: [1, 2]), "2": {}, "3": {}}, (5,4), ("1-3","2-3")), #test7 - ({"1": dict(input1=lambda: [1, 2]), "2": dict(input1=lambda: [1, 2]), "3": {}}, - (8,8), ("1-3","2-3")), #test8 - ]) +@pytest.mark.parametrize( + "iterables, expected, connect", + [ + ({ + "1": {}, + "2": dict(input1=lambda: [1, 2]), + "3": {} + }, (5, 4), ("1-2", "2-3")), # test6 + ({ + "1": dict(input1=lambda: [1, 2]), + "2": {}, + "3": {} + }, (5, 4), ("1-3", "2-3")), # test7 + ({ + "1": dict(input1=lambda: [1, 2]), + "2": dict(input1=lambda: [1, 2]), + "3": {} + }, (8, 8), ("1-3", "2-3")), # test8 + ]) def test_3mods(iterables, expected, connect): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=EngineTestInterface(), name='mod1') mod2 = pe.Node(interface=EngineTestInterface(), name='mod2') mod3 = pe.Node(interface=EngineTestInterface(), name='mod3') for nr in ["1", "2", "3"]: - setattr(eval("mod"+nr), "iterables", iterables[nr]) - if connect == ("1-2","2-3"): + setattr(eval("mod" + nr), "iterables", iterables[nr]) + if connect == ("1-2", "2-3"): pipe.connect([(mod1, mod2, [('output1', 'input2')]), (mod2, mod3, [('output1', 'input2')])]) - elif connect == ("1-3","2-3"): + elif connect == ("1-3", "2-3"): pipe.connect([(mod1, mod3, [('output1', 'input1')]), (mod2, mod3, [('output1', 'input2')])]) else: - raise Exception("connect pattern is not implemented yet within the test function") + raise Exception( + "connect pattern is not implemented yet within the test function") pipe._flatgraph = pipe._create_flat_graph() pipe._execgraph = pe.generate_expanded_graph(deepcopy(pipe._flatgraph)) assert len(pipe._execgraph.nodes()) == expected[0] @@ -155,7 +193,8 @@ def test_expansion(): pipe5 = pe.Workflow(name="pipe5") pipe5.add_nodes([pipe4]) pipe6 = pe.Workflow(name="pipe6") - pipe6.connect([(pipe5, pipe3, [('pipe4.mod5.output1', 'pipe2.mod3.input1')])]) + pipe6.connect([(pipe5, pipe3, [('pipe4.mod5.output1', + 'pipe2.mod3.input1')])]) pipe6._flatgraph = pipe6._create_flat_graph() @@ -256,8 +295,12 @@ def test_itersource_synchronize1_expansion(): wf1.connect(node1, 'output1', node2, 'input1') node3 = pe.Node(EngineTestInterface(), name='node3') node3.itersource = ('node1', ['input1', 'input2']) - node3.iterables = [('input1', {(1, 3): [5, 6]}), - ('input2', {(1, 3): [7, 8], (2, 4): [9]})] + node3.iterables = [('input1', { + (1, 3): [5, 6] + }), ('input2', { + (1, 3): [7, 8], + (2, 4): [9] + })] wf1.connect(node2, 'output1', node3, 'input1') node4 = pe.Node(EngineTestInterface(), name='node4') wf1.connect(node3, 'output1', node4, 'input1') @@ -288,8 +331,10 @@ def test_itersource_synchronize2_expansion(): node3 = pe.Node(EngineTestInterface(), name='node3') node3.itersource = ('node1', ['input1', 'input2']) node3.synchronize = True - node3.iterables = [('input1', 'input2'), - {(1, 3): [(5, 7), (6, 8)], (2, 4):[(None, 9)]}] + node3.iterables = [('input1', 'input2'), { + (1, 3): [(5, 7), (6, 8)], + (2, 4): [(None, 9)] + }] wf1.connect(node2, 'output1', node3, 'input1') node4 = pe.Node(EngineTestInterface(), name='node4') wf1.connect(node3, 'output1', node4, 'input1') @@ -369,7 +414,6 @@ def test_doubleconnect(): wf1.write_graph(graph2use='exec') ''' - ''' import nipype.pipeline.engine as pe import nipype.interfaces.spm as spm @@ -412,7 +456,8 @@ def test_doubleconnect(): def test_node_init(): - with pytest.raises(Exception): pe.Node() + with pytest.raises(Exception): + pe.Node() try: node = pe.Node(EngineTestInterface, name='test') except IOError: @@ -430,8 +475,10 @@ def test_workflow_add(): w1 = pe.Workflow(name='test') w1.connect(n1, 'a', n2, 'c') for node in [n1, n2, n3]: - with pytest.raises(IOError): w1.add_nodes([node]) - with pytest.raises(IOError): w1.connect([(w1, n2, [('n1.a', 'd')])]) + with pytest.raises(IOError): + w1.add_nodes([node]) + with pytest.raises(IOError): + w1.connect([(w1, n2, [('n1.a', 'd')])]) def test_node_get_output(): @@ -444,33 +491,33 @@ def test_node_get_output(): def test_mapnode_iterfield_check(): - mod1 = pe.MapNode(EngineTestInterface(), - iterfield=['input1'], - name='mod1') - with pytest.raises(ValueError): mod1._check_iterfield() - mod1 = pe.MapNode(EngineTestInterface(), - iterfield=['input1', 'input2'], - name='mod1') + mod1 = pe.MapNode(EngineTestInterface(), iterfield=['input1'], name='mod1') + with pytest.raises(ValueError): + mod1._check_iterfield() + mod1 = pe.MapNode( + EngineTestInterface(), iterfield=['input1', 'input2'], name='mod1') mod1.inputs.input1 = [1, 2] mod1.inputs.input2 = 3 - with pytest.raises(ValueError): mod1._check_iterfield() + with pytest.raises(ValueError): + mod1._check_iterfield() -@pytest.mark.parametrize("x_inp, f_exp", [ - (3, [6]), ([2, 3], [4, 6]), ((2, 3), [4, 6]), - (range(3), [0, 2, 4]), - ("Str", ["StrStr"]), (["Str1", "Str2"], ["Str1Str1", "Str2Str2"]) - ]) +@pytest.mark.parametrize("x_inp, f_exp", + [(3, [6]), ([2, 3], [4, 6]), ((2, 3), [4, 6]), + (range(3), [0, 2, 4]), ("Str", ["StrStr"]), + (["Str1", "Str2"], ["Str1Str1", "Str2Str2"])]) def test_mapnode_iterfield_type(x_inp, f_exp): from nipype import MapNode, Function + def double_func(x): return 2 * x + double = Function(["x"], ["f_x"], double_func) double_node = MapNode(double, name="double", iterfield=["x"]) double_node.inputs.x = x_inp - res = double_node.run() + res = double_node.run() assert res.outputs.f_x == f_exp @@ -480,22 +527,21 @@ def test_mapnode_nested(tmpdir): def func1(in1): return in1 + 1 - n1 = MapNode(Function(input_names=['in1'], - output_names=['out'], - function=func1), - iterfield=['in1'], - nested=True, - name='n1') + + n1 = MapNode( + Function(input_names=['in1'], output_names=['out'], function=func1), + iterfield=['in1'], + nested=True, + name='n1') n1.inputs.in1 = [[1, [2]], 3, [4, 5]] n1.run() assert n1.get_output('out') == [[2, [3]], 4, [5, 6]] - n2 = MapNode(Function(input_names=['in1'], - output_names=['out'], - function=func1), - iterfield=['in1'], - nested=False, - name='n1') + n2 = MapNode( + Function(input_names=['in1'], output_names=['out'], function=func1), + iterfield=['in1'], + nested=False, + name='n1') n2.inputs.in1 = [[1, [2]], 3, [4, 5]] with pytest.raises(Exception) as excinfo: @@ -510,19 +556,19 @@ def test_mapnode_expansion(tmpdir): def func1(in1): return in1 + 1 - mapnode = MapNode(Function(function=func1), - iterfield='in1', - name='mapnode', - n_procs=2, - mem_gb=2) + mapnode = MapNode( + Function(function=func1), + iterfield='in1', + name='mapnode', + n_procs=2, + mem_gb=2) mapnode.inputs.in1 = [1, 2] for idx, node in mapnode._make_nodes(): for attr in ('overwrite', 'run_without_submitting', 'plugin_args'): assert getattr(node, attr) == getattr(mapnode, attr) for attr in ('_n_procs', '_mem_gb'): - assert (getattr(node, attr) == - getattr(mapnode, attr)) + assert (getattr(node, attr) == getattr(mapnode, attr)) def test_node_hash(tmpdir): @@ -534,14 +580,13 @@ def func1(): def func2(a): return a + 1 - n1 = pe.Node(Function(input_names=[], - output_names=['a'], - function=func1), - name='n1') - n2 = pe.Node(Function(input_names=['a'], - output_names=['b'], - function=func2), - name='n2') + + n1 = pe.Node( + Function(input_names=[], output_names=['a'], function=func1), + name='n1') + n2 = pe.Node( + Function(input_names=['a'], output_names=['b'], function=func2), + name='n2') w1 = pe.Workflow(name='test') modify = lambda x: x + 1 n1.inputs.a = 1 @@ -550,9 +595,11 @@ def func2(a): # generate outputs w1.run(plugin='Linear') # ensure plugin is being called - w1.config['execution'] = {'stop_on_first_crash': 'true', - 'local_hash_check': 'false', - 'crashdump_dir': os.getcwd()} + w1.config['execution'] = { + 'stop_on_first_crash': 'true', + 'local_hash_check': 'false', + 'crashdump_dir': os.getcwd() + } # create dummy distributed plugin class from nipype.pipeline.plugins.base import DistributedPluginBase @@ -572,9 +619,11 @@ def _submit_job(self, node, updatehash=False): # rerun to ensure we have outputs w1.run(plugin='Linear') # set local check - w1.config['execution'] = {'stop_on_first_crash': 'true', - 'local_hash_check': 'true', - 'crashdump_dir': os.getcwd()} + w1.config['execution'] = { + 'stop_on_first_crash': 'true', + 'local_hash_check': 'true', + 'crashdump_dir': os.getcwd() + } w1.run(plugin=RaiseError()) @@ -589,14 +638,13 @@ def func1(): def func2(a): return a + 1 - n1 = pe.Node(Function(input_names=[], - output_names=['a'], - function=func1), - name='n1') - n2 = pe.Node(Function(input_names=['a'], - output_names=['b'], - function=func2), - name='n2') + + n1 = pe.Node( + Function(input_names=[], output_names=['a'], function=func1), + name='n1') + n2 = pe.Node( + Function(input_names=['a'], output_names=['b'], function=func2), + name='n2') w1 = pe.Workflow(name='test') modify = lambda x: x + 1 n1.inputs.a = 1 @@ -618,11 +666,11 @@ def test_mapnode_json(tmpdir): def func1(in1): return in1 + 1 - n1 = MapNode(Function(input_names=['in1'], - output_names=['out'], - function=func1), - iterfield=['in1'], - name='n1') + + n1 = MapNode( + Function(input_names=['in1'], output_names=['out'], function=func1), + iterfield=['in1'], + name='n1') n1.inputs.in1 = [1] w1 = Workflow(name='test') w1.base_dir = wd @@ -664,7 +712,6 @@ def test_parameterize_dirs_false(tmpdir): wf.config['execution']['parameterize_dirs'] = False wf.connect([(n1, n2, [('output1', 'in1')])]) - wf.run() @@ -675,21 +722,23 @@ def test_serial_input(tmpdir): def func1(in1): return in1 - n1 = MapNode(Function(input_names=['in1'], - output_names=['out'], - function=func1), - iterfield=['in1'], - name='n1') + + n1 = MapNode( + Function(input_names=['in1'], output_names=['out'], function=func1), + iterfield=['in1'], + name='n1') n1.inputs.in1 = [1, 2, 3] w1 = Workflow(name='test') w1.base_dir = wd w1.add_nodes([n1]) # set local check - w1.config['execution'] = {'stop_on_first_crash': 'true', - 'local_hash_check': 'true', - 'crashdump_dir': wd, - 'poll_sleep_duration': 2} + w1.config['execution'] = { + 'stop_on_first_crash': 'true', + 'local_hash_check': 'true', + 'crashdump_dir': wd, + 'poll_sleep_duration': 2 + } # test output of num_subnodes method when serial is default (False) assert n1.num_subnodes() == len(n1.inputs.in1) @@ -715,14 +764,15 @@ def test_write_graph_runs(tmpdir): mod2 = pe.Node(interface=EngineTestInterface(), name='mod2') pipe.connect([(mod1, mod2, [('output1', 'input1')])]) try: - pipe.write_graph(graph2use=graph, simple_form=simple, - format='dot') + pipe.write_graph( + graph2use=graph, simple_form=simple, format='dot') except Exception: assert False, \ 'Failed to plot {} {} graph'.format( - 'simple' if simple else 'detailed', graph) + 'simple' if simple else 'detailed', graph) - assert os.path.exists('graph.dot') or os.path.exists('graph_detailed.dot') + assert os.path.exists('graph.dot') or os.path.exists( + 'graph_detailed.dot') try: os.remove('graph.dot') except OSError: @@ -747,14 +797,15 @@ def test_deep_nested_write_graph_runs(tmpdir): mod1 = pe.Node(interface=EngineTestInterface(), name='mod1') parent.add_nodes([mod1]) try: - pipe.write_graph(graph2use=graph, simple_form=simple, - format='dot') + pipe.write_graph( + graph2use=graph, simple_form=simple, format='dot') except Exception as e: assert False, \ 'Failed to plot {} {} deep graph: {!s}'.format( - 'simple' if simple else 'detailed', graph, e) + 'simple' if simple else 'detailed', graph, e) - assert os.path.exists('graph.dot') or os.path.exists('graph_detailed.dot') + assert os.path.exists('graph.dot') or os.path.exists( + 'graph_detailed.dot') try: os.remove('graph.dot') except OSError: @@ -788,7 +839,8 @@ def testx2(test): kvnode = pe.Node(TestKV(), name='testkv') from nipype.interfaces.utility import Function func = pe.Node( - Function(input_names=['test'], output_names=['test2'], function=testx2), + Function( + input_names=['test'], output_names=['test2'], function=testx2), name='func') exception_not_raised = True try: diff --git a/nipype/pipeline/engine/tests/test_join.py b/nipype/pipeline/engine/tests/test_join.py index a77745eb03..436d29d9e7 100644 --- a/nipype/pipeline/engine/tests/test_join.py +++ b/nipype/pipeline/engine/tests/test_join.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Tests for join expansion """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -15,8 +16,8 @@ class PickFirstSpec(nib.TraitedSpec): - in_files = traits.List(File(exists=True), argstr="%s", position=2, - mandatory=True) + in_files = traits.List( + File(exists=True), argstr="%s", position=2, mandatory=True) class PickFirstOutSpec(nib.TraitedSpec): @@ -59,6 +60,7 @@ def _list_outputs(self): outputs['output1'] = self.inputs.input1 + self.inputs.inc return outputs + _sums = [] _sum_operands = [] @@ -163,8 +165,11 @@ def test_join_expansion(tmpdir): pre_join2 = pe.Node(IncrementInterface(), name='pre_join2') wf.connect(pre_join1, 'output1', pre_join2, 'input1') # the join node - join = pe.JoinNode(SumInterface(), joinsource='inputspec', - joinfield='input1', name='join') + join = pe.JoinNode( + SumInterface(), + joinsource='inputspec', + joinfield='input1', + name='join') wf.connect(pre_join2, 'output1', join, 'input1') # an uniterated post-join node post_join1 = pe.Node(IncrementInterface(), name='post_join1') @@ -182,10 +187,12 @@ def test_join_expansion(tmpdir): # the expanded graph contains 2 * 2 = 4 iteration pre-join nodes, 1 join # node, 1 non-iterated post-join node and 2 * 1 iteration post-join nodes. # Nipype factors away the IdentityInterface. - assert len(result.nodes()) == 8, "The number of expanded nodes is incorrect." + assert len( + result.nodes()) == 8, "The number of expanded nodes is incorrect." # the join Sum result is (1 + 1 + 1) + (2 + 1 + 1) assert len(_sums) == 1, "The number of join outputs is incorrect" - assert _sums[0] == 7, "The join Sum output value is incorrect: %s." % _sums[0] + assert _sums[ + 0] == 7, "The join Sum output value is incorrect: %s." % _sums[0] # the join input preserves the iterables input order assert _sum_operands[0] == [3, 4], \ "The join Sum input is incorrect: %s." % _sum_operands[0] @@ -198,18 +205,16 @@ def test_node_joinsource(tmpdir): """Test setting the joinsource to a Node.""" tmpdir.chdir() - # Make the workflow. - wf = pe.Workflow(name='test') # the iterated input node inputspec = pe.Node(IdentityInterface(fields=['n']), name='inputspec') inputspec.iterables = [('n', [1, 2])] # the join node - join = pe.JoinNode(SetInterface(), joinsource=inputspec, - joinfield='input1', name='join') + join = pe.JoinNode( + SetInterface(), joinsource=inputspec, joinfield='input1', name='join') # the joinsource is the inputspec name assert join.joinsource == inputspec.name, \ - "The joinsource is not set to the node name." + "The joinsource is not set to the node name." def test_set_join_node(tmpdir): @@ -225,8 +230,11 @@ def test_set_join_node(tmpdir): pre_join1 = pe.Node(IncrementInterface(), name='pre_join1') wf.connect(inputspec, 'n', pre_join1, 'input1') # the set join node - join = pe.JoinNode(SetInterface(), joinsource='inputspec', - joinfield='input1', name='join') + join = pe.JoinNode( + SetInterface(), + joinsource='inputspec', + joinfield='input1', + name='join') wf.connect(pre_join1, 'output1', join, 'input1') wf.run() @@ -251,14 +259,18 @@ def test_unique_join_node(tmpdir): pre_join1 = pe.Node(IncrementInterface(), name='pre_join1') wf.connect(inputspec, 'n', pre_join1, 'input1') # the set join node - join = pe.JoinNode(SumInterface(), joinsource='inputspec', - joinfield='input1', unique=True, name='join') + join = pe.JoinNode( + SumInterface(), + joinsource='inputspec', + joinfield='input1', + unique=True, + name='join') wf.connect(pre_join1, 'output1', join, 'input1') wf.run() assert _sum_operands[0] == [4, 2, 3], \ - "The unique join output value is incorrect: %s." % _sum_operands[0] + "The unique join output value is incorrect: %s." % _sum_operands[0] def test_multiple_join_nodes(tmpdir): @@ -276,18 +288,22 @@ def test_multiple_join_nodes(tmpdir): pre_join1 = pe.Node(IncrementInterface(), name='pre_join1') wf.connect(inputspec, 'n', pre_join1, 'input1') # the first join node - join1 = pe.JoinNode(IdentityInterface(fields=['vector']), - joinsource='inputspec', joinfield='vector', - name='join1') + join1 = pe.JoinNode( + IdentityInterface(fields=['vector']), + joinsource='inputspec', + joinfield='vector', + name='join1') wf.connect(pre_join1, 'output1', join1, 'vector') # an uniterated post-join node post_join1 = pe.Node(SumInterface(), name='post_join1') wf.connect(join1, 'vector', post_join1, 'input1') # the downstream join node connected to both an upstream join # path output and a separate input in the iterated path - join2 = pe.JoinNode(IdentityInterface(fields=['vector', 'scalar']), - joinsource='inputspec', joinfield='vector', - name='join2') + join2 = pe.JoinNode( + IdentityInterface(fields=['vector', 'scalar']), + joinsource='inputspec', + joinfield='vector', + name='join2') wf.connect(pre_join1, 'output1', join2, 'vector') wf.connect(post_join1, 'output1', join2, 'scalar') # a second post-join node @@ -323,16 +339,17 @@ def test_identity_join_node(tmpdir): # Make the workflow. wf = pe.Workflow(name='test') # the iterated input node - inputspec = pe.Node(IdentityInterface(fields=['n']), - name='inputspec') + inputspec = pe.Node(IdentityInterface(fields=['n']), name='inputspec') inputspec.iterables = [('n', [1, 2, 3])] # a pre-join node in the iterated path pre_join1 = pe.Node(IncrementInterface(), name='pre_join1') wf.connect(inputspec, 'n', pre_join1, 'input1') # the IdentityInterface join node - join = pe.JoinNode(IdentityInterface(fields=['vector']), - joinsource='inputspec', joinfield='vector', - name='join') + join = pe.JoinNode( + IdentityInterface(fields=['vector']), + joinsource='inputspec', + joinfield='vector', + name='join') wf.connect(pre_join1, 'output1', join, 'vector') # an uniterated post-join node post_join1 = pe.Node(SumInterface(), name='post_join1') @@ -358,8 +375,7 @@ def test_multifield_join_node(tmpdir): # Make the workflow. wf = pe.Workflow(name='test') # the iterated input node - inputspec = pe.Node(IdentityInterface(fields=['m', 'n']), - name='inputspec') + inputspec = pe.Node(IdentityInterface(fields=['m', 'n']), name='inputspec') inputspec.iterables = [('m', [1, 2]), ('n', [3, 4])] # two pre-join nodes in a parallel iterated path inc1 = pe.Node(IncrementInterface(), name='inc1') @@ -367,13 +383,15 @@ def test_multifield_join_node(tmpdir): inc2 = pe.Node(IncrementInterface(), name='inc2') wf.connect(inputspec, 'n', inc2, 'input1') # the join node - join = pe.JoinNode(IdentityInterface(fields=['vector1', 'vector2']), - joinsource='inputspec', name='join') + join = pe.JoinNode( + IdentityInterface(fields=['vector1', 'vector2']), + joinsource='inputspec', + name='join') wf.connect(inc1, 'output1', join, 'vector1') wf.connect(inc2, 'output1', join, 'vector2') # a post-join node - prod = pe.MapNode(ProductInterface(), name='prod', - iterfield=['input1', 'input2']) + prod = pe.MapNode( + ProductInterface(), name='prod', iterfield=['input1', 'input2']) wf.connect(join, 'vector1', prod, 'input1') wf.connect(join, 'vector2', prod, 'input2') @@ -407,12 +425,15 @@ def test_synchronize_join_node(tmpdir): inc2 = pe.Node(IncrementInterface(), name='inc2') wf.connect(inputspec, 'n', inc2, 'input1') # the join node - join = pe.JoinNode(IdentityInterface(fields=['vector1', 'vector2']), - joinsource='inputspec', name='join') + join = pe.JoinNode( + IdentityInterface(fields=['vector1', 'vector2']), + joinsource='inputspec', + name='join') wf.connect(inc1, 'output1', join, 'vector1') wf.connect(inc2, 'output1', join, 'vector2') # a post-join node - prod = pe.MapNode(ProductInterface(), name='prod', iterfield=['input1', 'input2']) + prod = pe.MapNode( + ProductInterface(), name='prod', iterfield=['input1', 'input2']) wf.connect(join, 'vector1', prod, 'input1') wf.connect(join, 'vector2', prod, 'input2') @@ -422,7 +443,7 @@ def test_synchronize_join_node(tmpdir): # thus, the expanded graph contains 2 * 2 iteration pre-join nodes, 1 join # node and 1 post-join node. assert len(result.nodes()) == 6, \ - "The number of expanded nodes is incorrect." + "The number of expanded nodes is incorrect." # the product inputs are [2, 3] and [4, 5] assert _products == [8, 15], \ "The post-join products is incorrect: %s." % _products @@ -449,8 +470,11 @@ def test_itersource_join_source_node(tmpdir): pre_join3 = pe.Node(IncrementInterface(), name='pre_join3') wf.connect(pre_join2, 'output1', pre_join3, 'input1') # the join node - join = pe.JoinNode(IdentityInterface(fields=['vector']), - joinsource='pre_join2', joinfield='vector', name='join') + join = pe.JoinNode( + IdentityInterface(fields=['vector']), + joinsource='pre_join2', + joinfield='vector', + name='join') wf.connect(pre_join3, 'output1', join, 'vector') # a join successor node post_join1 = pe.Node(SumInterface(), name='post_join1') @@ -478,7 +502,7 @@ def test_itersource_join_source_node(tmpdir): assert [16, 19] in _sum_operands, \ "The join Sum input is incorrect: %s." % _sum_operands assert [7, 9] in _sum_operands, \ - "The join Sum input is incorrect: %s." % _sum_operands + "The join Sum input is incorrect: %s." % _sum_operands def test_itersource_two_join_nodes(tmpdir): @@ -503,15 +527,21 @@ def test_itersource_two_join_nodes(tmpdir): pre_join3 = pe.Node(IncrementInterface(), name='pre_join3') wf.connect(pre_join2, 'output1', pre_join3, 'input1') # the first join node - join1 = pe.JoinNode(IdentityInterface(fields=['vector']), - joinsource='pre_join2', joinfield='vector', name='join1') + join1 = pe.JoinNode( + IdentityInterface(fields=['vector']), + joinsource='pre_join2', + joinfield='vector', + name='join1') wf.connect(pre_join3, 'output1', join1, 'vector') # a join successor node post_join1 = pe.Node(SumInterface(), name='post_join1') wf.connect(join1, 'vector', post_join1, 'input1') # a summary join node - join2 = pe.JoinNode(IdentityInterface(fields=['vector']), - joinsource='inputspec', joinfield='vector', name='join2') + join2 = pe.JoinNode( + IdentityInterface(fields=['vector']), + joinsource='inputspec', + joinfield='vector', + name='join2') wf.connect(post_join1, 'output1', join2, 'vector') result = wf.run() @@ -532,13 +562,16 @@ def test_set_join_node_file_input(tmpdir): wf = pe.Workflow(name='test') # the iterated input node inputspec = pe.Node(IdentityInterface(fields=['n']), name='inputspec') - inputspec.iterables = [('n', [tmpdir.join('test.nii').strpath, tmpdir.join('test2.nii').strpath])] + inputspec.iterables = [('n', [ + tmpdir.join('test.nii').strpath, + tmpdir.join('test2.nii').strpath + ])] # a pre-join node in the iterated path pre_join1 = pe.Node(IdentityInterface(fields=['n']), name='pre_join1') wf.connect(inputspec, 'n', pre_join1, 'n') # the set join node - join = pe.JoinNode(PickFirst(), joinsource='inputspec', - joinfield='in_files', name='join') + join = pe.JoinNode( + PickFirst(), joinsource='inputspec', joinfield='in_files', name='join') wf.connect(pre_join1, 'n', join, 'in_files') wf.run() @@ -550,26 +583,27 @@ def test_nested_workflow_join(tmpdir): # Make the nested workflow def nested_wf(i, name='smallwf'): - #iterables with list of nums + # iterables with list of nums inputspec = pe.Node(IdentityInterface(fields=['n']), name='inputspec') inputspec.iterables = [('n', i)] # increment each iterable before joining - pre_join = pe.Node(IncrementInterface(), - name='pre_join') + pre_join = pe.Node(IncrementInterface(), name='pre_join') # rejoin nums into list - join = pe.JoinNode(IdentityInterface(fields=['n']), - joinsource='inputspec', - joinfield='n', - name='join') - #define and connect nested workflow - wf = pe.Workflow(name='wf_%d'%i[0]) + join = pe.JoinNode( + IdentityInterface(fields=['n']), + joinsource='inputspec', + joinfield='n', + name='join') + # define and connect nested workflow + wf = pe.Workflow(name='wf_%d' % i[0]) wf.connect(inputspec, 'n', pre_join, 'input1') wf.connect(pre_join, 'output1', join, 'n') return wf + # master wf meta_wf = pe.Workflow(name='meta', base_dir='.') # add each mini-workflow to master - for i in [[1,3],[2,4]]: + for i in [[1, 3], [2, 4]]: mini_wf = nested_wf(i) meta_wf.add_nodes([mini_wf]) @@ -578,5 +612,3 @@ def nested_wf(i, name='smallwf'): # there should be six nodes in total assert len(result.nodes()) == 6, \ "The number of expanded nodes is incorrect." - - diff --git a/nipype/pipeline/engine/tests/test_utils.py b/nipype/pipeline/engine/tests/test_utils.py index 23c7a16fc6..92d5b703bb 100644 --- a/nipype/pipeline/engine/tests/test_utils.py +++ b/nipype/pipeline/engine/tests/test_utils.py @@ -3,10 +3,12 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Tests for the engine utils module """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, open -import os, sys +import os +import sys from copy import deepcopy from shutil import rmtree import pytest @@ -19,15 +21,16 @@ def test_identitynode_removal(tmpdir): - def test_function(arg1, arg2, arg3): import numpy as np return (np.array(arg1) + arg2 + arg3).tolist() - wf = pe.Workflow(name="testidentity", base_dir=tmpdir.strpath) - n1 = pe.Node(niu.IdentityInterface(fields=['a', 'b']), name='src', base_dir=tmpdir.strpath) + n1 = pe.Node( + niu.IdentityInterface(fields=['a', 'b']), + name='src', + base_dir=tmpdir.strpath) n1.iterables = ('b', [0, 1, 2, 3]) n1.inputs.a = [0, 1, 2, 3] @@ -35,7 +38,10 @@ def test_function(arg1, arg2, arg3): wf.connect(n1, ('a', test_function, 1, -1), n2, 'inlist') wf.connect(n1, 'b', n2, 'index') - n3 = pe.Node(niu.IdentityInterface(fields=['c', 'd']), name='passer', base_dir=tmpdir.strpath) + n3 = pe.Node( + niu.IdentityInterface(fields=['c', 'd']), + name='passer', + base_dir=tmpdir.strpath) n3.inputs.c = [1, 2, 3, 4] wf.connect(n2, 'out', n3, 'd') @@ -56,11 +62,14 @@ class OutputSpec(nib.TraitedSpec): class InputSpec(nib.TraitedSpec): infile = nib.File() + outputs = OutputSpec() inputs = InputSpec() - filenames = ['file.hdr', 'file.img', 'file.BRIK', 'file.HEAD', - '_0x1234.json', 'foo.txt'] + filenames = [ + 'file.hdr', 'file.img', 'file.BRIK', 'file.HEAD', '_0x1234.json', + 'foo.txt' + ] outfiles = [] for filename in filenames: outfile = tmpdir.join(filename) @@ -74,13 +83,13 @@ class InputSpec(nib.TraitedSpec): assert os.path.exists(outfiles[5]) config.set_default_config() config.set('execution', 'remove_unnecessary_outputs', False) - out = clean_working_directory(outputs, tmpdir.strpath, inputs, needed_outputs, - deepcopy(config._sections)) + out = clean_working_directory(outputs, tmpdir.strpath, inputs, + needed_outputs, deepcopy(config._sections)) assert os.path.exists(outfiles[5]) assert out.others == outfiles[5] config.set('execution', 'remove_unnecessary_outputs', True) - out = clean_working_directory(outputs, tmpdir.strpath, inputs, needed_outputs, - deepcopy(config._sections)) + out = clean_working_directory(outputs, tmpdir.strpath, inputs, + needed_outputs, deepcopy(config._sections)) assert os.path.exists(outfiles[1]) assert os.path.exists(outfiles[3]) assert os.path.exists(outfiles[4]) @@ -91,7 +100,6 @@ class InputSpec(nib.TraitedSpec): def test_outputs_removal(tmpdir): - def test_function(arg1): import os file1 = os.path.join(os.getcwd(), 'file1.txt') @@ -104,21 +112,23 @@ def test_function(arg1): fp.close() return file1, file2 - n1 = pe.Node(niu.Function(input_names=['arg1'], - output_names=['file1', 'file2'], - function=test_function), - base_dir=tmpdir.strpath, - name='testoutputs') + n1 = pe.Node( + niu.Function( + input_names=['arg1'], + output_names=['file1', 'file2'], + function=test_function), + base_dir=tmpdir.strpath, + name='testoutputs') n1.inputs.arg1 = 1 n1.config = {'execution': {'remove_unnecessary_outputs': True}} n1.config = merge_dict(deepcopy(config._sections), n1.config) n1.run() - assert tmpdir.join(n1.name,'file1.txt').check() - assert tmpdir.join(n1.name,'file1.txt').check() + assert tmpdir.join(n1.name, 'file1.txt').check() + assert tmpdir.join(n1.name, 'file1.txt').check() n1.needed_outputs = ['file2'] n1.run() - assert not tmpdir.join(n1.name,'file1.txt').check() - assert tmpdir.join(n1.name,'file2.txt').check() + assert not tmpdir.join(n1.name, 'file1.txt').check() + assert tmpdir.join(n1.name, 'file2.txt').check() class InputSpec(nib.TraitedSpec): @@ -146,24 +156,22 @@ def _list_outputs(self): def test_inputs_removal(tmpdir): file1 = tmpdir.join('file1.txt') file1.write('dummy_file') - n1 = pe.Node(UtilsTestInterface(), - base_dir=tmpdir.strpath, - name='testinputs') + n1 = pe.Node( + UtilsTestInterface(), base_dir=tmpdir.strpath, name='testinputs') n1.inputs.in_file = file1.strpath n1.config = {'execution': {'keep_inputs': True}} n1.config = merge_dict(deepcopy(config._sections), n1.config) n1.run() - assert tmpdir.join(n1.name,'file1.txt').check() + assert tmpdir.join(n1.name, 'file1.txt').check() n1.inputs.in_file = file1.strpath n1.config = {'execution': {'keep_inputs': False}} n1.config = merge_dict(deepcopy(config._sections), n1.config) n1.overwrite = True n1.run() - assert not tmpdir.join(n1.name,'file1.txt').check() + assert not tmpdir.join(n1.name, 'file1.txt').check() def test_outputs_removal_wf(tmpdir): - def test_function(arg1): import os file1 = os.path.join(os.getcwd(), 'file1.txt') @@ -193,65 +201,67 @@ def test_function3(arg): import os return arg - - for plugin in ('Linear',): # , 'MultiProc'): - n1 = pe.Node(niu.Function(input_names=['arg1'], - output_names=['out_file1', 'out_file2', 'dir'], - function=test_function), - name='n1', base_dir=tmpdir.strpath) + for plugin in ('Linear', ): # , 'MultiProc'): + n1 = pe.Node( + niu.Function( + input_names=['arg1'], + output_names=['out_file1', 'out_file2', 'dir'], + function=test_function), + name='n1', + base_dir=tmpdir.strpath) n1.inputs.arg1 = 1 - n2 = pe.Node(niu.Function(input_names=['in_file', 'arg'], - output_names=['out_file1', 'out_file2', 'n'], - function=test_function2), - name='n2', base_dir=tmpdir.strpath) + n2 = pe.Node( + niu.Function( + input_names=['in_file', 'arg'], + output_names=['out_file1', 'out_file2', 'n'], + function=test_function2), + name='n2', + base_dir=tmpdir.strpath) n2.inputs.arg = 2 - n3 = pe.Node(niu.Function(input_names=['arg'], - output_names=['n'], - function=test_function3), - name='n3', base_dir=tmpdir.strpath) + n3 = pe.Node( + niu.Function( + input_names=['arg'], + output_names=['n'], + function=test_function3), + name='n3', + base_dir=tmpdir.strpath) - wf = pe.Workflow(name="node_rem_test" + plugin, base_dir=tmpdir.strpath) + wf = pe.Workflow( + name="node_rem_test" + plugin, base_dir=tmpdir.strpath) wf.connect(n1, "out_file1", n2, "in_file") wf.run(plugin='Linear') for remove_unnecessary_outputs in [True, False]: config.set_default_config() - wf.config = {'execution': {'remove_unnecessary_outputs': remove_unnecessary_outputs}} + wf.config = { + 'execution': { + 'remove_unnecessary_outputs': remove_unnecessary_outputs + } + } rmtree(os.path.join(wf.base_dir, wf.name)) wf.run(plugin=plugin) - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n1.name, - 'file2.txt')) != remove_unnecessary_outputs - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n1.name, - "subdir", - 'file1.txt')) != remove_unnecessary_outputs - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n1.name, - 'file1.txt')) - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n1.name, - 'file3.txt')) != remove_unnecessary_outputs - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n2.name, - 'file1.txt')) - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n2.name, - 'file2.txt')) - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n2.name, - 'file3.txt')) != remove_unnecessary_outputs + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n1.name, + 'file2.txt')) != remove_unnecessary_outputs + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n1.name, "subdir", + 'file1.txt')) != remove_unnecessary_outputs + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n1.name, 'file1.txt')) + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n1.name, + 'file3.txt')) != remove_unnecessary_outputs + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n2.name, 'file1.txt')) + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n2.name, 'file2.txt')) + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n2.name, + 'file3.txt')) != remove_unnecessary_outputs n4 = pe.Node(UtilsTestInterface(), name='n4', base_dir=tmpdir.strpath) wf.connect(n2, "out_file1", n4, "in_file") @@ -263,21 +273,23 @@ def pick_first(l): for remove_unnecessary_outputs in [True, False]: for keep_inputs in [True, False]: config.set_default_config() - wf.config = {'execution': {'keep_inputs': keep_inputs, 'remove_unnecessary_outputs': remove_unnecessary_outputs}} + wf.config = { + 'execution': { + 'keep_inputs': keep_inputs, + 'remove_unnecessary_outputs': + remove_unnecessary_outputs + } + } rmtree(os.path.join(wf.base_dir, wf.name)) wf.run(plugin=plugin) - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n2.name, - 'file1.txt')) - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n2.name, - 'file2.txt')) != remove_unnecessary_outputs - assert os.path.exists(os.path.join(wf.base_dir, - wf.name, - n4.name, - 'file1.txt')) == keep_inputs + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n2.name, 'file1.txt')) + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n2.name, + 'file2.txt')) != remove_unnecessary_outputs + assert os.path.exists( + os.path.join(wf.base_dir, wf.name, n4.name, + 'file1.txt')) == keep_inputs def fwhm(fwhm): @@ -286,15 +298,15 @@ def fwhm(fwhm): def create_wf(name): pipe = pe.Workflow(name=name) - process = pe.Node(niu.Function(input_names=['fwhm'], - output_names=['fwhm'], - function=fwhm), - name='proc') + process = pe.Node( + niu.Function( + input_names=['fwhm'], output_names=['fwhm'], function=fwhm), + name='proc') process.iterables = ('fwhm', [0]) - process2 = pe.Node(niu.Function(input_names=['fwhm'], - output_names=['fwhm'], - function=fwhm), - name='proc2') + process2 = pe.Node( + niu.Function( + input_names=['fwhm'], output_names=['fwhm'], function=fwhm), + name='proc2') process2.iterables = ('fwhm', [0]) pipe.connect(process, 'fwhm', process2, 'fwhm') return pipe @@ -323,16 +335,18 @@ def dummy_func(value): return value + 1 -@pytest.mark.skipif(sys.version_info < (3,0), - reason="the famous segfault #1788") +@pytest.mark.skipif( + sys.version_info < (3, 0), reason="the famous segfault #1788") def test_mapnode_crash(tmpdir): """Test mapnode crash when stop_on_first_crash is True""" cwd = os.getcwd() - node = pe.MapNode(niu.Function(input_names=['WRONG'], - output_names=['newstring'], - function=dummy_func), - iterfield=['WRONG'], - name='myfunc') + node = pe.MapNode( + niu.Function( + input_names=['WRONG'], + output_names=['newstring'], + function=dummy_func), + iterfield=['WRONG'], + name='myfunc') node.inputs.WRONG = ['string{}'.format(i) for i in range(3)] node.config = deepcopy(config._sections) node.config['execution']['stop_on_first_crash'] = True @@ -342,16 +356,18 @@ def test_mapnode_crash(tmpdir): os.chdir(cwd) -@pytest.mark.skipif(sys.version_info < (3,0), - reason="the famous segfault #1788") +@pytest.mark.skipif( + sys.version_info < (3, 0), reason="the famous segfault #1788") def test_mapnode_crash2(tmpdir): """Test mapnode crash when stop_on_first_crash is False""" cwd = os.getcwd() - node = pe.MapNode(niu.Function(input_names=['WRONG'], - output_names=['newstring'], - function=dummy_func), - iterfield=['WRONG'], - name='myfunc') + node = pe.MapNode( + niu.Function( + input_names=['WRONG'], + output_names=['newstring'], + function=dummy_func), + iterfield=['WRONG'], + name='myfunc') node.inputs.WRONG = ['string{}'.format(i) for i in range(3)] node.base_dir = tmpdir.strpath @@ -360,21 +376,23 @@ def test_mapnode_crash2(tmpdir): os.chdir(cwd) -@pytest.mark.skipif(sys.version_info < (3,0), - reason="the famous segfault #1788") +@pytest.mark.skipif( + sys.version_info < (3, 0), reason="the famous segfault #1788") def test_mapnode_crash3(tmpdir): """Test mapnode crash when mapnode is embedded in a workflow""" tmpdir.chdir() - node = pe.MapNode(niu.Function(input_names=['WRONG'], - output_names=['newstring'], - function=dummy_func), - iterfield=['WRONG'], - name='myfunc') + node = pe.MapNode( + niu.Function( + input_names=['WRONG'], + output_names=['newstring'], + function=dummy_func), + iterfield=['WRONG'], + name='myfunc') node.inputs.WRONG = ['string{}'.format(i) for i in range(3)] wf = pe.Workflow('testmapnodecrash') wf.add_nodes([node]) wf.base_dir = tmpdir.strpath - #changing crashdump dir to cwl (to avoid problems with read-only systems) + # changing crashdump dir to cwl (to avoid problems with read-only systems) wf.config["execution"]["crashdump_dir"] = os.getcwd() with pytest.raises(RuntimeError): wf.run(plugin='Linear') diff --git a/nipype/pipeline/engine/tests/test_workflows.py b/nipype/pipeline/engine/tests/test_workflows.py index 32b2fa3505..d2b23ae586 100644 --- a/nipype/pipeline/engine/tests/test_workflows.py +++ b/nipype/pipeline/engine/tests/test_workflows.py @@ -13,7 +13,7 @@ def test_duplicate_node_check(): wf = pe.Workflow(name="testidentity") - original_list = [0,1,2,3,4,5,6,7,8,9] + original_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] selector1 = pe.Node(niu.Select(), name="selector1") selector1.inputs.index = original_list[:-1] @@ -26,10 +26,10 @@ def test_duplicate_node_check(): selector4.inputs.index = original_list[:-4] wf_connections = [ - (selector1, selector2, [("out","inlist")]), - (selector2, selector3, [("out","inlist")]), - (selector3, selector4, [("out","inlist")]), - ] + (selector1, selector2, [("out", "inlist")]), + (selector2, selector3, [("out", "inlist")]), + (selector3, selector4, [("out", "inlist")]), + ] with pytest.raises(IOError) as excinfo: wf.connect(wf_connections) diff --git a/nipype/pipeline/engine/utils.py b/nipype/pipeline/engine/utils.py index 61937faac3..b2bb7f7c75 100644 --- a/nipype/pipeline/engine/utils.py +++ b/nipype/pipeline/engine/utils.py @@ -2,7 +2,8 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Utility routines for workflow graphs""" -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, open, next, zip, range import os @@ -25,20 +26,26 @@ from ... import logging, config, LooseVersion from ...utils.filemanip import ( - relpath, makedirs, fname_presuffix, to_str, - filename_to_list, get_related_files, FileNotFoundError, - save_json, savepkl, - write_rst_header, write_rst_dict, write_rst_list, + relpath, + makedirs, + fname_presuffix, + to_str, + filename_to_list, + get_related_files, + FileNotFoundError, + save_json, + savepkl, + write_rst_header, + write_rst_dict, + write_rst_list, ) from ...utils.misc import str2bool from ...utils.functions import create_function_from_source -from ...interfaces.base import ( - Bunch, CommandLine, isdefined, Undefined, - InterfaceResult, traits) +from ...interfaces.base import (Bunch, CommandLine, isdefined, Undefined, + InterfaceResult, traits) from ...interfaces.utility import IdentityInterface from ...utils.provenance import ProvStore, pm, nipype_ns, get_id - try: from inspect import signature except ImportError: @@ -80,8 +87,7 @@ def save_hashfile(hashfile, hashed_inputs): with open(hashfile, 'wt') as fd: fd.writelines(str(hashed_inputs)) - logger.debug( - 'Unable to write a particular type to the json file') + logger.debug('Unable to write a particular type to the json file') else: logger.critical('Unable to open the file in write mode: %s', hashfile) @@ -127,13 +133,14 @@ def write_report(node, report_type=None, is_mapnode=False): report_file = os.path.join(report_dir, 'report.rst') makedirs(report_dir, exist_ok=True) - logger.debug('[Node] Writing %s-exec report to "%s"', - report_type[:-4], report_file) + logger.debug('[Node] Writing %s-exec report to "%s"', report_type[:-4], + report_file) if report_type.startswith('pre'): lines = [ write_rst_header('Node: %s' % get_print_name(node), level=0), - write_rst_list(['Hierarchy : %s' % node.fullname, - 'Exec ID : %s' % node._id]), + write_rst_list( + ['Hierarchy : %s' % node.fullname, + 'Exec ID : %s' % node._id]), write_rst_header('Original Inputs', level=1), write_rst_dict(node.inputs.get()), ] @@ -163,15 +170,12 @@ def write_report(node, report_type=None, is_mapnode=False): if is_mapnode: lines.append(write_rst_header('Subnode reports', level=1)) - nitems = len(filename_to_list( - getattr(node.inputs, node.iterfield[0]))) + nitems = len(filename_to_list(getattr(node.inputs, node.iterfield[0]))) subnode_report_files = [] for i in range(nitems): - nodecwd = os.path.join( - cwd, 'mapflow', '_%s%d' % (node.name, i), - '_report', 'report.rst') - subnode_report_files.append( - 'subnode %d : %s' % (i, nodecwd)) + nodecwd = os.path.join(cwd, 'mapflow', '_%s%d' % (node.name, i), + '_report', 'report.rst') + subnode_report_files.append('subnode %d : %s' % (i, nodecwd)) lines.append(write_rst_list(subnode_report_files)) @@ -235,8 +239,7 @@ def save_resultfile(result, cwd, name): outputs = result.outputs.get() except TypeError: outputs = result.outputs.dictcopy() # outputs was a bunch - result.outputs.set(**modify_paths( - outputs, relative=True, basedir=cwd)) + result.outputs.set(**modify_paths(outputs, relative=True, basedir=cwd)) savepkl(resultsfile, result) logger.debug('saved results in %s', resultsfile) @@ -292,9 +295,8 @@ def load_resultfile(path, name): except TypeError: outputs = result.outputs.dictcopy() # outputs == Bunch try: - result.outputs.set(**modify_paths(outputs, - relative=False, - basedir=path)) + result.outputs.set( + **modify_paths(outputs, relative=False, basedir=path)) except FileNotFoundError: logger.debug('conversion to full path results in ' 'non existent file') @@ -327,17 +329,19 @@ def _write_inputs(node): except RuntimeError: lines.append("%s.inputs.%s = '%s'" % (nodename, key, val)) else: - funcname = [name for name in func.__globals__ - if name != '__builtins__'][0] + funcname = [ + name for name in func.__globals__ + if name != '__builtins__' + ][0] lines.append(pickle.loads(val)) if funcname == nodename: lines[-1] = lines[-1].replace(' %s(' % funcname, ' %s_1(' % funcname) funcname = '%s_1' % funcname - lines.append('from nipype.utils.functions import getsource') - lines.append("%s.inputs.%s = getsource(%s)" % (nodename, - key, - funcname)) + lines.append( + 'from nipype.utils.functions import getsource') + lines.append("%s.inputs.%s = getsource(%s)" % + (nodename, key, funcname)) else: lines.append('%s.inputs.%s = %s' % (nodename, key, val)) return lines @@ -360,8 +364,9 @@ def format_node(node, format='python', include_config=False): filled_args = [] for arg in args: if hasattr(node.interface, '_%s' % arg): - filled_args.append('%s=%s' % (arg, getattr(node.interface, - '_%s' % arg))) + filled_args.append('%s=%s' % + (arg, + getattr(node.interface, '_%s' % arg))) args = ', '.join(filled_args) else: args = '' @@ -375,11 +380,11 @@ def format_node(node, format='python', include_config=False): lines = [importline, comment, nodedef] if include_config: - lines = [importline, - "from future import standard_library", - "standard_library.install_aliases()", - "from collections import OrderedDict", - comment, nodedef] + lines = [ + importline, "from future import standard_library", + "standard_library.install_aliases()", + "from collections import OrderedDict", comment, nodedef + ] lines.append('%s.config = %s' % (name, node.config)) if node.iterables is not None: @@ -408,14 +413,14 @@ def modify_paths(object, relative=True, basedir=None): out = {} for key, val in sorted(object.items()): if isdefined(val): - out[key] = modify_paths(val, relative=relative, - basedir=basedir) + out[key] = modify_paths( + val, relative=relative, basedir=basedir) elif isinstance(object, (list, tuple)): out = [] for val in object: if isdefined(val): - out.append(modify_paths(val, relative=relative, - basedir=basedir)) + out.append( + modify_paths(val, relative=relative, basedir=basedir)) if isinstance(object, tuple): out = tuple(out) else: @@ -509,14 +514,14 @@ def _write_detailed_dot(graph, dotfilename): inport = cd[1] ipstrip = 'in%s' % _replacefunk(inport) opstrip = 'out%s' % _replacefunk(outport) - edges.append('%s:%s:e -> %s:%s:w;' % (str(u).replace('.', ''), - opstrip, - str(v).replace('.', ''), - ipstrip)) + edges.append( + '%s:%s:e -> %s:%s:w;' % (str(u).replace('.', ''), opstrip, + str(v).replace('.', ''), ipstrip)) if inport not in inports: inports.append(inport) - inputstr = ['{IN'] + ['| %s' % (_replacefunk(ip), ip) - for ip in sorted(inports)] + ['}'] + inputstr = ['{IN'] + [ + '| %s' % (_replacefunk(ip), ip) for ip in sorted(inports) + ] + ['}'] outports = [] for u, v, d in graph.out_edges(nbunch=n, data=True): for cd in d['connect']: @@ -526,8 +531,10 @@ def _write_detailed_dot(graph, dotfilename): outport = cd[0][0] if outport not in outports: outports.append(outport) - outputstr = ['{OUT'] + ['| %s' % (_replacefunk(oport), oport) - for oport in sorted(outports)] + ['}'] + outputstr = ['{OUT'] + [ + '| %s' % (_replacefunk(oport), oport) + for oport in sorted(outports) + ] + ['}'] srcpackage = '' if hasattr(n, '_interface'): pkglist = n.interface.__class__.__module__.split('.') @@ -535,12 +542,12 @@ def _write_detailed_dot(graph, dotfilename): srcpackage = pkglist[2] srchierarchy = '.'.join(nodename.split('.')[1:-1]) nodenamestr = '{ %s | %s | %s }' % (nodename.split('.')[-1], - srcpackage, - srchierarchy) - text += ['%s [label="%s|%s|%s"];' % (nodename.replace('.', ''), - ''.join(inputstr), - nodenamestr, - ''.join(outputstr))] + srcpackage, srchierarchy) + text += [ + '%s [label="%s|%s|%s"];' % + (nodename.replace('.', ''), ''.join(inputstr), nodenamestr, + ''.join(outputstr)) + ] # write edges for edge in sorted(edges): text.append(edge) @@ -551,8 +558,8 @@ def _write_detailed_dot(graph, dotfilename): def _replacefunk(x): - return x.replace('_', '').replace( - '.', '').replace('@', '').replace('-', '') + return x.replace('_', '').replace('.', '').replace('@', '').replace( + '-', '') # Graph manipulations for iterable expansion @@ -659,8 +666,7 @@ def synchronize_iterables(iterables): def evaluate_connect_function(function_source, args, first_arg): func = create_function_from_source(function_source) try: - output_value = func(first_arg, - *list(args)) + output_value = func(first_arg, *list(args)) except NameError as e: if e.args[0].startswith("global name") and \ e.args[0].endswith("is not defined"): @@ -680,8 +686,13 @@ def get_levels(G): return levels -def _merge_graphs(supergraph, nodes, subgraph, nodeid, iterables, - prefix, synchronize=False): +def _merge_graphs(supergraph, + nodes, + subgraph, + nodeid, + iterables, + prefix, + synchronize=False): """Merges two graphs that share a subset of nodes. If the subgraph needs to be replicated for multiple iterables, the @@ -723,12 +734,12 @@ def _merge_graphs(supergraph, nodes, subgraph, nodeid, iterables, for n in list(subgraph.nodes()): nidx = ids.index(n._hierarchy + n._id) for edge in supergraph.in_edges(list(supernodes)[nidx]): - # make sure edge is not part of subgraph + # make sure edge is not part of subgraph if edge[0] not in subgraph.nodes(): if n._hierarchy + n._id not in list(edgeinfo.keys()): edgeinfo[n._hierarchy + n._id] = [] - edgeinfo[n._hierarchy + n._id].append((edge[0], - supergraph.get_edge_data(*edge))) + edgeinfo[n._hierarchy + n._id].append( + (edge[0], supergraph.get_edge_data(*edge))) supergraph.remove_nodes_from(nodes) # Add copies of the subgraph depending on the number of iterables iterable_params = expand_iterables(iterables, synchronize) @@ -746,8 +757,8 @@ def _merge_graphs(supergraph, nodes, subgraph, nodeid, iterables, rootnode = list(Gc.nodes())[nodeidx] paramstr = '' for key, val in sorted(params.items()): - paramstr = '{}_{}_{}'.format( - paramstr, _get_valid_pathstr(key), _get_valid_pathstr(val)) + paramstr = '{}_{}_{}'.format(paramstr, _get_valid_pathstr(key), + _get_valid_pathstr(val)) rootnode.set_input(key, val) logger.debug('Parameterization: paramstr=%s', paramstr) @@ -810,9 +821,11 @@ def _identity_nodes(graph, include_iterables): are included if and only if the include_iterables flag is set to True. """ - return [node for node in nx.topological_sort(graph) - if isinstance(node.interface, IdentityInterface) and - (include_iterables or getattr(node, 'iterables') is None)] + return [ + node for node in nx.topological_sort(graph) + if isinstance(node.interface, IdentityInterface) and ( + include_iterables or getattr(node, 'iterables') is None) + ] def _remove_identity_node(graph, node): @@ -862,8 +875,7 @@ def _propagate_root_output(graph, node, field, connections): for destnode, inport, src in connections: value = getattr(node.inputs, field) if isinstance(src, tuple): - value = evaluate_connect_function(src[1], src[2], - value) + value = evaluate_connect_function(src[1], src[2], value) destnode.set_input(inport, value) @@ -880,16 +892,21 @@ def _propagate_internal_output(graph, node, field, connections, portinputs): raise ValueError("Does not support two inline functions " "in series ('{}' and '{}'), found when " "connecting {} to {}. Please use a Function " - "node.".format(src_func, dst_func, srcnode, destnode)) + "node.".format(src_func, dst_func, srcnode, + destnode)) - connect = graph.get_edge_data(srcnode, destnode, - default={'connect': []}) + connect = graph.get_edge_data( + srcnode, destnode, default={ + 'connect': [] + }) if isinstance(src, tuple): connect['connect'].append(((srcport, src[1], src[2]), inport)) else: connect = {'connect': [(srcport, inport)]} - old_connect = graph.get_edge_data(srcnode, destnode, - default={'connect': []}) + old_connect = graph.get_edge_data( + srcnode, destnode, default={ + 'connect': [] + }) old_connect['connect'] += connect['connect'] graph.add_edges_from([(srcnode, destnode, old_connect)]) else: @@ -925,10 +942,11 @@ def generate_expanded_graph(graph_in): logger.debug("Expanding the iterable node %s...", inode) # the join successor nodes of the current iterable node - jnodes = [node for node in graph_in.nodes() - if hasattr(node, 'joinsource') and - inode.name == node.joinsource and - nx.has_path(graph_in, inode, node)] + jnodes = [ + node for node in graph_in.nodes() + if hasattr(node, 'joinsource') and inode.name == node.joinsource + and nx.has_path(graph_in, inode, node) + ] # excise the join in-edges. save the excised edges in a # {jnode: {source name: (destination name, edge data)}} @@ -943,8 +961,8 @@ def generate_expanded_graph(graph_in): for src, dest in edges2remove: graph_in.remove_edge(src, dest) - logger.debug("Excised the %s -> %s join node in-edge.", - src, dest) + logger.debug("Excised the %s -> %s join node in-edge.", src, + dest) if inode.itersource: # the itersource is a (node name, fields) tuple @@ -955,19 +973,21 @@ def generate_expanded_graph(graph_in): # find the unique iterable source node in the graph try: iter_src = next((node for node in graph_in.nodes() - if node.name == src_name and - nx.has_path(graph_in, node, inode))) + if node.name == src_name + and nx.has_path(graph_in, node, inode))) except StopIteration: raise ValueError("The node %s itersource %s was not found" - " among the iterable predecessor nodes" - % (inode, src_name)) - logger.debug("The node %s has iterable source node %s", - inode, iter_src) + " among the iterable predecessor nodes" % + (inode, src_name)) + logger.debug("The node %s has iterable source node %s", inode, + iter_src) # look up the iterables for this particular itersource descendant # using the iterable source ancestor values as a key iterables = {} # the source node iterables values - src_values = [getattr(iter_src.inputs, field) for field in src_fields] + src_values = [ + getattr(iter_src.inputs, field) for field in src_fields + ] # if there is one source field, then the key is the the source value, # otherwise the key is the tuple of source values if len(src_values) == 1: @@ -977,14 +997,17 @@ def generate_expanded_graph(graph_in): # The itersource iterables is a {field: lookup} dictionary, where the # lookup is a {source key: iteration list} dictionary. Look up the # current iterable value using the predecessor itersource input values. - iter_dict = dict([(field, lookup[key]) for field, lookup in - inode.iterables if key in lookup]) + iter_dict = dict([(field, lookup[key]) + for field, lookup in inode.iterables + if key in lookup]) + # convert the iterables to the standard {field: function} format def make_field_func(*pair): return pair[0], lambda: pair[1] - iterables = dict([make_field_func(*pair) for pair in list(iter_dict.items())]) + iterables = dict( + [make_field_func(*pair) for pair in list(iter_dict.items())]) else: iterables = inode.iterables.copy() inode.iterables = None @@ -1014,9 +1037,9 @@ def make_field_func(*pair): subgraph = graph_in.subgraph(subnodes) else: subgraph = graph_in.subgraph(subnodes).copy() - graph_in = _merge_graphs(graph_in, subnodes, - subgraph, inode._hierarchy + inode._id, - iterables, iterable_prefix, inode.synchronize) + graph_in = _merge_graphs(graph_in, subnodes, subgraph, + inode._hierarchy + inode._id, iterables, + iterable_prefix, inode.synchronize) # reconnect the join nodes for jnode in jnodes: @@ -1040,7 +1063,9 @@ def make_field_func(*pair): iter_cnt = count_iterables(iterables, inode.synchronize) # make new join node fields to connect to each replicated # join in-edge source node. - slot_dicts = [jnode._add_join_item_fields() for _ in range(iter_cnt)] + slot_dicts = [ + jnode._add_join_item_fields() for _ in range(iter_cnt) + ] # for each join in-edge, connect every expanded source node # which matches on the in-edge source name to the destination # join node. Qualify each edge connect join field name by @@ -1058,8 +1083,10 @@ def make_field_func(*pair): # the (source, destination) field tuples connects = newdata['connect'] # the join fields connected to the source - join_fields = [field for _, field in connects - if field in jnode.joinfield] + join_fields = [ + field for _, field in connects + if field in jnode.joinfield + ] # the {field: slot fields} maps assigned to the input # node, e.g. {'image': 'imageJ3', 'mask': 'maskJ3'} # for the third join source expansion replicate of a @@ -1084,8 +1111,9 @@ def make_field_func(*pair): for node in graph_in.nodes(): if node.parameterization: - node.parameterization = [param for _, param in - sorted(node.parameterization)] + node.parameterization = [ + param for _, param in sorted(node.parameterization) + ] logger.debug("PE: expanding iterables ... done") return _remove_nonjoin_identity_nodes(graph_in) @@ -1153,10 +1181,13 @@ def _standardize_iterables(node): # Convert a values list to a function. This is a legacy # Nipype requirement with unknown rationale. if not node.itersource: + def make_field_func(*pair): return pair[0], lambda: pair[1] - iter_items = [make_field_func(*field_value1) for field_value1 in iterables] + iter_items = [ + make_field_func(*field_value1) for field_value1 in iterables + ] iterables = dict(iter_items) node.iterables = iterables @@ -1181,12 +1212,12 @@ def _validate_iterables(node, iterables, fields): raise ValueError("The %s iterables is not a [(field, values)]" " list" % node.name) except TypeError as e: - raise TypeError("A %s iterables member is not iterable: %s" - % (node.name, e)) + raise TypeError("A %s iterables member is not iterable: %s" % + (node.name, e)) field, _ = item if field not in fields: - raise ValueError("The %s iterables field is unrecognized: %s" - % (node.name, field)) + raise ValueError("The %s iterables field is unrecognized: %s" % + (node.name, field)) def _transpose_iterables(fields, values): @@ -1208,12 +1239,18 @@ def _transpose_iterables(fields, values): transposed[fields[idx]][key].append(val) return list(transposed.items()) - return list(zip(fields, [[v for v in list(transpose) if v is not None] - for transpose in zip(*values)])) + return list( + zip(fields, [[v for v in list(transpose) if v is not None] + for transpose in zip(*values)])) -def export_graph(graph_in, base_dir=None, show=False, use_execgraph=False, - show_connectinfo=False, dotfilename='graph.dot', format='png', +def export_graph(graph_in, + base_dir=None, + show=False, + use_execgraph=False, + show_connectinfo=False, + dotfilename='graph.dot', + format='png', simple_form=True): """ Displays the graph layout of the pipeline @@ -1245,27 +1282,23 @@ def export_graph(graph_in, base_dir=None, show=False, use_execgraph=False, base_dir = os.getcwd() makedirs(base_dir, exist_ok=True) - outfname = fname_presuffix(dotfilename, - suffix='_detailed.dot', - use_ext=False, - newpath=base_dir) + outfname = fname_presuffix( + dotfilename, suffix='_detailed.dot', use_ext=False, newpath=base_dir) _write_detailed_dot(graph, outfname) if format != 'dot': cmd = 'dot -T%s -O %s' % (format, outfname) - res = CommandLine(cmd, terminal_output='allatonce', - resource_monitor=False).run() + res = CommandLine( + cmd, terminal_output='allatonce', resource_monitor=False).run() if res.runtime.returncode: logger.warning('dot2png: %s', res.runtime.stderr) pklgraph = _create_dot_graph(graph, show_connectinfo, simple_form) - simplefname = fname_presuffix(dotfilename, - suffix='.dot', - use_ext=False, - newpath=base_dir) + simplefname = fname_presuffix( + dotfilename, suffix='.dot', use_ext=False, newpath=base_dir) nx.drawing.nx_pydot.write_dot(pklgraph, simplefname) if format != 'dot': cmd = 'dot -T%s -O %s' % (format, simplefname) - res = CommandLine(cmd, terminal_output='allatonce', - resource_monitor=False).run() + res = CommandLine( + cmd, terminal_output='allatonce', resource_monitor=False).run() if res.runtime.returncode: logger.warning('dot2png: %s', res.runtime.stderr) if show: @@ -1288,7 +1321,9 @@ def format_dot(dotfilename, format='png'): CommandLine(cmd, resource_monitor=False).run() except IOError as ioe: if "could not be found" in str(ioe): - raise IOError("Cannot draw directed graph; executable 'dot' is unavailable") + raise IOError( + "Cannot draw directed graph; executable 'dot' is unavailable" + ) else: raise ioe dotfilename += '.%s' % format @@ -1332,8 +1367,13 @@ def walk_files(cwd): yield os.path.join(path, f) -def clean_working_directory(outputs, cwd, inputs, needed_outputs, config, - files2keep=None, dirs2keep=None): +def clean_working_directory(outputs, + cwd, + inputs, + needed_outputs, + config, + files2keep=None, + dirs2keep=None): """Removes all files not needed for further analysis from the directory """ if not outputs: @@ -1353,8 +1393,10 @@ def clean_working_directory(outputs, cwd, inputs, needed_outputs, config, inputdict = inputs.get() input_files.extend(walk_outputs(inputdict)) needed_files += [path for path, type in input_files if type == 'f'] - for extra in ['_0x*.json', 'provenance.*', 'pyscript*.m', 'pyjobs*.mat', - 'command.txt', 'result*.pklz', '_inputs.pklz', '_node.pklz']: + for extra in [ + '_0x*.json', 'provenance.*', 'pyscript*.m', 'pyjobs*.mat', + 'command.txt', 'result*.pklz', '_inputs.pklz', '_node.pklz' + ]: needed_files.extend(glob(os.path.join(cwd, extra))) if files2keep: needed_files.extend(filename_to_list(files2keep)) @@ -1454,16 +1496,18 @@ def write_workflow_prov(graph, filename=None, format='all'): result = node.result classname = node.interface.__class__.__name__ _, hashval, _, _ = node.hash_exists() - attrs = {pm.PROV["type"]: nipype_ns[classname], - pm.PROV["label"]: '_'.join((classname, node.name)), - nipype_ns['hashval']: hashval} + attrs = { + pm.PROV["type"]: nipype_ns[classname], + pm.PROV["label"]: '_'.join((classname, node.name)), + nipype_ns['hashval']: hashval + } process = ps.g.activity(get_id(), None, None, attrs) if isinstance(result.runtime, list): process.add_attributes({pm.PROV["type"]: nipype_ns["MapNode"]}) # add info about sub processes for idx, runtime in enumerate(result.runtime): - subresult = InterfaceResult(result.interface[idx], - runtime, outputs={}) + subresult = InterfaceResult( + result.interface[idx], runtime, outputs={}) if result.inputs: if idx < len(result.inputs): subresult.inputs = result.inputs[idx] @@ -1473,12 +1517,14 @@ def write_workflow_prov(graph, filename=None, format='all'): if isdefined(values) and idx < len(values): subresult.outputs[key] = values[idx] sub_doc = ProvStore().add_results(subresult) - sub_bundle = pm.ProvBundle(sub_doc.get_records(), - identifier=get_id()) + sub_bundle = pm.ProvBundle( + sub_doc.get_records(), identifier=get_id()) ps.g.add_bundle(sub_bundle) - bundle_entity = ps.g.entity(sub_bundle.identifier, - other_attributes={'prov:type': - pm.PROV_BUNDLE}) + bundle_entity = ps.g.entity( + sub_bundle.identifier, + other_attributes={ + 'prov:type': pm.PROV_BUNDLE + }) ps.g.wasGeneratedBy(bundle_entity, process) else: process.add_attributes({pm.PROV["type"]: nipype_ns["Node"]}) @@ -1486,20 +1532,23 @@ def write_workflow_prov(graph, filename=None, format='all'): prov_doc = result.provenance else: prov_doc = ProvStore().add_results(result) - result_bundle = pm.ProvBundle(prov_doc.get_records(), - identifier=get_id()) + result_bundle = pm.ProvBundle( + prov_doc.get_records(), identifier=get_id()) ps.g.add_bundle(result_bundle) - bundle_entity = ps.g.entity(result_bundle.identifier, - other_attributes={'prov:type': - pm.PROV_BUNDLE}) + bundle_entity = ps.g.entity( + result_bundle.identifier, + other_attributes={ + 'prov:type': pm.PROV_BUNDLE + }) ps.g.wasGeneratedBy(bundle_entity, process) processes.append(process) # add dependencies (edges) # Process->Process for idx, edgeinfo in enumerate(graph.in_edges()): - ps.g.wasStartedBy(processes[list(nodes).index(edgeinfo[1])], - starter=processes[list(nodes).index(edgeinfo[0])]) + ps.g.wasStartedBy( + processes[list(nodes).index(edgeinfo[1])], + starter=processes[list(nodes).index(edgeinfo[0])]) # write provenance ps.write_provenance(filename, format=format) @@ -1521,8 +1570,7 @@ def write_workflow_resources(graph, filename=None, append=None): filename = os.path.join(os.getcwd(), 'resource_monitor.json') if append is None: - append = str2bool(config.get( - 'monitoring', 'summary_append', 'true')) + append = str2bool(config.get('monitoring', 'summary_append', 'true')) big_dict = { 'time': [], @@ -1548,8 +1596,7 @@ def write_workflow_resources(graph, filename=None, append=None): params = '' if node.parameterization: - params = '_'.join(['{}'.format(p) - for p in node.parameterization]) + params = '_'.join(['{}'.format(p) for p in node.parameterization]) try: rt_list = node.result.runtime @@ -1603,7 +1650,9 @@ def topological_sort(graph, depth_first=False): indices = [] for node in desc: indices.append(nodesort.index(node)) - nodes.extend(np.array(nodesort)[np.array(indices)[np.argsort(indices)]].tolist()) + nodes.extend( + np.array(nodesort)[np.array(indices)[np.argsort(indices)]] + .tolist()) for node in desc: nodesort.remove(node) groups.extend([group] * len(desc)) diff --git a/nipype/pipeline/engine/workflows.py b/nipype/pipeline/engine/workflows.py index e00f105c5e..b1f7e4a173 100644 --- a/nipype/pipeline/engine/workflows.py +++ b/nipype/pipeline/engine/workflows.py @@ -14,7 +14,8 @@ os.chdir(datadir) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, bytes, open import os @@ -32,14 +33,12 @@ from ...utils.misc import str2bool from ...utils.functions import (getsource, create_function_from_source) -from ...interfaces.base import ( - traits, TraitedSpec, TraitDictObject, TraitListObject) +from ...interfaces.base import (traits, TraitedSpec, TraitDictObject, + TraitListObject) from ...utils.filemanip import save_json, makedirs, to_str -from .utils import ( - generate_expanded_graph, export_graph, write_workflow_prov, - write_workflow_resources, format_dot, topological_sort, - get_print_name, merge_dict, format_node -) +from .utils import (generate_expanded_graph, export_graph, write_workflow_prov, + write_workflow_resources, format_dot, topological_sort, + get_print_name, merge_dict, format_node) from .base import EngineBase from .nodes import MapNode @@ -153,8 +152,7 @@ def connect(self, *args, **kwargs): for srcnode, destnode, _ in connection_list: if self in [srcnode, destnode]: msg = ('Workflow connect cannot contain itself as node:' - ' src[%s] dest[%s] workflow[%s]') % (srcnode, - destnode, + ' src[%s] dest[%s] workflow[%s]') % (srcnode, destnode, self.name) raise IOError(msg) @@ -190,16 +188,17 @@ def connect(self, *args, **kwargs): connected. """ % (srcnode, source, destnode, dest, dest, destnode)) if not (hasattr(destnode, '_interface') and - ('.io' in str(destnode._interface.__class__) or - any(['.io' in str(val) for val in - destnode._interface.__class__.__bases__])) - ): + ('.io' in str(destnode._interface.__class__) or any([ + '.io' in str(val) + for val in destnode._interface.__class__.__bases__ + ]))): if not destnode._check_inputs(dest): not_found.append(['in', destnode.name, dest]) if not (hasattr(srcnode, '_interface') and - ('.io' in str(srcnode._interface.__class__) or - any(['.io' in str(val) - for val in srcnode._interface.__class__.__bases__]))): + ('.io' in str(srcnode._interface.__class__) or any([ + '.io' in str(val) + for val in srcnode._interface.__class__.__bases__ + ]))): if isinstance(source, tuple): # handles the case that source is specified # with a function @@ -207,25 +206,27 @@ def connect(self, *args, **kwargs): elif isinstance(source, (str, bytes)): sourcename = source else: - raise Exception(('Unknown source specification in ' - 'connection from output of %s') % - srcnode.name) + raise Exception( + ('Unknown source specification in ' + 'connection from output of %s') % srcnode.name) if sourcename and not srcnode._check_outputs(sourcename): not_found.append(['out', srcnode.name, sourcename]) connected_ports[destnode] += [dest] infostr = [] for info in not_found: - infostr += ["Module %s has no %sput called %s\n" % (info[1], - info[0], - info[2])] + infostr += [ + "Module %s has no %sput called %s\n" % (info[1], info[0], + info[2]) + ] if not_found: - raise Exception('\n'.join(['Some connections were not found'] + - infostr)) + raise Exception( + '\n'.join(['Some connections were not found'] + infostr)) # turn functions into strings for srcnode, destnode, connects in connection_list: for idx, (src, dest) in enumerate(connects): - if isinstance(src, tuple) and not isinstance(src[1], (str, bytes)): + if isinstance(src, + tuple) and not isinstance(src[1], (str, bytes)): function_source = getsource(src[1]) connects[idx] = ((src[0], function_source, src[2:]), dest) @@ -233,8 +234,8 @@ def connect(self, *args, **kwargs): for srcnode, destnode, connects in connection_list: edge_data = self._graph.get_edge_data(srcnode, destnode, None) if edge_data: - logger.debug('(%s, %s): Edge data exists: %s', srcnode, destnode, - to_str(edge_data)) + logger.debug('(%s, %s): Edge data exists: %s', srcnode, + destnode, to_str(edge_data)) for data in connects: if data not in edge_data['connect']: edge_data['connect'].append(data) @@ -242,19 +243,21 @@ def connect(self, *args, **kwargs): logger.debug('Removing connection: %s', to_str(data)) edge_data['connect'].remove(data) if edge_data['connect']: - self._graph.add_edges_from([(srcnode, - destnode, + self._graph.add_edges_from([(srcnode, destnode, edge_data)]) else: # pass - logger.debug('Removing connection: %s->%s', srcnode, destnode) + logger.debug('Removing connection: %s->%s', srcnode, + destnode) self._graph.remove_edges_from([(srcnode, destnode)]) elif not disconnect: logger.debug('(%s, %s): No edge data', srcnode, destnode) - self._graph.add_edges_from([(srcnode, destnode, - {'connect': connects})]) + self._graph.add_edges_from([(srcnode, destnode, { + 'connect': connects + })]) edge_data = self._graph.get_edge_data(srcnode, destnode) - logger.debug('(%s, %s): new edge data: %s', srcnode, destnode, to_str(edge_data)) + logger.debug('(%s, %s): new edge data: %s', srcnode, destnode, + to_str(edge_data)) def disconnect(self, *args): """Disconnect nodes @@ -269,7 +272,8 @@ def disconnect(self, *args): 'of connection tuples (%d args given)' % len(args)) for srcnode, dstnode, conn in connection_list: - logger.debug('disconnect(): %s->%s %s', srcnode, dstnode, to_str(conn)) + logger.debug('disconnect(): %s->%s %s', srcnode, dstnode, + to_str(conn)) if self in [srcnode, dstnode]: raise IOError( 'Workflow connect cannot contain itself as node: src[%s] ' @@ -279,8 +283,9 @@ def disconnect(self, *args): if not self._has_node(srcnode) or not self._has_node(dstnode): continue - edge_data = self._graph.get_edge_data( - srcnode, dstnode, {'connect': []}) + edge_data = self._graph.get_edge_data(srcnode, dstnode, { + 'connect': [] + }) ed_conns = [(c[0], c[1]) for c in edge_data['connect']] remove = [] @@ -323,7 +328,8 @@ def add_nodes(self, nodes): return for node in newnodes: if not issubclass(node.__class__, EngineBase): - raise Exception('Node %s must be a subclass of EngineBase', node) + raise Exception('Node %s must be a subclass of EngineBase', + node) self._check_nodes(newnodes) for node in newnodes: if node._hierarchy is None: @@ -354,8 +360,10 @@ def get_node(self, name): """ nodenames = name.split('.') nodename = nodenames[0] - outnode = [node for node in self._graph.nodes() if - str(node).endswith('.' + nodename)] + outnode = [ + node for node in self._graph.nodes() + if str(node).endswith('.' + nodename) + ] if outnode: outnode = outnode[0] if nodenames[1:] and issubclass(outnode.__class__, Workflow): @@ -370,14 +378,19 @@ def list_node_names(self): outlist = [] for node in nx.topological_sort(self._graph): if isinstance(node, Workflow): - outlist.extend(['.'.join((node.name, nodename)) for nodename in - node.list_node_names()]) + outlist.extend([ + '.'.join((node.name, nodename)) + for nodename in node.list_node_names() + ]) else: outlist.append(node.name) return sorted(outlist) - def write_graph(self, dotfilename='graph.dot', graph2use='hierarchical', - format="png", simple_form=True): + def write_graph(self, + dotfilename='graph.dot', + graph2use='hierarchical', + format="png", + simple_form=True): """Generates a graphviz dot file and a png file Parameters @@ -419,9 +432,10 @@ def write_graph(self, dotfilename='graph.dot', graph2use='hierarchical', raise ValueError('{} graph failed, workflow name cannot begin ' 'with a number'.format(graph2use)) dotfilename = op.join(base_dir, dotfilename) - self.write_hierarchical_dotfile(dotfilename=dotfilename, - colored=graph2use == "colored", - simple_form=simple_form) + self.write_hierarchical_dotfile( + dotfilename=dotfilename, + colored=graph2use == "colored", + simple_form=simple_form) outfname = format_dot(dotfilename, format=format) else: graph = self._graph @@ -429,18 +443,26 @@ def write_graph(self, dotfilename='graph.dot', graph2use='hierarchical', graph = self._create_flat_graph() if graph2use == 'exec': graph = generate_expanded_graph(deepcopy(graph)) - outfname = export_graph(graph, base_dir, dotfilename=dotfilename, - format=format, simple_form=simple_form) - - logger.info('Generated workflow graph: %s (graph2use=%s, simple_form=%s).' % ( - outfname, graph2use, simple_form)) + outfname = export_graph( + graph, + base_dir, + dotfilename=dotfilename, + format=format, + simple_form=simple_form) + + logger.info( + 'Generated workflow graph: %s (graph2use=%s, simple_form=%s).' % + (outfname, graph2use, simple_form)) return outfname - def write_hierarchical_dotfile(self, dotfilename=None, colored=False, + def write_hierarchical_dotfile(self, + dotfilename=None, + colored=False, simple_form=True): dotlist = ['digraph %s{' % self.name] - dotlist.append(self._get_dot(prefix=' ', colored=colored, - simple_form=simple_form)) + dotlist.append( + self._get_dot( + prefix=' ', colored=colored, simple_form=simple_form)) dotlist.append('}') dotstr = '\n'.join(dotlist) if dotfilename: @@ -450,7 +472,10 @@ def write_hierarchical_dotfile(self, dotfilename=None, colored=False, else: logger.info(dotstr) - def export(self, filename=None, prefix="output", format="python", + def export(self, + filename=None, + prefix="output", + format="python", include_config=False): """Export object into a different format @@ -473,8 +498,10 @@ def export(self, filename=None, prefix="output", format="python", nodes = nx.topological_sort(flatgraph) lines = ['# Workflow'] - importlines = ['from nipype.pipeline.engine import Workflow, ' - 'Node, MapNode'] + importlines = [ + 'from nipype.pipeline.engine import Workflow, ' + 'Node, MapNode' + ] functions = {} if format == "python": connect_template = '%s.connect(%%s, %%s, %%s, "%%s")' % self.name @@ -487,8 +514,8 @@ def export(self, filename=None, prefix="output", format="python", for idx, node in enumerate(nodes): nodename = node.fullname.replace('.', '_') # write nodes - nodelines = format_node(node, format='python', - include_config=include_config) + nodelines = format_node( + node, format='python', include_config=include_config) for line in nodelines: if line.startswith('from'): if line not in importlines: @@ -496,8 +523,7 @@ def export(self, filename=None, prefix="output", format="python", else: lines.append(line) # write connections - for u, _, d in flatgraph.in_edges(nbunch=node, - data=True): + for u, _, d in flatgraph.in_edges(nbunch=node, data=True): for cd in d['connect']: if isinstance(cd[0], tuple): args = list(cd[0]) @@ -505,19 +531,21 @@ def export(self, filename=None, prefix="output", format="python", funcname = functions[args[1]] else: func = create_function_from_source(args[1]) - funcname = [name for name in func.__globals__ - if name != '__builtins__'][0] + funcname = [ + name for name in func.__globals__ + if name != '__builtins__' + ][0] functions[args[1]] = funcname args[1] = funcname args = tuple([arg for arg in args if arg]) - line_args = (u.fullname.replace('.', '_'), - args, nodename, cd[1]) + line_args = (u.fullname.replace('.', '_'), args, + nodename, cd[1]) line = connect_template % line_args line = line.replace("'%s'" % funcname, funcname) lines.append(line) else: - line_args = (u.fullname.replace('.', '_'), - cd[0], nodename, cd[1]) + line_args = (u.fullname.replace('.', '_'), cd[0], + nodename, cd[1]) lines.append(connect_template2 % line_args) functionlines = ['# Functions'] for function in functions: @@ -559,7 +587,8 @@ def run(self, plugin=None, plugin_args=None, updatehash=False): runner = plugin_mod(plugin_args=plugin_args) flatgraph = self._create_flat_graph() self.config = merge_dict(deepcopy(config._sections), self.config) - logger.info('Workflow %s settings: %s', self.name, to_str(sorted(self.config))) + logger.info('Workflow %s settings: %s', self.name, + to_str(sorted(self.config))) self._set_needed_outputs(flatgraph) execgraph = generate_expanded_graph(deepcopy(flatgraph)) for index, node in enumerate(execgraph.nodes()): @@ -583,8 +612,7 @@ def run(self, plugin=None, plugin_args=None, updatehash=False): base_dir = self.base_dir or os.getcwd() write_workflow_resources( execgraph, - filename=op.join(base_dir, self.name, 'resource_monitor.json') - ) + filename=op.join(base_dir, self.name, 'resource_monitor.json')) return execgraph # PRIVATE API AND FUNCTIONS @@ -594,12 +622,12 @@ def _write_report_info(self, workingdir, name, graph): workingdir = os.getcwd() report_dir = op.join(workingdir, name) makedirs(report_dir, exist_ok=True) - shutil.copyfile(op.join(op.dirname(__file__), - 'report_template.html'), - op.join(report_dir, 'index.html')) - shutil.copyfile(op.join(op.dirname(__file__), - '..', '..', 'external', 'd3.js'), - op.join(report_dir, 'd3.js')) + shutil.copyfile( + op.join(op.dirname(__file__), 'report_template.html'), + op.join(report_dir, 'index.html')) + shutil.copyfile( + op.join(op.dirname(__file__), '..', '..', 'external', 'd3.js'), + op.join(report_dir, 'd3.js')) nodes, groups = topological_sort(graph, depth_first=True) graph_file = op.join(report_dir, 'graph1.json') json_dict = {'nodes': [], 'links': [], 'groups': [], 'maxN': 0} @@ -609,24 +637,24 @@ def _write_report_info(self, workingdir, name, graph): result_file = "%s/result_%s.pklz" % \ (node.output_dir().replace(report_dir, ''), node.name) - json_dict['nodes'].append(dict(name='%d_%s' % (i, node.name), - report=report_file, - result=result_file, - group=groups[i])) + json_dict['nodes'].append( + dict( + name='%d_%s' % (i, node.name), + report=report_file, + result=result_file, + group=groups[i])) maxN = 0 for gid in np.unique(groups): procs = [i for i, val in enumerate(groups) if val == gid] N = len(procs) if N > maxN: maxN = N - json_dict['groups'].append(dict(procs=procs, - total=N, - name='Group_%05d' % gid)) + json_dict['groups'].append( + dict(procs=procs, total=N, name='Group_%05d' % gid)) json_dict['maxN'] = maxN for u, v in graph.in_edges(): - json_dict['links'].append(dict(source=nodes.index(u), - target=nodes.index(v), - value=1)) + json_dict['links'].append( + dict(source=nodes.index(u), target=nodes.index(v), value=1)) save_json(graph_file, json_dict) graph_file = op.join(report_dir, 'graph.json') # Avoid RuntimeWarning: divide by zero encountered in log10 @@ -641,15 +669,18 @@ def getname(u, i): name_parts = u.fullname.split('.') # return '.'.join(name_parts[:-1] + [template % i + name_parts[-1]]) return template % i + name_parts[-1] + json_dict = [] for i, node in enumerate(nodes): imports = [] for u, v in graph.in_edges(nbunch=node): imports.append(getname(u, nodes.index(u))) - json_dict.append(dict(name=getname(node, i), - size=1, - group=groups[i], - imports=imports)) + json_dict.append( + dict( + name=getname(node, i), + size=1, + group=groups[i], + imports=imports)) save_json(graph_file, json_dict) def _set_needed_outputs(self, graph): @@ -661,10 +692,13 @@ def _set_needed_outputs(self, graph): node.needed_outputs = [] for edge in graph.out_edges(node): data = graph.get_edge_data(*edge) - sourceinfo = [v1[0] if isinstance(v1, tuple) else v1 - for v1, v2 in data['connect']] - node.needed_outputs += [v for v in sourceinfo - if v not in node.needed_outputs] + sourceinfo = [ + v1[0] if isinstance(v1, tuple) else v1 + for v1, v2 in data['connect'] + ] + node.needed_outputs += [ + v for v in sourceinfo if v not in node.needed_outputs + ] if node.needed_outputs: node.needed_outputs = sorted(node.needed_outputs) @@ -693,10 +727,12 @@ def _check_nodes(self, nodes): try: this_node_lineage = node_lineage[idx] except IndexError: - raise IOError('Duplicate node name "%s" found.' % node.name) + raise IOError( + 'Duplicate node name "%s" found.' % node.name) else: if this_node_lineage in [node._hierarchy, self.name]: - raise IOError('Duplicate node name "%s" found.' % node.name) + raise IOError( + 'Duplicate node name "%s" found.' % node.name) else: node_names.append(node.name) @@ -748,16 +784,15 @@ def _get_inputs(self): setattr(inputdict, node.name, node.inputs) else: taken_inputs = [] - for _, _, d in self._graph.in_edges(nbunch=node, - data=True): + for _, _, d in self._graph.in_edges(nbunch=node, data=True): for cd in d['connect']: taken_inputs.append(cd[1]) unconnectedinputs = TraitedSpec() for key, trait in list(node.inputs.items()): if key not in taken_inputs: unconnectedinputs.add_trait(key, - traits.Trait(trait, - node=node)) + traits.Trait( + trait, node=node)) value = getattr(node.inputs, key) setattr(unconnectedinputs, key, value) setattr(inputdict, node.name, unconnectedinputs) @@ -855,7 +890,8 @@ def _generate_flatgraph(self): # disconnections to take place properly. otherwise, the # edge dict is modified. # dj: added list() for networkx ver.2 - for u, _, d in list(self._graph.in_edges(nbunch=node, data=True)): + for u, _, d in list( + self._graph.in_edges(nbunch=node, data=True)): logger.debug('in: connections-> %s', to_str(d['connect'])) for cd in deepcopy(d['connect']): logger.debug("in: %s", to_str(cd)) @@ -869,7 +905,8 @@ def _generate_flatgraph(self): self.connect(srcnode, srcout, dstnode, dstin) # do not use out_edges_iter for reasons stated in in_edges # dj: for ver 2 use list(out_edges) - for _, v, d in list(self._graph.out_edges(nbunch=node, data=True)): + for _, v, d in list( + self._graph.out_edges(nbunch=node, data=True)): logger.debug('out: connections-> %s', to_str(d['connect'])) for cd in deepcopy(d['connect']): logger.debug("out: %s", to_str(cd)) @@ -878,8 +915,8 @@ def _generate_flatgraph(self): parameter = cd[0][0] else: parameter = cd[0] - srcnode = node._get_parameter_node(parameter, - subtype='out') + srcnode = node._get_parameter_node( + parameter, subtype='out') if isinstance(cd[0], tuple): srcout = list(cd[0]) srcout[0] = parameter.split('.')[-1] @@ -887,8 +924,8 @@ def _generate_flatgraph(self): else: srcout = parameter.split('.')[-1] dstin = cd[1] - logger.debug('out edges: %s %s %s %s', - srcnode, srcout, dstnode, dstin) + logger.debug('out edges: %s %s %s %s', srcnode, srcout, + dstnode, dstin) self.disconnect(node, cd[0], v, cd[1]) self.connect(srcnode, srcout, dstnode, dstin) # expand the workflow node @@ -903,19 +940,32 @@ def _generate_flatgraph(self): self._graph.remove_nodes_from(nodes2remove) logger.debug('finished expanding workflow: %s', self) - def _get_dot(self, prefix=None, hierarchy=None, colored=False, - simple_form=True, level=0): + def _get_dot(self, + prefix=None, + hierarchy=None, + colored=False, + simple_form=True, + level=0): """Create a dot file with connection info """ if prefix is None: prefix = ' ' if hierarchy is None: hierarchy = [] - colorset = ['#FFFFC8', # Y - '#0000FF', '#B4B4FF', '#E6E6FF', # B - '#FF0000', '#FFB4B4', '#FFE6E6', # R - '#00A300', '#B4FFB4', '#E6FFE6', # G - '#0000FF', '#B4B4FF'] # loop B + colorset = [ + '#FFFFC8', # Y + '#0000FF', + '#B4B4FF', + '#E6E6FF', # B + '#FF0000', + '#FFB4B4', + '#FFE6E6', # R + '#00A300', + '#B4FFB4', + '#E6FFE6', # G + '#0000FF', + '#B4B4FF' + ] # loop B if level > len(colorset) - 2: level = 3 # Loop back to blue @@ -930,17 +980,17 @@ def _get_dot(self, prefix=None, hierarchy=None, colored=False, if hasattr(node, 'iterables') and node.iterables: dotlist.append(('%s[label="%s", shape=box3d,' 'style=filled, color=black, colorscheme' - '=greys7 fillcolor=2];') % (nodename, - node_class_name)) + '=greys7 fillcolor=2];') % + (nodename, node_class_name)) else: if colored: - dotlist.append(('%s[label="%s", style=filled,' - ' fillcolor="%s"];') - % (nodename, node_class_name, - colorset[level])) + dotlist.append( + ('%s[label="%s", style=filled,' + ' fillcolor="%s"];') % (nodename, node_class_name, + colorset[level])) else: - dotlist.append(('%s[label="%s"];') - % (nodename, node_class_name)) + dotlist.append(('%s[label="%s"];') % (nodename, + node_class_name)) for node in nx.topological_sort(self._graph): if isinstance(node, Workflow): @@ -948,13 +998,18 @@ def _get_dot(self, prefix=None, hierarchy=None, colored=False, nodename = fullname.replace('.', '_') dotlist.append('subgraph cluster_%s {' % nodename) if colored: - dotlist.append(prefix + prefix + 'edge [color="%s"];' % (colorset[level + 1])) + dotlist.append(prefix + prefix + 'edge [color="%s"];' % + (colorset[level + 1])) dotlist.append(prefix + prefix + 'style=filled;') - dotlist.append(prefix + prefix + 'fillcolor="%s";' % (colorset[level + 2])) - dotlist.append(node._get_dot(prefix=prefix + prefix, - hierarchy=hierarchy + [self.name], - colored=colored, - simple_form=simple_form, level=level + 3)) + dotlist.append(prefix + prefix + 'fillcolor="%s";' % + (colorset[level + 2])) + dotlist.append( + node._get_dot( + prefix=prefix + prefix, + hierarchy=hierarchy + [self.name], + colored=colored, + simple_form=simple_form, + level=level + 3)) dotlist.append('}') else: for subnode in self._graph.successors(node): @@ -962,8 +1017,8 @@ def _get_dot(self, prefix=None, hierarchy=None, colored=False, continue if not isinstance(subnode, Workflow): nodefullname = '.'.join(hierarchy + [node.fullname]) - subnodefullname = '.'.join(hierarchy + - [subnode.fullname]) + subnodefullname = '.'.join( + hierarchy + [subnode.fullname]) nodename = nodefullname.replace('.', '_') subnodename = subnodefullname.replace('.', '_') for _ in self._graph.get_edge_data(node, diff --git a/nipype/pipeline/plugins/__init__.py b/nipype/pipeline/plugins/__init__.py index 34d3abdebc..fd93146adb 100644 --- a/nipype/pipeline/plugins/__init__.py +++ b/nipype/pipeline/plugins/__init__.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from .debug import DebugPlugin from .linear import LinearPlugin @@ -20,4 +21,4 @@ from .slurm import SLURMPlugin from .slurmgraph import SLURMGraphPlugin -from . import semaphore_singleton +from . import semaphore_singleton diff --git a/nipype/pipeline/plugins/base.py b/nipype/pipeline/plugins/base.py index ec8c68a148..f37bcff883 100644 --- a/nipype/pipeline/plugins/base.py +++ b/nipype/pipeline/plugins/base.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Common graph operations for execution """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, object, open from copy import deepcopy @@ -137,8 +138,7 @@ def run(self, graph, config, updatehash=False): progress_stats = (len(self.proc_done), np.sum(self.proc_done ^ self.proc_pending), np.sum(self.proc_done & self.proc_pending), - len(jobs_ready), - len(self.pending_tasks), + len(jobs_ready), len(self.pending_tasks), np.sum(~self.proc_done & ~self.proc_pending)) display_stats = progress_stats != old_progress_stats if display_stats: @@ -153,14 +153,19 @@ def run(self, graph, config, updatehash=False): try: result = self._get_result(taskid) except Exception: - notrun.append(self._clean_queue( - jobid, graph, result={'result': None, - 'traceback': format_exc()})) + notrun.append( + self._clean_queue( + jobid, + graph, + result={ + 'result': None, + 'traceback': format_exc() + })) else: if result: if result['traceback']: - notrun.append(self._clean_queue(jobid, graph, - result=result)) + notrun.append( + self._clean_queue(jobid, graph, result=result)) else: self._task_finished_cb(jobid) self._remove_node_dirs() @@ -220,8 +225,7 @@ def _clean_queue(self, jobid, graph, result=None): if str2bool(self._config['execution']['stop_on_first_crash']): raise RuntimeError("".join(result['traceback'])) - crashfile = self._report_crash(self.procs[jobid], - result=result) + crashfile = self._report_crash(self.procs[jobid], result=result) if jobid in self.mapnodesubids: # remove current jobid self.proc_pending[jobid] = False @@ -239,20 +243,19 @@ def _submit_mapnode(self, jobid): self.mapnodes.append(jobid) mapnodesubids = self.procs[jobid].get_subnodes() numnodes = len(mapnodesubids) - logger.debug('Adding %d jobs for mapnode %s', - numnodes, self.procs[jobid]._id) + logger.debug('Adding %d jobs for mapnode %s', numnodes, + self.procs[jobid]._id) for i in range(numnodes): self.mapnodesubids[self.depidx.shape[0] + i] = jobid self.procs.extend(mapnodesubids) - self.depidx = ssp.vstack((self.depidx, - ssp.lil_matrix(np.zeros( - (numnodes, self.depidx.shape[1])))), - 'lil') - self.depidx = ssp.hstack((self.depidx, - ssp.lil_matrix( - np.zeros((self.depidx.shape[0], - numnodes)))), - 'lil') + self.depidx = ssp.vstack( + (self.depidx, + ssp.lil_matrix(np.zeros( + (numnodes, self.depidx.shape[1])))), 'lil') + self.depidx = ssp.hstack( + (self.depidx, + ssp.lil_matrix(np.zeros( + (self.depidx.shape[0], numnodes)))), 'lil') self.depidx[-numnodes:, jobid] = 1 self.proc_done = np.concatenate((self.proc_done, np.zeros(numnodes, dtype=bool))) @@ -316,8 +319,9 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): self._task_finished_cb(jobid) self._remove_node_dirs() else: - tid = self._submit_job(deepcopy(self.procs[jobid]), - updatehash=updatehash) + tid = self._submit_job( + deepcopy(self.procs[jobid]), + updatehash=updatehash) if tid is None: self.proc_done[jobid] = False self.proc_pending[jobid] = False @@ -329,8 +333,8 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): break def _local_hash_check(self, jobid, graph): - if not str2bool(self.procs[jobid].config['execution'][ - 'local_hash_check']): + if not str2bool( + self.procs[jobid].config['execution']['local_hash_check']): return False logger.debug('Checking hash (%d) locally', jobid) @@ -339,8 +343,8 @@ def _local_hash_check(self, jobid, graph): overwrite = self.procs[jobid].overwrite always_run = self.procs[jobid]._interface.always_run - if hash_exists and (overwrite is False or - overwrite is None and not always_run): + if hash_exists and (overwrite is False + or overwrite is None and not always_run): logger.debug('Skipping cached node %s with ID %s.', self.procs[jobid]._id, jobid) try: @@ -359,9 +363,8 @@ def _task_finished_cb(self, jobid, cached=False): This is called when a job is completed. """ - logger.info('[Job %d] %s (%s).', jobid, - 'Cached' if cached else 'Completed', - self.procs[jobid].fullname) + logger.info('[Job %d] %s (%s).', jobid, 'Cached' + if cached else 'Completed', self.procs[jobid].fullname) if self._status_callback: self._status_callback(self.procs[jobid], 'end') # Update job and worker queues @@ -377,12 +380,10 @@ def _generate_dependency_list(self, graph): """ self.procs, _ = topological_sort(graph) try: - self.depidx = nx.to_scipy_sparse_matrix(graph, - nodelist=self.procs, - format='lil') + self.depidx = nx.to_scipy_sparse_matrix( + graph, nodelist=self.procs, format='lil') except: - self.depidx = nx.to_scipy_sparse_matrix(graph, - nodelist=self.procs) + self.depidx = nx.to_scipy_sparse_matrix(graph, nodelist=self.procs) self.refidx = deepcopy(self.depidx) self.refidx.astype = np.int self.proc_done = np.zeros(len(self.procs), dtype=bool) @@ -394,9 +395,8 @@ def _remove_node_deps(self, jobid, crashfile, graph): idx = self.procs.index(node) self.proc_done[idx] = True self.proc_pending[idx] = False - return dict(node=self.procs[jobid], - dependents=subnodes, - crashfile=crashfile) + return dict( + node=self.procs[jobid], dependents=subnodes, crashfile=crashfile) def _remove_node_dirs(self): """Removes directories whose outputs have already been used up @@ -466,9 +466,11 @@ def _get_result(self, taskid): logger.debug(e) sleep(2) if timed_out: - result_data = {'hostname': 'unknown', - 'result': None, - 'traceback': None} + result_data = { + 'hostname': 'unknown', + 'result': None, + 'traceback': None + } results_file = None try: error_message = ('Job id ({0}) finished or terminated, but ' @@ -501,8 +503,8 @@ def _submit_job(self, node, updatehash=False): pyscript = create_pyscript(node, updatehash=updatehash) batch_dir, name = os.path.split(pyscript) name = '.'.join(name.split('.')[:-1]) - batchscript = '\n'.join((self._template, - '%s %s' % (sys.executable, pyscript))) + batchscript = '\n'.join((self._template, '%s %s' % (sys.executable, + pyscript))) batchscriptfile = os.path.join(batch_dir, 'batchscript_%s.sh' % name) with open(batchscriptfile, 'wt') as fp: fp.writelines(batchscript) @@ -529,11 +531,12 @@ def run(self, graph, config, updatehash=False): nodes = nx.topological_sort(graph) logger.debug('Creating executable python files for each node') for idx, node in enumerate(nodes): - pyfiles.append(create_pyscript(node, - updatehash=updatehash, - store_exception=False)) - dependencies[idx] = [nodes.index(prevnode) for prevnode in - graph.predecessors(node)] + pyfiles.append( + create_pyscript( + node, updatehash=updatehash, store_exception=False)) + dependencies[idx] = [ + nodes.index(prevnode) for prevnode in graph.predecessors(node) + ] self._submit_graph(pyfiles, dependencies, nodes) def _get_args(self, node, keywords): @@ -543,18 +546,18 @@ def _get_args(self, node, keywords): if keyword == "template" and os.path.isfile(value): with open(value) as f: value = f.read() - if (hasattr(node, "plugin_args") and - isinstance(node.plugin_args, dict) and - keyword in node.plugin_args): - if (keyword == "template" and - os.path.isfile(node.plugin_args[keyword])): + if (hasattr(node, "plugin_args") + and isinstance(node.plugin_args, dict) + and keyword in node.plugin_args): + if (keyword == "template" + and os.path.isfile(node.plugin_args[keyword])): with open(node.plugin_args[keyword]) as f: tmp_value = f.read() else: tmp_value = node.plugin_args[keyword] - if ('overwrite' in node.plugin_args and - node.plugin_args['overwrite']): + if ('overwrite' in node.plugin_args + and node.plugin_args['overwrite']): value = tmp_value else: value += tmp_value diff --git a/nipype/pipeline/plugins/condor.py b/nipype/pipeline/plugins/condor.py index 0548a7afbc..ae2e46cccb 100644 --- a/nipype/pipeline/plugins/condor.py +++ b/nipype/pipeline/plugins/condor.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via Condor """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os from time import sleep @@ -47,9 +48,8 @@ def __init__(self, **kwargs): super(CondorPlugin, self).__init__(template, **kwargs) def _is_pending(self, taskid): - cmd = CommandLine('condor_q', - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'condor_q', resource_monitor=False, terminal_output='allatonce') cmd.inputs.args = '%d' % taskid # check condor cluster oldlevel = iflogger.level @@ -61,9 +61,11 @@ def _is_pending(self, taskid): return False def _submit_batchtask(self, scriptfile, node): - cmd = CommandLine('condor_qsub', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'condor_qsub', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') path = os.path.dirname(scriptfile) qsubargs = '' if self._qsub_args: @@ -81,18 +83,14 @@ def _submit_batchtask(self, scriptfile, node): if '-e' not in qsubargs: qsubargs = '%s -e %s' % (qsubargs, path) if node._hierarchy: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._hierarchy, + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._hierarchy, node._id)) else: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._id)) + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._id)) jobnameitems = jobname.split('.') jobnameitems.reverse() jobname = '.'.join(jobnameitems) - cmd.inputs.args = '%s -N %s %s' % (qsubargs, - jobname, - scriptfile) + cmd.inputs.args = '%s -N %s %s' % (qsubargs, jobname, scriptfile) oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName('CRITICAL')) tries = 0 @@ -102,7 +100,7 @@ def _submit_batchtask(self, scriptfile, node): except Exception as e: if tries < self._max_tries: tries += 1 - sleep(self._retry_timeout) # sleep 2 seconds and try again. + sleep(self._retry_timeout) # sleep 2 seconds and try again else: iflogger.setLevel(oldlevel) raise RuntimeError('\n'.join((('Could not submit condor ' diff --git a/nipype/pipeline/plugins/dagman.py b/nipype/pipeline/plugins/dagman.py index ce2a2a5592..28b766f2ea 100644 --- a/nipype/pipeline/plugins/dagman.py +++ b/nipype/pipeline/plugins/dagman.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via Condor DAGMan """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -81,21 +82,25 @@ def __init__(self, **kwargs): if 'plugin_args' in kwargs \ and not kwargs['plugin_args'] is None \ and id_ in kwargs['plugin_args']: - if id_ == 'wrapper_cmd': - val = os.path.abspath(kwargs['plugin_args'][id_]) - elif id_ == 'block': - val = kwargs['plugin_args'][id_] - else: - val = self._get_str_or_file(kwargs['plugin_args'][id_]) + if id_ == 'wrapper_cmd': + val = os.path.abspath(kwargs['plugin_args'][id_]) + elif id_ == 'block': + val = kwargs['plugin_args'][id_] + else: + val = self._get_str_or_file(kwargs['plugin_args'][id_]) setattr(self, var, val) # TODO remove after some time if 'plugin_args' in kwargs \ and not kwargs['plugin_args'] is None: plugin_args = kwargs['plugin_args'] if 'template' in plugin_args: - warn("the 'template' argument is deprecated, use 'initial_specs' instead") + warn( + "the 'template' argument is deprecated, use 'initial_specs' instead" + ) if 'submit_specs' in plugin_args: - warn("the 'submit_specs' argument is deprecated, use 'override_specs' instead") + warn( + "the 'submit_specs' argument is deprecated, use 'override_specs' instead" + ) super(CondorDAGManPlugin, self).__init__(**kwargs) def _submit_graph(self, pyfiles, dependencies, nodes): @@ -116,10 +121,9 @@ def _submit_graph(self, pyfiles, dependencies, nodes): "override_specs", "wrapper_cmd", "wrapper_args"]) # add required slots to the template - template = '%s\n%s\n%s\nqueue\n' % ( - '%(initial_specs)s', - template, - '%(override_specs)s') + template = '%s\n%s\n%s\nqueue\n' % ('%(initial_specs)s', + template, + '%(override_specs)s') batch_dir, name = os.path.split(pyscript) name = '.'.join(name.split('.')[:-1]) specs = dict( @@ -128,8 +132,7 @@ def _submit_graph(self, pyfiles, dependencies, nodes): executable=sys.executable, nodescript=pyscript, basename=os.path.join(batch_dir, name), - override_specs=override_specs - ) + override_specs=override_specs) if wrapper_cmd is not None: specs['executable'] = wrapper_cmd specs['nodescript'] = \ @@ -138,8 +141,7 @@ def _submit_graph(self, pyfiles, dependencies, nodes): pyscript) submitspec = template % specs # write submit spec for this job - submitfile = os.path.join(batch_dir, - '%s.submit' % name) + submitfile = os.path.join(batch_dir, '%s.submit' % name) with open(submitfile, 'wt') as submitfileprt: submitfileprt.writelines(submitspec) submitfileprt.close() @@ -149,13 +151,15 @@ def _submit_graph(self, pyfiles, dependencies, nodes): for child in dependencies: parents = dependencies[child] if len(parents): - dagfileptr.write('PARENT %s CHILD %i\n' - % (' '.join([str(i) for i in parents]), - child)) + dagfileptr.write('PARENT %s CHILD %i\n' % + (' '.join([str(i) for i in parents]), + child)) # hand over DAG to condor_dagman - cmd = CommandLine('condor_submit_dag', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'condor_submit_dag', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') # needs -update_submit or re-running a workflow will fail cmd.inputs.args = '%s -update_submit %s' % (self._dagman_args, dagfilename) @@ -165,7 +169,9 @@ def _submit_graph(self, pyfiles, dependencies, nodes): # wait for DAGMan to settle down, no time wasted it is already running time.sleep(10) if not os.path.exists('%s.condor.sub' % dagfilename): - raise EnvironmentError("DAGMan did not create its submit file, please check the logs") + raise EnvironmentError( + "DAGMan did not create its submit file, please check the logs" + ) # wait for completion logger.info('waiting for DAGMan to finish') lockfilename = '%s.lock' % dagfilename diff --git a/nipype/pipeline/plugins/debug.py b/nipype/pipeline/plugins/debug.py index 7c8fd451aa..9921bb9cf4 100644 --- a/nipype/pipeline/plugins/debug.py +++ b/nipype/pipeline/plugins/debug.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Debug plugin """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import networkx as nx from .base import PluginBase, logger diff --git a/nipype/pipeline/plugins/ipython.py b/nipype/pipeline/plugins/ipython.py index b19b4221f6..0ac21b04f8 100644 --- a/nipype/pipeline/plugins/ipython.py +++ b/nipype/pipeline/plugins/ipython.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Parallel workflow execution via IPython controller """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from future import standard_library standard_library.install_aliases() @@ -22,7 +23,6 @@ IPython_not_loaded = True - def execute_task(pckld_task, node_config, updatehash): from socket import gethostname from traceback import format_exc @@ -55,8 +55,10 @@ def __init__(self, plugin_args=None): valid_args = ('url_file', 'profile', 'cluster_id', 'context', 'debug', 'timeout', 'config', 'username', 'sshserver', 'sshkey', 'password', 'paramiko') - self.client_args = {arg: plugin_args[arg] - for arg in valid_args if arg in plugin_args} + self.client_args = { + arg: plugin_args[arg] + for arg in valid_args if arg in plugin_args + } self.iparallel = None self.taskclient = None self.taskmap = {} @@ -72,20 +74,24 @@ def run(self, graph, config, updatehash=False): __import__(name) self.iparallel = sys.modules[name] except ImportError as e: - raise_from(ImportError("ipyparallel not found. Parallel execution " - "will be unavailable"), e) + raise_from( + ImportError("ipyparallel not found. Parallel execution " + "will be unavailable"), e) try: self.taskclient = self.iparallel.Client(**self.client_args) except Exception as e: if isinstance(e, TimeoutError): raise_from(Exception("No IPython clients found."), e) if isinstance(e, IOError): - raise_from(Exception("ipcluster/ipcontroller has not been started"), e) + raise_from( + Exception("ipcluster/ipcontroller has not been started"), + e) if isinstance(e, ValueError): raise_from(Exception("Ipython kernel not installed"), e) else: raise e - return super(IPythonPlugin, self).run(graph, config, updatehash=updatehash) + return super(IPythonPlugin, self).run( + graph, config, updatehash=updatehash) def _get_result(self, taskid): if taskid not in self.taskmap: @@ -102,10 +108,8 @@ def _get_result(self, taskid): def _submit_job(self, node, updatehash=False): pckld_node = dumps(node, 2) - result_object = self.taskclient.load_balanced_view().apply(execute_task, - pckld_node, - node.config, - updatehash) + result_object = self.taskclient.load_balanced_view().apply( + execute_task, pckld_node, node.config, updatehash) self._taskid += 1 self.taskmap[self._taskid] = result_object return self._taskid @@ -114,8 +118,7 @@ def _report_crash(self, node, result=None): if result and result['traceback']: node._result = result['result'] node._traceback = result['traceback'] - return report_crash(node, - traceback=result['traceback']) + return report_crash(node, traceback=result['traceback']) else: return report_crash(node) diff --git a/nipype/pipeline/plugins/ipythonx.py b/nipype/pipeline/plugins/ipythonx.py index d76cdfeb98..2ab583314d 100644 --- a/nipype/pipeline/plugins/ipythonx.py +++ b/nipype/pipeline/plugins/ipythonx.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Parallel workflow execution via IPython controller """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import sys from future.utils import raise_from @@ -28,8 +29,7 @@ def __init__(self, plugin_args=None): if LooseVersion(IPyversion) > LooseVersion('0.10.1'): raise EnvironmentError(('The IPythonX plugin can only be used with' ' older IPython versions. Please use the ' - 'IPython plugin instead.' - )) + 'IPython plugin instead.')) DeprecationWarning('This plugin will be deprecated as of version 0.13') if IPython_not_loaded: raise ImportError('ipyparallel could not be imported') @@ -47,8 +47,9 @@ def run(self, graph, config, updatehash=False): __import__(name) self.ipyclient = sys.modules[name] except ImportError as e: - raise_from(ImportError("Ipython kernel not found. Parallel execution " - "will be unavailable"), e) + raise_from( + ImportError("Ipython kernel not found. Parallel " + "execution will be unavailable"), e) try: self.taskclient = self.ipyclient.TaskClient() except Exception as e: @@ -56,7 +57,8 @@ def run(self, graph, config, updatehash=False): raise_from(Exception("No IPython clients found."), e) if isinstance(e, ValueError): raise_from(Exception("Ipython kernel not installed"), e) - return super(IPythonXPlugin, self).run(graph, config, updatehash=updatehash) + return super(IPythonXPlugin, self).run( + graph, config, updatehash=updatehash) def _get_result(self, taskid): return self.taskclient.get_task_result(taskid, block=False) @@ -73,18 +75,17 @@ def _submit_job(self, node, updatehash=False): traceback = format_exception(etype,eval,etr) result = task.result """ - task = self.ipyclient.StringTask(cmdstr, - push=dict(task=node, - updatehash=updatehash), - pull=['result', 'traceback']) + task = self.ipyclient.StringTask( + cmdstr, + push=dict(task=node, updatehash=updatehash), + pull=['result', 'traceback']) return self.taskclient.run(task, block=False) def _report_crash(self, node, result=None): if result and result['traceback']: node._result = result['result'] node._traceback = result['traceback'] - return report_crash(node, - traceback=result['traceback']) + return report_crash(node, traceback=result['traceback']) else: return report_crash(node) diff --git a/nipype/pipeline/plugins/linear.py b/nipype/pipeline/plugins/linear.py index bdb61b8c44..2180d614ad 100644 --- a/nipype/pipeline/plugins/linear.py +++ b/nipype/pipeline/plugins/linear.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Local serial workflow execution """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os @@ -52,9 +53,8 @@ def run(self, graph, config, updatehash=False): crashfile = report_crash(node) # remove dependencies from queue subnodes = [s for s in dfs_preorder(graph, node)] - notrun.append(dict(node=node, - dependents=subnodes, - crashfile=crashfile)) + notrun.append( + dict(node=node, dependents=subnodes, crashfile=crashfile)) donotrun.extend(subnodes) if self._status_callback: self._status_callback(node, 'exception') diff --git a/nipype/pipeline/plugins/lsf.py b/nipype/pipeline/plugins/lsf.py index 5ee0483221..dffc1acd82 100644 --- a/nipype/pipeline/plugins/lsf.py +++ b/nipype/pipeline/plugins/lsf.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via LSF """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import re @@ -42,13 +43,13 @@ def __init__(self, **kwargs): super(LSFPlugin, self).__init__(template, **kwargs) def _is_pending(self, taskid): - """LSF lists a status of 'PEND' when a job has been submitted but is waiting to be picked up, - and 'RUN' when it is actively being processed. But _is_pending should return True until a job has - finished and is ready to be checked for completeness. So return True if status is either 'PEND' - or 'RUN'""" - cmd = CommandLine('bjobs', - resource_monitor=False, - terminal_output='allatonce') + """LSF lists a status of 'PEND' when a job has been submitted but is + waiting to be picked up, and 'RUN' when it is actively being processed. + But _is_pending should return True until a job has finished and is + ready to be checked for completeness. So return True if status is + either 'PEND' or 'RUN'""" + cmd = CommandLine( + 'bjobs', resource_monitor=False, terminal_output='allatonce') cmd.inputs.args = '%d' % taskid # check lsf task oldlevel = iflogger.level @@ -62,10 +63,11 @@ def _is_pending(self, taskid): return True def _submit_batchtask(self, scriptfile, node): - cmd = CommandLine('bsub', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') - path = os.path.dirname(scriptfile) + cmd = CommandLine( + 'bsub', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') bsubargs = '' if self._bsub_args: bsubargs = self._bsub_args @@ -78,19 +80,17 @@ def _submit_batchtask(self, scriptfile, node): if '-o' not in bsubargs: # -o outfile bsubargs = '%s -o %s' % (bsubargs, scriptfile + ".log") if '-e' not in bsubargs: - bsubargs = '%s -e %s' % (bsubargs, scriptfile + ".log") # -e error file + # -e error file + bsubargs = '%s -e %s' % (bsubargs, scriptfile + ".log") if node._hierarchy: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._hierarchy, + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._hierarchy, node._id)) else: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._id)) + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._id)) jobnameitems = jobname.split('.') jobnameitems.reverse() jobname = '.'.join(jobnameitems) - cmd.inputs.args = '%s -J %s sh %s' % (bsubargs, - jobname, + cmd.inputs.args = '%s -J %s sh %s' % (bsubargs, jobname, scriptfile) # -J job_name_spec logger.debug('bsub ' + cmd.inputs.args) oldlevel = iflogger.level diff --git a/nipype/pipeline/plugins/multiproc.py b/nipype/pipeline/plugins/multiproc.py index 86c021decd..bc66a026e5 100644 --- a/nipype/pipeline/plugins/multiproc.py +++ b/nipype/pipeline/plugins/multiproc.py @@ -6,7 +6,8 @@ Support for child processes running as non-daemons based on http://stackoverflow.com/a/8963618/1183453 """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) # Import packages from multiprocessing import Process, Pool, cpu_count, pool @@ -25,6 +26,7 @@ try: from textwrap import indent except ImportError: + def indent(text, prefix): """ A textwrap.indent replacement for Python < 3.3 """ if not prefix: @@ -32,6 +34,7 @@ def indent(text, prefix): splittext = text.splitlines(True) return prefix + prefix.join(splittext) + # Init logger logger = logging.getLogger('workflow') @@ -145,8 +148,8 @@ def __init__(self, plugin_args=None): NipypePool = NonDaemonPool if non_daemon else Pool try: - self.pool = NipypePool(processes=self.processors, - maxtasksperchild=maxtasks) + self.pool = NipypePool( + processes=self.processors, maxtasksperchild=maxtasks) except TypeError: self.pool = NipypePool(processes=self.processors) @@ -232,16 +235,20 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): tasks_list_msg = '' if logger.level <= INFO: - running_tasks = [' * %s' % self.procs[jobid].fullname - for _, jobid in self.pending_tasks] + running_tasks = [ + ' * %s' % self.procs[jobid].fullname + for _, jobid in self.pending_tasks + ] if running_tasks: tasks_list_msg = '\nCurrently running:\n' tasks_list_msg += '\n'.join(running_tasks) tasks_list_msg = indent(tasks_list_msg, ' ' * 21) - logger.info('[MultiProc] Running %d tasks, and %d jobs ready. Free ' - 'memory (GB): %0.2f/%0.2f, Free processors: %d/%d.%s', - len(self.pending_tasks), len(jobids), free_memory_gb, self.memory_gb, - free_processors, self.processors, tasks_list_msg) + logger.info( + '[MultiProc] Running %d tasks, and %d jobs ready. Free ' + 'memory (GB): %0.2f/%0.2f, Free processors: %d/%d.%s', + len(self.pending_tasks), len(jobids), free_memory_gb, + self.memory_gb, free_processors, self.processors, + tasks_list_msg) self._stats = stats if free_memory_gb < 0.01 or free_processors == 0: @@ -253,8 +260,8 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): 'be submitted to the queue. Potential deadlock') return - jobids = self._sort_jobs(jobids, - scheduler=self.plugin_args.get('scheduler')) + jobids = self._sort_jobs( + jobids, scheduler=self.plugin_args.get('scheduler')) # Run garbage collector before potentially submitting jobs gc.collect() @@ -268,9 +275,12 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): except Exception: traceback = format_exception(*sys.exc_info()) self._clean_queue( - jobid, graph, - result={'result': None, 'traceback': traceback} - ) + jobid, + graph, + result={ + 'result': None, + 'traceback': traceback + }) self.proc_pending[jobid] = False continue if num_subnodes > 1: @@ -311,9 +321,12 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): except Exception: traceback = format_exception(*sys.exc_info()) self._clean_queue( - jobid, graph, - result={'result': None, 'traceback': traceback} - ) + jobid, + graph, + result={ + 'result': None, + 'traceback': traceback + }) # Release resources self._task_finished_cb(jobid) @@ -331,8 +344,8 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): # Send job to task manager and add to pending tasks if self._status_callback: self._status_callback(self.procs[jobid], 'start') - tid = self._submit_job(deepcopy(self.procs[jobid]), - updatehash=updatehash) + tid = self._submit_job( + deepcopy(self.procs[jobid]), updatehash=updatehash) if tid is None: self.proc_done[jobid] = False self.proc_pending[jobid] = False @@ -343,6 +356,9 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): def _sort_jobs(self, jobids, scheduler='tsort'): if scheduler == 'mem_thread': - return sorted(jobids, key=lambda item: ( - self.procs[item].mem_gb, self.procs[item].n_procs)) + return sorted( + jobids, + key= + lambda item: (self.procs[item].mem_gb, self.procs[item].n_procs) + ) return jobids diff --git a/nipype/pipeline/plugins/oar.py b/nipype/pipeline/plugins/oar.py index e3f5ef7947..8880ee5093 100644 --- a/nipype/pipeline/plugins/oar.py +++ b/nipype/pipeline/plugins/oar.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via OAR http://oar.imag.fr """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, open import os @@ -15,6 +16,7 @@ from .base import SGELikeBatchManagerBase, logger iflogger = logging.getLogger('interface') + class OARPlugin(SGELikeBatchManagerBase): """Execute using OAR @@ -54,67 +56,53 @@ def __init__(self, **kwargs): def _is_pending(self, taskid): # subprocess.Popen requires taskid to be a string proc = subprocess.Popen( - ['oarstat', '-J', '-s', - '-j', taskid], + ['oarstat', '-J', '-s', '-j', taskid], stdout=subprocess.PIPE, - stderr=subprocess.PIPE - ) + stderr=subprocess.PIPE) o, e = proc.communicate() parsed_result = json.loads(o)[taskid].lower() - is_pending = ( - ('error' not in parsed_result) and - ('terminated' not in parsed_result) - ) + is_pending = (('error' not in parsed_result) + and ('terminated' not in parsed_result)) return is_pending def _submit_batchtask(self, scriptfile, node): - cmd = CommandLine('oarsub', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'oarsub', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') path = os.path.dirname(scriptfile) oarsubargs = '' if self._oarsub_args: oarsubargs = self._oarsub_args if 'oarsub_args' in node.plugin_args: - if ( - 'overwrite' in node.plugin_args and - node.plugin_args['overwrite'] - ): + if ('overwrite' in node.plugin_args + and node.plugin_args['overwrite']): oarsubargs = node.plugin_args['oarsub_args'] else: oarsubargs += (" " + node.plugin_args['oarsub_args']) if node._hierarchy: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._hierarchy, + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._hierarchy, node._id)) else: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._id)) + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._id)) jobnameitems = jobname.split('.') jobnameitems.reverse() jobname = '.'.join(jobnameitems) jobname = jobname[0:self._max_jobname_len] if '-O' not in oarsubargs: - oarsubargs = '%s -O %s' % ( - oarsubargs, - os.path.join(path, jobname + '.stdout') - ) + oarsubargs = '%s -O %s' % (oarsubargs, + os.path.join(path, jobname + '.stdout')) if '-E' not in oarsubargs: - oarsubargs = '%s -E %s' % ( - oarsubargs, - os.path.join(path, jobname + '.stderr') - ) + oarsubargs = '%s -E %s' % (oarsubargs, + os.path.join(path, jobname + '.stderr')) if '-J' not in oarsubargs: oarsubargs = '%s -J' % (oarsubargs) os.chmod(scriptfile, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE) - cmd.inputs.args = '%s -n %s -S %s' % ( - oarsubargs, - jobname, - scriptfile - ) + cmd.inputs.args = '%s -n %s -S %s' % (oarsubargs, jobname, scriptfile) oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName('CRITICAL')) diff --git a/nipype/pipeline/plugins/pbs.py b/nipype/pipeline/plugins/pbs.py index 6154abad74..3c0667605c 100644 --- a/nipype/pipeline/plugins/pbs.py +++ b/nipype/pipeline/plugins/pbs.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via PBS/Torque """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, open import os @@ -43,16 +44,17 @@ def __init__(self, **kwargs): if 'max_tries' in kwargs['plugin_args']: self._max_tries = kwargs['plugin_args']['max_tries'] if 'max_jobname_len' in kwargs['plugin_args']: - self._max_jobname_len = kwargs['plugin_args']['max_jobname_len'] + self._max_jobname_len = kwargs['plugin_args'][ + 'max_jobname_len'] super(PBSPlugin, self).__init__(template, **kwargs) def _is_pending(self, taskid): - result = CommandLine('qstat {}'.format(taskid), - environ=dict(os.environ), - terminal_output='allatonce', - resource_monitor=False, - ignore_exception=True).run() - stderr = result.runtime.stderr + result = CommandLine( + 'qstat {}'.format(taskid), + environ=dict(os.environ), + terminal_output='allatonce', + resource_monitor=False, + ignore_exception=True).run() errmsg = 'Unknown Job Id' # %s' % taskid success = 'Job has finished' if success in e: # Fix for my PBS @@ -61,9 +63,11 @@ def _is_pending(self, taskid): return errmsg not in e def _submit_batchtask(self, scriptfile, node): - cmd = CommandLine('qsub', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'qsub', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') path = os.path.dirname(scriptfile) qsubargs = '' if self._qsub_args: @@ -79,19 +83,15 @@ def _submit_batchtask(self, scriptfile, node): if '-e' not in qsubargs: qsubargs = '%s -e %s' % (qsubargs, path) if node._hierarchy: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._hierarchy, + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._hierarchy, node._id)) else: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._id)) + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._id)) jobnameitems = jobname.split('.') jobnameitems.reverse() jobname = '.'.join(jobnameitems) jobname = jobname[0:self._max_jobname_len] - cmd.inputs.args = '%s -N %s %s' % (qsubargs, - jobname, - scriptfile) + cmd.inputs.args = '%s -N %s %s' % (qsubargs, jobname, scriptfile) oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName('CRITICAL')) @@ -102,17 +102,20 @@ def _submit_batchtask(self, scriptfile, node): except Exception as e: if tries < self._max_tries: tries += 1 - sleep(self._retry_timeout) # sleep 2 seconds and try again. + # sleep 2 seconds and try again. + sleep(self._retry_timeout) else: iflogger.setLevel(oldlevel) raise RuntimeError( - 'Could not submit pbs task for node {}\n{}'.format(node._id, e)) + 'Could not submit pbs task for node {}\n{}'.format( + node._id, e)) else: break iflogger.setLevel(oldlevel) # retrieve pbs taskid taskid = result.runtime.stdout.split('.')[0] self._pending[taskid] = node.output_dir() - logger.debug('submitted pbs task: {} for node {}'.format(taskid, node._id)) + logger.debug('submitted pbs task: {} for node {}'.format( + taskid, node._id)) return taskid diff --git a/nipype/pipeline/plugins/pbsgraph.py b/nipype/pipeline/plugins/pbsgraph.py index 719b82578c..68fc651f5f 100644 --- a/nipype/pipeline/plugins/pbsgraph.py +++ b/nipype/pipeline/plugins/pbsgraph.py @@ -1,6 +1,7 @@ """Parallel workflow execution via PBS/Torque """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -33,13 +34,13 @@ def _submit_graph(self, pyfiles, dependencies, nodes): fp.writelines('#!/usr/bin/env sh\n') for idx, pyscript in enumerate(pyfiles): node = nodes[idx] - template, qsub_args = self._get_args( - node, ["template", "qsub_args"]) + template, qsub_args = self._get_args(node, + ["template", "qsub_args"]) batch_dir, name = os.path.split(pyscript) name = '.'.join(name.split('.')[:-1]) - batchscript = '\n'.join((template, - '%s %s' % (sys.executable, pyscript))) + batchscript = '\n'.join((template, '%s %s' % (sys.executable, + pyscript))) batchscriptfile = os.path.join(batch_dir, 'batchscript_%s.sh' % name) with open(batchscriptfile, 'wt') as batchfp: @@ -47,16 +48,18 @@ def _submit_graph(self, pyfiles, dependencies, nodes): batchfp.close() deps = '' if idx in dependencies: - values = ['$job%05d' % - jobid for jobid in dependencies[idx]] + values = [ + '$job%05d' % jobid for jobid in dependencies[idx] + ] if len(values): deps = '-W depend=afterok:%s' % ':'.join(values) - fp.writelines('job%05d=`qsub %s %s %s`\n' % (idx, deps, - qsub_args, - batchscriptfile)) - cmd = CommandLine('sh', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + fp.writelines('job%05d=`qsub %s %s %s`\n' % + (idx, deps, qsub_args, batchscriptfile)) + cmd = CommandLine( + 'sh', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') cmd.inputs.args = '%s' % submitjobsfile cmd.run() logger.info('submitted all jobs to queue') diff --git a/nipype/pipeline/plugins/semaphore_singleton.py b/nipype/pipeline/plugins/semaphore_singleton.py index 786026a695..96dfe657bd 100644 --- a/nipype/pipeline/plugins/semaphore_singleton.py +++ b/nipype/pipeline/plugins/semaphore_singleton.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import threading semaphore = threading.Semaphore(0) diff --git a/nipype/pipeline/plugins/sge.py b/nipype/pipeline/plugins/sge.py index 42aa4bc915..fc487e66cf 100644 --- a/nipype/pipeline/plugins/sge.py +++ b/nipype/pipeline/plugins/sge.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via SGE """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import object @@ -30,21 +31,22 @@ def sge_debug_print(message): class QJobInfo(object): - """Information about a single job created by OGE/SGE or similar Each job is responsible for knowing it's own refresh state :author Hans J. Johnson """ - def __init__(self, job_num, job_queue_state, job_time, job_queue_name, job_slots, qsub_command_line): + def __init__(self, job_num, job_queue_state, job_time, job_queue_name, + job_slots, qsub_command_line): # self._jobName = None # Ascii text name of job not unique self._job_num = int( - job_num) # The primary unique identifier for this job, must be an integer! + job_num + ) # The primary unique identifier for this job, must be an integer! # self._jobOwn = None # Who owns this job self._job_queue_state = str( - job_queue_state) # ["running","zombie",...??] + job_queue_state) # ["running","zombie",...??] # self._jobActionState = str(jobActionState) # ['r','qw','S',...??] - self._job_time = job_time # The job start time + self._job_time = job_time # The job start time self._job_info_creation_time = time.time( ) # When this job was created (for comparing against initalization) self._job_queue_name = job_queue_name # Where the job is running @@ -75,20 +77,23 @@ def is_job_state_pending(self): time_diff = (time.time() - self._job_info_creation_time) if self.is_zombie(): sge_debug_print( - "DONE! QJobInfo.IsPending found in 'zombie' list, returning False so claiming done!\n{0}".format(self)) + "DONE! QJobInfo.IsPending found in 'zombie' list, returning False so claiming done!\n{0}". + format(self)) is_pending_status = False # Job explicitly found as being completed! elif self.is_initializing() and (time_diff > 600): # if initializing for more than 5 minute, failure due to # initialization and completion before registration sge_debug_print( "FAILURE! QJobInfo.IsPending found long running at {1} seconds" - "'initializing' returning False for to break loop!\n{0}".format(self, time_diff)) + "'initializing' returning False for to break loop!\n{0}". + format(self, time_diff)) is_pending_status = True # Job initialization took too long, so report! else: # self.is_running() || self.is_pending(): is_pending_status = True # Job cache last listed as running return is_pending_status # The job is in one of the hold states - def update_info(self, job_queue_state, job_time, job_queue_name, job_slots): + def update_info(self, job_queue_state, job_time, job_queue_name, + job_slots): self._job_queue_state = job_queue_state self._job_time = job_time self._job_queue_name = job_queue_name @@ -99,11 +104,12 @@ def set_state(self, new_state): class QstatSubstitute(object): - """A wrapper for Qstat to avoid overloading the SGE/OGS server with rapid continuous qstat requests""" - def __init__(self, qstat_instant_executable='qstat', qstat_cached_executable='qstat'): + def __init__(self, + qstat_instant_executable='qstat', + qstat_cached_executable='qstat'): """ :param qstat_instant_executable: :param qstat_cached_executable: @@ -131,8 +137,9 @@ def add_startup_job(self, taskid, qsub_command_line): :return: NONE """ taskid = int(taskid) # Ensure that it is an integer - self._task_dictionary[taskid] = QJobInfo(taskid, "initializing", time.time(), - "noQueue", 1, qsub_command_line) + self._task_dictionary[taskid] = QJobInfo(taskid, "initializing", + time.time(), "noQueue", 1, + qsub_command_line) @staticmethod def _qacct_verified_complete(taskid): @@ -150,7 +157,11 @@ def _qacct_verified_complete(taskid): qacct_retries -= 1 try: proc = subprocess.Popen( - [this_command, '-o', pwd.getpwuid(os.getuid())[0], '-j', str(taskid)], + [ + this_command, '-o', + pwd.getpwuid(os.getuid())[0], '-j', + str(taskid) + ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) qacct_result, _ = proc.communicate() @@ -177,18 +188,21 @@ def _parse_qstat_job_list(self, xml_job_list): except: job_queue_name = "unknown" try: - job_slots = int(current_job_element.getElementsByTagName( - 'slots')[0].childNodes[0].data) + job_slots = int( + current_job_element.getElementsByTagName('slots')[0] + .childNodes[0].data) except: job_slots = -1 job_queue_state = current_job_element.getAttribute('state') - job_num = int(current_job_element.getElementsByTagName( - 'JB_job_number')[0].childNodes[0].data) + job_num = int( + current_job_element.getElementsByTagName('JB_job_number')[0] + .childNodes[0].data) try: job_time_text = current_job_element.getElementsByTagName( 'JAT_start_time')[0].childNodes[0].data - job_time = float(time.mktime(time.strptime( - job_time_text, "%Y-%m-%dT%H:%M:%S"))) + job_time = float( + time.mktime( + time.strptime(job_time_text, "%Y-%m-%dT%H:%M:%S"))) except: job_time = float(0.0) # Make job entry @@ -219,17 +233,20 @@ def _parse_qstat_job_list(self, xml_job_list): self._task_dictionary[dictionary_job].set_state("zombie") else: sge_debug_print("ERROR: Job not in current parselist, " - "and not in done list {0}: {1}".format(dictionary_job, - self._task_dictionary[dictionary_job])) + "and not in done list {0}: {1}".format( + dictionary_job, + self._task_dictionary[dictionary_job])) pass if self._task_dictionary[dictionary_job].is_initializing(): is_completed = self._qacct_verified_complete(dictionary_job) if is_completed: self._task_dictionary[dictionary_job].set_state("zombie") else: - sge_debug_print("ERROR: Job not in still in intializing mode, " - "and not in done list {0}: {1}".format(dictionary_job, - self._task_dictionary[dictionary_job])) + sge_debug_print( + "ERROR: Job not in still in intializing mode, " + "and not in done list {0}: {1}".format( + dictionary_job, + self._task_dictionary[dictionary_job])) pass def _run_qstat(self, reason_for_qstat, force_instant=True): @@ -252,7 +269,10 @@ def _run_qstat(self, reason_for_qstat, force_instant=True): qstat_retries -= 1 try: proc = subprocess.Popen( - [this_command, '-u', pwd.getpwuid(os.getuid())[0], '-xml', '-s', 'psrz'], + [ + this_command, '-u', + pwd.getpwuid(os.getuid())[0], '-xml', '-s', 'psrz' + ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) qstat_xml_result, _ = proc.communicate() @@ -264,9 +284,8 @@ def _run_qstat(self, reason_for_qstat, force_instant=True): break except Exception as inst: exception_message = "QstatParsingError:\n\t{0}\n\t{1}\n".format( - type( - inst), # the exception instance - inst # __str__ allows args to printed directly + type(inst), # the exception instance + inst # __str__ allows args to printed directly ) sge_debug_print(exception_message) time.sleep(5) @@ -282,24 +301,31 @@ def is_job_pending(self, task_id): # Check if the task is in the dictionary first (before running qstat) if task_id in self._task_dictionary: # Trust the cache, only False if state='zombie' - job_is_pending = self._task_dictionary[task_id].is_job_state_pending() + job_is_pending = self._task_dictionary[ + task_id].is_job_state_pending() # Double check pending jobs in case of change (since we don't check at the beginning) if job_is_pending: - self._run_qstat("checking job pending status {0}".format(task_id), False) - job_is_pending = self._task_dictionary[task_id].is_job_state_pending() + self._run_qstat( + "checking job pending status {0}".format(task_id), False) + job_is_pending = self._task_dictionary[ + task_id].is_job_state_pending() else: - self._run_qstat("checking job pending status {0}".format(task_id), True) + self._run_qstat("checking job pending status {0}".format(task_id), + True) if task_id in self._task_dictionary: # Trust the cache, only False if state='zombie' - job_is_pending = self._task_dictionary[task_id].is_job_state_pending() + job_is_pending = self._task_dictionary[ + task_id].is_job_state_pending() else: sge_debug_print("ERROR: Job {0} not in task list, " "even after forced qstat!".format(task_id)) job_is_pending = False if not job_is_pending: - sge_debug_print("DONE! Returning for {0} claiming done!".format(task_id)) + sge_debug_print( + "DONE! Returning for {0} claiming done!".format(task_id)) if task_id in self._task_dictionary: - sge_debug_print("NOTE: Adding {0} to OutOfScopeJobs list!".format(task_id)) + sge_debug_print( + "NOTE: Adding {0} to OutOfScopeJobs list!".format(task_id)) self._out_of_scope_jobs.append(int(task_id)) self._task_dictionary.pop(task_id) else: @@ -325,7 +351,6 @@ def qsub_sanitize_job_name(testjobname): class SGEPlugin(SGELikeBatchManagerBase): - """Execute using SGE (OGE not tested) The plugin_args input to run can be used to control the SGE execution. @@ -364,9 +389,11 @@ def _is_pending(self, taskid): return self._refQstatSubstitute.is_job_pending(int(taskid)) def _submit_batchtask(self, scriptfile, node): - cmd = CommandLine('qsub', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'qsub', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') path = os.path.dirname(scriptfile) qsubargs = '' if self._qsub_args: @@ -382,19 +409,15 @@ def _submit_batchtask(self, scriptfile, node): if '-e' not in qsubargs: qsubargs = '%s -e %s' % (qsubargs, path) if node._hierarchy: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._hierarchy, + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._hierarchy, node._id)) else: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._id)) + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._id)) jobnameitems = jobname.split('.') jobnameitems.reverse() jobname = '.'.join(jobnameitems) jobname = qsub_sanitize_job_name(jobname) - cmd.inputs.args = '%s -N %s %s' % (qsubargs, - jobname, - scriptfile) + cmd.inputs.args = '%s -N %s %s' % (qsubargs, jobname, scriptfile) oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName('CRITICAL')) tries = 0 @@ -417,8 +440,9 @@ def _submit_batchtask(self, scriptfile, node): iflogger.setLevel(oldlevel) # retrieve sge taskid lines = [line for line in result.runtime.stdout.split('\n') if line] - taskid = int(re.match("Your job ([0-9]*) .* has been submitted", - lines[-1]).groups()[0]) + taskid = int( + re.match("Your job ([0-9]*) .* has been submitted", + lines[-1]).groups()[0]) self._pending[taskid] = node.output_dir() self._refQstatSubstitute.add_startup_job(taskid, cmd.cmdline) logger.debug('submitted sge task: %d for node %s with %s' % diff --git a/nipype/pipeline/plugins/sgegraph.py b/nipype/pipeline/plugins/sgegraph.py index 882c455450..fa07d6a436 100644 --- a/nipype/pipeline/plugins/sgegraph.py +++ b/nipype/pipeline/plugins/sgegraph.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via SGE """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -18,10 +19,9 @@ def node_completed_status(checknode): :return: boolean value True indicates that the node does not need to be run. """ """ TODO: place this in the base.py file and refactor """ - node_state_does_not_require_overwrite = (checknode.overwrite is False or - (checknode.overwrite is None and not - checknode._interface.always_run) - ) + node_state_does_not_require_overwrite = ( + checknode.overwrite is False or + (checknode.overwrite is None and not checknode._interface.always_run)) hash_exists = False try: hash_exists, _, _, _ = checknode.hash_exists() @@ -59,7 +59,8 @@ def __init__(self, **kwargs): if 'qsub_args' in plugin_args: self._qsub_args = plugin_args['qsub_args'] if 'dont_resubmit_completed_jobs' in plugin_args: - self._dont_resubmit_completed_jobs = plugin_args['dont_resubmit_completed_jobs'] + self._dont_resubmit_completed_jobs = plugin_args[ + 'dont_resubmit_completed_jobs'] super(SGEGraphPlugin, self).__init__(**kwargs) def _submit_graph(self, pyfiles, dependencies, nodes): @@ -71,8 +72,10 @@ def make_job_name(jobnumber, nodeslist): """ job_name = 'j{0}_{1}'.format(jobnumber, nodeslist[jobnumber]._id) # Condition job_name to be a valid bash identifier (i.e. - is invalid) - job_name = job_name.replace('-', '_').replace('.', '_').replace(':', '_') + job_name = job_name.replace('-', '_').replace('.', '_').replace( + ':', '_') return job_name + batch_dir, _ = os.path.split(pyfiles[0]) submitjobsfile = os.path.join(batch_dir, 'submit_jobs.sh') @@ -87,9 +90,11 @@ def make_job_name(jobnumber, nodeslist): if node_status_done and idx in dependencies: for child_idx in dependencies[idx]: if child_idx in cache_doneness_per_node: - child_status_done = cache_doneness_per_node[child_idx] + child_status_done = cache_doneness_per_node[ + child_idx] else: - child_status_done = node_completed_status(nodes[child_idx]) + child_status_done = node_completed_status( + nodes[child_idx]) node_status_done = node_status_done and child_status_done cache_doneness_per_node[idx] = node_status_done @@ -107,8 +112,8 @@ def make_job_name(jobnumber, nodeslist): batch_dir, name = os.path.split(pyscript) name = '.'.join(name.split('.')[:-1]) - batchscript = '\n'.join((template, - '%s %s' % (sys.executable, pyscript))) + batchscript = '\n'.join( + (template, '%s %s' % (sys.executable, pyscript))) batchscriptfile = os.path.join(batch_dir, 'batchscript_%s.sh' % name) @@ -123,8 +128,9 @@ def make_job_name(jobnumber, nodeslist): values = ' ' for jobid in dependencies[idx]: # Avoid dependancies of done jobs - if not self._dont_resubmit_completed_jobs or cache_doneness_per_node[jobid] == False: - values += "${{{0}}},".format(make_job_name(jobid, nodes)) + if not self._dont_resubmit_completed_jobs or not cache_doneness_per_node[jobid]: + values += "${{{0}}},".format( + make_job_name(jobid, nodes)) if values != ' ': # i.e. if some jobs were added to dependency list values = values.rstrip(',') deps = '-hold_jid%s' % values @@ -146,9 +152,11 @@ def make_job_name(jobnumber, nodeslist): dependantIndex=deps, batchscript=batchscriptfile) fp.writelines(full_line) - cmd = CommandLine('bash', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'bash', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') cmd.inputs.args = '%s' % submitjobsfile cmd.run() logger.info('submitted all jobs to queue') diff --git a/nipype/pipeline/plugins/slurm.py b/nipype/pipeline/plugins/slurm.py index e5b797da5d..b608cbf1ee 100644 --- a/nipype/pipeline/plugins/slurm.py +++ b/nipype/pipeline/plugins/slurm.py @@ -5,7 +5,8 @@ Parallel workflow execution with SLURM ''' -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -62,10 +63,11 @@ def __init__(self, **kwargs): def _is_pending(self, taskid): # subprocess.Popen requires taskid to be a string - res = CommandLine('squeue', - args=' '.join(['-j', '%s' % taskid]), - resource_monitor=False, - terminal_output='allatonce').run() + res = CommandLine( + 'squeue', + args=' '.join(['-j', '%s' % taskid]), + resource_monitor=False, + terminal_output='allatonce').run() return res.runtime.stdout.find(str(taskid)) > -1 def _submit_batchtask(self, scriptfile, node): @@ -74,9 +76,11 @@ def _submit_batchtask(self, scriptfile, node): variable names, different command line switches, and different output formatting/processing """ - cmd = CommandLine('sbatch', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'sbatch', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') path = os.path.dirname(scriptfile) sbatch_args = '' @@ -89,22 +93,20 @@ def _submit_batchtask(self, scriptfile, node): else: sbatch_args += (" " + node.plugin_args['sbatch_args']) if '-o' not in sbatch_args: - sbatch_args = '%s -o %s' % (sbatch_args, os.path.join(path, 'slurm-%j.out')) + sbatch_args = '%s -o %s' % (sbatch_args, + os.path.join(path, 'slurm-%j.out')) if '-e' not in sbatch_args: - sbatch_args = '%s -e %s' % (sbatch_args, os.path.join(path, 'slurm-%j.out')) + sbatch_args = '%s -e %s' % (sbatch_args, + os.path.join(path, 'slurm-%j.out')) if node._hierarchy: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._hierarchy, + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._hierarchy, node._id)) else: - jobname = '.'.join((dict(os.environ)['LOGNAME'], - node._id)) + jobname = '.'.join((dict(os.environ)['LOGNAME'], node._id)) jobnameitems = jobname.split('.') jobnameitems.reverse() jobname = '.'.join(jobnameitems) - cmd.inputs.args = '%s -J %s %s' % (sbatch_args, - jobname, - scriptfile) + cmd.inputs.args = '%s -J %s %s' % (sbatch_args, jobname, scriptfile) oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName('CRITICAL')) tries = 0 @@ -114,21 +116,21 @@ def _submit_batchtask(self, scriptfile, node): except Exception as e: if tries < self._max_tries: tries += 1 - sleep(self._retry_timeout) # sleep 2 seconds and try again. + # sleep 2 seconds and try again. + sleep(self._retry_timeout) else: iflogger.setLevel(oldlevel) - raise RuntimeError('\n'.join((('Could not submit sbatch task' - ' for node %s') % node._id, - str(e)))) + raise RuntimeError('\n'.join( + (('Could not submit sbatch task' + ' for node %s') % node._id, str(e)))) else: break logger.debug('Ran command ({0})'.format(cmd.cmdline)) iflogger.setLevel(oldlevel) # retrieve taskid lines = [line for line in result.runtime.stdout.split('\n') if line] - taskid = int(re.match(self._jobid_re, - lines[-1]).groups()[0]) + taskid = int(re.match(self._jobid_re, lines[-1]).groups()[0]) self._pending[taskid] = node.output_dir() - logger.debug('submitted sbatch task: %d for node %s' % (taskid, node._id)) + logger.debug('submitted sbatch task: %d for node %s' % (taskid, + node._id)) return taskid - diff --git a/nipype/pipeline/plugins/slurmgraph.py b/nipype/pipeline/plugins/slurmgraph.py index ed571ecffe..4d85939501 100644 --- a/nipype/pipeline/plugins/slurmgraph.py +++ b/nipype/pipeline/plugins/slurmgraph.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via SLURM """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -18,10 +19,9 @@ def node_completed_status(checknode): :return: boolean value True indicates that the node does not need to be run. """ """ TODO: place this in the base.py file and refactor """ - node_state_does_not_require_overwrite = (checknode.overwrite is False or - (checknode.overwrite is None and not - checknode._interface.always_run) - ) + node_state_does_not_require_overwrite = ( + checknode.overwrite is False or + (checknode.overwrite is None and not checknode._interface.always_run)) hash_exists = False try: hash_exists, _, _, _ = checknode.hash_exists() @@ -56,7 +56,8 @@ def __init__(self, **kwargs): if 'sbatch_args' in kwargs['plugin_args']: self._sbatch_args = kwargs['plugin_args']['sbatch_args'] if 'dont_resubmit_completed_jobs' in kwargs['plugin_args']: - self._dont_resubmit_completed_jobs = kwargs['plugin_args']['dont_resubmit_completed_jobs'] + self._dont_resubmit_completed_jobs = kwargs['plugin_args'][ + 'dont_resubmit_completed_jobs'] else: self._dont_resubmit_completed_jobs = False super(SLURMGraphPlugin, self).__init__(**kwargs) @@ -70,8 +71,10 @@ def make_job_name(jobnumber, nodeslist): """ job_name = 'j{0}_{1}'.format(jobnumber, nodeslist[jobnumber]._id) # Condition job_name to be a valid bash identifier (i.e. - is invalid) - job_name = job_name.replace('-', '_').replace('.', '_').replace(':', '_') + job_name = job_name.replace('-', '_').replace('.', '_').replace( + ':', '_') return job_name + batch_dir, _ = os.path.split(pyfiles[0]) submitjobsfile = os.path.join(batch_dir, 'submit_jobs.sh') @@ -86,9 +89,11 @@ def make_job_name(jobnumber, nodeslist): if node_status_done and idx in dependencies: for child_idx in dependencies[idx]: if child_idx in cache_doneness_per_node: - child_status_done = cache_doneness_per_node[child_idx] + child_status_done = cache_doneness_per_node[ + child_idx] else: - child_status_done = node_completed_status(nodes[child_idx]) + child_status_done = node_completed_status( + nodes[child_idx]) node_status_done = node_status_done and child_status_done cache_doneness_per_node[idx] = node_status_done @@ -106,8 +111,8 @@ def make_job_name(jobnumber, nodeslist): batch_dir, name = os.path.split(pyscript) name = '.'.join(name.split('.')[:-1]) - batchscript = '\n'.join((template, - '%s %s' % (sys.executable, pyscript))) + batchscript = '\n'.join( + (template, '%s %s' % (sys.executable, pyscript))) batchscriptfile = os.path.join(batch_dir, 'batchscript_%s.sh' % name) @@ -122,8 +127,9 @@ def make_job_name(jobnumber, nodeslist): values = '' for jobid in dependencies[idx]: # Avoid dependancies of done jobs - if not self._dont_resubmit_completed_jobs or cache_doneness_per_node[jobid] == False: - values += "${{{0}}}:".format(make_job_name(jobid, nodes)) + if not self._dont_resubmit_completed_jobs or not cache_doneness_per_node[jobid]: + values += "${{{0}}}:".format( + make_job_name(jobid, nodes)) if values != '': # i.e. if some jobs were added to dependency list values = values.rstrip(':') deps = '--dependency=afterok:%s' % values @@ -145,9 +151,11 @@ def make_job_name(jobnumber, nodeslist): dependantIndex=deps, batchscript=batchscriptfile) fp.writelines(full_line) - cmd = CommandLine('bash', environ=dict(os.environ), - resource_monitor=False, - terminal_output='allatonce') + cmd = CommandLine( + 'bash', + environ=dict(os.environ), + resource_monitor=False, + terminal_output='allatonce') cmd.inputs.args = '%s' % submitjobsfile cmd.run() logger.info('submitted all jobs to queue') diff --git a/nipype/pipeline/plugins/somaflow.py b/nipype/pipeline/plugins/somaflow.py index f384e35adf..174b277c6f 100644 --- a/nipype/pipeline/plugins/somaflow.py +++ b/nipype/pipeline/plugins/somaflow.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """Parallel workflow execution via PBS/Torque """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import sys @@ -30,9 +31,7 @@ def _submit_graph(self, pyfiles, dependencies, nodes): soma_deps = [] for idx, fname in enumerate(pyfiles): name = os.path.splitext(os.path.split(fname)[1])[0] - jobs.append(Job(command=[sys.executable, - fname], - name=name)) + jobs.append(Job(command=[sys.executable, fname], name=name)) for key, values in list(dependencies.items()): for val in values: soma_deps.append((jobs[val], jobs[key])) diff --git a/nipype/pipeline/plugins/tests/test_base.py b/nipype/pipeline/plugins/tests/test_base.py index f8838e691a..49928cfe4b 100644 --- a/nipype/pipeline/plugins/tests/test_base.py +++ b/nipype/pipeline/plugins/tests/test_base.py @@ -6,12 +6,14 @@ import numpy as np import scipy.sparse as ssp + def test_scipy_sparse(): foo = ssp.lil_matrix(np.eye(3, k=1)) goo = foo.getrowview(0) goo[goo.nonzero()] = 0 assert foo[0, 1] == 0 + ''' Can use the following code to test that a mapnode crash continues successfully Need to put this into a nose-test with a timeout @@ -26,7 +28,8 @@ def func(arg1): raise Exception('arg cannot be ' + str(arg1)) return arg1 -funkynode = pe.MapNode(niu.Function(function=func, input_names=['arg1'], output_names=['out']), +funkynode = pe.MapNode(niu.Function(function=func, input_names=['arg1'], + output_names=['out']), iterfield=['arg1'], name = 'functor') funkynode.inputs.arg1 = [1,2] diff --git a/nipype/pipeline/plugins/tests/test_callback.py b/nipype/pipeline/plugins/tests/test_callback.py index 7212ff7302..29c5cbd404 100644 --- a/nipype/pipeline/plugins/tests/test_callback.py +++ b/nipype/pipeline/plugins/tests/test_callback.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """Tests for workflow callbacks """ @@ -22,7 +21,6 @@ def bad_func(): class Status(object): - def __init__(self): self.statuses = [] @@ -35,9 +33,9 @@ def test_callback_normal(tmpdir): so = Status() wf = pe.Workflow(name='test', base_dir=tmpdir.strpath) - f_node = pe.Node(niu.Function(function=func, input_names=[], - output_names=[]), - name='f_node') + f_node = pe.Node( + niu.Function(function=func, input_names=[], output_names=[]), + name='f_node') wf.add_nodes([f_node]) wf.config['execution'] = {'crashdump_dir': wf.base_dir} wf.run(plugin="Linear", plugin_args={'status_callback': so.callback}) @@ -53,9 +51,9 @@ def test_callback_exception(tmpdir): so = Status() wf = pe.Workflow(name='test', base_dir=tmpdir.strpath) - f_node = pe.Node(niu.Function(function=bad_func, input_names=[], - output_names=[]), - name='f_node') + f_node = pe.Node( + niu.Function(function=bad_func, input_names=[], output_names=[]), + name='f_node') wf.add_nodes([f_node]) wf.config['execution'] = {'crashdump_dir': wf.base_dir} try: @@ -68,14 +66,15 @@ def test_callback_exception(tmpdir): assert so.statuses[0][1] == 'start' assert so.statuses[1][1] == 'exception' + def test_callback_multiproc_normal(tmpdir): tmpdir.chdir() so = Status() wf = pe.Workflow(name='test', base_dir=tmpdir.strpath) - f_node = pe.Node(niu.Function(function=func, input_names=[], - output_names=[]), - name='f_node') + f_node = pe.Node( + niu.Function(function=func, input_names=[], output_names=[]), + name='f_node') wf.add_nodes([f_node]) wf.config['execution']['crashdump_dir'] = wf.base_dir wf.config['execution']['poll_sleep_duration'] = 2 @@ -86,20 +85,23 @@ def test_callback_multiproc_normal(tmpdir): assert so.statuses[0][1] == 'start' assert so.statuses[1][1] == 'end' + def test_callback_multiproc_exception(tmpdir): tmpdir.chdir() so = Status() wf = pe.Workflow(name='test', base_dir=tmpdir.strpath) - f_node = pe.Node(niu.Function(function=bad_func, input_names=[], - output_names=[]), - name='f_node') + f_node = pe.Node( + niu.Function(function=bad_func, input_names=[], output_names=[]), + name='f_node') wf.add_nodes([f_node]) wf.config['execution'] = {'crashdump_dir': wf.base_dir} try: - wf.run(plugin='MultiProc', - plugin_args={'status_callback': so.callback}) + wf.run( + plugin='MultiProc', plugin_args={ + 'status_callback': so.callback + }) except: pass assert len(so.statuses) == 2 @@ -107,4 +109,3 @@ def test_callback_multiproc_exception(tmpdir): assert n.name == 'f_node' assert so.statuses[0][1] == 'start' assert so.statuses[1][1] == 'exception' - diff --git a/nipype/pipeline/plugins/tests/test_debug.py b/nipype/pipeline/plugins/tests/test_debug.py index e7997ba7f0..bd06ecb775 100644 --- a/nipype/pipeline/plugins/tests/test_debug.py +++ b/nipype/pipeline/plugins/tests/test_debug.py @@ -38,15 +38,15 @@ def test_debug(tmpdir): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(DebugTestInterface(), name='mod1') - mod2 = pe.MapNode(DebugTestInterface(), iterfield=['input1'], - name='mod2') + mod2 = pe.MapNode(DebugTestInterface(), iterfield=['input1'], name='mod2') pipe.connect([(mod1, mod2, [('output1', 'input1')])]) pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 run_wf = lambda: pipe.run(plugin="Debug") - with pytest.raises(ValueError): run_wf() + with pytest.raises(ValueError): + run_wf() exc = None try: diff --git a/nipype/pipeline/plugins/tests/test_linear.py b/nipype/pipeline/plugins/tests/test_linear.py index afb916f6eb..6484432baa 100644 --- a/nipype/pipeline/plugins/tests/test_linear.py +++ b/nipype/pipeline/plugins/tests/test_linear.py @@ -33,14 +33,15 @@ def test_run_in_series(tmpdir): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=LinearTestInterface(), name='mod1') - mod2 = pe.MapNode(interface=LinearTestInterface(), - iterfield=['input1'], - name='mod2') + mod2 = pe.MapNode( + interface=LinearTestInterface(), iterfield=['input1'], name='mod2') pipe.connect([(mod1, mod2, [('output1', 'input1')])]) pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="Linear") - names = ['.'.join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [ + '.'.join((node._hierarchy, node.name)) for node in execgraph.nodes() + ] node = list(execgraph.nodes())[names.index('pipe.mod1')] result = node.get_output('output1') assert result == [1, 1] diff --git a/nipype/pipeline/plugins/tests/test_multiproc.py b/nipype/pipeline/plugins/tests/test_multiproc.py index 780763405c..7ba9001c39 100644 --- a/nipype/pipeline/plugins/tests/test_multiproc.py +++ b/nipype/pipeline/plugins/tests/test_multiproc.py @@ -38,9 +38,8 @@ def test_run_multiproc(tmpdir): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(MultiprocTestInterface(), name='mod1') - mod2 = pe.MapNode(MultiprocTestInterface(), - iterfield=['input1'], - name='mod2') + mod2 = pe.MapNode( + MultiprocTestInterface(), iterfield=['input1'], name='mod2') pipe.connect([(mod1, mod2, [('output1', 'input1')])]) pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 @@ -91,9 +90,12 @@ def test_no_more_memory_than_specified(tmpdir): max_memory = 0.5 with pytest.raises(RuntimeError): - pipe.run(plugin='MultiProc', - plugin_args={'memory_gb': max_memory, - 'n_procs': 2}) + pipe.run( + plugin='MultiProc', + plugin_args={ + 'memory_gb': max_memory, + 'n_procs': 2 + }) def test_no_more_threads_than_specified(tmpdir): @@ -113,8 +115,7 @@ def test_no_more_threads_than_specified(tmpdir): max_threads = 2 with pytest.raises(RuntimeError): - pipe.run(plugin='MultiProc', - plugin_args={'n_procs': max_threads}) + pipe.run(plugin='MultiProc', plugin_args={'n_procs': max_threads}) def test_hold_job_until_procs_available(tmpdir): @@ -133,5 +134,4 @@ def test_hold_job_until_procs_available(tmpdir): n1.inputs.input1 = 4 max_threads = 2 - pipe.run(plugin='MultiProc', - plugin_args={'n_procs': max_threads}) + pipe.run(plugin='MultiProc', plugin_args={'n_procs': max_threads}) diff --git a/nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py b/nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py index 7112aa2448..ee5f0bd6f5 100644 --- a/nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py +++ b/nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py @@ -3,11 +3,13 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Testing module for functions and classes from multiproc.py """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, open # Import packages -import os, sys +import os +import sys from tempfile import mkdtemp from shutil import rmtree import pytest @@ -59,8 +61,7 @@ def dummyFunction(filename): # create a temp file to use as the data exchange container tmpFile = tempfile.mkstemp('.txt', 'test_engine_')[1] f[n] = tmpFile # keep track of the temp file - t[n] = multiprocessing.Process(target=dummyFunction, - args=(tmpFile,)) + t[n] = multiprocessing.Process(target=dummyFunction, args=(tmpFile, )) # fire up the job t[n].start() @@ -89,6 +90,7 @@ def dummyFunction(filename): return total + def run_multiproc_nondaemon_with_flag(nondaemon_flag): ''' Start a pipe with two nodes using the resource multiproc plugin and @@ -101,14 +103,18 @@ def run_multiproc_nondaemon_with_flag(nondaemon_flag): pipe = pe.Workflow(name='pipe') - f1 = pe.Node(interface=Function(function=mytestFunction, - input_names=['insum'], - output_names=['sum_out']), - name='f1') - f2 = pe.Node(interface=Function(function=mytestFunction, - input_names=['insum'], - output_names=['sum_out']), - name='f2') + f1 = pe.Node( + interface=Function( + function=mytestFunction, + input_names=['insum'], + output_names=['sum_out']), + name='f1') + f2 = pe.Node( + interface=Function( + function=mytestFunction, + input_names=['insum'], + output_names=['sum_out']), + name='f2') pipe.connect([(f1, f2, [('sum_out', 'insum')])]) pipe.base_dir = os.getcwd() @@ -116,35 +122,44 @@ def run_multiproc_nondaemon_with_flag(nondaemon_flag): pipe.config['execution']['stop_on_first_crash'] = True - # execute the pipe using the MultiProc plugin with 2 processes and the non_daemon flag - # to enable child processes which start other multiprocessing jobs - execgraph = pipe.run(plugin="MultiProc", - plugin_args={'n_procs': 2, - 'non_daemon': nondaemon_flag}) - - names = ['.'.join((node._hierarchy, node.name)) for node in execgraph.nodes()] + # execute the pipe using the MultiProc plugin with 2 processes and the + # non_daemon flag to enable child processes which start other + # multiprocessing jobs + execgraph = pipe.run( + plugin="MultiProc", + plugin_args={ + 'n_procs': 2, + 'non_daemon': nondaemon_flag + }) + + names = [ + '.'.join((node._hierarchy, node.name)) for node in execgraph.nodes() + ] node = list(execgraph.nodes())[names.index('pipe.f2')] result = node.get_output('sum_out') os.chdir(cur_dir) rmtree(temp_dir) return result + def test_run_multiproc_nondaemon_false(): ''' - This is the entry point for the test. Two times a pipe of several multiprocessing jobs gets - executed. First, without the nondaemon flag. Second, with the nondaemon flag. + This is the entry point for the test. Two times a pipe of several + multiprocessing jobs gets executed. First, without the nondaemon flag. + Second, with the nondaemon flag. - Since the processes of the pipe start child processes, the execution only succeeds when the - non_daemon flag is on. + Since the processes of the pipe start child processes, the execution only + succeeds when the non_daemon flag is on. ''' shouldHaveFailed = False try: - # with nondaemon_flag = False, the execution should fail + # with nondaemon_flag = False, the execution should fail run_multiproc_nondaemon_with_flag(False) except: shouldHaveFailed = True assert shouldHaveFailed + def test_run_multiproc_nondaemon_true(): # with nondaemon_flag = True, the execution should succeed result = run_multiproc_nondaemon_with_flag(True) diff --git a/nipype/pipeline/plugins/tests/test_oar.py b/nipype/pipeline/plugins/tests/test_oar.py index 181aff0f6f..fd4f0b950c 100644 --- a/nipype/pipeline/plugins/tests/test_oar.py +++ b/nipype/pipeline/plugins/tests/test_oar.py @@ -39,16 +39,14 @@ def test_run_oar(): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=OarTestInterface(), name='mod1') - mod2 = pe.MapNode(interface=OarTestInterface(), - iterfield=['input1'], - name='mod2') + mod2 = pe.MapNode( + interface=OarTestInterface(), iterfield=['input1'], name='mod2') pipe.connect([(mod1, mod2, [('output1', 'input1')])]) pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="OAR") names = [ - '.'.join((node._hierarchy, node.name)) - for node in execgraph.nodes() + '.'.join((node._hierarchy, node.name)) for node in execgraph.nodes() ] node = list(execgraph.nodes())[names.index('pipe.mod1')] result = node.get_output('output1') diff --git a/nipype/pipeline/plugins/tests/test_pbs.py b/nipype/pipeline/plugins/tests/test_pbs.py index 719ffbfc72..f6aa6c88e0 100644 --- a/nipype/pipeline/plugins/tests/test_pbs.py +++ b/nipype/pipeline/plugins/tests/test_pbs.py @@ -40,14 +40,15 @@ def test_run_pbsgraph(): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=PbsTestInterface(), name='mod1') - mod2 = pe.MapNode(interface=PbsTestInterface(), - iterfield=['input1'], - name='mod2') + mod2 = pe.MapNode( + interface=PbsTestInterface(), iterfield=['input1'], name='mod2') pipe.connect([(mod1, mod2, [('output1', 'input1')])]) pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="PBSGraph") - names = ['.'.join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [ + '.'.join((node._hierarchy, node.name)) for node in execgraph.nodes() + ] node = list(execgraph.nodes())[names.index('pipe.mod1')] result = node.get_output('output1') assert result == [1, 1] diff --git a/nipype/pipeline/plugins/tests/test_somaflow.py b/nipype/pipeline/plugins/tests/test_somaflow.py index 7449d0d3ae..68cefcdc17 100644 --- a/nipype/pipeline/plugins/tests/test_somaflow.py +++ b/nipype/pipeline/plugins/tests/test_somaflow.py @@ -38,14 +38,15 @@ def test_run_somaflow(tmpdir): pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=SomaTestInterface(), name='mod1') - mod2 = pe.MapNode(interface=SomaTestInterface(), - iterfield=['input1'], - name='mod2') + mod2 = pe.MapNode( + interface=SomaTestInterface(), iterfield=['input1'], name='mod2') pipe.connect([(mod1, mod2, [('output1', 'input1')])]) pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="SomaFlow") - names = ['.'.join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [ + '.'.join((node._hierarchy, node.name)) for node in execgraph.nodes() + ] node = list(execgraph.nodes())[names.index('pipe.mod1')] result = node.get_output('output1') assert result == [1, 1] diff --git a/nipype/pipeline/plugins/tests/test_tools.py b/nipype/pipeline/plugins/tests/test_tools.py index 479cc773df..49b2de63dc 100644 --- a/nipype/pipeline/plugins/tests/test_tools.py +++ b/nipype/pipeline/plugins/tests/test_tools.py @@ -11,26 +11,31 @@ from nipype.pipeline.plugins.tools import report_crash + def test_report_crash(): with mock.patch('pickle.dump', mock.MagicMock()) as mock_pickle_dump: - with mock.patch('nipype.pipeline.plugins.tools.format_exception', mock.MagicMock()): # see iss 1517 + with mock.patch('nipype.pipeline.plugins.tools.format_exception', + mock.MagicMock()): # see iss 1517 mock_pickle_dump.return_value = True mock_node = mock.MagicMock(name='mock_node') mock_node._id = 'an_id' mock_node.config = { - 'execution' : { - 'crashdump_dir' : '.', - 'crashfile_format' : 'pklz', + 'execution': { + 'crashdump_dir': '.', + 'crashfile_format': 'pklz', } } actual_crashfile = report_crash(mock_node) - expected_crashfile = re.compile('.*/crash-.*-an_id-[0-9a-f\-]*.pklz') + expected_crashfile = re.compile( + '.*/crash-.*-an_id-[0-9a-f\-]*.pklz') - assert expected_crashfile.match(actual_crashfile).group() == actual_crashfile + assert expected_crashfile.match( + actual_crashfile).group() == actual_crashfile assert mock_pickle_dump.call_count == 1 + ''' Can use the following code to test that a mapnode crash continues successfully Need to put this into a nose-test with a timeout @@ -45,7 +50,8 @@ def func(arg1): raise Exception('arg cannot be ' + str(arg1)) return arg1 -funkynode = pe.MapNode(niu.Function(function=func, input_names=['arg1'], output_names=['out']), +funkynode = pe.MapNode(niu.Function(function=func, input_names=['arg1'], + output_names=['out']), iterfield=['arg1'], name = 'functor') funkynode.inputs.arg1 = [1,2] diff --git a/nipype/pipeline/plugins/tools.py b/nipype/pipeline/plugins/tools.py index c07a8966b6..e20a01049d 100644 --- a/nipype/pipeline/plugins/tools.py +++ b/nipype/pipeline/plugins/tools.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Common graph operations for execution """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import open import os @@ -38,8 +39,8 @@ def report_crash(node, traceback=None, hostname=None): traceback = format_exception(*sys.exc_info()) timeofcrash = strftime('%Y%m%d-%H%M%S') login_name = getpass.getuser() - crashfile = 'crash-%s-%s-%s-%s' % ( - timeofcrash, login_name, name, str(uuid.uuid4())) + crashfile = 'crash-%s-%s-%s-%s' % (timeofcrash, login_name, name, + str(uuid.uuid4())) crashdir = node.config['execution'].get('crashdump_dir', os.getcwd()) makedirs(crashdir, exist_ok=True) @@ -67,9 +68,8 @@ def report_nodes_not_run(notrun): if notrun: logger.info("***********************************") for info in notrun: - logger.error("could not run node: %s" % - '.'.join((info['node']._hierarchy, - info['node']._id))) + logger.error("could not run node: %s" % '.'.join( + (info['node']._hierarchy, info['node']._id))) logger.info("crashfile: %s" % info['crashfile']) logger.debug("The following dependent nodes were not run") for subnode in info['dependents']: @@ -85,8 +85,7 @@ def create_pyscript(node, updatehash=False, store_exception=True): if node._hierarchy: suffix = '%s_%s_%s' % (timestamp, node._hierarchy, node._id) batch_dir = os.path.join(node.base_dir, - node._hierarchy.split('.')[0], - 'batch') + node._hierarchy.split('.')[0], 'batch') else: suffix = '%s_%s' % (timestamp, node._id) batch_dir = os.path.join(node.base_dir, 'batch') diff --git a/nipype/pkg_info.py b/nipype/pkg_info.py index f1323750a1..9378d18c68 100644 --- a/nipype/pkg_info.py +++ b/nipype/pkg_info.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from future import standard_library standard_library.install_aliases() @@ -13,11 +14,12 @@ COMMIT_INFO_FNAME = 'COMMIT_INFO.txt' PY3 = sys.version_info[0] >= 3 + def pkg_commit_hash(pkg_path): ''' Get short form of commit hash given directory `pkg_path` There should be a file called 'COMMIT_INFO.txt' in `pkg_path`. This is a - file in INI file format, with at least one section: ``commit hash``, and two + file in INI file format, with at least one section: ``commit hash`` and two variables ``archive_subst_hash`` and ``install_hash``. The first has a substitution pattern in it which may have been filled by the execution of ``git archive`` if this is an archive generated that way. The second is @@ -60,10 +62,12 @@ def pkg_commit_hash(pkg_path): if install_subst != '': return 'installation', install_subst # maybe we are in a repository - proc = subprocess.Popen('git rev-parse --short HEAD', - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - cwd=pkg_path, shell=True) + proc = subprocess.Popen( + 'git rev-parse --short HEAD', + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=pkg_path, + shell=True) repo_commit, _ = proc.communicate() if repo_commit: if PY3: diff --git a/nipype/refs.py b/nipype/refs.py index 3b4d394136..0478d7ceed 100644 --- a/nipype/refs.py +++ b/nipype/refs.py @@ -3,14 +3,18 @@ # And calls this with duecredit (as in `python -m duecredit script.py`): from .external.due import due, Doi, BibTeX -due.cite(Doi("10.3389/fninf.2011.00013"), - description="A flexible, lightweight and extensible neuroimaging data" - " processing framework in Python", - path="nipype", - tags=["implementation"],) +due.cite( + Doi("10.3389/fninf.2011.00013"), + description="A flexible, lightweight and extensible neuroimaging data" + " processing framework in Python", + path="nipype", + tags=["implementation"], +) -due.cite(Doi("10.5281/zenodo.50186"), - description="A flexible, lightweight and extensible neuroimaging data" - " processing framework in Python", - path="nipype", - tags=["implementation"],) +due.cite( + Doi("10.5281/zenodo.50186"), + description="A flexible, lightweight and extensible neuroimaging data" + " processing framework in Python", + path="nipype", + tags=["implementation"], +) diff --git a/nipype/scripts/__init__.py b/nipype/scripts/__init__.py index 8b13789179..e69de29bb2 100644 --- a/nipype/scripts/__init__.py +++ b/nipype/scripts/__init__.py @@ -1 +0,0 @@ - diff --git a/nipype/scripts/cli.py b/nipype/scripts/cli.py index 520030741e..59d8672cfb 100644 --- a/nipype/scripts/cli.py +++ b/nipype/scripts/cli.py @@ -6,17 +6,20 @@ import click from .instance import list_interfaces -from .utils import (CONTEXT_SETTINGS, - UNKNOWN_OPTIONS, - ExistingDirPath, - ExistingFilePath, - UnexistingFilePath, - RegularExpression, - PythonModule, - check_not_none,) +from .utils import ( + CONTEXT_SETTINGS, + UNKNOWN_OPTIONS, + ExistingDirPath, + ExistingFilePath, + UnexistingFilePath, + RegularExpression, + PythonModule, + check_not_none, +) from .. import __version__ + # declare the CLI group @click.group(context_settings=CONTEXT_SETTINGS) def cli(): @@ -25,8 +28,12 @@ def cli(): @cli.command(context_settings=CONTEXT_SETTINGS) @click.argument('logdir', type=ExistingDirPath, callback=check_not_none) -@click.option('-r', '--regex', type=RegularExpression(), callback=check_not_none, - help='Regular expression to be searched in each traceback.') +@click.option( + '-r', + '--regex', + type=RegularExpression(), + callback=check_not_none, + help='Regular expression to be searched in each traceback.') def search(logdir, regex): """Search for tracebacks content. @@ -48,14 +55,25 @@ def search(logdir, regex): @cli.command(context_settings=CONTEXT_SETTINGS) @click.argument('crashfile', type=ExistingFilePath, callback=check_not_none) -@click.option('-r', '--rerun', is_flag=True, flag_value=True, - help='Rerun crashed node.') -@click.option('-d', '--debug', is_flag=True, flag_value=True, - help='Enable Python debugger when re-executing.') -@click.option('-i', '--ipydebug', is_flag=True, flag_value=True, - help='Enable IPython debugger when re-executing.') -@click.option('-w', '--dir', type=ExistingDirPath, - help='Directory where to run the node in.') +@click.option( + '-r', '--rerun', is_flag=True, flag_value=True, help='Rerun crashed node.') +@click.option( + '-d', + '--debug', + is_flag=True, + flag_value=True, + help='Enable Python debugger when re-executing.') +@click.option( + '-i', + '--ipydebug', + is_flag=True, + flag_value=True, + help='Enable IPython debugger when re-executing.') +@click.option( + '-w', + '--dir', + type=ExistingDirPath, + help='Directory where to run the node in.') def crash(crashfile, rerun, debug, ipydebug, dir): """Display Nipype crash files. @@ -71,9 +89,8 @@ def crash(crashfile, rerun, debug, ipydebug, dir): if debug == 'ipython': import sys from IPython.core import ultratb - sys.excepthook = ultratb.FormattedTB(mode='Verbose', - color_scheme='Linux', - call_pdb=1) + sys.excepthook = ultratb.FormattedTB( + mode='Verbose', color_scheme='Linux', call_pdb=1) display_crash_file(crashfile, rerun, debug, dir) @@ -93,13 +110,20 @@ def show(pklz_file): @cli.command(context_settings=UNKNOWN_OPTIONS) -@click.argument('module', type=PythonModule(), required=False, - callback=check_not_none) +@click.argument( + 'module', type=PythonModule(), required=False, callback=check_not_none) @click.argument('interface', type=str, required=False) -@click.option('--list', is_flag=True, flag_value=True, - help='List the available Interfaces inside the given module.') -@click.option('-h', '--help', is_flag=True, flag_value=True, - help='Show help message and exit.') +@click.option( + '--list', + is_flag=True, + flag_value=True, + help='List the available Interfaces inside the given module.') +@click.option( + '-h', + '--help', + is_flag=True, + flag_value=True, + help='Show help message and exit.') @click.pass_context def run(ctx, module, interface, list, help): """Run a Nipype Interface. @@ -128,11 +152,10 @@ def run(ctx, module, interface, list, help): elif (module_given and interface): # create the argument parser description = "Run {}".format(interface) - prog = " ".join([ctx.command_path, - module.__name__, - interface] + ctx.args) - iface_parser = argparse.ArgumentParser(description=description, - prog=prog) + prog = " ".join( + [ctx.command_path, module.__name__, interface] + ctx.args) + iface_parser = argparse.ArgumentParser( + description=description, prog=prog) # instantiate the interface node = getattr(module, interface)() @@ -152,11 +175,13 @@ def run(ctx, module, interface, list, help): args = iface_parser.parse_args(args=ctx.args) run_instance(node, args) + @cli.command(context_settings=CONTEXT_SETTINGS) def version(): """Print current version of Nipype.""" click.echo(__version__) + @cli.group() def convert(): """Export nipype interfaces to other formats.""" @@ -164,27 +189,59 @@ def convert(): @convert.command(context_settings=CONTEXT_SETTINGS) -@click.option("-i", "--interface", type=str, required=True, - help="Name of the Nipype interface to export.") -@click.option("-m", "--module", type=PythonModule(), required=True, - callback=check_not_none, - help="Module where the interface is defined.") -@click.option("-o", "--output", type=UnexistingFilePath, required=True, - callback=check_not_none, - help="JSON file name where the Boutiques descriptor will be written.") -@click.option("-t", "--ignored-template-inputs", type=str, multiple=True, - help="Interface inputs ignored in path template creations.") -@click.option("-d", "--docker-image", type=str, - help="Name of the Docker image where the Nipype interface is available.") -@click.option("-r", "--docker-index", type=str, - help="Docker index where the Docker image is stored (e.g. http://index.docker.io).") -@click.option("-n", "--ignore-template-numbers", is_flag=True, flag_value=True, - help="Ignore all numbers in path template creations.") -@click.option("-v", "--verbose", is_flag=True, flag_value=True, - help="Enable verbose output.") -def boutiques(interface, module, output, ignored_template_inputs, - docker_image, docker_index, ignore_template_numbers, - verbose): +@click.option( + "-i", + "--interface", + type=str, + required=True, + help="Name of the Nipype interface to export.") +@click.option( + "-m", + "--module", + type=PythonModule(), + required=True, + callback=check_not_none, + help="Module where the interface is defined.") +@click.option( + "-o", + "--output", + type=UnexistingFilePath, + required=True, + callback=check_not_none, + help="JSON file name where the Boutiques descriptor will be " + "written.") +@click.option( + "-t", + "--ignored-template-inputs", + type=str, + multiple=True, + help="Interface inputs ignored in path template creations.") +@click.option( + "-d", + "--docker-image", + type=str, + help="Name of the Docker image where the Nipype interface is " + "available.") +@click.option( + "-r", + "--docker-index", + type=str, + help="Docker index where the Docker image is stored (e.g. " + "http://index.docker.io).") +@click.option( + "-n", + "--ignore-template-numbers", + is_flag=True, + flag_value=True, + help="Ignore all numbers in path template creations.") +@click.option( + "-v", + "--verbose", + is_flag=True, + flag_value=True, + help="Enable verbose output.") +def boutiques(interface, module, output, ignored_template_inputs, docker_image, + docker_index, ignore_template_numbers, verbose): """Nipype to Boutiques exporter. See Boutiques specification at https://github.com/boutiques/schema. @@ -192,13 +249,9 @@ def boutiques(interface, module, output, ignored_template_inputs, from nipype.utils.nipype2boutiques import generate_boutiques_descriptor # Generates JSON string - json_string = generate_boutiques_descriptor(module, - interface, - ignored_template_inputs, - docker_image, - docker_index, - verbose, - ignore_template_numbers) + json_string = generate_boutiques_descriptor( + module, interface, ignored_template_inputs, docker_image, docker_index, + verbose, ignore_template_numbers) # Writes JSON string to file with open(output, 'w') as f: diff --git a/nipype/scripts/crash_files.py b/nipype/scripts/crash_files.py index 363e0abf80..b7b83dff5c 100644 --- a/nipype/scripts/crash_files.py +++ b/nipype/scripts/crash_files.py @@ -68,7 +68,7 @@ def display_crash_file(crashfile, rerun, debug, directory): print("\n") print("Traceback: ") print(''.join(tb)) - print ("\n") + print("\n") if rerun: if node is None: diff --git a/nipype/scripts/instance.py b/nipype/scripts/instance.py index 959bb6b82a..1f44a43bda 100644 --- a/nipype/scripts/instance.py +++ b/nipype/scripts/instance.py @@ -14,8 +14,8 @@ def import_module(module_path): absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor - for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') - will import pkg.mod). + for resolving the package name (e.g. import_module('..mod', + 'pkg.subpkg') will import pkg.mod). Parameters ---------- @@ -29,7 +29,8 @@ def import_module(module_path): try: mod = importlib.import_module(module_path) except: - raise ImportError('Error when importing object {}.'.format(module_path)) + raise ImportError( + 'Error when importing object {}.'.format(module_path)) else: return mod diff --git a/nipype/scripts/utils.py b/nipype/scripts/utils.py index e35f4d464e..f4b8a86fb1 100644 --- a/nipype/scripts/utils.py +++ b/nipype/scripts/utils.py @@ -2,7 +2,8 @@ """ Utilities for the CLI functions. """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import bytes, str @@ -13,15 +14,13 @@ from .instance import import_module from ..interfaces.base import InputMultiPath, traits - # different context options CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) -UNKNOWN_OPTIONS = dict(allow_extra_args=True, - ignore_unknown_options=True) +UNKNOWN_OPTIONS = dict(allow_extra_args=True, ignore_unknown_options=True) # specification of existing ParamTypes -ExistingDirPath = click.Path(exists=True, file_okay=False, resolve_path=True) -ExistingFilePath = click.Path(exists=True, dir_okay=False, resolve_path=True) +ExistingDirPath = click.Path(exists=True, file_okay=False, resolve_path=True) +ExistingFilePath = click.Path(exists=True, dir_okay=False, resolve_path=True) UnexistingFilePath = click.Path(dir_okay=False, resolve_path=True) @@ -40,7 +39,8 @@ def convert(self, value, param, ctx): try: rex = re.compile(value, re.IGNORECASE) except ValueError: - self.fail('%s is not a valid regular expression.' % value, param, ctx) + self.fail('%s is not a valid regular expression.' % value, param, + ctx) else: return rex @@ -61,7 +61,8 @@ def add_args_options(arg_parser, interface): """Add arguments to `arg_parser` to create a CLI for `interface`.""" inputs = interface.input_spec() for name, spec in sorted(interface.inputs.traits(transient=None).items()): - desc = "\n".join(interface._get_trait_desc(inputs, name, spec))[len(name) + 2:] + desc = "\n".join(interface._get_trait_desc(inputs, name, + spec))[len(name) + 2:] # Escape any % signs with a % desc = desc.replace('%', '%%') args = {} @@ -119,7 +120,7 @@ def add_args_options(arg_parser, interface): else: args["nargs"] = "*" if not has_multiple_inner_traits: - arg_parser.add_argument("--%s" % name, dest=name, - help=desc, **args) + arg_parser.add_argument( + "--%s" % name, dest=name, help=desc, **args) return arg_parser diff --git a/nipype/sphinxext/__init__.py b/nipype/sphinxext/__init__.py index b2033960f3..5f8ba4da2b 100644 --- a/nipype/sphinxext/__init__.py +++ b/nipype/sphinxext/__init__.py @@ -2,4 +2,5 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -from __future__ import print_function, division, absolute_import, unicode_literals +from __future__ import (print_function, division, absolute_import, + unicode_literals) diff --git a/nipype/sphinxext/plot_workflow.py b/nipype/sphinxext/plot_workflow.py index 8876a6878d..7fa0769401 100644 --- a/nipype/sphinxext/plot_workflow.py +++ b/nipype/sphinxext/plot_workflow.py @@ -108,7 +108,12 @@ """ from __future__ import print_function, division, absolute_import, unicode_literals -import sys, os, shutil, io, re, textwrap +import sys +import os +import shutil +import io +import re +import textwrap from os.path import relpath from errno import EEXIST import traceback @@ -124,14 +129,17 @@ try: # Sphinx depends on either Jinja or Jinja2 import jinja2 + def format_template(template, **kw): return jinja2.Template(template).render(**kw) except ImportError as e: missing_imports.append(str(e)) try: import jinja + def format_template(template, **kw): return jinja.from_string(template, **kw) + missing_imports.pop() except ImportError as e: missing_imports.append(str(e)) @@ -141,6 +149,7 @@ def format_template(template, **kw): PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 + def _mkdirp(folder): """ Equivalent to bash's mkdir -p @@ -158,14 +167,17 @@ def _mkdirp(folder): return folder -def wf_directive(name, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): +def wf_directive(name, arguments, options, content, lineno, content_offset, + block_text, state, state_machine): if len(missing_imports) == 0: return run(arguments, content, options, state_machine, state, lineno) else: raise ImportError('\n'.join(missing_imports)) + + wf_directive.__doc__ = __doc__ + def _option_boolean(arg): if not arg or not arg.strip(): # no argument given, assume used as a flag @@ -177,8 +189,11 @@ def _option_boolean(arg): else: raise ValueError('"%s" unknown boolean' % arg) + def _option_graph2use(arg): - return directives.choice(arg, ('hierarchical', 'colored', 'flat', 'orig', 'exec')) + return directives.choice( + arg, ('hierarchical', 'colored', 'flat', 'orig', 'exec')) + def _option_context(arg): if arg in [None, 'reset', 'close-figs']: @@ -191,8 +206,8 @@ def _option_format(arg): def _option_align(arg): - return directives.choice(arg, ("top", "middle", "bottom", "left", "center", - "right")) + return directives.choice( + arg, ("top", "middle", "bottom", "left", "center", "right")) def mark_wf_labels(app, document): @@ -231,20 +246,21 @@ def setup(app): setup.config = app.config setup.confdir = app.confdir - options = {'alt': directives.unchanged, - 'height': directives.length_or_unitless, - 'width': directives.length_or_percentage_or_unitless, - 'scale': directives.nonnegative_int, - 'align': _option_align, - 'class': directives.class_option, - 'include-source': _option_boolean, - 'format': _option_format, - 'context': _option_context, - 'nofigs': directives.flag, - 'encoding': directives.encoding, - 'graph2use': _option_graph2use, - 'simple_form': _option_boolean - } + options = { + 'alt': directives.unchanged, + 'height': directives.length_or_unitless, + 'width': directives.length_or_percentage_or_unitless, + 'scale': directives.nonnegative_int, + 'align': _option_align, + 'class': directives.class_option, + 'include-source': _option_boolean, + 'format': _option_format, + 'context': _option_context, + 'nofigs': directives.flag, + 'encoding': directives.encoding, + 'graph2use': _option_graph2use, + 'simple_form': _option_boolean + } app.add_directive('workflow', wf_directive, True, (0, 2, False), **options) app.add_config_value('graph2use', 'hierarchical', 'html') @@ -260,15 +276,17 @@ def setup(app): app.add_config_value('wf_working_directory', None, True) app.add_config_value('wf_template', None, True) - app.connect('doctree-read'.encode() if PY2 else 'doctree-read', mark_wf_labels) + app.connect('doctree-read'.encode() + if PY2 else 'doctree-read', mark_wf_labels) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata -#------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ # Doctest handling -#------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ + def contains_doctest(text): try: @@ -309,10 +327,10 @@ def remove_coding(text): sub_re = re.compile("^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE) return sub_re.sub("", text) -#------------------------------------------------------------------------------ -# Template -#------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ +# Template +# ------------------------------------------------------------------------------ TEMPLATE = """ {{ source_code }} @@ -376,6 +394,7 @@ def remove_coding(text): # :context: option wf_context = dict() + class ImageFile(object): def __init__(self, basename, dirname): self.basename = basename @@ -394,9 +413,9 @@ def out_of_date(original, derived): Returns True if derivative is out-of-date wrt original, both of which are full file paths. """ - return (not os.path.exists(derived) or - (os.path.exists(original) and - os.stat(derived).st_mtime < os.stat(original).st_mtime)) + return (not os.path.exists(derived) + or (os.path.exists(original) + and os.stat(derived).st_mtime < os.stat(original).st_mtime)) class GraphError(RuntimeError): @@ -418,13 +437,15 @@ def run_code(code, code_path, ns=None, function_name=None): try: os.chdir(setup.config.wf_working_directory) except OSError as err: - raise OSError(str(err) + '\n`wf_working_directory` option in' - 'Sphinx configuration file must be a valid ' - 'directory path') + raise OSError( + str(err) + '\n`wf_working_directory` option in' + 'Sphinx configuration file must be a valid ' + 'directory path') except TypeError as err: - raise TypeError(str(err) + '\n`wf_working_directory` option in ' - 'Sphinx configuration file must be a string or ' - 'None') + raise TypeError( + str(err) + '\n`wf_working_directory` option in ' + 'Sphinx configuration file must be a string or ' + 'None') sys.path.insert(0, setup.config.wf_working_directory) elif code_path is not None: dirname = os.path.abspath(os.path.dirname(code_path)) @@ -473,6 +494,7 @@ def _dummy_print(*arg, **kwarg): sys.stdout = stdout return ns + def get_wf_formats(config): default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200} formats = [] @@ -496,9 +518,17 @@ def get_wf_formats(config): return formats -def render_figures(code, code_path, output_dir, output_base, context, - function_name, config, graph2use, simple_form, - context_reset=False, close_figs=False): +def render_figures(code, + code_path, + output_dir, + output_base, + context, + function_name, + config, + graph2use, + simple_form, + context_reset=False, + close_figs=False): """ Run a nipype workflow creation script and save the graph in *output_dir*. Save the images under *output_dir* with file names derived from @@ -517,11 +547,13 @@ def render_figures(code, code_path, output_dir, output_base, context, img_path = img.filename(fmt) imgname, ext = os.path.splitext(os.path.basename(img_path)) ns['wf'].base_dir = output_dir - src = ns['wf'].write_graph(imgname, format=ext[1:], - graph2use=graph2use, - simple_form=simple_form) + src = ns['wf'].write_graph( + imgname, + format=ext[1:], + graph2use=graph2use, + simple_form=simple_form) shutil.move(src, img_path) - except Exception as err: + except Exception: raise GraphError(traceback.format_exc()) img.formats.append(fmt) @@ -601,9 +633,8 @@ def run(arguments, content, options, state_machine, state, lineno): source_rel_dir = source_rel_dir[1:] # build_dir: where to place output files (temporarily) - build_dir = os.path.join(os.path.dirname(setup.app.doctreedir), - 'wf_directive', - source_rel_dir) + build_dir = os.path.join( + os.path.dirname(setup.app.doctreedir), 'wf_directive', source_rel_dir) # get rid of .. in paths, also changes pathsep # see note in Python docs for warning about symbolic links on Windows. # need to compare source and dest paths at end @@ -613,14 +644,15 @@ def run(arguments, content, options, state_machine, state, lineno): os.makedirs(build_dir) # output_dir: final location in the builder's directory - dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir, - source_rel_dir)) + dest_dir = os.path.abspath( + os.path.join(setup.app.builder.outdir, source_rel_dir)) if not os.path.exists(dest_dir): - os.makedirs(dest_dir) # no problem here for me, but just use built-ins + os.makedirs(dest_dir) # no problem here for me, but just use built-ins # how to link to files from the RST file - dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir), - source_rel_dir).replace(os.path.sep, '/') + dest_dir_link = os.path.join( + relpath(setup.confdir, rst_dir), source_rel_dir).replace( + os.path.sep, '/') try: build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/') except ValueError: @@ -631,30 +663,32 @@ def run(arguments, content, options, state_machine, state, lineno): # make figures try: - results = render_figures(code, - source_file_name, - build_dir, - output_base, - keep_context, - function_name, - config, - graph2use, - simple_form, - context_reset=context_opt == 'reset', - close_figs=context_opt == 'close-figs') + results = render_figures( + code, + source_file_name, + build_dir, + output_base, + keep_context, + function_name, + config, + graph2use, + simple_form, + context_reset=context_opt == 'reset', + close_figs=context_opt == 'close-figs') errors = [] except GraphError as err: reporter = state.memo.reporter sm = reporter.system_message( - 2, "Exception occurred in plotting %s\n from %s:\n%s" % (output_base, - source_file_name, err), + 2, + "Exception occurred in plotting %s\n from %s:\n%s" % + (output_base, source_file_name, err), line=lineno) results = [(code, [])] errors = [sm] # Properly indent the caption - caption = '\n'.join(' ' + line.strip() - for line in caption.split('\n')) + caption = '\n'.join( + ' ' + line.strip() for line in caption.split('\n')) # generate output restructuredtext total_lines = [] @@ -665,8 +699,9 @@ def run(arguments, content, options, state_machine, state, lineno): lines += [row.rstrip() for row in code_piece.split('\n')] else: lines = ['.. code-block:: python', ''] - lines += [' %s' % row.rstrip() - for row in code_piece.split('\n')] + lines += [ + ' %s' % row.rstrip() for row in code_piece.split('\n') + ] source_code = "\n".join(lines) else: source_code = "" @@ -674,8 +709,10 @@ def run(arguments, content, options, state_machine, state, lineno): if nofigs: images = [] - opts = [':%s: %s' % (key, val) for key, val in list(options.items()) - if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] + opts = [ + ':%s: %s' % (key, val) for key, val in list(options.items()) + if key in ('alt', 'height', 'width', 'scale', 'align', 'class') + ] only_html = ".. only:: html" only_latex = ".. only:: latex" diff --git a/nipype/testing/__init__.py b/nipype/testing/__init__.py index 74217aacf8..9d57ba87af 100644 --- a/nipype/testing/__init__.py +++ b/nipype/testing/__init__.py @@ -16,7 +16,6 @@ template = funcfile transfm = funcfile - from . import decorators as dec from .utils import package_check, TempFATFS diff --git a/nipype/testing/decorators.py b/nipype/testing/decorators.py index 35de0cbf00..f849815700 100644 --- a/nipype/testing/decorators.py +++ b/nipype/testing/decorators.py @@ -5,7 +5,7 @@ Extend numpy's decorators to use nipype's gui and data labels. """ -from numpy.testing.decorators import * +from numpy.testing.decorators import knownfailureif, skipif from nibabel.data import DataError @@ -17,10 +17,10 @@ def make_label_dec(label, ds=None): ---------- label : str or sequence One or more labels that will be applied by the decorator to the - functions it decorates. Labels are attributes of the decorated function + functions it decorates. Labels are attributes of the decorated function with their value set to True. ds : str - An optional docstring for the resulting decorator. If not given, a + An optional docstring for the resulting decorator. If not given, a default docstring is auto-generated. Returns @@ -60,12 +60,14 @@ def decor(f): for label in labels: setattr(f, label, True) return f + # Apply the user's docstring if ds is None: ds = "Labels a test as %r" % label decor.__doc__ = ds return decor + # For tests that need further review @@ -77,8 +79,10 @@ def needs_review(msg): msg : string msg regarding the review that needs to be done """ + def skip_func(func): return skipif(True, msg)(func) + return skip_func diff --git a/nipype/testing/fixtures.py b/nipype/testing/fixtures.py index 550346d1db..fb2ed1327a 100644 --- a/nipype/testing/fixtures.py +++ b/nipype/testing/fixtures.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: - """ Pytest fixtures used in tests. """ -from __future__ import print_function, division, unicode_literals, absolute_import - +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import pytest @@ -41,7 +40,7 @@ def nifti_image_files(outdir, filelist, shape): def create_files_in_directory(request, tmpdir): cwd = tmpdir.chdir() filelist = ['a.nii', 'b.nii'] - nifti_image_files(tmpdir.strpath, filelist, shape=(3,3,3,4)) + nifti_image_files(tmpdir.strpath, filelist, shape=(3, 3, 3, 4)) def change_directory(): cwd.chdir() @@ -67,7 +66,7 @@ def change_directory(): def create_files_in_directory_plus_dummy_file(request, tmpdir): cwd = tmpdir.chdir() filelist = ['a.nii', 'b.nii'] - nifti_image_files(tmpdir.strpath, filelist, shape=(3,3,3,4)) + nifti_image_files(tmpdir.strpath, filelist, shape=(3, 3, 3, 4)) tmpdir.join('reg.dat').write('dummy file') filelist.append('reg.dat') @@ -103,12 +102,13 @@ def set_output_type(fsl_output_type): FSLCommand.set_default_output_type(Info.output_type()) return prev_output_type -@pytest.fixture(params=[None]+list(Info.ftypes)) + +@pytest.fixture(params=[None] + list(Info.ftypes)) def create_files_in_directory_plus_output_type(request, tmpdir): func_prev_type = set_output_type(request.param) origdir = tmpdir.chdir() filelist = ['a.nii', 'b.nii'] - nifti_image_files(tmpdir.strpath, filelist, shape=(3,3,3,4)) + nifti_image_files(tmpdir.strpath, filelist, shape=(3, 3, 3, 4)) out_ext = Info.output_type_to_ext(Info.output_type()) diff --git a/nipype/testing/tests/test_utils.py b/nipype/testing/tests/test_utils.py index 838c3d167a..798f640805 100644 --- a/nipype/testing/tests/test_utils.py +++ b/nipype/testing/tests/test_utils.py @@ -20,8 +20,10 @@ def test_tempfatfs(): with fatfs as tmp_dir: assert os.path.exists(tmp_dir) -@patch('subprocess.check_call', MagicMock( - side_effect=subprocess.CalledProcessError('',''))) + +@patch( + 'subprocess.check_call', + MagicMock(side_effect=subprocess.CalledProcessError('', ''))) def test_tempfatfs_calledprocesserror(): try: TempFATFS() @@ -31,6 +33,7 @@ def test_tempfatfs_calledprocesserror(): else: assert False + @patch('subprocess.check_call', MagicMock()) @patch('subprocess.Popen', MagicMock(side_effect=OSError())) def test_tempfatfs_oserror(): diff --git a/nipype/testing/utils.py b/nipype/testing/utils.py index 7c03ca6d04..716b16da78 100644 --- a/nipype/testing/utils.py +++ b/nipype/testing/utils.py @@ -3,7 +3,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Additional handy utilities for testing """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import range, object, open import os @@ -55,15 +56,14 @@ def __init__(self, size_in_mbytes=8, delay=0.5): mount_args = ['fusefat', '-o', 'rw+', '-f', vfatfile, self.vfatmount] try: - subprocess.check_call(args=mkfs_args, stdout=self.dev_null, - stderr=self.dev_null) + subprocess.check_call( + args=mkfs_args, stdout=self.dev_null, stderr=self.dev_null) except CalledProcessError as e: raise_from(IOError("mkfs.vfat failed"), e) try: - self.fusefat = subprocess.Popen(args=mount_args, - stdout=self.dev_null, - stderr=self.dev_null) + self.fusefat = subprocess.Popen( + args=mount_args, stdout=self.dev_null, stderr=self.dev_null) except OSError as e: raise_from(IOError("fusefat is not installed"), e) @@ -93,6 +93,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): self.dev_null.close() shutil.rmtree(self.tmpdir) + def save_toy_nii(ndarray, filename): toy = nb.Nifti1Image(ndarray, np.eye(4)) nb.nifti1.save(toy, filename) diff --git a/nipype/tests/test_nipype.py b/nipype/tests/test_nipype.py index 05aa1abf86..3dde1e4772 100644 --- a/nipype/tests/test_nipype.py +++ b/nipype/tests/test_nipype.py @@ -1,13 +1,14 @@ from .. import get_info + def test_nipype_info(): exception_not_raised = True try: get_info() - except Exception as e: + except Exception: exception_not_raised = False assert exception_not_raised + # def test_fail_always(): # assert False - diff --git a/nipype/utils/config.py b/nipype/utils/config.py index 15dfe0f447..15264b9ed1 100644 --- a/nipype/utils/config.py +++ b/nipype/utils/config.py @@ -9,7 +9,8 @@ @author: Chris Filo Gorgolewski ''' -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) import os import sys import errno @@ -28,7 +29,6 @@ standard_library.install_aliases() - CONFIG_DEPRECATIONS = { 'profile_runtime': ('monitoring.enabled', '1.0'), 'filemanip_level': ('logging.utils_level', '1.0'), @@ -104,15 +104,18 @@ def __init__(self, *args, **kwargs): self._resource_monitor = None if os.path.exists(config_dir): - self._config.read([os.path.join(config_dir, 'nipype.cfg'), 'nipype.cfg']) + self._config.read( + [os.path.join(config_dir, 'nipype.cfg'), 'nipype.cfg']) for option in CONFIG_DEPRECATIONS: for section in ['execution', 'logging', 'monitoring']: if self.has_option(section, option): - new_section, new_option = CONFIG_DEPRECATIONS[option][0].split('.') + new_section, new_option = CONFIG_DEPRECATIONS[option][ + 0].split('.') if not self.has_option(new_section, new_option): # Warn implicit in get - self.set(new_section, new_option, self.get(section, option)) + self.set(new_section, new_option, + self.get(section, option)) @property def cwd(self): @@ -123,15 +126,16 @@ def cwd(self): try: self._cwd = os.getcwd() except OSError: - warn('Trying to run Nipype from a nonexistent directory "{}".'.format( - os.getenv('PWD', 'unknown')), RuntimeWarning) + warn('Trying to run Nipype from a nonexistent directory "{}".'. + format(os.getenv('PWD', 'unknown')), RuntimeWarning) raise return self._cwd def set_default_config(self): """Read default settings template and set into config object""" default_cfg = DEFAULT_CONFIG_TPL( - log_dir=os.path.expanduser('~'), # Get $HOME in a platform-agnostic way + log_dir=os.path.expanduser( + '~'), # Get $HOME in a platform-agnostic way crashdump_dir=self.cwd # Read cached cwd ) @@ -160,9 +164,10 @@ def set_log_dir(self, log_dir): def get(self, section, option, default=None): """Get an option""" if option in CONFIG_DEPRECATIONS: - msg = ('Config option "%s" has been deprecated as of nipype %s. Please use ' - '"%s" instead.') % (option, CONFIG_DEPRECATIONS[option][1], - CONFIG_DEPRECATIONS[option][0]) + msg = ('Config option "%s" has been deprecated as of nipype %s. ' + 'Please use "%s" instead.') % ( + option, CONFIG_DEPRECATIONS[option][1], + CONFIG_DEPRECATIONS[option][0]) warn(msg) section, option = CONFIG_DEPRECATIONS[option][0].split('.') @@ -176,9 +181,10 @@ def set(self, section, option, value): value = str(value) if option in CONFIG_DEPRECATIONS: - msg = ('Config option "%s" has been deprecated as of nipype %s. Please use ' - '"%s" instead.') % (option, CONFIG_DEPRECATIONS[option][1], - CONFIG_DEPRECATIONS[option][0]) + msg = ('Config option "%s" has been deprecated as of nipype %s. ' + 'Please use "%s" instead.') % ( + option, CONFIG_DEPRECATIONS[option][1], + CONFIG_DEPRECATIONS[option][0]) warn(msg) section, option = CONFIG_DEPRECATIONS[option][0].split('.') @@ -248,8 +254,8 @@ def resource_monitor(self): return self._resource_monitor # Cache config from nipype config - self.resource_monitor = str2bool(self._config.get( - 'monitoring', 'enabled')) or False + self.resource_monitor = str2bool( + self._config.get('monitoring', 'enabled')) or False return self._resource_monitor @resource_monitor.setter @@ -262,7 +268,8 @@ def resource_monitor(self, value): self._resource_monitor = False elif value is True: if not self._resource_monitor: - # Before setting self._resource_monitor check psutil availability + # Before setting self._resource_monitor check psutil + # availability self._resource_monitor = False try: import psutil @@ -272,8 +279,8 @@ def resource_monitor(self, value): pass finally: if not self._resource_monitor: - warn('Could not enable the resource monitor: psutil>=5.0' - ' could not be imported.') + warn('Could not enable the resource monitor: ' + 'psutil>=5.0 could not be imported.') self._config.set('monitoring', 'enabled', ('%s' % self._resource_monitor).lower()) @@ -326,8 +333,8 @@ def _mock(): from xvfbwrapper import Xvfb except ImportError: raise RuntimeError( - 'A display server was required, but $DISPLAY is not defined ' - 'and Xvfb could not be imported.') + 'A display server was required, but $DISPLAY is not ' + 'defined and Xvfb could not be imported.') self._display = Xvfb(nolisten='tcp') self._display.start() @@ -344,7 +351,8 @@ def stop_display(self): if self._display is not None: from .. import logging self._display.stop() - logging.getLogger('interface').debug('Closing display (if virtual)') + logging.getLogger('interface').debug( + 'Closing display (if virtual)') @atexit.register diff --git a/nipype/utils/docparse.py b/nipype/utils/docparse.py index 0d6bce7d45..1df779f2ce 100644 --- a/nipype/utils/docparse.py +++ b/nipype/utils/docparse.py @@ -13,7 +13,8 @@ docstring = docparse.get_doc(better.cmd, better.opt_map) """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) from builtins import str, open, bytes import subprocess @@ -37,10 +38,8 @@ def grab_doc(cmd, trap_error=True): The command line documentation """ - proc = subprocess.Popen(cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) + proc = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = proc.communicate() if trap_error and proc.returncode: @@ -253,9 +252,10 @@ def get_doc(cmd, opt_map, help_flag=None, trap_error=True): The formated docstring """ - res = CommandLine('which %s' % cmd.split(' ')[0], - resource_monitor=False, - terminal_output='allatonce').run() + res = CommandLine( + 'which %s' % cmd.split(' ')[0], + resource_monitor=False, + terminal_output='allatonce').run() cmd_path = res.runtime.stdout.strip() if cmd_path == '': raise Exception('Command %s not found' % cmd.split(' ')[0]) @@ -289,9 +289,11 @@ def _parse_doc(doc, style=['--']): style = [style] for line in doclist: linelist = line.split() - flag = [item for i, item in enumerate(linelist) if i < 2 and - any([item.startswith(s) for s in style]) and - len(item) > 1] + flag = [ + item for i, item in enumerate(linelist) + if i < 2 and any([item.startswith(s) + for s in style]) and len(item) > 1 + ] if flag: if len(flag) == 1: style_idx = [flag[0].startswith(s) for s in style].index(True) @@ -330,9 +332,10 @@ def get_params_from_doc(cmd, style='--', help_flag=None, trap_error=True): Contains a mapping from input to command line variables """ - res = CommandLine('which %s' % cmd.split(' ')[0], - resource_monitor=False, - terminal_output='allatonce').run() + res = CommandLine( + 'which %s' % cmd.split(' ')[0], + resource_monitor=False, + terminal_output='allatonce').run() cmd_path = res.runtime.stdout.strip() if cmd_path == '': raise Exception('Command %s not found' % cmd.split(' ')[0]) diff --git a/nipype/utils/draw_gantt_chart.py b/nipype/utils/draw_gantt_chart.py index 8731aa32eb..7a52205090 100644 --- a/nipype/utils/draw_gantt_chart.py +++ b/nipype/utils/draw_gantt_chart.py @@ -5,7 +5,8 @@ Module to draw an html gantt chart from logfile produced by ``nipype.utils.profiler.log_nodes_cb()`` """ -from __future__ import print_function, division, unicode_literals, absolute_import +from __future__ import (print_function, division, unicode_literals, + absolute_import) # Import packages import sys @@ -22,12 +23,13 @@ try: import pandas as pd except ImportError: - print('Pandas not found; in order for full functionality of this module '\ + print('Pandas not found; in order for full functionality of this module ' 'install the pandas package') pass PY3 = sys.version_info[0] > 2 + def create_event_dict(start_time, nodes_list): ''' Function to generate a dictionary of event (start/finish) nodes @@ -247,9 +249,10 @@ def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes, result = '' scale = space_between_minutes / minute_scale space_between_minutes = space_between_minutes / scale - end_times = [datetime.datetime(start.year, start.month, start.day, - start.hour, start.minute, start.second) \ - for core in range(cores)] + end_times = [ + datetime.datetime(start.year, start.month, start.day, start.hour, + start.minute, start.second) for core in range(cores) + ] # For each node in the pipeline for node in nodes_list: @@ -258,9 +261,10 @@ def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes, node_finish = node['finish'] # Calculate an offset and scale duration offset = ((node_start - start).total_seconds() / 60) * scale * \ - space_between_minutes + 220 + space_between_minutes + 220 # Scale duration - scale_duration = (node['duration'] / 60) * scale * space_between_minutes + scale_duration = ( + node['duration'] / 60) * scale * space_between_minutes if scale_duration < 5: scale_duration = 5 scale_duration -= 2 @@ -269,12 +273,9 @@ def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes, for core in range(len(end_times)): if end_times[core] < node_start: left += core * 30 - end_times[core] = datetime.datetime(node_finish.year, - node_finish.month, - node_finish.day, - node_finish.hour, - node_finish.minute, - node_finish.second) + end_times[core] = datetime.datetime( + node_finish.year, node_finish.month, node_finish.day, + node_finish.hour, node_finish.minute, node_finish.second) break # Get color for node object @@ -283,14 +284,16 @@ def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes, color = 'red' # Setup dictionary for node html string insertion - node_dict = {'left' : left, - 'offset' : offset, - 'scale_duration' : scale_duration, - 'color' : color, - 'node_name' : node['name'], - 'node_dur' : node['duration'] / 60.0, - 'node_start' : node_start.strftime("%Y-%m-%d %H:%M:%S"), - 'node_finish' : node_finish.strftime("%Y-%m-%d %H:%M:%S")} + node_dict = { + 'left': left, + 'offset': offset, + 'scale_duration': scale_duration, + 'color': color, + 'node_name': node['name'], + 'node_dur': node['duration'] / 60.0, + 'node_start': node_start.strftime("%Y-%m-%d %H:%M:%S"), + 'node_finish': node_finish.strftime("%Y-%m-%d %H:%M:%S") + } # Create new node string new_node = "