<jupyter_start><jupyter_text>02 Using Nipype to load fMRI data===================== Date: Feb 7 2018; Author: Farahana<jupyter_code>from nipype import SelectFiles, Node, DataSink
from nipype.interfaces.base import Bunch

import pandas as pd<jupyter_output>/home/farahana/anaconda3/lib/python3.5/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters<jupyter_text>We will try to do "Preprocessing" based on figure below;![nipype flow](images/neuro_1.png "Neuroimaging Flow")We are using OpenfMRI.org dataset according to BIDS structure.<jupyter_code># The template string
templates = { 'anat' : 'sub*/anatomy/highres001.nii*',
              'func' : 'sub*/BOLD/task001_run{ses_no}/bold.nii*'}

# How to address and import using SelectFiles node
sf = Node(SelectFiles(templates),
          name='selectfiles')

sf.inputs.base_directory = '/home/farahana/Documents/dataset/Multi_Subject/ds117'
# We will feed the {}-based placeholder strings with values
sf.inputs.ses_no = "001"
#sf.inputs.task_name = 'reversalweatherprediction'
sf.run().outputs<jupyter_output>180212-12:39:53,232 workflow INFO:
	 Executing node selectfiles in dir: /tmp/tmplaa08ypp/selectfiles
180212-12:39:53,234 workflow INFO:
	 Running node "selectfiles" ("nipype.interfaces.io.SelectFiles").<jupyter_text>Let us look at the TSV file of the dataset<jupyter_code>trialinfo = pd.read_table('/home/farahana/Documents/dataset/ds052/sub-01/func/sub-01_task-reversalweatherprediction_run-1_events.tsv')
trialinfo.head()<jupyter_output><empty_output><jupyter_text>We will split based on two conditions:<jupyter_code>for group in trialinfo.groupby('trial_type'):
    print(group)
conditions = []
onsets = []
durations = []

for group in trialinfo.groupby('trial_type'):
    conditions.append(group[0])
    onsets.append(group[1].onset.tolist())
    durations.append(group[1].duration.tolist())

subject_info = Bunch(conditions=conditions,
                     onsets=onsets,
                     durations=durations)
#subject_info.items()
sink = DataSink()
experiment_dir = '/experiment_folder'
sink.inputs.base_directory = experiment_dir + '/output_folder'
import nipype.interfaces.afni as afni
realign =afni.Retroicor()
import nipype.interfaces.freesurfer as fs
coreg = fs.BBRegister()
import nipype.interfaces.ants as ants
normalize = ants.WarpTimeSeriesImageMultiTransform()
from nipype.pipeline.engine import Workflow
# Create a preprocessing workflow
preproc = Workflow(name='preproc')
preproc.connect([(sf -> realign),
                 (realign -> coreg),
                 (coreg -> normalize),
                 (normalize -> sink)])
preproc.connect(sf, realign, [("out_file", "in_file")])
!bet /home/farahana/Documents/dataset/ds052/sub-01/anat/sub-01_run-1_T1w.nii.gz output/T1_bet.nii.gz
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import nibabel as nib
from nilearn.plotting import plot_img, plot_anat, plot_stat_map

# Import BET from the FSL interface
from nipype.interfaces.fsl import BET<jupyter_output><empty_output><jupyter_text>Plotting Before and after Brain Extraction of Anatomical maps<jupyter_code>skullstrip = BET(in_file="/home/farahana/Documents/dataset/Multi_Subject/ds117/sub003/anatomy/highres001.nii.gz",
                out_file = "output/ds117_run001_bet.nii.gz", mask = True)
skullstrip.run()
plot_anat('/home/farahana/Documents/dataset/Multi_Subject/ds117/sub003/anatomy/highres001.nii.gz',
           cut_coords=(36, -27, 30))
plot_anat('output/ds117_run001_bet.nii.gz', cut_coords=(36, -27, 30))<jupyter_output><empty_output><jupyter_text>Plotting Before and after Brain Extraction of Functional maps<jupyter_code>skullstrip_func = BET(in_file="/home/farahana/Documents/dataset/Multi_Subject/ds117/sub003/BOLD/task001_run001/bold.nii",
                out_file = "output/func_ds117_run001_bet.nii.gz")
skullstrip_func.run()
from nilearn import image
func_ds117_mean = image.mean_img('/home/farahana/Documents/dataset/Multi_Subject/ds117/sub003/BOLD/task001_run001/bold.nii')
func_ds117_bet_mean = image.mean_img('output/func_ds117_run001_bet.nii.gz')
plot_anat(np.asarray (data_1.dataobj[:,:,:,0]),
              cut_coords=(36, -27, 30))
aff = data_1.get_affine()
ctr = np.dot(np.linalg.inv(aff), [0, 0, 0, 1])[:3]
vmin, vmax = (0, 1) if data_1.get_fdata().dtype == np.int16 else (30, 150)
data = data_1.get_fdata()
%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(np.rot90(data_1[:, :, ctr[2] + 5]), 
               cmap="gray", vmin=vmin, vmax=vmax)
plot_anat(func_ds117_bet_mean,
              cut_coords=(36, -27, 30))
data_1 = nib.load('/home/farahana/Documents/dataset/Multi_Subject/ds117/sub003/BOLD/task001_run001/bold.nii')
a = np.array(data_1)
a = data_1.get_data()
a.shape
b = a[:,:,:,0]
b.shape
plot_anat(b,cut_coords=(36, -27, 30) )
a = data_1<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12997820487418268, 'fraction_numerical': 0.044977214186645534, 'mean_word_length': 5.023866348448688, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '488645', 'license': 'MIT', 'n_tokens_mistral': 1989, 'n_tokens_neox': 1812, 'n_words': 339, 'path': '02-Nipype.ipynb', 'repo_name': 'farahanams/Pytorch-fMRI', 'size': '5047'}