In [8]:
# - compatibility with Python 3
from __future__ import print_function  # print('me') instead of print 'me'
from __future__ import division  # 1/2 == 0.5, not 0
In [9]:
# - show figures inside the notebook
%matplotlib inline
In [10]:
# - import common modules
import numpy as np  # the Python array package
import matplotlib.pyplot as plt  # the Python plotting package
In [11]:
# - set gray colormap and nearest neighbor interpolation by default
plt.rcParams['image.cmap'] = 'gray'
plt.rcParams['image.interpolation'] = 'nearest'

Introducing nipype

Nipype is a Python module that provides Python interfaces to many imaging tools, including SPM, AFNI and FSL.

We install it with the Python pip tool.

In our case we need the current development version to give us the most recent SPM interfaces.

We install like this (from your cmd or Terminal.app window):

pip install git+https://github.com/nipy/nipype.git

After this has run, check that you can import nipype with:

In [12]:
import nipype
nipype.__version__
Out[12]:
'1.0.0dev'

We are interested in the nipype interfaces sub-package. Specifically, we want the interfaces to the spm routines:

In [13]:
from nipype.interfaces import spm

Our first job is to make sure that nipype can run MATLAB. Let's check with a test call:

In [14]:
import nipype.interfaces.matlab as nim
mlab = nim.MatlabCommand()
mlab.inputs.script = "version"  # get MATLAB version
mlab.run()
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-14-e298d2a8617f> in <module>()
      2 mlab = nim.MatlabCommand()
      3 mlab.inputs.script = "version"  # get MATLAB version
----> 4 mlab.run()

/Users/mb312/.virtualenvs/test/lib/python2.7/site-packages/nipype/interfaces/base.pyc in run(self, **inputs)
   1001                     runtime.environ['DISPLAY'] = ':%s' % vdisplay_num
   1002 
-> 1003             runtime = self._run_interface(runtime)
   1004 
   1005             if self._redirect_x:

/Users/mb312/.virtualenvs/test/lib/python2.7/site-packages/nipype/interfaces/matlab.pyc in _run_interface(self, runtime)
    136     def _run_interface(self,runtime):
    137         self.inputs.terminal_output = 'allatonce'
--> 138         runtime = super(MatlabCommand, self)._run_interface(runtime)
    139         try:
    140             # Matlab can leave the terminal in a barbbled state

/Users/mb312/.virtualenvs/test/lib/python2.7/site-packages/nipype/interfaces/base.pyc in _run_interface(self, runtime, correct_return_codes)
   1445         if not exist_val:
   1446             raise IOError("%s could not be found on host %s" %
-> 1447                           (self.cmd.split()[0], runtime.hostname))
   1448         setattr(runtime, 'command_path', cmd_path)
   1449         setattr(runtime, 'dependencies', get_dependencies(executable_name,

IOError: matlab could not be found on host shanghai.local
Interface MatlabCommand failed to run. 

If nipype does not have the right command to start MATLAB, this will fail with an error. We can set the command to start MATLAB like this:

In [15]:
nim.MatlabCommand.set_default_matlab_cmd('/Applications/MATLAB_R2014a.app/bin/matlab')

Check this is working by running the same code as previously:

In [16]:
mlab = nim.MatlabCommand()
mlab.inputs.script = "version"  # get MATLAB version
mlab.run()
Out[16]:
<nipype.interfaces.base.InterfaceResult at 0x1074df8d0>

Next we need to make sure that nipype has SPM on the MATLAB path when it is running MATLAB. Try running this command to get the SPM version?

In [17]:
mlab = nim.MatlabCommand()
mlab.inputs.script = "spm ver"  # get SPM version
mlab.run()
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-17-024eb141edae> in <module>()
      1 mlab = nim.MatlabCommand()
      2 mlab.inputs.script = "spm ver"  # get SPM version
----> 3 mlab.run()

/Users/mb312/.virtualenvs/test/lib/python2.7/site-packages/nipype/interfaces/base.pyc in run(self, **inputs)
   1001                     runtime.environ['DISPLAY'] = ':%s' % vdisplay_num
   1002 
-> 1003             runtime = self._run_interface(runtime)
   1004 
   1005             if self._redirect_x:

/Users/mb312/.virtualenvs/test/lib/python2.7/site-packages/nipype/interfaces/matlab.pyc in _run_interface(self, runtime)
    144             pass
    145         if 'MATLAB code threw an exception' in runtime.stderr:
--> 146             self.raise_exception(runtime)
    147         return runtime
    148 

/Users/mb312/.virtualenvs/test/lib/python2.7/site-packages/nipype/interfaces/base.pyc in raise_exception(self, runtime)
   1381         message += "Standard error:\n" + runtime.stderr + "\n"
   1382         message += "Return code: " + str(runtime.returncode)
-> 1383         raise RuntimeError(message)
   1384 
   1385     @classmethod

RuntimeError: Command:
/Applications/MATLAB_R2014a.app/bin/matlab -nodesktop -nosplash -singleCompThread -r "addpath('/Users/mb312/dev_trees/pna2015/day12');pyscript;exit"
Standard output:

                            < M A T L A B (R) >
                  Copyright 1984-2014 The MathWorks, Inc.
                     R2014a (8.3.0.532) 64-bit (maci64)
                             February 11, 2014

[Warning: Name is nonexistent or not a directory: /Users/mb312/matlab/m2html] 
[Warning: Duplicate directory name: /Users/mb312/matlab] 
[Warning: Name is nonexistent or not a directory: /Users/mb312/matlab/m2html] 
[Warning: Duplicate directory name: /Users/mb312/matlab] 
 
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, visit www.mathworks.com.
 
Executing pyscript at 14-May-2015 18:59:57:
----------------------------------------------------------------------------------------------------
MATLAB Version: 8.3.0.532 (R2014a)
MATLAB License Number: 731130
Operating System: Mac OS X  Version: 10.9.5 Build: 13F1077 
Java Version: Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
----------------------------------------------------------------------------------------------------
MATLAB                                                Version 8.3        (R2014a)
Image Processing Toolbox                              Version 9.0        (R2014a)
MATLAB Compiler                                       Version 5.1        (R2014a)
Signal Processing Toolbox                             Version 6.21       (R2014a)
Statistics Toolbox                                    Version 9.0        (R2014a)
Wavelet Toolbox                                       Version 4.13       (R2014a)

Standard error:
MATLAB code threw an exception:
Undefined function 'spm' for input arguments of type 'char'.
File:/Users/mb312/dev_trees/pna2015/day12/pyscript.m
Name:pyscript
Line:3

Return code: 0
Interface MatlabCommand failed to run. 

If this does not work, you may not have SPM set up on your MATLAB path by default. You can add SPM to the path like this:

In [18]:
nim.MatlabCommand.set_default_paths('/Users/mb312/spm')

Now try running the spm ver command again:

In [19]:
mlab = nim.MatlabCommand()
mlab.inputs.script = "spm ver"  # get SPM version
mlab.run()
Out[19]:
<nipype.interfaces.base.InterfaceResult at 0x107458e10>

We are going to put the setup we need into a Python file we can import from any script that we write that uses nipype.

Change directory to your pna_code directory:

cd ~/pna_code

In this directory, make a new file called nipype_settings.py with contents like this:

""" Defaults for using nipype
"""
import nipype.interfaces.matlab as nim
# If you needed to set the default matlab command above
nim.MatlabCommand.set_default_matlab_cmd('/Applications/MATLAB_R2014a.app/bin/matlab')
# If you needed to set the SPM path above
nim.MatlabCommand.set_default_paths('/Users/mb312/spm')

Finally, open cmd or Terminal.app in this current directory, and do the following:

ipython

This starts the IPython console. Next, at the IPython prompt, type these lines:

import nipype_settings
import nipype.interfaces.matlab as nim
mlab = nim.MatlabCommand()
mlab.inputs.script = "spm ver"  # get SPM version
mlab.run()

These should run without error. Call us over for help if you did get an error.