Errors and Crashes

Probably the most important chapter in this section is about how to handle error and crashes. Because at the beginning you will run into a few.

For example:

  1. You specified file names or paths that don't exist.
  2. You try to give an interface a string as input, where a float value is expected or you try to specify a parameter that doesn't exist. Be sure to use the right input type and input name.
  3. You wanted to give a list of inputs [func1.nii, func2.nii, func3.nii] to a node that only expects one input file . MapNode is your solution.
  4. You wanted to run SPM's motion correction on compressed NIfTI files, i.e. *.nii.gz? SPM cannot handle that. Nipype's Gunzip interface can help.
  5. You haven't set up all necessary environment variables. Nipype for example doesn't find your MATLAB or SPM version.
  6. You forget to specify a mandatory input field.
  7. You try to connect a node to an input field that another node is already connected to.

Important note about crashfiles. Crashfiles are only created when you run a workflow, not during building a workflow. If you have a typo in a folder path, because they didn't happen during runtime, but still during workflow building.

Example Crash 1: File doesn't exist

When creating a new workflow, very often the initial errors are OSError, meaning Nipype cannot find the right files. For example, let's try to run a workflow on sub-11, that in our dataset doesn't exist.

Creating the crash


In [ ]:
from nipype import SelectFiles, Node, Workflow
from os.path import abspath as opap
from nipype.interfaces.fsl import MCFLIRT, IsotropicSmooth

# Create SelectFiles node
templates={'func': '{subject_id}/ses-test/func/{subject_id}_ses-test_task-fingerfootlips_bold.nii.gz'}
sf = Node(SelectFiles(templates),
          name='selectfiles')
sf.inputs.base_directory = opap('/data/ds000114')
sf.inputs.subject_id = 'sub-11'

# Create Motion Correction Node
mcflirt = Node(MCFLIRT(mean_vol=True,
                       save_plots=True),
               name='mcflirt')

# Create Smoothing node
smooth = Node(IsotropicSmooth(fwhm=4),
              name='smooth')

# Create a preprocessing workflow
wf = Workflow(name="preprocWF")
wf.base_dir = 'working_dir'

# Connect the three nodes to each other
wf.connect([(sf, mcflirt, [("func", "in_file")]),
            (mcflirt, smooth, [("out_file", "in_file")])])

# Let's the workflow
wf.run()


170904-05:50:16,92 workflow INFO:
	 Workflow preprocWF settings: ['check', 'execution', 'logging']
170904-05:50:16,96 workflow INFO:
	 Running serially.
170904-05:50:16,97 workflow INFO:
	 Executing node selectfiles in dir: /repos/nipype_tutorial/notebooks/working_dir/preprocWF/selectfiles
170904-05:50:16,102 workflow ERROR:
	 ['Node selectfiles failed to run on host e97878eefcf3.']
170904-05:50:16,104 workflow INFO:
	 Saving crash info to /repos/nipype_tutorial/notebooks/crash-20170904-055016-neuro-selectfiles-6d0af5ee-49f0-40e4-8340-9c229c8ede47.pklz
170904-05:50:16,106 workflow INFO:
	 Traceback (most recent call last):
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/linear.py", line 43, in run
    node.run(updatehash=updatehash)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 372, in run
    self._run_interface()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 482, in _run_interface
    self._result = self._run_command(execute)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 613, in _run_command
    result = self._interface.run()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1085, in run
    outputs = self.aggregate_outputs(runtime)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1156, in aggregate_outputs
    predicted_outputs = self._list_outputs()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/io.py", line 1314, in _list_outputs
    raise IOError(msg)
OSError: No files were found matching func template: /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz
Interface SelectFiles failed to run. 

170904-05:50:16,108 workflow INFO:
	 ***********************************
170904-05:50:16,110 workflow ERROR:
	 could not run node: preprocWF.selectfiles
170904-05:50:16,111 workflow INFO:
	 crashfile: /repos/nipype_tutorial/notebooks/crash-20170904-055016-neuro-selectfiles-6d0af5ee-49f0-40e4-8340-9c229c8ede47.pklz
170904-05:50:16,112 workflow INFO:
	 ***********************************
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-19-2d6e16b9d5a9> in <module>()
     28 
     29 # Let's the workflow
---> 30 wf.run()

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/workflows.py in run(self, plugin, plugin_args, updatehash)
    588         if str2bool(self.config['execution']['create_report']):
    589             self._write_report_info(self.base_dir, self.name, execgraph)
--> 590         runner.run(execgraph, updatehash=updatehash, config=self.config)
    591         datestr = datetime.utcnow().strftime('%Y%m%dT%H%M%S')
    592         if str2bool(self.config['execution']['write_provenance']):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/linear.py in run(self, graph, config, updatehash)
     59                 if self._status_callback:
     60                     self._status_callback(node, 'exception')
---> 61         report_nodes_not_run(notrun)

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/base.py in report_nodes_not_run(notrun)
     99                 logger.debug(subnode._id)
    100         logger.info("***********************************")
--> 101         raise RuntimeError(('Workflow did not execute cleanly. '
    102                             'Check log for details'))
    103 

RuntimeError: Workflow did not execute cleanly. Check log for details

Investigating the crash

Hidden, in the log file you can find the relevant information:

OSError: No files were found matching func template: /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz
Interface SelectFiles failed to run. 

170904-05:48:13,727 workflow INFO:
     ***********************************
170904-05:48:13,728 workflow ERROR:
     could not run node: preprocWF.selectfiles
170904-05:48:13,730 workflow INFO:
     crashfile: /repos/nipype_tutorial/notebooks/crash-20170904-054813-neuro-selectfiles-15f5400a-452e-4e0c-ae99-fc0d4b9a44f3.pklz
170904-05:48:13,731 workflow INFO:
     ***********************************

This part tells you that it's an OSError and that it looked for the file /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz.

After the line ***********************************, you can additional see, that it's the node preprocWF.selectfiles that crasehd and that you can find a crashfile to this crash under /opt/tutorial/notebooks.

Reading the crashfile

To get the full picture of the error, we can read the content of the crashfile (that has pklz format by default) with the bash command nipypecli crash. We will get the same information as above, but additionally, we can also see directly the input values of the Node that crashed.


In [ ]:
!nipypecli crash $(pwd)/crash-*selectfiles-*.pklz



File: /repos/nipype_tutorial/notebooks/crash-20170904-054813-neuro-selectfiles-15f5400a-452e-4e0c-ae99-fc0d4b9a44f3.pklz
Node: preprocWF.selectfiles
Working directory: /repos/nipype_tutorial/notebooks/working_dir/preprocWF/selectfiles


Node inputs:

base_directory = /data/ds000114
force_lists = False
ignore_exception = False
raise_on_empty = True
sort_filelist = True
subject_id = sub-11



Traceback: 
Traceback (most recent call last):
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/linear.py", line 43, in run
    node.run(updatehash=updatehash)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 372, in run
    self._run_interface()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 482, in _run_interface
    self._result = self._run_command(execute)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 613, in _run_command
    result = self._interface.run()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1085, in run
    outputs = self.aggregate_outputs(runtime)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1156, in aggregate_outputs
    predicted_outputs = self._list_outputs()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/io.py", line 1314, in _list_outputs
    raise IOError(msg)
OSError: No files were found matching func template: /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz
Interface SelectFiles failed to run. 



nipypecli allows you to rerun the crashed node using an additional option -r.


In [ ]:
!nipypecli crash -r $(pwd)/crash-*selectfiles-*.pklz



File: /repos/nipype_tutorial/notebooks/crash-20170904-054813-neuro-selectfiles-15f5400a-452e-4e0c-ae99-fc0d4b9a44f3.pklz
Node: preprocWF.selectfiles
Working directory: /repos/nipype_tutorial/notebooks/working_dir/preprocWF/selectfiles


Node inputs:

base_directory = /data/ds000114
force_lists = False
ignore_exception = False
raise_on_empty = True
sort_filelist = True
subject_id = sub-11



Traceback: 
Traceback (most recent call last):
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/linear.py", line 43, in run
    node.run(updatehash=updatehash)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 372, in run
    self._run_interface()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 482, in _run_interface
    self._result = self._run_command(execute)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 613, in _run_command
    result = self._interface.run()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1085, in run
    outputs = self.aggregate_outputs(runtime)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1156, in aggregate_outputs
    predicted_outputs = self._list_outputs()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/io.py", line 1314, in _list_outputs
    raise IOError(msg)
OSError: No files were found matching func template: /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz
Interface SelectFiles failed to run. 



Rerunning node
170904-05:48:16,670 workflow INFO:
	 Executing node selectfiles in dir: /tmp/tmp0_9bzwog/preprocWF/selectfiles
Traceback (most recent call last):
  File "/opt/conda/envs/neuro3/bin/nipypecli", line 11, in <module>
    load_entry_point('nipype==1.0.0.dev0', 'console_scripts', 'nipypecli')()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/click/core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/scripts/cli.py", line 77, in crash
    display_crash_file(crashfile, rerun, debug, dir)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/scripts/crash_files.py", line 81, in display_crash_file
    node.run()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 372, in run
    self._run_interface()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 482, in _run_interface
    self._result = self._run_command(execute)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 613, in _run_command
    result = self._interface.run()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1085, in run
    outputs = self.aggregate_outputs(runtime)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1156, in aggregate_outputs
    predicted_outputs = self._list_outputs()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/io.py", line 1314, in _list_outputs
    raise IOError(msg)
OSError: No files were found matching func template: /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz
Interface SelectFiles failed to run. 

When running in terminal you can also try options that enable the Python or Ipython debugger when re-executing: -d or -i.

If you don't want to have an option to rerun the crashed workflow, you can change the format of crashfile to a text format. You can either change this in a configuration file (you can read more here), or you can directly change the wf.config dictionary before running the workflow.


In [ ]:
wf.config['execution']['crashfile_format'] = 'txt'
wf.run()


170904-05:48:17,492 workflow INFO:
	 Workflow preprocWF settings: ['check', 'execution', 'logging']
170904-05:48:17,496 workflow INFO:
	 Running serially.
170904-05:48:17,497 workflow INFO:
	 Executing node selectfiles in dir: /repos/nipype_tutorial/notebooks/working_dir/preprocWF/selectfiles
170904-05:48:17,503 workflow ERROR:
	 ['Node selectfiles failed to run on host e97878eefcf3.']
170904-05:48:17,504 workflow INFO:
	 Saving crash info to /repos/nipype_tutorial/notebooks/crash-20170904-054817-neuro-selectfiles-7414f93d-2da8-41c9-bf5e-67bbcaa0469b.txt
170904-05:48:17,505 workflow INFO:
	 Traceback (most recent call last):
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/linear.py", line 43, in run
    node.run(updatehash=updatehash)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 372, in run
    self._run_interface()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 482, in _run_interface
    self._result = self._run_command(execute)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 613, in _run_command
    result = self._interface.run()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1085, in run
    outputs = self.aggregate_outputs(runtime)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1156, in aggregate_outputs
    predicted_outputs = self._list_outputs()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/io.py", line 1314, in _list_outputs
    raise IOError(msg)
OSError: No files were found matching func template: /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz
Interface SelectFiles failed to run. 

170904-05:48:17,506 workflow INFO:
	 ***********************************
170904-05:48:17,507 workflow ERROR:
	 could not run node: preprocWF.selectfiles
170904-05:48:17,507 workflow INFO:
	 crashfile: /repos/nipype_tutorial/notebooks/crash-20170904-054817-neuro-selectfiles-7414f93d-2da8-41c9-bf5e-67bbcaa0469b.txt
170904-05:48:17,508 workflow INFO:
	 ***********************************
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-4-f520620ca876> in <module>()
      1 wf.config['execution']['crashfile_format'] = 'txt'
----> 2 wf.run()

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/workflows.py in run(self, plugin, plugin_args, updatehash)
    588         if str2bool(self.config['execution']['create_report']):
    589             self._write_report_info(self.base_dir, self.name, execgraph)
--> 590         runner.run(execgraph, updatehash=updatehash, config=self.config)
    591         datestr = datetime.utcnow().strftime('%Y%m%dT%H%M%S')
    592         if str2bool(self.config['execution']['write_provenance']):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/linear.py in run(self, graph, config, updatehash)
     59                 if self._status_callback:
     60                     self._status_callback(node, 'exception')
---> 61         report_nodes_not_run(notrun)

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/base.py in report_nodes_not_run(notrun)
     99                 logger.debug(subnode._id)
    100         logger.info("***********************************")
--> 101         raise RuntimeError(('Workflow did not execute cleanly. '
    102                             'Check log for details'))
    103 

RuntimeError: Workflow did not execute cleanly. Check log for details

Now you should have a new text file with your crash report.


In [ ]:
!cat $(pwd)/crash-*selectfiles-*.txt


Node: preprocWF.selectfiles
Working directory: /repos/nipype_tutorial/notebooks/working_dir/preprocWF/selectfiles

Node inputs:

base_directory = /data/ds000114
force_lists = False
ignore_exception = False
raise_on_empty = True
sort_filelist = True
subject_id = sub-11

Traceback (most recent call last):
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/plugins/linear.py", line 43, in run
    node.run(updatehash=updatehash)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 372, in run
    self._run_interface()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 482, in _run_interface
    self._result = self._run_command(execute)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/nodes.py", line 613, in _run_command
    result = self._interface.run()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1085, in run
    outputs = self.aggregate_outputs(runtime)
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py", line 1156, in aggregate_outputs
    predicted_outputs = self._list_outputs()
  File "/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/io.py", line 1314, in _list_outputs
    raise IOError(msg)
OSError: No files were found matching func template: /data/ds000114/sub-11/ses-test/func/sub-11_ses-test_task-fingerfootlips_bold.nii.gz
Interface SelectFiles failed to run. 

Example Crash 2: Wrong Input Type or Typo in the parameter

Very simple, if an interface expects a float as input, but you give it a string, it will crash:


In [ ]:
from nipype.interfaces.fsl import IsotropicSmooth
smooth = IsotropicSmooth(fwhm='4')


---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-6-38d0489c2381> in <module>()
      1 from nipype.interfaces.fsl import IsotropicSmooth
----> 2 smooth = IsotropicSmooth(fwhm='4')

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/fsl/base.py in __init__(self, **inputs)
    172 
    173     def __init__(self, **inputs):
--> 174         super(FSLCommand, self).__init__(**inputs)
    175         self.inputs.on_trait_change(self._output_update, 'output_type')
    176 

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, command, **inputs)
   1662 
   1663     def __init__(self, command=None, **inputs):
-> 1664         super(CommandLine, self).__init__(**inputs)
   1665         self._environ = None
   1666         if not hasattr(self, '_cmd'):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, from_file, **inputs)
    773                             self.__class__.__name__)
    774 
--> 775         self.inputs = self.input_spec(**inputs)
    776         self.estimated_memory_gb = 0.25
    777         self.num_threads = 1

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, **kwargs)
    363         # therefore these args were being ignored.
    364         # super(TraitedSpec, self).__init__(*args, **kwargs)
--> 365         super(BaseTraitedSpec, self).__init__(**kwargs)
    366         traits.push_exception_handler(reraise_exceptions=True)
    367         undefined_traits = {}

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in error(self, object, name, value)
    170         """
    171         raise TraitError( object, name, self.full_info( object, name, value ),
--> 172                           value )
    173 
    174     def full_info ( self, object, name, value ):

TraitError: The 'fwhm' trait of an IsotropicSmoothInput instance must be a float, but a value of '4' <class 'str'> was specified.

This will give you the error: TraitError: The 'fwhm' trait of an IsotropicSmoothInput instance must be a float, but a value of '4' <type 'str'> was specified.

To make sure that you are using the right input types, just check the help section of a given interface. There you can see fwhm: (a float).


In [ ]:
IsotropicSmooth.help()


Wraps command **fslmaths**

Use fslmaths to spatially smooth an image with a gaussian kernel.

Inputs::

	[Mandatory]
	fwhm: (a float)
		fwhm of smoothing kernel [mm]
		flag: -s %.5f, position: 4
		mutually_exclusive: sigma
	in_file: (an existing file name)
		image to operate on
		flag: %s, position: 2
	sigma: (a float)
		sigma of smoothing kernel [mm]
		flag: -s %.5f, position: 4
		mutually_exclusive: fwhm

	[Optional]
	args: (a unicode string)
		Additional parameters to the command
		flag: %s
	environ: (a dictionary with keys which are a bytes or None or a value
		 of class 'str' and with values which are a bytes or None or a value
		 of class 'str', nipype default value: {})
		Environment variables
	ignore_exception: (a boolean, nipype default value: False)
		Print an error message instead of throwing an exception in case the
		interface fails to run
	internal_datatype: ('float' or 'char' or 'int' or 'short' or 'double'
		 or 'input')
		datatype to use for calculations (default is float)
		flag: -dt %s, position: 1
	nan2zeros: (a boolean)
		change NaNs to zeros before doing anything
		flag: -nan, position: 3
	out_file: (a file name)
		image to write
		flag: %s, position: -2
	output_datatype: ('float' or 'char' or 'int' or 'short' or 'double'
		 or 'input')
		datatype to use for output (default uses input type)
		flag: -odt %s, position: -1
	output_type: ('NIFTI' or 'NIFTI_PAIR' or 'NIFTI_GZ' or
		 'NIFTI_PAIR_GZ')
		FSL output type
	terminal_output: ('stream' or 'allatonce' or 'file' or 'none')
		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

Outputs::

	out_file: (an existing file name)
		image written after calculations

References::
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},}', key='JenkinsonBeckmannBehrensWoolrichSmith2012')

In a similar way, you will also get an error message if the input type is correct but you have a type in the name:

TraitError: The 'output_type' trait of an IsotropicSmoothInput instance must be u'NIFTI_PAIR' or u'NIFTI_PAIR_GZ' or u'NIFTI_GZ' or u'NIFTI', but a value of 'NIFTIiii' <type 'str'> was specified.

In [ ]:
from nipype.interfaces.fsl import IsotropicSmooth
smooth = IsotropicSmooth(output_type='NIFTIiii')


---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-8-d47a236310af> in <module>()
      1 from nipype.interfaces.fsl import IsotropicSmooth
----> 2 smooth = IsotropicSmooth(output_type='NIFTIiii')

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/fsl/base.py in __init__(self, **inputs)
    172 
    173     def __init__(self, **inputs):
--> 174         super(FSLCommand, self).__init__(**inputs)
    175         self.inputs.on_trait_change(self._output_update, 'output_type')
    176 

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, command, **inputs)
   1662 
   1663     def __init__(self, command=None, **inputs):
-> 1664         super(CommandLine, self).__init__(**inputs)
   1665         self._environ = None
   1666         if not hasattr(self, '_cmd'):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, from_file, **inputs)
    773                             self.__class__.__name__)
    774 
--> 775         self.inputs = self.input_spec(**inputs)
    776         self.estimated_memory_gb = 0.25
    777         self.num_threads = 1

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, **kwargs)
    363         # therefore these args were being ignored.
    364         # super(TraitedSpec, self).__init__(*args, **kwargs)
--> 365         super(BaseTraitedSpec, self).__init__(**kwargs)
    366         traits.push_exception_handler(reraise_exceptions=True)
    367         undefined_traits = {}

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in error(self, object, name, value)
    170         """
    171         raise TraitError( object, name, self.full_info( object, name, value ),
--> 172                           value )
    173 
    174     def full_info ( self, object, name, value ):

TraitError: The 'output_type' trait of an IsotropicSmoothInput instance must be 'NIFTI' or 'NIFTI_PAIR' or 'NIFTI_GZ' or 'NIFTI_PAIR_GZ', but a value of 'NIFTIiii' <class 'str'> was specified.

Example Crash 3: Giving an array as input where a single file is expected

As you an see in the MapNode example, if you try to feed an array as an input into a field that only expects a single file, you will get a TraitError.


In [ ]:
from nipype.algorithms.misc import Gunzip
from nipype.pipeline.engine import Node

files = ['/data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz',
         '/data/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-fingerfootlips_bold.nii.gz']

gunzip = Node(Gunzip(), name='gunzip',)
gunzip.inputs.in_file = files


---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-9-b3419896813b> in <module>()
      6 
      7 gunzip = Node(Gunzip(), name='gunzip',)
----> 8 gunzip.inputs.in_file = files

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/traits_extension.py in validate(self, object, name, value)
     81             Note: The 'fast validator' version performs this check in C.
     82         """
---> 83         validated_value = super(BaseFile, self).validate(object, name, value)
     84         if not self.exists:
     85             return validated_value

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_types.py in validate(self, object, name, value)
    409             return str( value )
    410 
--> 411         self.error( object, name, value )
    412 
    413     def create_editor ( self ):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in error(self, object, name, value)
    170         """
    171         raise TraitError( object, name, self.full_info( object, name, value ),
--> 172                           value )
    173 
    174     def full_info ( self, object, name, value ):

TraitError: The 'in_file' trait of a GunzipInputSpec instance must be an existing file name, but a value of ['/data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz', '/data/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-fingerfootlips_bold.nii.gz'] <class 'list'> was specified.

This can be solved by using a MapNode:


In [ ]:
from nipype.pipeline.engine import MapNode
gunzip = MapNode(Gunzip(), name='gunzip', iterfield=['in_file'])
gunzip.inputs.in_file = files

Now, make sure that you specify files that actually exist, otherwise you can the same problem as in crash example 1, but this time labeled as TraitError:

TraitError: Each element of the 'in_file' trait of a DynamicTraitedSpec instance must be an existing file name, but a value of '/data/ds102/sub-06/func/sub-06_task-flanker_run-1_bold.nii.gz' <type 'str'> was specified.

In [ ]:
files = ['/data/ds000114/sub-01/func/sub-01_task-fingerfootlips_bold.nii.gz',
         '/data/ds000114/sub-03/func/sub-03_task-fingerfootlips_bold.nii.gz']
gunzip.inputs.in_file = files


---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-11-9ac9ba7f011f> in <module>()
      1 files = ['/data/ds000114/sub-01/func/sub-01_task-fingerfootlips_bold.nii.gz',
      2          '/data/ds000114/sub-03/func/sub-03_task-fingerfootlips_bold.nii.gz']
----> 3 gunzip.inputs.in_file = files

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in validate(self, object, name, value)
   2081                 isinstance(value[0], list)):
   2082             newvalue = [value]
-> 2083         value = super(MultiPath, self).validate(object, name, newvalue)
   2084 
   2085         if len(value) > 0:

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_types.py in validate(self, object, name, value)
   2334                 return value
   2335 
-> 2336             return TraitListObject( self, object, name, value )
   2337 
   2338         self.error( object, name, value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in __init__(self, trait, object, name, value)
   2311             except TraitError as excp:
   2312                 excp.set_prefix( 'Each element of the' )
-> 2313                 raise excp
   2314 
   2315         self.len_error( len( value ) )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in __init__(self, trait, object, name, value)
   2303                 validate = trait.item_trait.handler.validate
   2304                 if validate is not None:
-> 2305                     value = [ validate( object, name, val ) for val in value ]
   2306 
   2307                 list.__setitem__(self, slice(0, 0), value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in <listcomp>(.0)
   2303                 validate = trait.item_trait.handler.validate
   2304                 if validate is not None:
-> 2305                     value = [ validate( object, name, val ) for val in value ]
   2306 
   2307                 list.__setitem__(self, slice(0, 0), value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/traits_extension.py in validate(self, object, name, value)
     90                 args='The trait \'{}\' of {} instance is {}, but the path '
     91                      ' \'{}\' does not exist.'.format(name, class_of(object),
---> 92                                                       self.info_text, value))
     93 
     94         self.error(object, name, value)

TraitError: The trait 'in_file' of a DynamicTraitedSpec instance is an existing file name, but the path  '/data/ds000114/sub-01/func/sub-01_task-fingerfootlips_bold.nii.gz' does not exist.

By the way, not that those crashes don't create a crashfile, because they didn't happen during runtime, but still during workflow building.

Example Crash 4: SPM doesn't like *.nii.gz files

SPM12 cannot handle compressed NIfTI files (*nii.gz). If you try to run the node nonetheless, it can give you different kind of problems:

SPM Problem 1 with *.nii.gz files

SPM12 has a problem with handling *.nii.gz files. For it a compressed functional image has no temporal dimension and therefore seems to be just a 3D file. So if we try to run the Realign interface on a compressed file, we will get a TraitError error.


In [ ]:
from nipype.interfaces.spm import Smooth
smooth = Smooth(in_files='/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz')
smooth.run()


---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-12-c3f4b7d7df81> in <module>()
      1 from nipype.interfaces.spm import Smooth
----> 2 smooth = Smooth(in_files='/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz')
      3 smooth.run()

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/spm/base.py in __init__(self, **inputs)
    249 
    250     def __init__(self, **inputs):
--> 251         super(SPMCommand, self).__init__(**inputs)
    252         self.inputs.on_trait_change(self._matlab_cmd_update, ['matlab_cmd',
    253                                                               'mfile',

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, from_file, **inputs)
    773                             self.__class__.__name__)
    774 
--> 775         self.inputs = self.input_spec(**inputs)
    776         self.estimated_memory_gb = 0.25
    777         self.num_threads = 1

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, **kwargs)
    363         # therefore these args were being ignored.
    364         # super(TraitedSpec, self).__init__(*args, **kwargs)
--> 365         super(BaseTraitedSpec, self).__init__(**kwargs)
    366         traits.push_exception_handler(reraise_exceptions=True)
    367         undefined_traits = {}

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in validate(self, object, name, value)
   2081                 isinstance(value[0], list)):
   2082             newvalue = [value]
-> 2083         value = super(MultiPath, self).validate(object, name, newvalue)
   2084 
   2085         if len(value) > 0:

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_types.py in validate(self, object, name, value)
   2334                 return value
   2335 
-> 2336             return TraitListObject( self, object, name, value )
   2337 
   2338         self.error( object, name, value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in __init__(self, trait, object, name, value)
   2311             except TraitError as excp:
   2312                 excp.set_prefix( 'Each element of the' )
-> 2313                 raise excp
   2314 
   2315         self.len_error( len( value ) )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in __init__(self, trait, object, name, value)
   2303                 validate = trait.item_trait.handler.validate
   2304                 if validate is not None:
-> 2305                     value = [ validate( object, name, val ) for val in value ]
   2306 
   2307                 list.__setitem__(self, slice(0, 0), value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in <listcomp>(.0)
   2303                 validate = trait.item_trait.handler.validate
   2304                 if validate is not None:
-> 2305                     value = [ validate( object, name, val ) for val in value ]
   2306 
   2307                 list.__setitem__(self, slice(0, 0), value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/traits_extension.py in validate(self, object, name, value)
    284                 raise TraitError(
    285                     args="{} is not included in allowed types: {}".format(
--> 286                         validated_value, ', '.join(self._exts)))
    287         return validated_value
    288 

TraitError: /data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz is not included in allowed types: .nii, .img, .hdr

SPM problem 2 with *.nii.gz files

Sometimes TraitError can be more misleading.


In [ ]:
from nipype.interfaces.spm import Realign
realign = Realign(in_files='/data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz')
realign.run()


---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-13-fe2499047fd5> in <module>()
      1 from nipype.interfaces.spm import Realign
----> 2 realign = Realign(in_files='/data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz')
      3 realign.run()

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/spm/base.py in __init__(self, **inputs)
    249 
    250     def __init__(self, **inputs):
--> 251         super(SPMCommand, self).__init__(**inputs)
    252         self.inputs.on_trait_change(self._matlab_cmd_update, ['matlab_cmd',
    253                                                               'mfile',

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, from_file, **inputs)
    773                             self.__class__.__name__)
    774 
--> 775         self.inputs = self.input_spec(**inputs)
    776         self.estimated_memory_gb = 0.25
    777         self.num_threads = 1

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, **kwargs)
    363         # therefore these args were being ignored.
    364         # super(TraitedSpec, self).__init__(*args, **kwargs)
--> 365         super(BaseTraitedSpec, self).__init__(**kwargs)
    366         traits.push_exception_handler(reraise_exceptions=True)
    367         undefined_traits = {}

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in validate(self, object, name, value)
   2081                 isinstance(value[0], list)):
   2082             newvalue = [value]
-> 2083         value = super(MultiPath, self).validate(object, name, newvalue)
   2084 
   2085         if len(value) > 0:

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_types.py in validate(self, object, name, value)
   2334                 return value
   2335 
-> 2336             return TraitListObject( self, object, name, value )
   2337 
   2338         self.error( object, name, value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in __init__(self, trait, object, name, value)
   2311             except TraitError as excp:
   2312                 excp.set_prefix( 'Each element of the' )
-> 2313                 raise excp
   2314 
   2315         self.len_error( len( value ) )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in __init__(self, trait, object, name, value)
   2303                 validate = trait.item_trait.handler.validate
   2304                 if validate is not None:
-> 2305                     value = [ validate( object, name, val ) for val in value ]
   2306 
   2307                 list.__setitem__(self, slice(0, 0), value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in <listcomp>(.0)
   2303                 validate = trait.item_trait.handler.validate
   2304                 if validate is not None:
-> 2305                     value = [ validate( object, name, val ) for val in value ]
   2306 
   2307                 list.__setitem__(self, slice(0, 0), value )

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in validate(self, object, name, value)
   1981             except TraitError:
   1982                pass
-> 1983         return self.slow_validate( object, name, value )
   1984 
   1985     def slow_validate ( self, object, name, value ):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in slow_validate(self, object, name, value)
   1989             except TraitError:
   1990                pass
-> 1991         self.error( object, name, value )
   1992 
   1993     def full_info ( self, object, name, value ):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/traits/trait_handlers.py in error(self, object, name, value)
    170         """
    171         raise TraitError( object, name, self.full_info( object, name, value ),
--> 172                           value )
    173 
    174     def full_info ( self, object, name, value ):

TraitError: Each element of the 'in_files' trait of a RealignInputSpec instance must be a list of items which are an existing file name or an existing file name, but a value of '/data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz' <class 'str'> was specified.

This issue can be solved by unzipping the compressed NIfTI file before giving it as an input to an SPM node. This can either be done by using the Gunzip interface from Nipype or even better, if the input is coming from a FSL interface, most of them have an input filed output_type='NIFTI', that you can set to NIFIT.

Example Crash 5: Nipype cannot find the right software

Especially at the beginning, just after installation, you sometimes forgot to specify some environment variables. If you try to use an interface where the environment variables of the software are not specified, e.g. if you try to run:

from nipype.interfaces.freesurfer import MRIConvert
convert = MRIConvert(in_file='/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz',
                     out_type='nii')

you migh get an errors, such as:

IOError: command 'mri_convert' could not be found on host mnotter
Interface MRIConvert failed to run.

Or if you try to use SPM, but forgot to tell Nipype where to find it. If you forgot to tell the system where to find MATLAB (or MCR), than you will get same kind of error as above. But if you forgot to specify which SPM you want to use, you'll get the following RuntimeError:

Standard error:
MATLAB code threw an exception:
SPM not in matlab path


You can solve this issue by specifying the path to your SPM version:

from nipype.interfaces.matlab import MatlabCommand
MatlabCommand.set_default_paths('/usr/local/MATLAB/R2017a/toolbox/spm12')

Example Crash 6: You forget mandatory inputs or use input fields that don't exist

One of the simpler errors are the ones connected to input and output fields.

Forgetting mandatory input fields

Let's see what happens if you forget a [Mandatory] input field.


In [ ]:
from nipype.interfaces.spm import Realign
realign = Realign(register_to_mean=True)
realign.run()


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-29d156abbd26> in <module>()
      1 from nipype.interfaces.spm import Realign
      2 realign = Realign(register_to_mean=True)
----> 3 realign.run()

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in run(self, **inputs)
   1065         """
   1066         self.inputs.trait_set(**inputs)
-> 1067         self._check_mandatory_inputs()
   1068         self._check_version_requirements(self.inputs)
   1069         interface = self.__class__

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in _check_mandatory_inputs(self)
    970                        "For a list of required inputs, see %s.help()" %
    971                        (self.__class__.__name__, name, self.__class__.__name__))
--> 972                 raise ValueError(msg)
    973             if isdefined(value):
    974                 self._check_requires(spec, name, value)

ValueError: Realign requires a value for input 'in_files'. For a list of required inputs, see Realign.help()

This gives you the error:

ValueError: Realign requires a value for input 'in_files'. For a list of required inputs, see Realign.help()

As described by the error text, if we use the help() function, we can actually see, which inputs are mandatory and which are optional.


In [ ]:
realign.help()


Use spm_realign for estimating within modality rigid body alignment

http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=25

Examples
--------

>>> import nipype.interfaces.spm as spm
>>> realign = spm.Realign()
>>> realign.inputs.in_files = 'functional.nii'
>>> realign.inputs.register_to_mean = True
>>> realign.run() # doctest: +SKIP

Inputs::

	[Mandatory]
	in_files: (a list of items which are a list of items which are an
		 existing file name or an existing file name)
		list of filenames to realign

	[Optional]
	fwhm: (a floating point number >= 0.0)
		gaussian smoothing kernel width
	ignore_exception: (a boolean, nipype default value: False)
		Print an error message instead of throwing an exception in case the
		interface fails to run
	interp: (0 <= a long integer <= 7)
		degree of b-spline used for interpolation
	jobtype: ('estwrite' or 'estimate' or 'write', nipype default value:
		 estwrite)
		one of: estimate, write, estwrite
	matlab_cmd: (a unicode string)
		matlab command to use
	mfile: (a boolean, nipype default value: True)
		Run m-code using m-file
	out_prefix: (a string, nipype default value: r)
		realigned output prefix
	paths: (a list of items which are a directory name)
		Paths to add to matlabpath
	quality: (0.0 <= a floating point number <= 1.0)
		0.1 = fast, 1.0 = precise
	register_to_mean: (a boolean)
		Indicate whether realignment is done to the mean image
	separation: (a floating point number >= 0.0)
		sampling separation in mm
	use_mcr: (a boolean)
		Run m-code using SPM MCR
	use_v8struct: (a boolean, nipype default value: True)
		Generate SPM8 and higher compatible jobs
	weight_img: (an existing file name)
		filename of weighting image
	wrap: (a list of from 3 to 3 items which are an integer (int or
		 long))
		Check if interpolation should wrap in [x,y,z]
	write_interp: (0 <= a long integer <= 7)
		degree of b-spline used for interpolation
	write_mask: (a boolean)
		True/False mask output image
	write_which: (a list of items which are a value of class 'int',
		 nipype default value: [2, 1])
		determines which images to reslice
	write_wrap: (a list of from 3 to 3 items which are an integer (int or
		 long))
		Check if interpolation should wrap in [x,y,z]

Outputs::

	mean_image: (an existing file name)
		Mean image file from the realignment
	modified_in_files: (a list of items which are a list of items which
		 are an existing file name or an existing file name)
		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: (a list of items which are a list of items which are
		 an existing file name or an existing file name)
		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: (a list of items which are an existing file
		 name)
		Estimated translation and rotation parameters

References::
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},}', key='FrackowiakFristonFrithDolanMazziotta1997')

Using input fields that don't exist

Let's see what happens if we try to specify a parameter that doesn't exist as an input field:


In [ ]:
from nipype.interfaces.afni import Despike
despike = Despike(in_file='/data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz',
                  output_type='NIFTI')
despike.run()


---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-16-fe8670ce6587> in <module>()
      1 from nipype.interfaces.afni import Despike
      2 despike = Despike(in_file='/data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz',
----> 3                   output_type='NIFTI')
      4 despike.run()

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/afni/base.py in __init__(self, **inputs)
    178 
    179     def __init__(self, **inputs):
--> 180         super(AFNICommand, self).__init__(**inputs)
    181         self.inputs.on_trait_change(self._output_update, 'outputtype')
    182 

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, command, **inputs)
   1662 
   1663     def __init__(self, command=None, **inputs):
-> 1664         super(CommandLine, self).__init__(**inputs)
   1665         self._environ = None
   1666         if not hasattr(self, '_cmd'):

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, from_file, **inputs)
    773                             self.__class__.__name__)
    774 
--> 775         self.inputs = self.input_spec(**inputs)
    776         self.estimated_memory_gb = 0.25
    777         self.num_threads = 1

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/interfaces/base.py in __init__(self, **kwargs)
    363         # therefore these args were being ignored.
    364         # super(TraitedSpec, self).__init__(*args, **kwargs)
--> 365         super(BaseTraitedSpec, self).__init__(**kwargs)
    366         traits.push_exception_handler(reraise_exceptions=True)
    367         undefined_traits = {}

TraitError: Cannot set the undefined 'output_type' attribute of a 'DespikeInputSpec' object.

This results in the TraitError:

TraitError: Cannot set the undefined 'output_type' attribute of a 'DespikeInputSpec' object.

So what went wrong? If you use the help() function, you will see that the correct input filed is called outputtype and not output_type.

Example Crash 7: Trying to connect a node to an input field that is already occupied

Sometimes when you build a new workflow, you might forget that an output field was already connected and you try to connect a new node to the already occupied field.

First, let's create a simple workflow:


In [ ]:
from nipype import SelectFiles, Node, Workflow
from os.path import abspath as opap
from nipype.interfaces.fsl import MCFLIRT, IsotropicSmooth

# Create SelectFiles node
templates={'func': '{subject_id}/func/{subject_id}_task-fingerfootlips_bold.nii.gz'}
sf = Node(SelectFiles(templates),
          name='selectfiles')
sf.inputs.base_directory = opap('/data/ds000114')
sf.inputs.subject_id = 'sub-01'

# Create Motion Correction Node
mcflirt = Node(MCFLIRT(mean_vol=True,
                       save_plots=True),
               name='mcflirt')

# Create Smoothing node
smooth = Node(IsotropicSmooth(fwhm=4),
              name='smooth')

# Create a preprocessing workflow
wf = Workflow(name="preprocWF")
wf.base_dir = 'working_dir'

# Connect the three nodes to each other
wf.connect([(sf, mcflirt, [("func", "in_file")]),
            (mcflirt, smooth, [("out_file", "in_file")])])

Now, let's create a new node and connect it to the already occupied input field in_file of the smooth node:


In [ ]:
# Create a new node
mcflirt_NEW = Node(MCFLIRT(mean_vol=True),
                   name='mcflirt_NEW')

# Connect it to an already connected input field
wf.connect([(mcflirt_NEW, smooth, [("out_file", "in_file")])])


---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-18-10d23e4325e2> in <module>()
      4 
      5 # Connect it to an already connected input field
----> 6 wf.connect([(mcflirt_NEW, smooth, [("out_file", "in_file")])])

/opt/conda/envs/neuro3/lib/python3.6/site-packages/nipype/pipeline/engine/workflows.py in connect(self, *args, **kwargs)
    199 Trying to connect %s:%s to %s:%s but input '%s' of node '%s' is already
    200 connected.
--> 201 """ % (srcnode, source, destnode, dest, dest, destnode))
    202                 if not (hasattr(destnode, '_interface') and
    203                             ('.io' in str(destnode._interface.__class__) or

Exception: 
Trying to connect preprocWF.mcflirt_NEW:out_file to preprocWF.smooth:in_file but input 'in_file' of node 'preprocWF.smooth' is already
connected.

This will lead to the error:

Exception: 
Trying to connect preprocWF.mcflirt_NEW:out_file to preprocWF.smooth:in_file but input 'in_file' of node 'preprocWF.smooth' is already connected.