Post processing:

  • Global Signal Regression using orthogonalization
  • Band Pass filtering 0.1 - 0.01 Hz
  • Motion regression using GLM

In [460]:
from bids.grabbids import BIDSLayout
from nipype.interfaces.fsl import (BET, ExtractROI, FAST, FLIRT, ImageMaths,
                                   MCFLIRT, SliceTimer, Threshold,Info, ConvertXFM,MotionOutliers)
from nipype.interfaces.afni import Resample
from nipype.interfaces.io import DataSink
from nipype.pipeline import Node, MapNode, Workflow, JoinNode
from nipype.interfaces.utility import IdentityInterface, Function
import os
from os.path import join as opj
from nipype.interfaces import afni
import nibabel as nib
import json    
import numpy as np

In [461]:
# Paths

path_cwd = os.getcwd()
path_split_list = path_cwd.split('/')
s = path_split_list[0:-2] # for getting to the parent dir of pwd
s = opj('/',*s) # *s converts list to path, # very important to add '/' in the begining so it is read as directory later

In [462]:
# json_path = opj(data_directory,'task-rest_bold.json')

json_path = '../scripts/json/paths.json'
with open(json_path, 'rt') as fp:
    task_info = json.load(fp)

In [463]:
# base_directory = opj(s,'result') 
# parent_wf_directory = 'preprocessPipeline_ABIDE2_GU1_withfloat'
# child_wf_directory = 'coregistrationPipeline'

# data_directory = opj(s,"data/ABIDE2-BIDS/GU1")

# datasink_name = 'datasink_preprocessed_ABIDE2_GU1_withfloat'

base_directory = opj(s,task_info["base_directory_for_results"]) 
motion_correction_bet_directory = task_info["motion_correction_bet_directory"]
parent_wf_directory = task_info["parent_wf_directory"]
# functional_connectivity_directory = task_info["functional_connectivity_directory"]
functional_connectivity_directory = 'temp_fc'
coreg_reg_directory = task_info["coreg_reg_directory"]
atlas_resize_reg_directory = task_info["atlas_resize_reg_directory"]
data_directory = opj(s,task_info["data_directory"])
datasink_name = task_info["datasink_name"]
fc_datasink_name = task_info["fc_datasink_name"]
fc_datasink_name = 'temp_dataSink'
atlasPath = opj(s,task_info["atlas_path"])


# mask_file = '/media/varun/LENOVO4/Projects/result/preprocessPipeline/coregistrationPipeline/_subject_id_0050952/skullStrip/sub-0050952_T1w_resample_brain_mask.nii.gz'
# os.chdir(path)

In [464]:
# opj(base_directory,parent_wf_directory,motion_correction_bet_directory,coreg_reg_directory,'resample_mni')

In [465]:
brain_path = opj(base_directory,datasink_name,'preprocessed_brain_paths/brain_file_list.npy')
mask_path = opj(base_directory,datasink_name,'preprocessed_mask_paths/mask_file_list.npy')
atlas_path = opj(base_directory,datasink_name,'atlas_paths/atlas_file_list.npy')
tr_path = opj(base_directory,datasink_name,'tr_paths/tr_list.npy')
motion_params_path = opj(base_directory,datasink_name,'motion_params_paths/motion_params_file_list.npy')

func2std_mat_path = opj(base_directory, datasink_name,'joint_xformation_matrix_paths/joint_xformation_matrix_file_list.npy')

MNI3mm_path = opj(base_directory,parent_wf_directory,motion_correction_bet_directory,coreg_reg_directory,'resample_mni/MNI152_T1_2mm_brain_resample.nii') 

# brain_list = np.load('../results_again_again/ABIDE1_Preprocess_Datasink/preprocessed_brain_paths/brain_file_list.npy')

In [466]:
# brain_path,mask_path,atlas_path,tr_path,motion_params_path,func2std_mat_path

In [ ]:


In [467]:
brain_path = np.load(brain_path)
mask_path = np.load(mask_path)
atlas_path = np.load(atlas_path)
tr_path = np.load(tr_path)
motion_params_path = np.load(motion_params_path)
func2std_mat_path = np.load(func2std_mat_path)

In [468]:
# for a,b,c,d,e in zip(brain_path,mask_path,atlas_path,tr_path,motion_params_path):
#     print (a,b,c,d,e,'\n')

In [ ]:


In [ ]:


In [469]:
layout = BIDSLayout(data_directory)

number_of_subjects = 2 # Number of subjects you wish to preprocess
# number_of_subjects = len(layout.get_subjects())

Checking the Data directory Structure


In [470]:
# len(layout.get_subjects()) # working!Gives us list of all the subjects

In [471]:
# layout.get_subjects();

To get the metadata associated with a subject. [Takes as argumment the filename of subject ]

Create a list of subjects


In [472]:
subject_list = (layout.get_subjects())#[0:number_of_subjects]
subject_list = list(map(int, subject_list))

Check which subjects have volumes > 'vol'


In [473]:
import pandas as pd

demographics_file_path = '/home1/varunk/Autism-Connectome-Analysis-brain_connectivity/notebooks/demographics.csv'
phenotype_file_path = '/home1/varunk/data/ABIDE1/RawDataBIDs/composite_phenotypic_file.csv'

df_phenotype = pd.read_csv(phenotype_file_path)
df_phenotype = df_phenotype.sort_values(['SUB_ID'])
df_phenotype_sub_id = df_phenotype.as_matrix(['SITE_ID','SUB_ID']).squeeze()

df_demographics = pd.read_csv(demographics_file_path)
df_demographics_volumes = df_demographics.as_matrix(['SITE_NAME','VOLUMES']).squeeze()

In [474]:
# df_phenotype.sort_values(['SUB_ID'])

In [475]:
df_demographics_volumes


Out[475]:
array([['CALTECH', 150.0],
       ['CMU', 240.0],
       ['KKI', 156.0],
       ['LEUVEN_1', 250.0],
       ['LEUVEN_2', 250.0],
       ['MAX_MUN', 120.0],
       ['NYU', 180.0],
       ['OHSU', 82.0],
       ['OLIN', 210.0],
       ['PITT', 200.0],
       ['SBL', 200.0],
       ['SDSU', 180.0],
       ['STANFORD', 180.0],
       ['TRINITY', 150.0],
       ['UCLA_1', 120.0],
       ['UCLA_2', 120.0],
       ['UM_1', 300.0],
       ['UM_2', 300.0],
       ['USM', 240.0],
       ['YALE', 200.0]], dtype=object)

In [476]:
# SUB_ID - Volumes Dictionary
site_vol_dict = dict(zip(df_demographics_volumes[:,0], df_demographics_volumes[:,1]))

# for site_subid in df_demographics_volumes:
    

# subid_site_dict = dict(zip(df_phenotype_sub_id[:,1], df_phenotype_sub_id[:,0]))

In [477]:
subid_vol_dict = dict(zip(df_phenotype_sub_id[:,1],[site_vol_dict[site] for site in df_phenotype_sub_id[:,0]] ))

In [478]:
(subid_vol_dict)


Out[478]:
{50002: 200.0,
 50003: 200.0,
 50004: 200.0,
 50005: 200.0,
 50006: 200.0,
 50007: 200.0,
 50008: 200.0,
 50009: 200.0,
 50010: 200.0,
 50011: 200.0,
 50012: 200.0,
 50013: 200.0,
 50014: 200.0,
 50015: 200.0,
 50016: 200.0,
 50017: 200.0,
 50019: 200.0,
 50020: 200.0,
 50022: 200.0,
 50023: 200.0,
 50024: 200.0,
 50025: 200.0,
 50026: 200.0,
 50027: 200.0,
 50028: 200.0,
 50029: 200.0,
 50030: 200.0,
 50031: 200.0,
 50032: 200.0,
 50033: 200.0,
 50034: 200.0,
 50035: 200.0,
 50036: 200.0,
 50037: 200.0,
 50038: 200.0,
 50039: 200.0,
 50040: 200.0,
 50041: 200.0,
 50042: 200.0,
 50043: 200.0,
 50044: 200.0,
 50045: 200.0,
 50046: 200.0,
 50047: 200.0,
 50048: 200.0,
 50049: 200.0,
 50050: 200.0,
 50051: 200.0,
 50052: 200.0,
 50053: 200.0,
 50054: 200.0,
 50055: 200.0,
 50056: 200.0,
 50057: 200.0,
 50058: 200.0,
 50059: 200.0,
 50060: 200.0,
 50102: 210.0,
 50103: 210.0,
 50104: 210.0,
 50105: 210.0,
 50106: 210.0,
 50107: 210.0,
 50108: 210.0,
 50109: 210.0,
 50110: 210.0,
 50111: 210.0,
 50112: 210.0,
 50113: 210.0,
 50114: 210.0,
 50115: 210.0,
 50116: 210.0,
 50117: 210.0,
 50118: 210.0,
 50119: 210.0,
 50120: 210.0,
 50121: 210.0,
 50122: 210.0,
 50123: 210.0,
 50124: 210.0,
 50125: 210.0,
 50126: 210.0,
 50127: 210.0,
 50128: 210.0,
 50129: 210.0,
 50130: 210.0,
 50131: 210.0,
 50132: 210.0,
 50133: 210.0,
 50134: 210.0,
 50135: 210.0,
 50136: 210.0,
 50137: 210.0,
 50142: 82.0,
 50143: 82.0,
 50144: 82.0,
 50145: 82.0,
 50146: 82.0,
 50147: 82.0,
 50148: 82.0,
 50149: 82.0,
 50150: 82.0,
 50152: 82.0,
 50153: 82.0,
 50155: 82.0,
 50156: 82.0,
 50157: 82.0,
 50158: 82.0,
 50159: 82.0,
 50160: 82.0,
 50161: 82.0,
 50162: 82.0,
 50163: 82.0,
 50164: 82.0,
 50165: 82.0,
 50166: 82.0,
 50167: 82.0,
 50168: 82.0,
 50169: 82.0,
 50170: 82.0,
 50171: 82.0,
 50182: 180.0,
 50183: 180.0,
 50184: 180.0,
 50185: 180.0,
 50186: 180.0,
 50187: 180.0,
 50188: 180.0,
 50189: 180.0,
 50190: 180.0,
 50191: 180.0,
 50192: 180.0,
 50193: 180.0,
 50194: 180.0,
 50195: 180.0,
 50196: 180.0,
 50197: 180.0,
 50198: 180.0,
 50199: 180.0,
 50200: 180.0,
 50201: 180.0,
 50202: 180.0,
 50203: 180.0,
 50204: 180.0,
 50205: 180.0,
 50206: 180.0,
 50207: 180.0,
 50208: 180.0,
 50209: 180.0,
 50210: 180.0,
 50211: 180.0,
 50212: 180.0,
 50213: 180.0,
 50214: 180.0,
 50215: 180.0,
 50216: 180.0,
 50217: 180.0,
 50232: 150.0,
 50233: 150.0,
 50234: 150.0,
 50235: 150.0,
 50236: 150.0,
 50237: 150.0,
 50238: 150.0,
 50239: 150.0,
 50240: 150.0,
 50241: 150.0,
 50242: 150.0,
 50243: 150.0,
 50244: 150.0,
 50245: 150.0,
 50246: 150.0,
 50247: 150.0,
 50248: 150.0,
 50249: 150.0,
 50250: 150.0,
 50251: 150.0,
 50252: 150.0,
 50253: 150.0,
 50254: 150.0,
 50255: 150.0,
 50257: 150.0,
 50259: 150.0,
 50260: 150.0,
 50261: 150.0,
 50262: 150.0,
 50263: 150.0,
 50264: 150.0,
 50265: 150.0,
 50266: 150.0,
 50267: 150.0,
 50268: 150.0,
 50269: 150.0,
 50270: 150.0,
 50271: 150.0,
 50272: 300.0,
 50273: 300.0,
 50274: 300.0,
 50275: 300.0,
 50276: 300.0,
 50277: 300.0,
 50278: 300.0,
 50279: 300.0,
 50280: 300.0,
 50281: 300.0,
 50282: 300.0,
 50283: 300.0,
 50284: 300.0,
 50285: 300.0,
 50286: 300.0,
 50287: 300.0,
 50288: 300.0,
 50289: 300.0,
 50290: 300.0,
 50291: 300.0,
 50292: 300.0,
 50293: 300.0,
 50294: 300.0,
 50295: 300.0,
 50296: 300.0,
 50297: 300.0,
 50298: 300.0,
 50299: 300.0,
 50300: 300.0,
 50301: 300.0,
 50302: 300.0,
 50303: 300.0,
 50304: 300.0,
 50305: 300.0,
 50306: 300.0,
 50307: 300.0,
 50308: 300.0,
 50309: 300.0,
 50310: 300.0,
 50311: 300.0,
 50312: 300.0,
 50313: 300.0,
 50314: 300.0,
 50315: 300.0,
 50316: 300.0,
 50317: 300.0,
 50318: 300.0,
 50319: 300.0,
 50320: 300.0,
 50321: 300.0,
 50322: 300.0,
 50323: 300.0,
 50324: 300.0,
 50325: 300.0,
 50326: 300.0,
 50327: 300.0,
 50328: 300.0,
 50329: 300.0,
 50330: 300.0,
 50331: 300.0,
 50332: 300.0,
 50333: 300.0,
 50334: 300.0,
 50335: 300.0,
 50336: 300.0,
 50337: 300.0,
 50338: 300.0,
 50339: 300.0,
 50340: 300.0,
 50341: 300.0,
 50342: 300.0,
 50343: 300.0,
 50344: 300.0,
 50345: 300.0,
 50346: 300.0,
 50347: 300.0,
 50348: 300.0,
 50349: 300.0,
 50350: 300.0,
 50351: 300.0,
 50352: 300.0,
 50353: 300.0,
 50354: 300.0,
 50355: 300.0,
 50356: 300.0,
 50357: 300.0,
 50358: 300.0,
 50359: 300.0,
 50360: 300.0,
 50361: 300.0,
 50362: 300.0,
 50363: 300.0,
 50364: 300.0,
 50365: 300.0,
 50366: 300.0,
 50367: 300.0,
 50368: 300.0,
 50369: 300.0,
 50370: 300.0,
 50371: 300.0,
 50372: 300.0,
 50373: 300.0,
 50374: 300.0,
 50375: 300.0,
 50376: 300.0,
 50377: 300.0,
 50378: 300.0,
 50379: 300.0,
 50380: 300.0,
 50381: 300.0,
 50382: 300.0,
 50383: 300.0,
 50385: 300.0,
 50386: 300.0,
 50387: 300.0,
 50388: 300.0,
 50390: 300.0,
 50391: 300.0,
 50397: 300.0,
 50399: 300.0,
 50402: 300.0,
 50403: 300.0,
 50404: 300.0,
 50405: 300.0,
 50406: 300.0,
 50407: 300.0,
 50408: 300.0,
 50410: 300.0,
 50411: 300.0,
 50412: 300.0,
 50413: 300.0,
 50414: 300.0,
 50415: 300.0,
 50416: 300.0,
 50417: 300.0,
 50418: 300.0,
 50419: 300.0,
 50421: 300.0,
 50422: 300.0,
 50423: 300.0,
 50424: 300.0,
 50425: 300.0,
 50426: 300.0,
 50427: 300.0,
 50428: 300.0,
 50432: 240.0,
 50433: 240.0,
 50434: 240.0,
 50435: 240.0,
 50436: 240.0,
 50437: 240.0,
 50438: 240.0,
 50439: 240.0,
 50440: 240.0,
 50441: 240.0,
 50442: 240.0,
 50443: 240.0,
 50444: 240.0,
 50445: 240.0,
 50446: 240.0,
 50447: 240.0,
 50448: 240.0,
 50449: 240.0,
 50450: 240.0,
 50451: 240.0,
 50452: 240.0,
 50453: 240.0,
 50454: 240.0,
 50455: 240.0,
 50456: 240.0,
 50457: 240.0,
 50458: 240.0,
 50459: 240.0,
 50460: 240.0,
 50461: 240.0,
 50462: 240.0,
 50463: 240.0,
 50464: 240.0,
 50465: 240.0,
 50466: 240.0,
 50467: 240.0,
 50468: 240.0,
 50469: 240.0,
 50470: 240.0,
 50471: 240.0,
 50472: 240.0,
 50473: 240.0,
 50474: 240.0,
 50475: 240.0,
 50476: 240.0,
 50477: 240.0,
 50478: 240.0,
 50479: 240.0,
 50480: 240.0,
 50481: 240.0,
 50482: 240.0,
 50483: 240.0,
 50484: 240.0,
 50485: 240.0,
 50486: 240.0,
 50487: 240.0,
 50488: 240.0,
 50489: 240.0,
 50490: 240.0,
 50491: 240.0,
 50492: 240.0,
 50493: 240.0,
 50494: 240.0,
 50495: 240.0,
 50496: 240.0,
 50497: 240.0,
 50498: 240.0,
 50499: 240.0,
 50500: 240.0,
 50501: 240.0,
 50502: 240.0,
 50503: 240.0,
 50504: 240.0,
 50505: 240.0,
 50506: 240.0,
 50507: 240.0,
 50508: 240.0,
 50509: 240.0,
 50510: 240.0,
 50511: 240.0,
 50512: 240.0,
 50513: 240.0,
 50514: 240.0,
 50515: 240.0,
 50516: 240.0,
 50517: 240.0,
 50518: 240.0,
 50519: 240.0,
 50520: 240.0,
 50521: 240.0,
 50522: 240.0,
 50523: 240.0,
 50524: 240.0,
 50525: 240.0,
 50526: 240.0,
 50527: 240.0,
 50528: 240.0,
 50529: 240.0,
 50530: 240.0,
 50531: 240.0,
 50532: 240.0,
 50551: 200.0,
 50552: 200.0,
 50553: 200.0,
 50554: 200.0,
 50555: 200.0,
 50556: 200.0,
 50557: 200.0,
 50558: 200.0,
 50559: 200.0,
 50560: 200.0,
 50561: 200.0,
 50562: 200.0,
 50563: 200.0,
 50564: 200.0,
 50565: 200.0,
 50566: 200.0,
 50567: 200.0,
 50568: 200.0,
 50569: 200.0,
 50570: 200.0,
 50571: 200.0,
 50572: 200.0,
 50573: 200.0,
 50574: 200.0,
 50575: 200.0,
 50576: 200.0,
 50577: 200.0,
 50578: 200.0,
 50601: 200.0,
 50602: 200.0,
 50603: 200.0,
 50604: 200.0,
 50605: 200.0,
 50606: 200.0,
 50607: 200.0,
 50608: 200.0,
 50609: 200.0,
 50610: 200.0,
 50611: 200.0,
 50612: 200.0,
 50613: 200.0,
 50614: 200.0,
 50615: 200.0,
 50616: 200.0,
 50617: 200.0,
 50618: 200.0,
 50619: 200.0,
 50620: 200.0,
 50621: 200.0,
 50622: 200.0,
 50623: 200.0,
 50624: 200.0,
 50625: 200.0,
 50626: 200.0,
 50627: 200.0,
 50628: 200.0,
 50642: 240.0,
 50643: 240.0,
 50644: 240.0,
 50645: 240.0,
 50646: 240.0,
 50647: 240.0,
 50648: 240.0,
 50649: 240.0,
 50650: 240.0,
 50651: 240.0,
 50652: 240.0,
 50653: 240.0,
 50654: 240.0,
 50655: 240.0,
 50656: 240.0,
 50657: 240.0,
 50658: 240.0,
 50659: 240.0,
 50660: 240.0,
 50661: 240.0,
 50663: 240.0,
 50664: 240.0,
 50665: 240.0,
 50666: 240.0,
 50667: 240.0,
 50668: 240.0,
 50669: 240.0,
 50682: 250.0,
 50683: 250.0,
 50685: 250.0,
 50686: 250.0,
 50687: 250.0,
 50688: 250.0,
 50689: 250.0,
 50690: 250.0,
 50691: 250.0,
 50692: 250.0,
 50693: 250.0,
 50694: 250.0,
 50695: 250.0,
 50696: 250.0,
 50697: 250.0,
 50698: 250.0,
 50699: 250.0,
 50700: 250.0,
 50701: 250.0,
 50702: 250.0,
 50703: 250.0,
 50704: 250.0,
 50705: 250.0,
 50706: 250.0,
 50707: 250.0,
 50708: 250.0,
 50709: 250.0,
 50710: 250.0,
 50711: 250.0,
 50722: 250.0,
 50723: 250.0,
 50724: 250.0,
 50725: 250.0,
 50726: 250.0,
 50727: 250.0,
 50728: 250.0,
 50730: 250.0,
 50731: 250.0,
 50732: 250.0,
 50733: 250.0,
 50734: 250.0,
 50735: 250.0,
 50736: 250.0,
 50737: 250.0,
 50738: 250.0,
 50739: 250.0,
 50740: 250.0,
 50741: 250.0,
 50742: 250.0,
 50743: 250.0,
 50744: 250.0,
 50745: 250.0,
 50746: 250.0,
 50747: 250.0,
 50748: 250.0,
 50749: 250.0,
 50750: 250.0,
 50751: 250.0,
 50752: 250.0,
 50753: 250.0,
 50754: 250.0,
 50755: 250.0,
 50756: 250.0,
 50757: 250.0,
 50772: 156.0,
 50773: 156.0,
 50774: 156.0,
 50775: 156.0,
 50776: 156.0,
 50777: 156.0,
 50778: 156.0,
 50779: 156.0,
 50780: 156.0,
 50781: 156.0,
 50782: 156.0,
 50783: 156.0,
 50784: 156.0,
 50785: 156.0,
 50786: 156.0,
 50787: 156.0,
 50788: 156.0,
 50789: 156.0,
 50790: 156.0,
 50791: 156.0,
 50792: 156.0,
 50793: 156.0,
 50794: 156.0,
 50795: 156.0,
 50796: 156.0,
 50797: 156.0,
 50798: 156.0,
 50799: 156.0,
 50800: 156.0,
 50801: 156.0,
 50802: 156.0,
 50803: 156.0,
 50804: 156.0,
 50805: 156.0,
 50806: 156.0,
 50807: 156.0,
 50808: 156.0,
 50809: 156.0,
 50810: 156.0,
 50811: 156.0,
 50812: 156.0,
 50813: 156.0,
 50814: 156.0,
 50815: 156.0,
 50816: 156.0,
 50817: 156.0,
 50818: 156.0,
 50819: 156.0,
 50820: 156.0,
 50821: 156.0,
 50822: 156.0,
 50823: 156.0,
 50824: 156.0,
 50825: 156.0,
 50826: 156.0,
 50952: 180.0,
 50953: 180.0,
 50954: 180.0,
 50955: 180.0,
 50956: 180.0,
 50957: 180.0,
 50958: 180.0,
 50959: 180.0,
 50960: 180.0,
 50961: 180.0,
 50962: 180.0,
 50964: 180.0,
 50965: 180.0,
 50966: 180.0,
 50967: 180.0,
 50968: 180.0,
 50969: 180.0,
 50970: 180.0,
 50971: 180.0,
 50972: 180.0,
 50973: 180.0,
 50974: 180.0,
 50975: 180.0,
 50976: 180.0,
 50977: 180.0,
 50978: 180.0,
 50979: 180.0,
 50980: 180.0,
 50981: 180.0,
 50982: 180.0,
 50983: 180.0,
 50984: 180.0,
 50985: 180.0,
 50986: 180.0,
 50987: 180.0,
 50988: 180.0,
 50989: 180.0,
 50990: 180.0,
 50991: 180.0,
 50992: 180.0,
 50993: 180.0,
 50994: 180.0,
 50995: 180.0,
 50996: 180.0,
 50997: 180.0,
 50998: 180.0,
 50999: 180.0,
 51000: 180.0,
 51001: 180.0,
 51002: 180.0,
 51003: 180.0,
 51006: 180.0,
 51007: 180.0,
 51008: 180.0,
 51009: 180.0,
 51010: 180.0,
 51011: 180.0,
 51012: 180.0,
 51013: 180.0,
 51014: 180.0,
 51015: 180.0,
 51016: 180.0,
 51017: 180.0,
 51018: 180.0,
 51019: 180.0,
 51020: 180.0,
 51021: 180.0,
 51023: 180.0,
 51024: 180.0,
 51025: 180.0,
 51026: 180.0,
 51027: 180.0,
 51028: 180.0,
 51029: 180.0,
 51030: 180.0,
 51032: 180.0,
 51033: 180.0,
 51034: 180.0,
 51035: 180.0,
 51036: 180.0,
 51038: 180.0,
 51039: 180.0,
 51040: 180.0,
 51041: 180.0,
 51042: 180.0,
 51044: 180.0,
 51045: 180.0,
 51046: 180.0,
 51047: 180.0,
 51048: 180.0,
 51049: 180.0,
 51050: 180.0,
 51051: 180.0,
 51052: 180.0,
 51053: 180.0,
 51054: 180.0,
 51055: 180.0,
 51056: 180.0,
 51057: 180.0,
 51058: 180.0,
 51059: 180.0,
 51060: 180.0,
 51061: 180.0,
 51062: 180.0,
 51063: 180.0,
 51064: 180.0,
 51065: 180.0,
 51066: 180.0,
 51067: 180.0,
 51068: 180.0,
 51069: 180.0,
 51070: 180.0,
 51071: 180.0,
 51072: 180.0,
 51073: 180.0,
 51074: 180.0,
 51075: 180.0,
 51076: 180.0,
 51077: 180.0,
 51078: 180.0,
 51079: 180.0,
 51080: 180.0,
 51081: 180.0,
 51082: 180.0,
 51083: 180.0,
 51084: 180.0,
 51085: 180.0,
 51086: 180.0,
 51087: 180.0,
 51088: 180.0,
 51089: 180.0,
 51090: 180.0,
 51091: 180.0,
 51093: 180.0,
 51094: 180.0,
 51095: 180.0,
 51096: 180.0,
 51097: 180.0,
 51098: 180.0,
 51099: 180.0,
 51100: 180.0,
 51101: 180.0,
 51102: 180.0,
 51103: 180.0,
 51104: 180.0,
 51105: 180.0,
 51106: 180.0,
 51107: 180.0,
 51108: 180.0,
 51109: 180.0,
 51110: 180.0,
 51111: 180.0,
 51112: 180.0,
 51113: 180.0,
 51114: 180.0,
 51115: 180.0,
 51116: 180.0,
 51117: 180.0,
 51118: 180.0,
 51119: 180.0,
 51120: 180.0,
 51121: 180.0,
 51122: 180.0,
 51123: 180.0,
 51124: 180.0,
 51125: 180.0,
 51126: 180.0,
 51127: 180.0,
 51128: 180.0,
 51129: 180.0,
 51130: 180.0,
 51131: 180.0,
 51132: 150.0,
 51133: 150.0,
 51134: 150.0,
 51135: 150.0,
 51136: 150.0,
 51137: 150.0,
 51138: 150.0,
 51139: 150.0,
 51140: 150.0,
 51141: 150.0,
 51142: 150.0,
 51146: 180.0,
 51147: 180.0,
 51148: 180.0,
 51149: 180.0,
 51150: 180.0,
 51151: 180.0,
 51152: 180.0,
 51153: 180.0,
 51154: 180.0,
 51155: 180.0,
 51156: 180.0,
 51159: 180.0,
 51160: 180.0,
 51161: 180.0,
 51162: 180.0,
 51163: 180.0,
 51164: 180.0,
 51165: 180.0,
 51166: 180.0,
 51167: 180.0,
 51168: 180.0,
 51169: 180.0,
 51170: 180.0,
 51171: 180.0,
 51172: 180.0,
 51173: 180.0,
 51174: 180.0,
 51175: 180.0,
 51176: 180.0,
 51177: 180.0,
 51178: 180.0,
 51179: 180.0,
 51180: 180.0,
 51181: 180.0,
 51182: 180.0,
 51183: 180.0,
 51184: 180.0,
 51185: 180.0,
 51186: 180.0,
 51187: 180.0,
 51188: 180.0,
 51189: 180.0,
 51190: 180.0,
 51191: 180.0,
 51192: 180.0,
 51193: 180.0,
 51194: 180.0,
 51195: 180.0,
 51196: 180.0,
 51197: 180.0,
 51198: 180.0,
 51199: 180.0,
 51201: 120.0,
 51202: 120.0,
 51203: 120.0,
 51204: 120.0,
 51205: 120.0,
 51206: 120.0,
 51207: 120.0,
 51208: 120.0,
 51209: 120.0,
 51210: 120.0,
 51211: 120.0,
 51212: 120.0,
 51213: 120.0,
 51214: 120.0,
 51215: 120.0,
 51216: 120.0,
 51217: 120.0,
 51218: 120.0,
 51219: 120.0,
 51220: 120.0,
 51221: 120.0,
 51222: 120.0,
 51223: 120.0,
 51224: 120.0,
 51225: 120.0,
 51226: 120.0,
 51227: 120.0,
 51228: 120.0,
 51229: 120.0,
 51230: 120.0,
 51231: 120.0,
 51232: 120.0,
 51233: 120.0,
 51234: 120.0,
 51235: 120.0,
 51236: 120.0,
 51237: 120.0,
 51238: 120.0,
 51239: 120.0,
 51240: 120.0,
 51241: 120.0,
 51242: 120.0,
 51243: 120.0,
 51244: 120.0,
 51245: 120.0,
 51246: 120.0,
 51247: 120.0,
 51248: 120.0,
 51249: 120.0,
 51250: 120.0,
 51251: 120.0,
 51252: 120.0,
 51253: 120.0,
 51254: 120.0,
 51255: 120.0,
 51256: 120.0,
 51257: 120.0,
 51258: 120.0,
 51259: 120.0,
 51260: 120.0,
 51261: 120.0,
 51262: 120.0,
 51263: 120.0,
 51264: 120.0,
 51265: 120.0,
 51266: 120.0,
 51267: 120.0,
 51268: 120.0,
 51269: 120.0,
 51270: 120.0,
 51271: 120.0,
 51272: 120.0,
 51273: 120.0,
 51274: 120.0,
 51275: 120.0,
 51276: 120.0,
 51277: 120.0,
 51278: 120.0,
 51279: 120.0,
 51280: 120.0,
 51281: 120.0,
 51282: 120.0,
 51291: 120.0,
 51292: 120.0,
 51293: 120.0,
 51294: 120.0,
 51295: 120.0,
 51296: 120.0,
 51297: 120.0,
 51298: 120.0,
 51299: 120.0,
 51300: 120.0,
 51301: 120.0,
 51302: 120.0,
 51303: 120.0,
 51304: 120.0,
 51305: 120.0,
 51306: 120.0,
 51307: 120.0,
 51308: 120.0,
 51309: 120.0,
 51310: 120.0,
 51311: 120.0,
 51312: 120.0,
 51313: 120.0,
 51314: 120.0,
 51315: 120.0,
 51316: 120.0,
 51317: 120.0,
 51318: 120.0,
 51319: 120.0,
 51320: 120.0,
 51321: 120.0,
 51322: 120.0,
 51323: 120.0,
 51324: 120.0,
 51325: 120.0,
 51326: 120.0,
 51327: 120.0,
 51328: 120.0,
 51329: 120.0,
 51330: 120.0,
 ...}

In [479]:
vols = 120
del_idx = []
for idx,df in enumerate(df_demographics_volumes):
#     print(idx,df[1])
    if df[1] < vols:
        del_idx.append(idx)
        
df_demographics_volumes = np.delete(df_demographics_volumes,del_idx, axis = 0)

In [ ]:


In [480]:
df_demographics_sites_refined = df_demographics_volumes[:,0]

In [481]:
df_demographics_sites_refined


Out[481]:
array(['CALTECH', 'CMU', 'KKI', 'LEUVEN_1', 'LEUVEN_2', 'MAX_MUN', 'NYU',
       'OLIN', 'PITT', 'SBL', 'SDSU', 'STANFORD', 'TRINITY', 'UCLA_1',
       'UCLA_2', 'UM_1', 'UM_2', 'USM', 'YALE'], dtype=object)

In [482]:
df_phenotype_sub_id


Out[482]:
array([['PITT', 50002],
       ['PITT', 50003],
       ['PITT', 50004],
       ..., 
       ['SBL', 51585],
       ['MAX_MUN', 51606],
       ['MAX_MUN', 51607]], dtype=object)

In [ ]:

Subject IDs to be considered -

subjects_refined


In [483]:
subjects_refined = []
for df in df_phenotype_sub_id:
    if df[0] in df_demographics_sites_refined:
#         print(df[1])
        subjects_refined.append(df[1])

In [484]:
len(subjects_refined)


Out[484]:
1084

In [485]:
subjects_refined = list(set(subjects_refined) - (set(df_phenotype_sub_id[:,1]) - set(subject_list) ) )

In [486]:
subject_list


Out[486]:
[50002,
 50003,
 50004,
 50005,
 50006,
 50007,
 50008,
 50009,
 50010,
 50011,
 50012,
 50013,
 50014,
 50015,
 50016,
 50017,
 50019,
 50020,
 50022,
 50023,
 50024,
 50025,
 50026,
 50027,
 50028,
 50029,
 50030,
 50031,
 50032,
 50033,
 50034,
 50035,
 50036,
 50037,
 50038,
 50039,
 50040,
 50041,
 50042,
 50043,
 50044,
 50045,
 50046,
 50047,
 50048,
 50049,
 50050,
 50051,
 50052,
 50053,
 50054,
 50055,
 50056,
 50057,
 50058,
 50059,
 50060,
 50102,
 50103,
 50104,
 50105,
 50106,
 50107,
 50108,
 50109,
 50110,
 50111,
 50112,
 50113,
 50114,
 50115,
 50116,
 50117,
 50118,
 50119,
 50120,
 50121,
 50122,
 50123,
 50124,
 50125,
 50126,
 50127,
 50128,
 50129,
 50130,
 50131,
 50132,
 50133,
 50134,
 50135,
 50136,
 50137,
 50142,
 50143,
 50144,
 50145,
 50146,
 50147,
 50148,
 50149,
 50150,
 50152,
 50153,
 50155,
 50156,
 50157,
 50158,
 50159,
 50160,
 50161,
 50162,
 50163,
 50164,
 50165,
 50166,
 50167,
 50168,
 50169,
 50170,
 50171,
 50182,
 50183,
 50184,
 50185,
 50186,
 50187,
 50188,
 50189,
 50190,
 50191,
 50192,
 50193,
 50194,
 50195,
 50196,
 50197,
 50198,
 50199,
 50200,
 50201,
 50202,
 50203,
 50204,
 50205,
 50206,
 50207,
 50208,
 50209,
 50210,
 50211,
 50212,
 50213,
 50214,
 50215,
 50216,
 50217,
 50232,
 50233,
 50234,
 50235,
 50236,
 50237,
 50238,
 50239,
 50240,
 50241,
 50242,
 50243,
 50244,
 50245,
 50246,
 50247,
 50248,
 50249,
 50250,
 50251,
 50252,
 50253,
 50254,
 50255,
 50257,
 50259,
 50260,
 50261,
 50262,
 50263,
 50264,
 50265,
 50266,
 50267,
 50268,
 50269,
 50270,
 50271,
 50272,
 50273,
 50274,
 50275,
 50276,
 50277,
 50278,
 50279,
 50280,
 50281,
 50282,
 50283,
 50284,
 50285,
 50286,
 50287,
 50288,
 50289,
 50290,
 50291,
 50292,
 50293,
 50294,
 50295,
 50296,
 50297,
 50298,
 50299,
 50300,
 50301,
 50302,
 50303,
 50304,
 50305,
 50306,
 50307,
 50308,
 50309,
 50310,
 50311,
 50312,
 50313,
 50314,
 50315,
 50316,
 50317,
 50318,
 50319,
 50320,
 50321,
 50322,
 50323,
 50324,
 50325,
 50326,
 50327,
 50328,
 50329,
 50330,
 50331,
 50332,
 50333,
 50334,
 50335,
 50336,
 50337,
 50338,
 50339,
 50340,
 50341,
 50342,
 50343,
 50344,
 50345,
 50346,
 50347,
 50348,
 50349,
 50350,
 50351,
 50352,
 50353,
 50354,
 50355,
 50356,
 50357,
 50358,
 50359,
 50360,
 50361,
 50362,
 50363,
 50364,
 50365,
 50366,
 50367,
 50368,
 50369,
 50370,
 50371,
 50372,
 50373,
 50374,
 50375,
 50376,
 50377,
 50378,
 50379,
 50380,
 50381,
 50382,
 50383,
 50385,
 50386,
 50387,
 50388,
 50390,
 50391,
 50397,
 50399,
 50402,
 50403,
 50404,
 50405,
 50406,
 50407,
 50408,
 50410,
 50411,
 50412,
 50413,
 50414,
 50415,
 50416,
 50417,
 50418,
 50419,
 50421,
 50422,
 50423,
 50424,
 50425,
 50426,
 50427,
 50428,
 50432,
 50433,
 50434,
 50435,
 50436,
 50437,
 50438,
 50439,
 50440,
 50441,
 50442,
 50443,
 50444,
 50445,
 50446,
 50447,
 50448,
 50449,
 50450,
 50451,
 50452,
 50453,
 50454,
 50455,
 50456,
 50457,
 50458,
 50459,
 50460,
 50461,
 50462,
 50463,
 50464,
 50465,
 50466,
 50467,
 50468,
 50469,
 50470,
 50471,
 50472,
 50473,
 50474,
 50475,
 50476,
 50477,
 50478,
 50479,
 50480,
 50481,
 50482,
 50483,
 50484,
 50485,
 50486,
 50487,
 50488,
 50489,
 50490,
 50491,
 50492,
 50493,
 50494,
 50495,
 50496,
 50497,
 50498,
 50499,
 50500,
 50501,
 50502,
 50503,
 50504,
 50505,
 50506,
 50507,
 50508,
 50509,
 50510,
 50511,
 50512,
 50513,
 50514,
 50515,
 50516,
 50517,
 50518,
 50519,
 50520,
 50521,
 50522,
 50523,
 50524,
 50525,
 50526,
 50527,
 50528,
 50529,
 50530,
 50531,
 50532,
 50551,
 50552,
 50553,
 50554,
 50555,
 50556,
 50557,
 50558,
 50559,
 50560,
 50561,
 50562,
 50563,
 50564,
 50565,
 50566,
 50567,
 50568,
 50569,
 50570,
 50571,
 50572,
 50573,
 50574,
 50575,
 50576,
 50577,
 50578,
 50601,
 50602,
 50603,
 50604,
 50605,
 50606,
 50607,
 50608,
 50609,
 50610,
 50611,
 50612,
 50613,
 50614,
 50615,
 50616,
 50617,
 50618,
 50619,
 50620,
 50621,
 50622,
 50623,
 50624,
 50625,
 50626,
 50627,
 50628,
 50642,
 50643,
 50644,
 50645,
 50646,
 50647,
 50648,
 50649,
 50650,
 50651,
 50652,
 50653,
 50654,
 50655,
 50656,
 50657,
 50658,
 50659,
 50660,
 50661,
 50663,
 50664,
 50665,
 50666,
 50667,
 50668,
 50669,
 50682,
 50683,
 50685,
 50686,
 50687,
 50688,
 50689,
 50690,
 50691,
 50692,
 50693,
 50694,
 50695,
 50696,
 50697,
 50698,
 50699,
 50700,
 50701,
 50702,
 50703,
 50704,
 50705,
 50706,
 50707,
 50708,
 50709,
 50710,
 50711,
 50722,
 50723,
 50724,
 50725,
 50726,
 50727,
 50728,
 50730,
 50731,
 50732,
 50733,
 50734,
 50735,
 50736,
 50737,
 50738,
 50739,
 50740,
 50741,
 50742,
 50743,
 50744,
 50745,
 50746,
 50747,
 50748,
 50749,
 50750,
 50751,
 50752,
 50753,
 50754,
 50755,
 50756,
 50757,
 50772,
 50773,
 50774,
 50775,
 50776,
 50777,
 50778,
 50779,
 50780,
 50781,
 50782,
 50783,
 50784,
 50785,
 50786,
 50787,
 50788,
 50789,
 50790,
 50791,
 50792,
 50793,
 50794,
 50795,
 50796,
 50797,
 50798,
 50799,
 50800,
 50801,
 50802,
 50803,
 50804,
 50805,
 50806,
 50807,
 50808,
 50809,
 50810,
 50811,
 50812,
 50813,
 50814,
 50815,
 50816,
 50817,
 50818,
 50819,
 50820,
 50821,
 50822,
 50823,
 50824,
 50825,
 50826,
 50952,
 50953,
 50954,
 50955,
 50956,
 50957,
 50958,
 50959,
 50960,
 50961,
 50962,
 50964,
 50965,
 50966,
 50967,
 50968,
 50969,
 50970,
 50971,
 50972,
 50973,
 50974,
 50975,
 50976,
 50977,
 50978,
 50979,
 50980,
 50981,
 50982,
 50983,
 50984,
 50985,
 50986,
 50987,
 50988,
 50989,
 50990,
 50991,
 50992,
 50993,
 50994,
 50995,
 50996,
 50997,
 50998,
 50999,
 51000,
 51001,
 51002,
 51003,
 51006,
 51007,
 51008,
 51009,
 51010,
 51011,
 51012,
 51013,
 51014,
 51015,
 51016,
 51017,
 51018,
 51019,
 51020,
 51021,
 51023,
 51024,
 51025,
 51026,
 51027,
 51028,
 51029,
 51030,
 51032,
 51033,
 51034,
 51035,
 51036,
 51038,
 51039,
 51040,
 51041,
 51042,
 51044,
 51045,
 51046,
 51047,
 51048,
 51049,
 51050,
 51051,
 51052,
 51053,
 51054,
 51055,
 51056,
 51057,
 51058,
 51059,
 51060,
 51061,
 51062,
 51063,
 51064,
 51065,
 51066,
 51067,
 51068,
 51069,
 51070,
 51071,
 51072,
 51073,
 51074,
 51075,
 51076,
 51077,
 51078,
 51079,
 51080,
 51081,
 51082,
 51083,
 51084,
 51085,
 51086,
 51087,
 51088,
 51089,
 51090,
 51091,
 51093,
 51094,
 51095,
 51096,
 51097,
 51098,
 51099,
 51100,
 51101,
 51102,
 51103,
 51104,
 51105,
 51106,
 51107,
 51108,
 51109,
 51110,
 51111,
 51112,
 51113,
 51114,
 51115,
 51116,
 51117,
 51118,
 51119,
 51120,
 51121,
 51122,
 51123,
 51124,
 51125,
 51126,
 51127,
 51128,
 51129,
 51130,
 51131,
 51132,
 51133,
 51134,
 51135,
 51136,
 51137,
 51138,
 51139,
 51140,
 51141,
 51142,
 51146,
 51147,
 51148,
 51149,
 51150,
 51151,
 51152,
 51153,
 51154,
 51155,
 51156,
 51159,
 51160,
 51161,
 51162,
 51163,
 51164,
 51165,
 51166,
 51167,
 51168,
 51169,
 51170,
 51171,
 51172,
 51173,
 51174,
 51175,
 51176,
 51177,
 51178,
 51179,
 51180,
 51181,
 51182,
 51183,
 51184,
 51185,
 51186,
 51187,
 51188,
 51189,
 51190,
 51191,
 51192,
 51193,
 51194,
 51195,
 51196,
 51197,
 51198,
 51199,
 51201,
 51202,
 51203,
 51204,
 51205,
 51206,
 51207,
 51208,
 51209,
 51210,
 51211,
 51212,
 51213,
 51214,
 51215,
 51216,
 51217,
 51218,
 51219,
 51220,
 51221,
 51222,
 51223,
 51224,
 51225,
 51226,
 51227,
 51228,
 51229,
 51230,
 51231,
 51234,
 51235,
 51236,
 51237,
 51238,
 51239,
 51240,
 51241,
 51248,
 51249,
 51250,
 51251,
 51252,
 51253,
 51254,
 51255,
 51256,
 51257,
 51258,
 51259,
 51260,
 51261,
 51262,
 51263,
 51264,
 51265,
 51266,
 51267,
 51268,
 51269,
 51271,
 51272,
 51273,
 51274,
 51275,
 51276,
 51277,
 51278,
 51279,
 51280,
 51281,
 51282,
 51291,
 51292,
 51293,
 51294,
 51295,
 51296,
 51297,
 51298,
 51299,
 51300,
 51301,
 51302,
 51303,
 51304,
 51305,
 51306,
 51307,
 51308,
 51309,
 51311,
 51312,
 51313,
 51314,
 51315,
 51316,
 51317,
 51318,
 51319,
 51320,
 51321,
 51322,
 51323,
 51324,
 51325,
 51326,
 51327,
 51328,
 51329,
 51330,
 51331,
 51332,
 51333,
 51334,
 51335,
 51336,
 51338,
 51339,
 51340,
 51341,
 ...]

In [487]:
len(subjects_refined)


Out[487]:
1074

In [488]:
subject_list = subjects_refined[0:number_of_subjects]

Volume correction

  • I have already extracted 4 volumes.
  • Now extract 120 - 4 = 116 volumes from each subject
  • So define vols = 114

In [489]:
vols = vols - 4

In [490]:
def vol_correct(sub_id, subid_vol_dict, vols):
    sub_vols = subid_vol_dict[sub_id] - 4
    if sub_vols > vols:
        t_min = sub_vols - vols
    elif sub_vols == vols:
        t_min = 0
    else:
        raise Exception('Volumes of Sub ',sub_id,' less than desired!')
    return int(t_min)

In [491]:
volCorrect = Node(Function(function=vol_correct, input_names=['sub_id','subid_vol_dict','vols'],
                                output_names=['t_min']), name='volCorrect')

volCorrect.inputs.subid_vol_dict = subid_vol_dict
volCorrect.inputs.vols = vols

In [492]:
# os.chdir('/home1/varunk/results_again_again/temp/')
# volCorrect.inputs.sub_id = 51456
# res = volCorrect.run()

In [493]:
# res.outputs

In [ ]:


In [494]:
# layout.get();

In [ ]:

Define a function to fetch the filenames of a particular subject ID


In [498]:
def get_subject_filenames(subject_id,brain_path,mask_path,atlas_path,tr_path,motion_params_path,func2std_mat_path,MNI3mm_path):
    import re

    for brain,mask,atlas,tr,motion_param,func2std_mat in zip(brain_path,mask_path,atlas_path,tr_path,motion_params_path,func2std_mat_path):
#         sub_id_extracted = re.search('.+_subject_id_(\d+)', brain).group(1)
#         if subject_id == sub_id_extracted:
        if str(subject_id) in brain:
#             print("Files for subject ",subject_id,brain,mask,atlas,tr,motion_param)
            return brain,mask,atlas,tr,motion_param,func2std_mat,MNI3mm_path
        
    print ('Unable to locate Subject: ',subject_id,'extracted: ',sub_id_extracted)
    return 0

In [499]:
# Make a node
getSubjectFilenames = Node(Function(function=get_subject_filenames, input_names=['subject_id','brain_path','mask_path','atlas_path','tr_path','motion_params_path','func2std_mat_path','MNI3mm_path'],
                                output_names=['brain','mask','atlas','tr','motion_param','func2std_mat', 'MNI3mm_path']), name='getSubjectFilenames')


getSubjectFilenames.inputs.brain_path = brain_path
getSubjectFilenames.inputs.mask_path = mask_path
getSubjectFilenames.inputs.atlas_path = atlas_path
getSubjectFilenames.inputs.tr_path = tr_path
getSubjectFilenames.inputs.motion_params_path = motion_params_path
getSubjectFilenames.inputs.func2std_mat_path = func2std_mat_path
getSubjectFilenames.inputs.MNI3mm_path = MNI3mm_path

In [500]:
# import re
# text = '/home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/coreg_reg/atlas_resize_reg_directory/_subject_id_0050004/111std2func_xform/fullbrain_atlas_thr0-2mm_resample_flirt.nii'

# try:
#     found = re.search('.+_subject_id_(\d+)', text).group(1)
# except AttributeError:
#     # AAA, ZZZ not found in the original string
#     found = '' # apply your error handling

# # found: 1234

In [501]:
# found

In [502]:
infosource = Node(IdentityInterface(fields=['subject_id']),
                  name="infosource")

infosource.iterables = [('subject_id',subject_list)]


# ,'brain_path','mask_path','atlas_path','tr_path','motion_params_path'
# infosource.brain_path = brain_path
# infosource.mask_path = mask_path
# infosource.atlas_path = atlas_path
# infosource.tr_path = tr_path
# infosource.motion_params_path = motion_params_path

Band Pass Filtering

Let's do a band pass filtering on the data using the code from https://neurostars.org/t/bandpass-filtering-different-outputs-from-fsl-and-nipype-custom-function/824/2


In [503]:
### AFNI

bandpass = Node(afni.Bandpass(highpass=0.01, lowpass=0.1, 
                         despike=False, no_detrend=True, notrans=True, 
                         outputtype='NIFTI_GZ'),name='bandpass')

# bandpass = Node(afni.Bandpass(highpass=0.001, lowpass=0.01, 
#                          despike=False, no_detrend=True, notrans=True, 
#                          tr=2.0,outputtype='NIFTI_GZ'),name='bandpass')


# bandpass.inputs.mask = MNI152_2mm.outputs.mask_file

# highpass=0.008, lowpass=0.08,

In [504]:
# Testing bandpass on the func data in subject's space

# First comment out the bandpass.inputs.mask as it is in standard space.

# subject_id = layout.get_subjects()[0] # gives the first subject's ID
# func_file_path = [f.filename for f in layout.get(subject=subject_id, type='bold', extensions=['nii', 'nii.gz'])] 
# bandpass.inputs.in_file = func_file_path[0]
# res = bandpass.run();

In [505]:
# res.outputs.out_file

Highpass filtering


In [506]:
# https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dBandpass.html
# os.chdir('/home1/varunk/Autism-Connectome-Analysis-bids-related/')
highpass = Node(afni.Bandpass(highpass=0.01, lowpass=99999, 
                         despike=False, no_detrend=True, notrans=True, 
                         outputtype='NIFTI_GZ'),name='highpass')

In [507]:
# # Test

# subject_id = layout.get_subjects()[0] # gives the first subject's ID
# func_file_path = [f.filename for f in layout.get(subject=subject_id, type='bold', extensions=['nii', 'nii.gz'])] 
# highpass.inputs.in_file = func_file_path[0]
# res = highpass.run();

Smoothing

Using 6mm fwhm

sigma = 6/2.3548 = 2.547987090198743


In [508]:
spatialSmooth = Node(interface=ImageMaths(op_string='-s 2.5479',
                                            suffix='_smoothed'),
                   name='spatialSmooth')

In [509]:
def orthogonalize(in_file, mask_file):
    import numpy as np
    import nibabel as nib
    import os
    from os.path import join as opj
    
    def gram_schmidt(voxel_time_series, mean_vector):
        numerator = np.dot(voxel_time_series,mean_vector)
        dinominator = np.dot(mean_vector,mean_vector)
        voxel_time_series_orthogonalized = voxel_time_series - (numerator/dinominator)*mean_vector
        
#         TO CONFIRM IF THE VECTORS ARE ORTHOGONAL
#         sum_dot_prod = np.sum(np.dot(voxel_time_series_orthogonalized,mean_vector))
        
#         print('Sum of entries of orthogonalized vector = ',sum_dot_prod)
        return voxel_time_series_orthogonalized
    
    
    mask_data = nib.load(mask_file)
    mask = mask_data.get_data()
    
    brain_data = nib.load(in_file)
    brain = brain_data.get_data()

    x_dim, y_dim, z_dim, t_dim = brain_data.shape
    
    
    
    # Find mean brain
    
    
    mean_vector = np.zeros(t_dim)
    
    
    num_brain_voxels = 0
    
    # Count the number of brain voxels
    for i in range(x_dim):
        for j in range(y_dim):
            for k in range(z_dim):
                if mask[i,j,k] == 1:
                    mean_vector = mean_vector + brain[i,j,k,:]
                    num_brain_voxels = num_brain_voxels + 1
                    
     
    mean_vector = mean_vector / num_brain_voxels
    
    # Orthogonalize
    for i in range(x_dim):
        for j in range(y_dim):
            for k in range(z_dim):
                if mask[i,j,k] == 1:
                    brain[i,j,k,:] = gram_schmidt(brain[i,j,k,:], mean_vector)
                    
    
    
    sub_id = in_file.split('/')[-1].split('.')[0].split('_')[0].split('-')[1]
    
    gsr_file_name = 'sub-' + sub_id + '_task-rest_run-1_bold.nii.gz'
    
#     gsr_file_name_nii = gsr_file_name + '.nii.gz'
    
    out_file = opj(os.getcwd(),gsr_file_name) # path
    
    brain_with_header = nib.Nifti1Image(brain, affine=brain_data.affine,header = brain_data.header)
    nib.save(brain_with_header,gsr_file_name)
    
    return out_file

In [510]:
globalSignalRemoval = Node(Function(function=orthogonalize, input_names=['in_file','mask_file'], 
                                  output_names=['out_file']), name='globalSignalRemoval' )
# globalSignalRemoval.inputs.mask_file = mask_file
# globalSignalRemoval.iterables = [('in_file',file_paths)]

In [ ]:


In [ ]:


In [ ]:

GLM for regression of motion parameters


In [511]:
def calc_residuals(subject,
                   motion_file):
    """
    Calculates residuals of nuisance regressors -motion parameters for every voxel for a subject using GLM.
    
    Parameters
    ----------
    subject : string
        Path of a subject's motion corrected nifti file.
    motion_par_file : string
        path of a subject's motion parameters
    
        
    Returns
    -------
    residual_file : string
        Path of residual file in nifti format
    
    """
    import nibabel as nb
    import numpy as np
    import os
    from os.path import join as opj
    nii = nb.load(subject)
    data = nii.get_data().astype(np.float32)
    global_mask = (data != 0).sum(-1) != 0

    
    # Check and define regressors which are provided from files
    if motion_file is not None:
        motion = np.genfromtxt(motion_file)
        if motion.shape[0] != data.shape[3]:
            raise ValueError('Motion parameters {0} do not match data '
                             'timepoints {1}'.format(motion.shape[0], 
                                                     data.shape[3]))
        if motion.size == 0:
            raise ValueError('Motion signal file {0} is '
                             'empty'.format(motion_file))

    # Calculate regressors
    regressor_map = {'constant' : np.ones((data.shape[3],1))}
        
    regressor_map['motion'] = motion
        
    
    X = np.zeros((data.shape[3], 1))
    
    for rname, rval in regressor_map.items():
        X = np.hstack((X, rval.reshape(rval.shape[0],-1)))

    X = X[:,1:]
    
    if np.isnan(X).any() or np.isnan(X).any():
        raise ValueError('Regressor file contains NaN')

    Y = data[global_mask].T

    try:
        B = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y)
    except np.linalg.LinAlgError as e:
        if "Singular matrix" in e:
            raise Exception("Error details: {0}\n\nSingular matrix error: "
                            "The nuisance regression configuration you "
                            "selected may have been too stringent, and the "
                            "regression could not be completed. Ensure your "
                            "parameters are not too "
                            "extreme.\n\n".format(e))
        else:
            raise Exception("Error details: {0}\n\nSomething went wrong with "
                            "nuisance regression.\n\n".format(e))

    Y_res = Y - X.dot(B)
    
    data[global_mask] = Y_res.T
    
    img = nb.Nifti1Image(data, header=nii.get_header(),
                         affine=nii.get_affine())
    
    subject_name = subject.split('/')[-1].split('.')[0]
    filename = subject_name + '_residual.nii.gz'
    residual_file = os.path.join(os.getcwd(),filename )
    img.to_filename(residual_file) # alt to nib.save
    
    return residual_file

In [512]:
# Create a Node for above
calc_residuals = Node(Function(function=calc_residuals, input_names=['subject','motion_file'],
                                output_names=['residual_file']), name='calc_residuals')

In [ ]:

Datasink

I needed to define the structure of what files are saved and where.


In [513]:
# Create DataSink object
dataSink = Node(DataSink(), name='datasink')

# Name of the output folder
dataSink.inputs.base_directory = opj(base_directory,fc_datasink_name)

To create the substitutions I looked the datasink folder where I was redirecting the output. I manually selected the part of file/folder name that I wanted to change and copied below to be substituted.


In [514]:
# Define substitution strings so that the data is similar to BIDS
substitutions = [('_subject_id_', 'sub-')]

# Feed the substitution strings to the DataSink node
dataSink.inputs.substitutions = substitutions

# ('_resample_brain_flirt.nii_brain', ''),
# ('_roi_st_mcf_flirt.nii_brain_flirt', ''),

In [515]:
base_directory


Out[515]:
'/home1/varunk/results_again_again'

Following is a Join Node that collects the preprocessed file paths and saves them in a file


In [516]:
def save_file_list_function(in_fc_map_brain_file):
    # Imports
    import numpy as np
    import os
    from os.path import join as opj
    
    
    file_list = np.asarray(in_fc_map_brain_file)
    print('######################## File List ######################: \n',file_list)

    np.save('fc_map_brain_file_list',file_list)
    file_name = 'fc_map_brain_file_list.npy'
    out_fc_map_brain_file = opj(os.getcwd(),file_name) # path

    
    
    
    
    
    return out_fc_map_brain_file

In [517]:
save_file_list = JoinNode(Function(function=save_file_list_function, input_names=['in_fc_map_brain_file'],
                 output_names=['out_fc_map_brain_file']),
                 joinsource="infosource",
                 joinfield=['in_fc_map_brain_file'],
                 name="save_file_list")

Create a FC node

This node:

  1. Exracts the average time series of the brain ROI's using the atlas and stores it as a matrix of size [ROIs x Volumes].
  2. Extracts the Voxel time series and stores it in matrix of size [Voxels x Volumes]

Saving the Brains instead of FC matrices


In [520]:
# Saves the brains instead of FC matrix files
def pear_coff(in_file, atlas_file, mask_file):
    # code to find how many voxels are in the brain region using the mask
    
        # imports
    import numpy as np
    import nibabel as nib
    import os
    from os.path import join as opj

    mask_data = nib.load(mask_file)
    mask = mask_data.get_data()

    x_dim, y_dim, z_dim = mask_data.shape

                    
    atlasPath = atlas_file
    # Read the atlas
    atlasObject = nib.load(atlasPath)
    atlas = atlasObject.get_data()
    
    num_ROIs = int((np.max(atlas) - np.min(atlas) ))


    # Read the brain in_file

    brain_data = nib.load(in_file)
    brain = brain_data.get_data()

    x_dim, y_dim, z_dim, num_volumes = brain.shape
    
    
    num_brain_voxels = 0

    x_dim, y_dim, z_dim = mask_data.shape

    for i in range(x_dim):
        for j in range(y_dim):
            for k in range(z_dim):
                if mask[i,j,k] == 1:
                    num_brain_voxels = num_brain_voxels + 1
    
    # Initialize a matrix of ROI time series and voxel time series

    ROI_matrix = np.zeros((num_ROIs, num_volumes))
    voxel_matrix = np.zeros((num_brain_voxels, num_volumes))
    
    # Fill up the voxel_matrix 

    voxel_counter = 0
    for i in range(x_dim):
        for j in range(y_dim):
            for k in range(z_dim):
                if mask[i,j,k] == 1:
                    voxel_matrix[voxel_counter,:] = brain[i,j,k,:] 
                    voxel_counter = voxel_counter + 1

                    
    # Fill up the ROI_matrix
    # Keep track of number of voxels per ROI as well by using an array - num_voxels_in_ROI[]

    num_voxels_in_ROI = np.zeros((num_ROIs,1)) # A column arrray containing number of voxels in each ROI

    for i in range(x_dim):
        for j in range(y_dim):
            for k in range(z_dim):
                label = int(atlas[i,j,k]) - 1
                if label != -1:
                    ROI_matrix[label,:] = np.add(ROI_matrix[label,:], brain[i,j,k,:])
                    num_voxels_in_ROI[label,0] = num_voxels_in_ROI[label,0] + 1

    ROI_matrix = np.divide(ROI_matrix,num_voxels_in_ROI) # Check if divide is working correctly

    X, Y = ROI_matrix, voxel_matrix


    # Subtract mean from X and Y

    X = np.subtract(X, np.mean(X, axis=1, keepdims=True))
    Y = np.subtract(Y, np.mean(Y, axis=1, keepdims=True))

    temp1 = np.dot(X,Y.T)
    temp2 = np.sqrt(np.sum(np.multiply(X,X), axis=1, keepdims=True))
    temp3 = np.sqrt(np.sum(np.multiply(Y,Y), axis=1, keepdims=True))
    temp4 = np.dot(temp2,temp3.T)
    coff_matrix = np.divide(temp1, (temp4 + 1e-7))
    
    
    # Check if any ROI is missing and replace the NAN values in coff_matrix by 0
    if np.argwhere(np.isnan(coff_matrix)).shape[0] != 0:
        print("Some ROIs are not present. Replacing NAN in coff matrix by 0")
        np.nan_to_num(coff_matrix, copy=False)

    # TODO: when I have added 1e-7 in the dinominator, then why did I feel the need to replace NAN by zeros 
    sub_id = in_file.split('/')[-1].split('.')[0].split('_')[0].split('-')[1]
    
    
    fc_file_name = sub_id + '_fc_map'
    
    print ("Pear Matrix calculated for subject: ",sub_id)

    roi_brain_matrix = coff_matrix
    brain_file = in_file


    x_dim, y_dim, z_dim, t_dim = brain.shape

    (brain_data.header).set_data_shape([x_dim,y_dim,z_dim,num_ROIs])

    brain_roi_tensor = np.zeros((brain_data.header.get_data_shape()))
    
    print("Creating brain for Subject-",sub_id)
    for roi in range(num_ROIs):
        brain_voxel_counter = 0
        for i in range(x_dim):
            for j in range(y_dim):
                for k in range(z_dim):
                    if mask[i,j,k] == 1:
                        brain_roi_tensor[i,j,k,roi] = roi_brain_matrix[roi,brain_voxel_counter]
                        brain_voxel_counter = brain_voxel_counter + 1

        
        assert (brain_voxel_counter == len(roi_brain_matrix[roi,:])) 
    print("Created brain for Subject-",sub_id)


    path = os.getcwd()
    fc_file_name = fc_file_name + '.nii.gz'
    out_file = opj(path,fc_file_name)
    
    brain_with_header = nib.Nifti1Image(brain_roi_tensor, affine=brain_data.affine,header = brain_data.header)
    nib.save(brain_with_header,out_file)
    
    
    fc_map_brain_file = out_file
    return fc_map_brain_file

In [521]:
# Again Create the Node and set default values to paths

pearcoff = Node(Function(function=pear_coff, input_names=['in_file','atlas_file','mask_file'],
                                output_names=['fc_map_brain_file']), name='pearcoff')


# output_names=['fc_map_brain_file']
# pearcoff.inputs.atlas_file = atlasPath
# pearcoff.inputs.num_brain_voxels = num_brain_voxels
# pearcoff.inputs.mask_file = mask_file

IMPORTANT:

  • The ROI 255 has been removed due to resampling. Therefore the FC maps will have nan at that row. So don't use that ROI :)
  • I came to know coz I keep getting this error: RuntimeWarning: invalid value encountered in true_divide
  • To debug it, I read the coff matrix and checked its diagnol to discover the nan value.

Extract volumes


In [522]:
# ExtractROI - skip dummy scans
extract = Node(ExtractROI(t_size=-1),
               output_type='NIFTI',
               name="extract")

# t_min=4,

Node for applying xformation matrix to functional data


In [523]:
func2std_xform = Node(FLIRT(output_type='NIFTI_GZ',
                         apply_xfm=True), name="func2std_xform")

In [524]:
# %%time
# pearcoff.run()

In [525]:
# motion_param_reg = [True, False]
# global_signal_reg = [True, False]
# band_pass_filt= [True, False]
# for motion_param_regression, global_signal_regression, band_pass_filtering in zip(motion_param_reg, global_signal_reg, band_pass_filt):
#     print (motion_param_regression, global_signal_regression, band_pass_filtering)

In [526]:
# import itertools
# itr = (list(itertools.product([0, 1], repeat=3)))

# for motion_param_regression, global_signal_regression, band_pass_filtering in itr:
#     print(motion_param_regression, global_signal_regression, band_pass_filtering)

In [527]:
# import itertools
# itr = (list(itertools.product([0, 1], repeat=3)))

# for motion_param_regression, global_signal_regression, band_pass_filtering in itr:

In [528]:
# base_directory

Write the code to convert the FC maps to brains instead


In [529]:
motion_param_regression = 1
band_pass_filtering = 1
global_signal_regression = 0
smoothing = 1
volcorrect = 1

num_proc = 7

combination = 'motionRegress' + str(int(motion_param_regression)) + 'filt' + \
              str(int(band_pass_filtering)) + 'global' + str(int(global_signal_regression)) + \
              'smoothing' + str(int(smoothing))
        
print("Combination: ",combination)

base_dir = opj(base_directory,functional_connectivity_directory)
# wf = Workflow(name=functional_connectivity_directory)
wf = Workflow(name=combination)

wf.base_dir = base_dir # Dir where all the outputs will be stored.

wf.connect([(infosource , getSubjectFilenames, [('subject_id','subject_id')])])


if motion_param_regression == 1 and global_signal_regression == 0 and band_pass_filtering == 1 and smoothing == 1 and volcorrect == 1: # 101

    wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
    wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
    
    wf.connect([( calc_residuals, extract, [('residual_file','in_file')])])
    
    wf.connect([(infosource, volCorrect, [('subject_id','sub_id')])])
    
    wf.connect([( volCorrect, extract, [('t_min','t_min')])])
    
    wf.connect([(extract, bandpass, [('roi_file','in_file')])])
    
    wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

    wf.connect([( bandpass, spatialSmooth, [('out_file','in_file')])])

    wf.connect([( spatialSmooth, pearcoff, [('out_file','in_file')])])
    
    
#     wf.connect([( extract, pearcoff, [('roi_file','in_file')])])
    
    # wf.connect([( bandpass, pearcoff, [('out_file','in_file')])])
    wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
    wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])

    # ---------------------------------------------------------------------------------------
    wf.connect([(pearcoff, func2std_xform, [('fc_map_brain_file','in_file')])])
    wf.connect([(getSubjectFilenames, func2std_xform, [('func2std_mat','in_matrix_file')])])
    wf.connect([(getSubjectFilenames, func2std_xform, [('MNI3mm_path','reference')])])

    #         -- send out file to save file list and then save the outputs



    folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



    wf.connect([(func2std_xform,  save_file_list, [('out_file','in_fc_map_brain_file')])])
    # --------------------------------------------------------------------------------------------


    wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

    wf.write_graph(graph2use='flat', format='png')
#     from IPython.display import Image
#     wf.write_graph(graph2use='exec', format='png', simple_form=True)
    
    wf.run('MultiProc', plugin_args={'n_procs': num_proc})
#     file_name = opj(base_dir,combination,'graph_detailed.dot.png')
#     Image(filename=file_name)
 
elif motion_param_regression == 1 and global_signal_regression == 1 and band_pass_filtering == 1 and smoothing == 1: #111
    wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
    wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
    
    wf.connect([( calc_residuals, extract, [('residual_file','in_file')])])
    
    wf.connect([(infosource, volCorrect, [('subject_id','sub_id')])])
    
    wf.connect([( volCorrect, extract, [('t_min','t_min')])])
    
    wf.connect([(extract, globalSignalRemoval, [('roi_file','in_file')])])
    

#     wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
    wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

    wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
    wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

    wf.connect([( bandpass, spatialSmooth, [('out_file','in_file')])])

    wf.connect([( spatialSmooth, pearcoff, [('out_file','in_file')])])

    # wf.connect([( bandpass, pearcoff, [('out_file','in_file')])])
    wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
    wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])

    # ---------------------------------------------------------------------------------------
    wf.connect([(pearcoff, func2std_xform, [('fc_map_brain_file','in_file')])])
    wf.connect([(getSubjectFilenames, func2std_xform, [('func2std_mat','in_matrix_file')])])
    wf.connect([(getSubjectFilenames, func2std_xform, [('MNI3mm_path','reference')])])

#         -- send out file to save file list and then save the outputs



    folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



    wf.connect([(func2std_xform,  save_file_list, [('out_file','in_fc_map_brain_file')])])
    # --------------------------------------------------------------------------------------------


    wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])


    #  wf.connect([(bandpass,  dataSink, [('out_file','motionRegress_filt_global.@out_file')])])


    # if motion_param_regression == 1 and global_signal_regression == 1:
    wf.write_graph(graph2use='flat', format='png')
    wf.run('MultiProc', plugin_args={'n_procs': num_proc})


Combination:  motionRegress1filt1global0smoothing1
171229-19:59:16,984 workflow INFO:
	 Generated workflow graph: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/graph.dot.png (graph2use=flat, simple_form=True).
171229-19:59:18,602 workflow INFO:
	 Workflow motionRegress1filt1global0smoothing1 settings: ['check', 'execution', 'logging']
171229-19:59:18,627 workflow INFO:
	 Running in parallel.
171229-19:59:18,630 workflow INFO:
	 Executing: volCorrect.a1 ID: 0
171229-19:59:18,637 workflow INFO:
	 [Job finished] jobname: volCorrect.a1 jobid: 0
171229-19:59:18,638 workflow INFO:
	 Executing: getSubjectFilenames.a1 ID: 1
171229-19:59:18,642 workflow INFO:
	 Executing: volCorrect.a0 ID: 8
171229-19:59:18,662 workflow INFO:
	 [Job finished] jobname: volCorrect.a0 jobid: 8
171229-19:59:18,664 workflow INFO:
	 Executing: getSubjectFilenames.a0 ID: 9
171229-19:59:18,662 workflow INFO:
	 Executing node getSubjectFilenames.a1 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/getSubjectFilenames
171229-19:59:18,676 workflow INFO:
	 Executing node getSubjectFilenames.a0 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/getSubjectFilenames
171229-19:59:19,11 workflow INFO:
	 [Job finished] jobname: getSubjectFilenames.a1 jobid: 1
171229-19:59:19,13 workflow INFO:
	 Executing: calc_residuals.a1 ID: 2
171229-19:59:19,30 workflow INFO:
	 Executing node calc_residuals.a1 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/calc_residuals
171229-19:59:19,109 workflow INFO:
	 [Job finished] jobname: getSubjectFilenames.a0 jobid: 9
171229-19:59:19,112 workflow INFO:
	 Executing: calc_residuals.a0 ID: 10
171229-19:59:19,129 workflow INFO:
	 Executing node calc_residuals.a0 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/calc_residuals
171229-19:59:22,411 workflow INFO:
	 [Job finished] jobname: calc_residuals.a1 jobid: 2
171229-19:59:22,414 workflow INFO:
	 Executing: extract.a1 ID: 3
171229-19:59:22,418 workflow INFO:
	 Executing node extract.a1 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/extract
171229-19:59:22,423 workflow INFO:
	 [Job finished] jobname: calc_residuals.a0 jobid: 10
171229-19:59:22,425 workflow INFO:
	 Executing: extract.a0 ID: 11
171229-19:59:22,426 workflow INFO:
	 Running: fslroi /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/calc_residuals/sub-0050003_task-rest_run-1_bold_roi_st_mcf_residual.nii.gz /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/extract/sub-0050003_task-rest_run-1_bold_roi_st_mcf_residual_roi.nii.gz 80 -1
171229-19:59:22,428 workflow INFO:
	 Executing node extract.a0 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/extract
171229-19:59:22,434 workflow INFO:
	 Running: fslroi /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/calc_residuals/sub-0050002_task-rest_run-1_bold_roi_st_mcf_residual.nii.gz /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/extract/sub-0050002_task-rest_run-1_bold_roi_st_mcf_residual_roi.nii.gz 80 -1
171229-19:59:24,697 workflow INFO:
	 [Job finished] jobname: extract.a1 jobid: 3
171229-19:59:24,700 workflow INFO:
	 Executing: bandpass.a1 ID: 4
171229-19:59:24,733 workflow INFO:
	 [Job finished] jobname: extract.a0 jobid: 11
171229-19:59:24,734 workflow INFO:
	 Executing node bandpass.a1 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/bandpass
171229-19:59:24,736 workflow INFO:
	 Executing: bandpass.a0 ID: 12
171229-19:59:24,741 workflow INFO:
	 Running: 3dBandpass -prefix sub-0050003_task-rest_run-1_bold_roi_st_mcf_residual_roi_bp.nii.gz -nodetrend -notrans -dt 1.500000 0.010000 0.100000 /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/bandpass/sub-0050003_task-rest_run-1_bold_roi_st_mcf_residual_roi.nii.gz
171229-19:59:24,745 workflow INFO:
	 Executing node bandpass.a0 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/bandpass
171229-19:59:24,749 workflow INFO:
	 Running: 3dBandpass -prefix sub-0050002_task-rest_run-1_bold_roi_st_mcf_residual_roi_bp.nii.gz -nodetrend -notrans -dt 1.500000 0.010000 0.100000 /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/bandpass/sub-0050002_task-rest_run-1_bold_roi_st_mcf_residual_roi.nii.gz
171229-19:59:27,629 workflow INFO:
	 [Job finished] jobname: bandpass.a0 jobid: 12
171229-19:59:27,632 workflow INFO:
	 Executing: spatialSmooth.a0 ID: 13
171229-19:59:27,634 workflow INFO:
	 Executing node spatialSmooth.a0 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/spatialSmooth
171229-19:59:27,638 workflow INFO:
	 Running: fslmaths /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/bandpass/sub-0050002_task-rest_run-1_bold_roi_st_mcf_residual_roi_bp.nii.gz -s 2.5479 /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/spatialSmooth/sub-0050002_task-rest_run-1_bold_roi_st_mcf_residual_roi_bp_smoothed.nii.gz
171229-19:59:27,655 workflow INFO:
	 [Job finished] jobname: bandpass.a1 jobid: 4
171229-19:59:27,658 workflow INFO:
	 Executing: spatialSmooth.a1 ID: 5
171229-19:59:27,660 workflow INFO:
	 Executing node spatialSmooth.a1 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/spatialSmooth
171229-19:59:27,664 workflow INFO:
	 Running: fslmaths /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/bandpass/sub-0050003_task-rest_run-1_bold_roi_st_mcf_residual_roi_bp.nii.gz -s 2.5479 /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/spatialSmooth/sub-0050003_task-rest_run-1_bold_roi_st_mcf_residual_roi_bp_smoothed.nii.gz
171229-19:59:32,292 workflow INFO:
	 [Job finished] jobname: spatialSmooth.a1 jobid: 5
171229-19:59:32,294 workflow INFO:
	 Executing: pearcoff.a1 ID: 6
171229-19:59:32,311 workflow INFO:
	 Executing node pearcoff.a1 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/pearcoff
171229-19:59:32,429 workflow INFO:
	 [Job finished] jobname: spatialSmooth.a0 jobid: 13
171229-19:59:32,432 workflow INFO:
	 Executing: pearcoff.a0 ID: 14
171229-19:59:32,448 workflow INFO:
	 Executing node pearcoff.a0 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/pearcoff
<string>:71: RuntimeWarning: invalid value encountered in true_divide
<string>:71: RuntimeWarning: invalid value encountered in true_divide
Some ROIs are not present. Replacing NAN in coff matrix by 0
Pear Matrix calculated for subject:  0050003
Creating brain for Subject- 0050003
Some ROIs are not present. Replacing NAN in coff matrix by 0
Pear Matrix calculated for subject:  0050002
Creating brain for Subject- 0050002
Created brain for Subject- 0050003
Created brain for Subject- 0050002
171229-20:00:17,324 workflow INFO:
	 [Job finished] jobname: pearcoff.a1 jobid: 6
171229-20:00:17,327 workflow INFO:
	 Executing: func2std_xform.a1 ID: 7
171229-20:00:17,343 workflow INFO:
	 Executing node func2std_xform.a1 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/func2std_xform
171229-20:00:17,348 workflow INFO:
	 Running: flirt -in /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/pearcoff/0050003_fc_map.nii.gz -ref /home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/coreg_reg/resample_mni/MNI152_T1_2mm_brain_resample.nii -out 0050003_fc_map_flirt.nii.gz -omat 0050003_fc_map_flirt.mat -applyxfm -init /home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/coreg_reg/_subject_id_0050003/concat_xform/sub-0050003_task-rest_run-1_bold_roi_st_mcf_mean_bet_flirt_sub-0050003_T1w_brain_resample_flirt.mat
171229-20:00:18,452 workflow INFO:
	 [Job finished] jobname: pearcoff.a0 jobid: 14
171229-20:00:18,454 workflow INFO:
	 Executing: func2std_xform.a0 ID: 15
171229-20:00:18,470 workflow INFO:
	 Executing node func2std_xform.a0 in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/func2std_xform
171229-20:00:18,475 workflow INFO:
	 Running: flirt -in /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/pearcoff/0050002_fc_map.nii.gz -ref /home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/coreg_reg/resample_mni/MNI152_T1_2mm_brain_resample.nii -out 0050002_fc_map_flirt.nii.gz -omat 0050002_fc_map_flirt.mat -applyxfm -init /home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/coreg_reg/_subject_id_0050002/concat_xform/sub-0050002_task-rest_run-1_bold_roi_st_mcf_mean_bet_flirt_sub-0050002_T1w_brain_resample_flirt.mat
171229-20:00:27,115 workflow INFO:
	 [Job finished] jobname: func2std_xform.a1 jobid: 7
171229-20:00:28,126 workflow INFO:
	 [Job finished] jobname: func2std_xform.a0 jobid: 15
171229-20:00:28,130 workflow INFO:
	 Executing: save_file_list ID: 16
171229-20:00:28,135 workflow INFO:
	 Executing node save_file_list in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/save_file_list
######################## File List ######################: 
 [ '/home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50002/func2std_xform/0050002_fc_map_flirt.nii.gz'
 '/home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/_subject_id_50003/func2std_xform/0050003_fc_map_flirt.nii.gz']
171229-20:00:28,149 workflow INFO:
	 [Job finished] jobname: save_file_list jobid: 16
171229-20:00:28,152 workflow INFO:
	 Executing: datasink ID: 17
171229-20:00:28,157 workflow INFO:
	 Executing node datasink in dir: /home1/varunk/results_again_again/temp_fc/motionRegress1filt1global0smoothing1/datasink
171229-20:00:28,172 workflow INFO:
	 [Job finished] jobname: datasink jobid: 17

In [530]:
# motion_param_regression = 1
# band_pass_filtering = 1
# global_signal_regression = 1
# smoothing = 1


# combination = 'motionRegress' + str(int(motion_param_regression)) + 'filt' + \
#               str(int(band_pass_filtering)) + 'global' + str(int(global_signal_regression)) + \
#               'smoothing' + str(int(smoothing))
        
# print("Combination: ",combination)

# wf = Workflow(name=functional_connectivity_directory)
# wf.base_dir = base_directory # Dir where all the outputs will be stored(inside BETFlow folder).

# wf.connect([(infosource , getSubjectFilenames, [('subject_id','subject_id')])])

# if motion_param_regression == 1 and global_signal_regression == 1 and band_pass_filtering == 1 and smoothing = 1:
#         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
#         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])

#         wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

#         wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
#         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])
        
#         wf.connect([( bandpass, spatialSmooth, [('out_file','in_file')])])
        
#         wf.connect([( spatialSmooth, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])
        
#         wf.connect([(pearcoff, func2std_xform, [('fc_map_brain_file','in_file')])])
#         wf.connect([(getSubjectFilenames, func2std_xform, [('func2std_mat','in_matrix_file')])])
#         wf.connect([(getSubjectFilenames, func2std_xform, [('MNI3mm_path','reference')])])
        
# #         -- send out file to save file list and then save the outputs



#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



#         wf.connect([(func2std_xform,  save_file_list, [('out_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])


#         #  wf.connect([(bandpass,  dataSink, [('out_file','motionRegress_filt_global.@out_file')])])


#         # if motion_param_regression == 1 and global_signal_regression == 1:    

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})
        
#         from IPython.display import Image
#         wf.write_graph(graph2use='exec', format='png', simple_form=True)
#         file_name = opj(base_directory,functional_connectivity_directory,'graph_detailed.dot.png')
#         Image(filename=file_name)

# elif motion_param_regression == 1 and global_signal_regression == 1 and band_pass_filtering == 0 and smoothing = 1: # 110
#         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
#         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])

#         wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

# #         wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
# #         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

#         wf.connect([( globalSignalRemoval, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])



#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})


# elif motion_param_regression == 1 and global_signal_regression == 0 and band_pass_filtering == 1  and smoothing = 1: # 101
#         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
#         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])

# #         wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

#         wf.connect([(calc_residuals, bandpass, [('residual_file','in_file')])])
#         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

#         wf.connect([( bandpass, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])



#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})      

# elif motion_param_regression == 1 and global_signal_regression == 0 and band_pass_filtering == 0 and smoothing = 1: # 100
#         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
#         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])

# #         wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

# #         wf.connect([(calc_residuals, bandpass, [('residual_file','in_file')])])
# #         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

#         wf.connect([( calc_residuals, pearcoff, [('residual_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])



#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})   


# elif motion_param_regression == 0 and global_signal_regression == 1 and band_pass_filtering == 1 and smoothing = 1: # 011
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])

#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('brain','in_file')] )])
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

#         wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
#         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

#         wf.connect([( bandpass, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])



#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})   



# elif motion_param_regression == 0 and global_signal_regression == 1 and band_pass_filtering == 0 and smoothing = 1: # 010
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])

#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('brain','in_file')] )])
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

# #         wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
# #         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

#         wf.connect([( globalSignalRemoval, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])



#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})


# elif motion_param_regression == 0 and global_signal_regression == 0 and band_pass_filtering == 1 and smoothing = 1: # 001
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])

# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('brain','in_file')] )])
# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])

#         wf.connect([(getSubjectFilenames, bandpass, [('out_file','in_file')])])
#         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])

#         wf.connect([( bandpass, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])



#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'



#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})

# else:

#         wf.connect([( getSubjectFilenames, pearcoff, [('brain','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])

#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'

#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])


#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})

In [531]:
X = np.load("../results_again_again/temp_dataSink/pearcoff_motionRegress1filt1global1/fc_map_brain_file_list.npy")
X


---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-531-a0b372e9a166> in <module>()
----> 1 X = np.load("../results_again_again/temp_dataSink/pearcoff_motionRegress1filt1global1/fc_map_brain_file_list.npy")
      2 X

~/anaconda3/lib/python3.6/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding)
    368     own_fid = False
    369     if isinstance(file, basestring):
--> 370         fid = open(file, "rb")
    371         own_fid = True
    372     elif is_pathlib_path(file):

FileNotFoundError: [Errno 2] No such file or directory: '../results_again_again/temp_dataSink/pearcoff_motionRegress1filt1global1/fc_map_brain_file_list.npy'

In [ ]:
!nipypecli show crash-20171125-133018-varunk-pearcoff.a1-7b869482-76ad-4f55-af87-8b01e34e975c.pklz

In [ ]:
# X = np.load('../results_again_again/fc_datasink/pearcoff_motionRegress1filt1global1/fc_map_brain_file_list.npy')
# X.shape

In [ ]:
# elif motion_param_regression == True and global_signal_regression == True and band_pass_filtering == False: # 110
#         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
#         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
        
#         wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])
        
# #         wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
# #         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])
    
#         wf.connect([( globalSignalRemoval, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])
        
        
        
#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'
        
        
        
#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])

        
#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})
        
        
# elif motion_param_regression == True and global_signal_regression == False and band_pass_filtering == True: # 101
#         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
#         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
        
# #         wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])
        
#         wf.connect([(calc_residuals, bandpass, [('residual_file','in_file')])])
#         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])
    
#         wf.connect([( bandpass, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])
        
        
        
#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'
        
        
        
#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])

        
#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})      

# elif motion_param_regression == True and global_signal_regression == False and band_pass_filtering == False: # 100
#         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
#         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
        
# #         wf.connect([(calc_residuals, globalSignalRemoval, [('residual_file','in_file')] )])
# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])
        
# #         wf.connect([(calc_residuals, bandpass, [('residual_file','in_file')])])
# #         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])
    
#         wf.connect([( calc_residuals, pearcoff, [('residual_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])
        
        
        
#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'
        
        
        
#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])

        
#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})   
        
        
# elif motion_param_regression == False and global_signal_regression == True and band_pass_filtering == True: # 011
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
        
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('brain','in_file')] )])
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])
        
#         wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
#         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])
    
#         wf.connect([( bandpass, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])
        
        
        
#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'
        
        
        
#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])

        
#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})   
        
        
        
# elif motion_param_regression == False and global_signal_regression == True and band_pass_filtering == False: # 010
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
        
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('brain','in_file')] )])
#         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])
        
# #         wf.connect([(globalSignalRemoval, bandpass, [('out_file','in_file')])])
# #         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])
    
#         wf.connect([( globalSignalRemoval, pearcoff, [('out_file','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])
        
        
        
#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'
        
        
        
#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])

        
#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})
        
        
# elif motion_param_regression == False and global_signal_regression == False and band_pass_filtering == True: # 001
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('brain','subject')])])
# #         wf.connect([(getSubjectFilenames, calc_residuals, [('motion_param', 'motion_file')])])
        
# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('brain','in_file')] )])
# #         wf.connect([(getSubjectFilenames, globalSignalRemoval, [('mask','mask_file')])])
        
# #         wf.connect([(getSubjectFilenames, bandpass, [('out_file','in_file')])])
# #         wf.connect([(getSubjectFilenames, bandpass, [('tr','tr')])])
    
#         wf.connect([( getSubjectFilenames, pearcoff, [('brain','in_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('atlas','atlas_file')])])
#         wf.connect([( getSubjectFilenames, pearcoff, [('mask','mask_file')])])
        
        
        
#         folder_name = 'pearcoff_' + combination + '.@fc_map_brain_file'
        
        
        
#         wf.connect([(pearcoff,  save_file_list, [('fc_map_brain_file','in_fc_map_brain_file')])])

        
#         wf.connect([(save_file_list,  dataSink, [('out_fc_map_brain_file',folder_name)])])

#         %time wf.run('MultiProc', plugin_args={'n_procs': 7})

In [ ]:
# 111 -
# 110 - 
# 101 - 
# 100
# 011
# 010
# 001
# 000

In [ ]:
# Visualize the detailed graph
# from IPython.display import Image
# wf.write_graph(graph2use='exec', format='png', simple_form=True)
# file_name = opj(base_directory,functional_connectivity_directory,'graph_detailed.dot.png')
# Image(filename=file_name)

In [ ]:
# def calc_residuals(subject,
#                    motion_file):
#     """
#     Calculates residuals of nuisance regressors -motion parameters for every voxel for a subject using GLM.
    
#     Parameters
#     ----------
#     subject : string
#         Path of a subject's motion corrected nifti file.
#     motion_par_file : string
#         path of a subject's motion parameters
    
        
#     Returns
#     -------
#     residual_file : string
#         Path of residual file in nifti format
    
#     """
#     import nibabel as nb
#     nii = nb.load(subject)
#     data = nii.get_data().astype(np.float32)
#     global_mask = (data != 0).sum(-1) != 0

    
#     # Check and define regressors which are provided from files
#     if motion_file is not None:
#         motion = np.genfromtxt(motion_file)
#         if motion.shape[0] != data.shape[3]:
#             raise ValueError('Motion parameters {0} do not match data '
#                              'timepoints {1}'.format(motion.shape[0], 
#                                                      data.shape[3]))
#         if motion.size == 0:
#             raise ValueError('Motion signal file {0} is '
#                              'empty'.format(motion_file))

#     # Calculate regressors
#     regressor_map = {'constant' : np.ones((data.shape[3],1))}
        
#     regressor_map['motion'] = motion
        
    
#     X = np.zeros((data.shape[3], 1))
    
#     for rname, rval in regressor_map.items():
#         X = np.hstack((X, rval.reshape(rval.shape[0],-1)))

#     X = X[:,1:]
    
#     if np.isnan(X).any() or np.isnan(X).any():
#         raise ValueError('Regressor file contains NaN')

#     Y = data[global_mask].T

#     try:
#         B = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y)
#     except np.linalg.LinAlgError as e:
#         if "Singular matrix" in e:
#             raise Exception("Error details: {0}\n\nSingular matrix error: "
#                             "The nuisance regression configuration you "
#                             "selected may have been too stringent, and the "
#                             "regression could not be completed. Ensure your "
#                             "parameters are not too "
#                             "extreme.\n\n".format(e))
#         else:
#             raise Exception("Error details: {0}\n\nSomething went wrong with "
#                             "nuisance regression.\n\n".format(e))

#     Y_res = Y - X.dot(B)
    
#     data[global_mask] = Y_res.T
    
#     img = nb.Nifti1Image(data, header=nii.get_header(),
#                          affine=nii.get_affine())
    
#     subject_name = subject.split('/')[-1].split('.')[0]
#     filename = subject_name + '_residual.nii.gz'
#     residual_file = os.path.join(os.getcwd(),filename )
#     img.to_filename(residual_file) # alt to nib.save
    
#     return residual_file

In [ ]:
# # Test
# brain = '/home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/_subject_id_0050005/applyMask/sub-0050005_task-rest_run-1_bold_roi_st_mcf.nii_brain.nii.gz'
# mask = '/home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/_subject_id_0050005/meanfuncmask/sub-0050005_task-rest_run-1_bold_roi_st_mcf_mean_brain_mask.nii.gz'
# atlas = '/home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/coreg_reg/atlas_resize_reg_directory/_subject_id_0050005/std2func_xform/fullbrain_atlas_thr0-2mm_resample_flirt.nii '
# # tr = 1.5
# par_file = '/home1/varunk/results_again_again/ABIDE1_Preprocess/motion_correction_bet/_subject_id_0050005/mcflirt/sub-0050005_task-rest_run-1_bold_roi_st_mcf.nii.par'

In [ ]:
# calc_residuals(brain,par_file)

In [ ]:
# motion = np.genfromtxt(par_file)

In [ ]:
import numpy as np
X = np.load('../results_again_again/fc_datasink/pearcoff_motionRegress0filt0global1/fc_map_brain_file_list.npy')
X.shape

In [ ]: