Nipype introduction

Starting with nipype

  • Nipype probably pronouncec as nipee..yipee is an abbreviation for Neuroimaging in Python pipleline and interfaces
  • It is a Toolbox for anylysing data coming from neuroimaging modalaties. It is written in Python.
  1. Installation
  2. Check your installation

Beginners Guide

  1. It is year 2017 guide, it can be tested and re written for others
  2. The main purpose of this toolbox is to provide an easy way to build a workflow termed as a pipleline, to facilitate the existing technologies used in neuroimaging analyis. All popular technololgies such as SPM, FreeSurfer, FSL etccan be used.
  3. It allows to combine these techonolgies in an specifed workflow, it is what you decided to use which technology for which prupose.
  4. For example
  5. The whole idea is to provide an environment where reasearch can be reproduced with the same data by sharing with others.

Nipype architechture:

It consist of many components, important ones are interfaces,Workflow Engines and Execution Plugins.

  1. Interfaces are the python programs (scripts) that are used to interface with existing technologies like MATLAB,AFNI,ANTs etc.
  2. Workflow Engine is a part that deals with the complexities involve in executing diferent task by gluing eachother. It uses following terms interchanably.
    • Node:An interface needs the information about the technologies it is dealing with and it is given in the form of node. A node describes these information.
    • MapNode:It is similar to node and takes multiple inputs of same type. For example 10 patient of same data analysis is performed on them.
    • Wordflow:It is graph a kind of directed acyclic graph or forest of grapsh that describes the dataflow interms of its Nodes, MapNodes or Workflows it self.
    • Execution Plugins: They descirbe how to execute your workfow in a physical machine by leaverging the power of differnet cores.

A conventional way of neuro imaging

  1. Acqusation of MRI data: you need to know how it is taken what varibales and terms are used. Which series of MRI is uses commonly known as modalaties. There are many like ( DTI, fMRI etc).
  2. The format of resulted images: Different scanners uses different formats e.g. DICOM , PAR or REC. To analyse these images they are to be converted into different format so that un necessary details can be removed. Initially data is kept in K-space and converted into different space. Mostly the format used is either nifti and now recetnly is gifti.
  3. Design of the experiment: Which kind of experimental design is used what parameters to take into accunt etc.
  4. Preprocessing of data:
    • Slice Timing Correction (fMRI images needes to be correcyted )
The below is taken verbatim from nipype Micheal tutorial.

Because functional MRI measurement sequences don’t acquire every slice in a volume at the same time we have to account for the time differences among the slices. For example, if you acquire a volume with 37 slices in ascending order, and each slice is acquired every 50ms, there is a difference of 1.8s between the first and the last slice acquired. You must know the order in which the slices were acquired to be able to apply the proper correction. Slices are typically acquired in one of three methods: descending order (top-down); ascending order (bottom-up); or interleaved (acquire every other slice in each direction), where the interleaving may start at the top or the bottom. (Left: ascending, Right: interleaved)

Slice Timing Correction is used to compensate for the time differences between the slice acquisitions by temporally interpolating the slices so that the resulting volume is close to equivalent to acquiring the whole brain image at a single time point. This temporal factor of acquisition especially has to be accounted for in fMRI models where timing is an important factor (e.g. for event related designs, where the type of stimulus changes from volume to volume).

Chec If nipype is working use import nipype or import nipype. Run the cell if gets error it means it is not working otherwise it is present.

  • Thouth the module has been imported successfully but it does not have any attribute or any function help() it thorws an error. The above command succeeded, it means it is working. we have nipype on our path. To see where it is loaded from use shift + tab

Getting ready for dataset

  • Make a directory data in current folder that is underneate your notebook folder. Then using datalad install dataset. Note the cell is used to execute bash programe, here it is refered as bash kernel. Other kernels can be used as well.
In [18]:
%%bash
mkdir -p data
cd data
datalad install -r ///workshops/nih-2017/ds000114
install(ok): /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114 (dataset)
install(ok): /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/fmriprep (dataset)
install(ok): /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/freesurfer (dataset)
action summary:
  install (ok: 3)
[INFO] Cloning dataset to <Dataset path=/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114> 
[INFO] Attempting to clone from http://datasets.datalad.org/workshops/nih-2017/ds000114 to /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114 
[INFO] Attempting to clone from http://datasets.datalad.org/workshops/nih-2017/ds000114/.git to /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114 
[INFO] Completed clone attempts for <Dataset path=/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114> 
[INFO] access to 1 dataset sibling datalad not auto-enabled, enable with:
| 		datalad siblings -d "/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114" enable -s datalad 
[INFO] Installing <Dataset path=/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114> underneath /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114 recursively 
[INFO] Cloning dataset to <Dataset path=/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/fmriprep> 
[INFO] Attempting to clone from http://datasets.datalad.org/workshops/nih-2017/ds000114/derivatives/fmriprep/.git to /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/fmriprep 
[INFO] Completed clone attempts for <Dataset path=/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/fmriprep> 
[INFO] Cloning dataset to <Dataset path=/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/freesurfer> 
[INFO] Attempting to clone from http://datasets.datalad.org/workshops/nih-2017/ds000114/derivatives/freesurfer/.git to /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/freesurfer 
[INFO] Completed clone attempts for <Dataset path=/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/derivatives/freesurfer> 
  • Looking into the dataset.
In [19]:
ls data/ds000114/
CHANGES                   sub-08/
dataset_description.json  sub-09/
derivatives/              sub-10/
dwi.bval@                 task-covertverbgeneration_bold.json
dwi.bvec@                 task-covertverbgeneration_events.tsv
sub-01/                   task-fingerfootlips_bold.json
sub-02/                   task-fingerfootlips_events.tsv
sub-03/                   task-linebisection_bold.json
sub-04/                   task-overtverbgeneration_bold.json
sub-05/                   task-overtverbgeneration_events.tsv
sub-06/                   task-overtwordrepetition_bold.json
sub-07/                   task-overtwordrepetition_events.tsv
In [34]:
# We have one anatomical image in every folder. Lets make sure it is there.
!ls data/ds000114/sub-01/ses-test/anat/
sub-01_ses-test_T1w.nii.gz

Using BET from fsl that we imorted in first step.

In [9]:
import os
from os.path import abspath

from nipype import Workflow, Node, MapNode, Function
from nipype.interfaces.fsl import BET, IsotropicSmooth, ApplyMask

from nilearn.plotting import plot_anat
%matplotlib inline
import matplotlib.pyplot as plt
from nipype.testing import  example_data
In [14]:
# reading file in a variable
working_dir = os.getcwd()
data_dir = working_dir + "/data"
print(data_dir)
input_file =  abspath(data_dir + "/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w")
print(input_file)
fn = "./sub-01_ses-test_T1w.nii.gz"
/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data
/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w
In [ ]:
 
In [19]:
bet = BET()
bet.inputs.in_file = input_file
bet.inputs.out_file = "T1.nii.gz"
res = bet.run()
---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-19-8f66ff4bee62> in <module>
      1 bet = BET()
----> 2 bet.inputs.in_file = input_file
      3 bet.inputs.out_file = "T1.nii.gz"
      4 res = bet.run()

~/anaconda3/envs/nipype/lib/python3.8/site-packages/nipype/interfaces/base/traits_extension.py in validate(self, objekt, name, value, return_pathlike)
    328     def validate(self, objekt, name, value, return_pathlike=False):
    329         """Validate a value change."""
--> 330         value = super(File, self).validate(objekt, name, value, return_pathlike=True)
    331         if self._exts:
    332             fname = value.name

~/anaconda3/envs/nipype/lib/python3.8/site-packages/nipype/interfaces/base/traits_extension.py in validate(self, objekt, name, value, return_pathlike)
    133         if self.exists:
    134             if not value.exists():
--> 135                 self.error(objekt, name, str(value))
    136 
    137             if self._is_file and not value.is_file():

~/anaconda3/envs/nipype/lib/python3.8/site-packages/traits/base_trait_handler.py in error(self, object, name, value)
     72             The proposed new value for the attribute.
     73         """
---> 74         raise TraitError(
     75             object, name, self.full_info(object, name, value), value
     76         )

TraitError: The 'in_file' trait of a BETInputSpec instance must be a pathlike object or string representing an existing file, but a value of '/home/sayyed/neuro-science/projects/nikola/mysite/notebooks/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w' <class 'str'> was specified.

Start working with nipype

  1. Importing few things
In [3]:
import os
from os.path import abspath
from os.path import relpath

from nipype import Workflow, Node, MapNode, Function
from nipype.interfaces.fsl import BET, IsotropicSmooth, ApplyMask

from nilearn.plotting import plot_anat
%matplotlib inline
import matplotlib.pyplot as plt
In [3]:
# will use a T1w from ds000114 dataset
input_file =  abspath("/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz")
In [5]:
bet = BET()
bet.inputs.in_file = abspath("data/sample-nifiti-file.nii")
bet.imputs.int_file= input_file
help(bet.inputs)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-125541a3dc72> in <module>
      1 bet = BET()
      2 bet.inputs.in_file = abspath("data/sample-nifiti-file.nii")
----> 3 bet.imputs.int_file= input_file
      4 help(bet.inputs)

NameError: name 'input_file' is not defined
In [17]:
bet.inputs.out_file = "sample_bet.nii.gz"
res = bet.run()
res.outputs
Out[17]:
inskull_mask_file = <undefined>
inskull_mesh_file = <undefined>
mask_file = <undefined>
meshfile = <undefined>
out_file = /home/sayyed/neuro-science/projects/nikola/mysite/notebooks/sample_bet.nii.gz
outline_file = <undefined>
outskin_mask_file = <undefined>
outskin_mesh_file = <undefined>
outskull_mask_file = <undefined>
outskull_mesh_file = <undefined>
skull_file = <undefined>
skull_mask_file = <undefined>
In [18]:
plot_anat("sample_bet.nii.gz", 
          display_mode='ortho', dim=-1, draw_cross=False, annotate=False);
In [ ]:
 

Comments