def epi_sbref_registration(name='EPI_SBrefRegistration'): workflow = pe.Workflow(name=name) inputnode = pe.Node( niu.IdentityInterface(fields=['epi_brain', 'sbref_brain']), name='inputnode') outputnode = pe.Node( niu.IdentityInterface(fields=['epi_registered', 'out_mat']), name='outputnode') mean = pe.Node(fsl.MeanImage(dimension='T'), name='EPImean') inu = pe.Node(ants.N4BiasFieldCorrection(dimension=3), name='EPImeanBias') epi_sbref = pe.Node(fsl.FLIRT(dof=6, out_matrix_file='init.mat'), name='EPI2SBRefRegistration') epi_split = pe.Node(fsl.Split(dimension='t'), name='EPIsplit') epi_xfm = pe.MapNode(fsl.ApplyXfm(), name='EPIapplyxfm', iterfield=['in_file']) epi_merge = pe.Node(fsl.Merge(dimension='t'), name='EPImergeback') workflow.connect([ (inputnode, epi_split, [('epi_brain', 'in_file')]), (inputnode, epi_sbref, [('sbref_brain', 'reference')]), (inputnode, epi_xfm, [('sbref_brain', 'reference')]), (inputnode, mean, [('epi_brain', 'in_file')]), (mean, inu, [('out_file', 'input_image')]), (inu, epi_sbref, [('output_image', 'in_file')]), (epi_split, epi_xfm, [('out_files', 'in_file')]), (epi_sbref, epi_xfm, [('out_matrix_file', 'in_matrix_file')]), (epi_xfm, epi_merge, [('out_file', 'in_files')]), (epi_sbref, outputnode, [('out_matrix_file', 'out_mat')]), (epi_merge, outputnode, [('merged_file', 'epi_registered')]) ]) return workflow
def mask_and_extract(featdir, allmasks, img_to_extract): regdir = os.path.join(featdir, 'reg') #registration directory ind_maskdir = os.path.join(featdir, 'masks') #individual mask directory if not os.path.exists(ind_maskdir): os.mkdir(ind_maskdir) #make the individual directory if not there #for each mask for maskname in allmasks: mask_out_file = os.path.join(ind_maskdir, maskname) if not os.path.exists(mask_out_file): temp_mat = tempfile.NamedTemporaryFile() #create a temporary file #nipype wrapper for FSL's applyxfm, warps mask from standard into native space applyxfm = fsl.ApplyXfm() applyxfm.inputs.in_file = maskname applyxfm.inputs.in_matrix_file = os.path.join( regdir, 'standard2example_func.mat') applyxfm.inputs.out_file = mask_out_file applyxfm.inputs.out_matrix_file = temp_mat.name applyxfm.inputs.reference = os.path.join(featdir, 'example_func.nii.gz') applyxfm.inputs.apply_xfm = True result = applyxfm.run() # print result.outputs imgname = img_to_extract.split('.')[0].replace('/', '_') ts_out_file = img_to_extract.replace('/', '_') ts_out_file = os.path.join(ind_maskdir, maskname.split('.')[0] + imgname + '.txt') in_file = featdir + img_to_extract print "extracting from %s into file %s" % (in_file, ts_out_file) #nipype wrapper for fslmeants meants = fsl.ImageMeants() meants.inputs.in_file = in_file meants.inputs.mask = os.path.join(ind_maskdir, maskname) meants.inputs.out_file = ts_out_file result2 = meants.run()
def freesurfer_reconall(population, workspace_dir, freesurferdir): #subject = population[subject_index] count= 0 for subject in population: count +=1 print '========================================================================================' print '%s- Runnning FREESURFER reconall on subject %s' %(count, subject) subject_dir = os.path.join(workspace_dir , subject[0:4]) anatomical_dir = os.path.join(subject_dir , 'anatomical_original') anatomical_file = os.path.join(anatomical_dir, 'ANATOMICAL.nii') # check if the file exists if os.path.isfile(anatomical_file): print '..' if os.path.isfile(os.path.join(freesurfer_dir, subject[0:10], 'mri', 'aseg.mgz')): print 'Brain already segmented .......................... moving on' #print 'check data here ---> %s' %(os.path.join(freesurfer_dir, subject)) else: #set freesurfer dir fs.FSCommand.set_default_subjects_dir(freesurferdir) seg_dir=freesurferdir+'/'+subject[0:10]+'/' print('saving outputs to ' + seg_dir) #run freesurfer segmentation reconall = fs.ReconAll() reconall.inputs.subject_id = subject[0:10] reconall.inputs.directive = 'all' reconall.inputs.T1_files = anatomical_file reconall.inputs.subjects_dir = freesurferdir reconall.run() else: print 'anatomical file for subject %s not found' %subject '============================================================================================' ' Convert Freesurfer MGZs to Nifti' '============================================================================================' seg_dir = os.path.join(freesurfer_dir, subject[0:10]) t1_mgz = os.path.join(seg_dir, 'mri', 'T1.mgz') # T1 image in freesurfer orientation aseg_mgz = os.path.join(seg_dir, 'mri', 'aseg.mgz') # freesurfer segmentation file if os.path.isfile(os.path.join(workspace_dir, subject[0:4], 'segmentation_freesurfer', 'aseg.nii')): print 'MGZs already converted to NIFTI .................. moving on' else: print 'converting Freesurfer MGZ files to NIFTI......' try: os.makedirs(os.path.join(workspace_dir, subject[0:4], 'segmentation_freesurfer')) except OSError: out_fs_dir = str(os.path.join(workspace_dir, subject[0:4], 'segmentation_freesurfer')) out_fs_dir = str(os.path.join(workspace_dir, subject[0:4], 'segmentation_freesurfer')) #convert T1 to nifti anat2nii = fs.MRIConvert() anat2nii.inputs.in_file = t1_mgz anat2nii.inputs.out_file = '%s/T1.nii' %out_fs_dir anat2nii.inputs.out_type = 'nii' anat2nii.run() #convert seg to nifti seg2nii = fs.MRIConvert() seg2nii.inputs.in_file = aseg_mgz seg2nii.inputs.out_file = '%s/aseg.nii' %out_fs_dir seg2nii.inputs.out_type = 'nii' seg2nii.run() '============================================================================================' ' Registration ' '============================================================================================' out_fs_dir = str(os.path.join(workspace_dir, subject[0:4], 'segmentation_freesurfer')) if os.path.isfile(os.path.join(out_fs_dir, 'freesurfer_aseg_2spm.nii.gz')): print 'Freesurfer to SPM affine already calculated....... moving on' else: print 'reorienting freesurfer files (T1 & aseg) to SPM space ..........' anat_spm = os.path.join(workspace_dir, subject[0:4], 'anatomical_original', 'ANATOMICAL.nii') fs_t1_nii = os.path.join(out_fs_dir, 'T1.nii') fs_aseg_nii = os.path.join(out_fs_dir, 'aseg.nii') #register freesurfer T1 to SPM space anat_flirt = fsl.FLIRT() anat_flirt.inputs.in_file = fs_t1_nii anat_flirt.inputs.reference = anat_spm anat_flirt.inputs.output_type = "NIFTI" anat_flirt.inputs.searchr_x = [-180, 180] anat_flirt.inputs.searchr_y = [-180, 180] anat_flirt.inputs.searchr_z = [-180, 180] anat_flirt.inputs.cost_func = 'mutualinfo' anat_flirt.inputs.out_file = '%s/freesurfer_T1_2spm.nii' %out_fs_dir anat_flirt.inputs.out_matrix_file = '%s/freesurfer_T1_2spm_xfm.mat' %out_fs_dir anat_flirt.run() # Apply fs2spm xfm to aseg file fs2spm_xfm = '%s/freesurfer_T1_2spm_xfm.mat' %out_fs_dir aseg_applyxfm = fsl.ApplyXfm() aseg_applyxfm.inputs.in_file = fs_aseg_nii aseg_applyxfm.inputs.reference = anat_spm aseg_applyxfm.inputs.in_matrix_file = fs2spm_xfm aseg_applyxfm.inputs.apply_xfm = True aseg_applyxfm.inputs.out_file = '%s/freesurfer_aseg_2spm.nii.gz' %out_fs_dir aseg_applyxfm.run() '============================================================================================' ' Create Tissue Masks ' '============================================================================================' out_fs_dir = str(os.path.join(workspace_dir, subject[0:4], 'segmentation_freesurfer')) if os.path.isfile(os.path.join(out_fs_dir, 'freesurfer_GM_mask.nii.gz')): print 'Tissues already extracted as nifti files.......... moving on' else: print '...' print 'Extracting Tissue classes from Labels and saving as a nifti file' aseg = str(os.path.join(workspace_dir, subject[0:4], 'segmentation_freesurfer','freesurfer_aseg_2spm.nii.gz')) aseg_data = nb.load(aseg).get_data() aseg_affine = nb.load(aseg).get_affine() wm_data = np.zeros(aseg_data.shape) gm_data = np.zeros(aseg_data.shape) csf_data = np.zeros(aseg_data.shape) for data, labels in zip([wm_data, gm_data, csf_data], [wm_labels, gm_labels, csf_labels]): for label in labels: data[np.where(aseg_data==label)] =1 wm_img = nb.Nifti1Image(wm_data , aseg_affine) gm_img = nb.Nifti1Image(gm_data , aseg_affine) csf_img = nb.Nifti1Image(csf_data , aseg_affine) nb.save(wm_img , '%s/freesurfer_WM_mask.nii.gz' %out_fs_dir) nb.save(gm_img , '%s/freesurfer_GM_mask.nii.gz' %out_fs_dir) nb.save(csf_img , '%s/freesurfer_CSF_mask.nii.gz' %out_fs_dir)
""" func_skullstrip = pe.Node(interface=fsl.BET(functional=True), name='stripfunc') #iterfield = ['in_file']) """ Run FAST on T1 anatomical image to obtain CSF mask. Create mask for three tissue types. """ getCSFmasks = pe.Node(interface=fsl.FAST(no_pve=True, segments=True), name='segment') """ Apply registration matrix to CSF segmentation mask. """ applyReg2CSFmask = pe.Node(interface=fsl.ApplyXfm(apply_xfm=True), name='applyreg2csfmask') """ Threshold CSF segmentation mask from .90 to 1 """ threshCSFseg = pe.Node( interface=fsl.ImageMaths(op_string=' -thr .90 -uthr 1 -bin '), name='threshcsfsegmask') """ Extract CSF timeseries """ avgCSF = pe.Node(interface=fsl.ImageMeants(), name='extractcsfts')
def create_dmn_pipeline_step1(name="dmn_step1", scale_by_glycemia=True, manual_seg_rois=False): inputfields = [ "subjects_dir", "subject_id", "dwi", "bvecs", "bvals", "fdgpet", "dose", "weight", "delay", "glycemie", "scan_time" ] if manual_seg_rois: inputfields.append("manual_seg_rois") inputnode = pe.Node(interface=util.IdentityInterface(fields=inputfields), name="inputnode") outputnode = pe.Node( interface=util.IdentityInterface( fields=[ # Outputs from the DWI workflow "single_fiber_mask", "fa", "rgb_fa", "md", "mode", "t1", "t1_brain", "wm_mask", "term_mask", "aparc_aseg", "tissue_class_files", "gm_prob", "wm_prob", "csf_prob", # Outputs from registration and labelling "rois", "rois_to_dwi", "wmmask_to_dwi", "termmask_to_dwi", "dwi_to_t1_matrix", "highres_t1_to_dwi_matrix", # Outputs from the PET workflow after SUV calculation "SUV_corrected_pet_to_t1", "AIF_corrected_pet_to_t1", "pet_results_npz", "pet_results_mat", "orig_pet_to_t1", # T1 in DWI space for reference "t1_to_dwi", "single_fiber_mask_cortex_only", ]), name="outputnode") t1_to_dwi = pe.Node(interface=fsl.ApplyXfm(), name='t1_to_dwi') termmask_to_dwi = t1_to_dwi.clone("termmask_to_dwi") compute_cmr_glc_interface = util.Function( input_names=[ "subject_id", "in_file", "dose", "weight", "delay", "glycemie", "scan_time" ], output_names=["out_file", "cax2", "mecalc", "denom"], function=CMR_glucose) compute_AIF_PET = pe.Node(interface=compute_cmr_glc_interface, name='compute_AIF_PET') compute_SUV_interface = util.Function(input_names=[ "subject_id", "in_file", "dose", "weight", "delay", "scan_time", "isotope", 'height', "glycemie" ], output_names=["out_file"], function=calculate_SUV) compute_SUV_norm_glycemia = pe.Node(interface=compute_SUV_interface, name='compute_SUV_norm_glycemia') scale_PVC_matrix_interface = util.Function( input_names=[ "subject_id", "in_file", "dose", "weight", "delay", "scan_time", "isotope", 'height', "glycemie", "scale_SUV_by_glycemia" ], output_names=["out_npz", "out_matlab_mat"], function=scale_PVC_matrix_fn) scale_PVC_matrix = pe.Node(interface=scale_PVC_matrix_interface, name='scale_PVC_matrix') scale_PVC_matrix.inputs.scale_SUV_by_glycemia = scale_by_glycemia single_fiber_mask_cortex_only = pe.Node( interface=fsl.MultiImageMaths(), name='single_fiber_mask_cortex_only') single_fiber_mask_cortex_only.inputs.op_string = "-mul %s" dtiproc = damaged_brain_dti_processing("dtiproc") reg_label = create_reg_and_label_wf("reg_label", manual_seg_rois) petquant = create_pet_quantification_wf("petquant", segment_t1=False) workflow = pe.Workflow(name=name) workflow.base_output_dir = name workflow.connect([(inputnode, dtiproc, [("subjects_dir", "inputnode.subjects_dir"), ("subject_id", "inputnode.subject_id"), ("dwi", "inputnode.dwi"), ("bvecs", "inputnode.bvecs"), ("bvals", "inputnode.bvals")])]) workflow.connect([(inputnode, reg_label, [("subject_id", "inputnode.subject_id")])]) if manual_seg_rois: workflow.connect([(inputnode, reg_label, [ ("manual_seg_rois", "inputnode.manual_seg_rois") ])]) workflow.connect([(dtiproc, reg_label, [ ("outputnode.wm_mask", "inputnode.wm_mask"), ("outputnode.term_mask", "inputnode.termination_mask"), ("outputnode.fa", "inputnode.fa"), ("outputnode.aparc_aseg", "inputnode.aparc_aseg"), ])]) workflow.connect([(reg_label, t1_to_dwi, [("outputnode.t1_to_dwi_matrix", "in_matrix_file")])]) workflow.connect([(dtiproc, t1_to_dwi, [("outputnode.t1", "in_file")])]) workflow.connect([(dtiproc, t1_to_dwi, [("outputnode.fa", "reference")])]) workflow.connect([(inputnode, t1_to_dwi, [ (('subject_id', add_subj_name_to_T1_dwi), 'out_file') ])]) workflow.connect([(reg_label, termmask_to_dwi, [("outputnode.t1_to_dwi_matrix", "in_matrix_file")])]) workflow.connect([(dtiproc, termmask_to_dwi, [("outputnode.term_mask", "in_file")])]) workflow.connect([(dtiproc, termmask_to_dwi, [("outputnode.fa", "reference")])]) workflow.connect([(inputnode, single_fiber_mask_cortex_only, [ (('subject_id', add_subj_name_to_cortex_sfmask), 'out_file') ])]) workflow.connect([(termmask_to_dwi, single_fiber_mask_cortex_only, [("out_file", "operand_files")])]) workflow.connect([(dtiproc, single_fiber_mask_cortex_only, [("outputnode.single_fiber_mask", "in_file")])]) workflow.connect([(inputnode, compute_SUV_norm_glycemia, [ ("subject_id", "subject_id"), ("dose", "dose"), ("weight", "weight"), ("delay", "delay"), ("scan_time", "scan_time"), ])]) if scale_by_glycemia == True: workflow.connect([(inputnode, compute_SUV_norm_glycemia, [("glycemie", "glycemie")])]) # This is for the arterial input function approximation for the FDG uptake workflow.connect([(inputnode, compute_AIF_PET, [ ("subject_id", "subject_id"), ("dose", "dose"), ("weight", "weight"), ("delay", "delay"), ("glycemie", "glycemie"), ("scan_time", "scan_time"), ])]) workflow.connect([(inputnode, scale_PVC_matrix, [ ("subject_id", "subject_id"), ("dose", "dose"), ("weight", "weight"), ("delay", "delay"), ("glycemie", "glycemie"), ("scan_time", "scan_time"), ])]) workflow.connect([(dtiproc, petquant, [ (('outputnode.tissue_class_files', select_GM), 'inputnode.gm_mask') ])]) workflow.connect([(dtiproc, petquant, [ ("outputnode.t1", "inputnode.t1"), ("outputnode.wm_prob", "inputnode.wm_prob"), ("outputnode.gm_prob", "inputnode.gm_prob"), ("outputnode.csf_prob", "inputnode.csf_prob"), ])]) workflow.connect([(inputnode, petquant, [("fdgpet", "inputnode.pet")])]) workflow.connect([(inputnode, petquant, [("subject_id", "inputnode.subject_id")])]) if manual_seg_rois: workflow.connect([(inputnode, petquant, [("manual_seg_rois", "inputnode.rois")])]) else: workflow.connect([(reg_label, petquant, [("outputnode.rois", "inputnode.rois")])]) workflow.connect([(petquant, compute_AIF_PET, [("outputnode.corrected_pet_to_t1", "in_file")])]) workflow.connect([(petquant, compute_SUV_norm_glycemia, [("outputnode.corrected_pet_to_t1", "in_file")])]) workflow.connect([(petquant, scale_PVC_matrix, [("outputnode.pet_results_npz", "in_file")])]) ''' Connect outputnode ''' workflow.connect([(t1_to_dwi, outputnode, [("out_file", "t1_to_dwi")])]) workflow.connect([(dtiproc, outputnode, [ ("outputnode.t1", "t1"), ("outputnode.wm_prob", "wm_prob"), ("outputnode.gm_prob", "gm_prob"), ("outputnode.csf_prob", "csf_prob"), ("outputnode.single_fiber_mask", "single_fiber_mask"), ("outputnode.fa", "fa"), ("outputnode.rgb_fa", "rgb_fa"), ("outputnode.md", "md"), ("outputnode.mode", "mode"), ("outputnode.t1_brain", "t1_brain"), ("outputnode.wm_mask", "wm_mask"), ("outputnode.term_mask", "term_mask"), ("outputnode.aparc_aseg", "aparc_aseg"), ("outputnode.tissue_class_files", "tissue_class_files"), ])]) workflow.connect([(reg_label, outputnode, [ ("outputnode.rois_to_dwi", "rois_to_dwi"), ("outputnode.wmmask_to_dwi", "wmmask_to_dwi"), ("outputnode.termmask_to_dwi", "termmask_to_dwi"), ("outputnode.dwi_to_t1_matrix", "dwi_to_t1_matrix"), ("outputnode.highres_t1_to_dwi_matrix", "highres_t1_to_dwi_matrix"), ])]) if manual_seg_rois: workflow.connect([(inputnode, outputnode, [("manual_seg_rois", "rois") ])]) else: workflow.connect([(reg_label, outputnode, [("outputnode.rois", "rois") ])]) workflow.connect([(compute_AIF_PET, outputnode, [("out_file", "SUV_corrected_pet_to_t1")])]) workflow.connect([(compute_SUV_norm_glycemia, outputnode, [("out_file", "AIF_corrected_pet_to_t1")])]) workflow.connect([(petquant, outputnode, [("outputnode.orig_pet_to_t1", "orig_pet_to_t1")])]) workflow.connect([(scale_PVC_matrix, outputnode, [("out_npz", "pet_results_npz")])]) workflow.connect([(scale_PVC_matrix, outputnode, [("out_matlab_mat", "pet_results_mat")])]) workflow.connect([(single_fiber_mask_cortex_only, outputnode, [("out_file", "single_fiber_mask_cortex_only")])]) return workflow
def create_reg_and_label_wf(name="reg_wf", manual_seg_rois=False): inputfields = [ "subject_id", "aparc_aseg", "fa", "wm_mask", "termination_mask" ] if manual_seg_rois: inputfields.append("manual_seg_rois") inputnode = pe.Node(interface=util.IdentityInterface(fields=inputfields), name="inputnode") outputnode = pe.Node(interface=util.IdentityInterface(fields=[ "dwi_to_t1_matrix", "t1_to_dwi_matrix", "rois_to_dwi", "rois", "wmmask_to_dwi", "termmask_to_dwi", "highres_t1_to_dwi_matrix" ]), name="outputnode") dmn_labels_if = util.Function(input_names=["in_file", "out_filename"], output_names=["out_file"], function=dmn_labels_combined) dmn_labelling = pe.Node(interface=dmn_labels_if, name='dmn_labelling') align_wmmask_to_dwi = coreg_without_resample("align_wmmask_to_fa") align_wmmask_to_dwi.inputs.inputnode.interp = "nearestneighbour" rois_to_dwi = pe.Node(interface=fsl.ApplyXfm(), name='rois_to_dwi') rois_to_dwi.inputs.interp = "nearestneighbour" threshold_fa = pe.Node(interface=fsl.ImageMaths(), name='threshold_fa') threshold_fa.inputs.op_string = "-thr 0.2 -bin" multiply_rois_by_termmask = pe.Node(interface=fsl.MultiImageMaths(), name='multiply_rois_by_termmask') multiply_rois_by_termmask.inputs.op_string = "-mul %s" termmask_to_dwi = rois_to_dwi.clone("termmask_to_dwi") invertxfm = pe.Node(interface=fsl.ConvertXFM(), name='invertxfm') invertxfm.inputs.invert_xfm = True ''' Define renaming nodes ''' rename_t1_to_dwi_mat = pe.Node( interface=util.Rename(format_string="%(subject_id)s_t1_to_dwi_matrix"), name='rename_t1_to_dwi_mat') rename_t1_to_dwi_mat.inputs.keep_ext = True rename_dwi_to_t1_mat = pe.Node( interface=util.Rename(format_string="%(subject_id)s_dwi_to_t1_matrix"), name='rename_dwi_to_t1_mat') rename_dwi_to_t1_mat.inputs.keep_ext = True rename_rois_dwi = pe.Node( interface=util.Rename(format_string="%(subject_id)s_rois_dwi"), name='rename_rois_dwi') rename_rois_dwi.inputs.keep_ext = True rename_rois = pe.Node( interface=util.Rename(format_string="%(subject_id)s_rois"), name='rename_rois') rename_rois.inputs.keep_ext = True rename_termmask_dwi = pe.Node( interface=util.Rename(format_string="%(subject_id)s_term_mask_dwi"), name='rename_termmask_dwi') rename_termmask_dwi.inputs.keep_ext = True rename_wmmask_dwi = pe.Node( interface=util.Rename(format_string="%(subject_id)s_wm_mask_dwi"), name='rename_wmmask_dwi') rename_wmmask_dwi.inputs.keep_ext = True rename_highres_matrix_file = pe.Node(interface=util.Rename( format_string="%(subject_id)s_t1_to_dwi_NoResample"), name='rename_highres_matrix_file') rename_highres_matrix_file.inputs.keep_ext = True workflow = pe.Workflow(name=name) workflow.connect([(inputnode, align_wmmask_to_dwi, [("wm_mask", "inputnode.moving_image")])]) workflow.connect([(inputnode, threshold_fa, [("fa", "in_file")])]) workflow.connect([(threshold_fa, align_wmmask_to_dwi, [("out_file", "inputnode.fixed_image")])]) if manual_seg_rois: workflow.connect([(inputnode, rois_to_dwi, [("manual_seg_rois", "in_file")])]) workflow.connect([(inputnode, rois_to_dwi, [("manual_seg_rois", "reference")])]) workflow.connect([(inputnode, outputnode, [("manual_seg_rois", "rois") ])]) else: workflow.connect([(inputnode, dmn_labelling, [ (('subject_id', add_subj_name_to_rois), 'out_filename') ])]) workflow.connect([(inputnode, dmn_labelling, [("aparc_aseg", "in_file") ])]) workflow.connect([(dmn_labelling, multiply_rois_by_termmask, [("out_file", "in_file")])]) workflow.connect([(inputnode, multiply_rois_by_termmask, [("termination_mask", "operand_files")])]) workflow.connect([(multiply_rois_by_termmask, rename_rois, [("out_file", "in_file")])]) workflow.connect([(inputnode, rename_rois, [("subject_id", "subject_id")])]) workflow.connect([(rename_rois, rois_to_dwi, [("out_file", "in_file")]) ]) workflow.connect([(rename_rois, rois_to_dwi, [("out_file", "reference") ])]) workflow.connect([(rename_rois, outputnode, [("out_file", "rois")])]) workflow.connect([(align_wmmask_to_dwi, rois_to_dwi, [ ("outputnode.highres_matrix_file", "in_matrix_file") ])]) workflow.connect([(inputnode, termmask_to_dwi, [("termination_mask", "in_file")])]) workflow.connect([(inputnode, termmask_to_dwi, [("termination_mask", "reference")])]) workflow.connect([(align_wmmask_to_dwi, termmask_to_dwi, [ ("outputnode.highres_matrix_file", "in_matrix_file") ])]) workflow.connect([(align_wmmask_to_dwi, invertxfm, [("outputnode.lowres_matrix_file", "in_file")])]) workflow.connect([(inputnode, rename_t1_to_dwi_mat, [("subject_id", "subject_id")])]) workflow.connect([(align_wmmask_to_dwi, rename_t1_to_dwi_mat, [("outputnode.lowres_matrix_file", "in_file")])]) workflow.connect([(rename_t1_to_dwi_mat, outputnode, [("out_file", "t1_to_dwi_matrix")])]) workflow.connect([(inputnode, rename_dwi_to_t1_mat, [("subject_id", "subject_id")])]) workflow.connect([(invertxfm, rename_dwi_to_t1_mat, [("out_file", "in_file")])]) workflow.connect([(rename_dwi_to_t1_mat, outputnode, [("out_file", "dwi_to_t1_matrix")])]) workflow.connect([(inputnode, rename_rois_dwi, [("subject_id", "subject_id")])]) workflow.connect([(rois_to_dwi, rename_rois_dwi, [("out_file", "in_file")]) ]) workflow.connect([(rename_rois_dwi, outputnode, [("out_file", "rois_to_dwi")])]) workflow.connect([(inputnode, rename_termmask_dwi, [("subject_id", "subject_id")])]) workflow.connect([(termmask_to_dwi, rename_termmask_dwi, [("out_file", "in_file")])]) workflow.connect([(rename_termmask_dwi, outputnode, [("out_file", "termmask_to_dwi")])]) workflow.connect([(inputnode, rename_wmmask_dwi, [("subject_id", "subject_id")])]) workflow.connect([(align_wmmask_to_dwi, rename_wmmask_dwi, [("outputnode.out_file", "in_file")])]) workflow.connect([(rename_wmmask_dwi, outputnode, [("out_file", "wmmask_to_dwi")])]) workflow.connect([(inputnode, rename_highres_matrix_file, [("subject_id", "subject_id")])]) workflow.connect([(align_wmmask_to_dwi, rename_highres_matrix_file, [("outputnode.highres_matrix_file", "in_file")])]) workflow.connect([(rename_highres_matrix_file, outputnode, [("out_file", "highres_t1_to_dwi_matrix")])]) return workflow
def do_pipe3_projection(subject_ID, freesurfer_dir, workflow_dir, output_dir, tract_number, use_sample=False): """ Packages and Data Setup ======================= Import necessary modules from nipype. """ import nipype.interfaces.io as io # Data i/o import nipype.interfaces.utility as util # utility import nipype.pipeline.engine as pe # pipeline engine import nipype.interfaces.fsl as fsl import nipype.interfaces.freesurfer as fsurf # freesurfer import nipype.interfaces.ants as ants import os.path as op # system functions from nipype.interfaces.utility import Function from dmri_pipe_aux import get_connectivity_matrix from dmri_pipe_aux import surf2file from dmri_pipe_aux import voxels2nii from dmri_pipe_aux import normalize_matrix from dmri_pipe_aux import interface2surf from dmri_pipe_aux import read_voxels from dmri_pipe_aux import downsample_matrix from dmri_pipe_aux import merge_matrices """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """ Point to the freesurfer subjects directory (Recon-all must have been run on the subjects) """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" subjects_dir = op.abspath(freesurfer_dir) fsurf.FSCommand.set_default_subjects_dir(subjects_dir) fsl.FSLCommand.set_default_output_type('NIFTI') """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """ define the workflow """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" dmripipeline = pe.Workflow(name='pipe3_projection') """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """ Use datasource node to perform the actual data grabbing. Templates for the associated images are used to obtain the correct images. """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" data_template = subject_ID + "/%s/" + "%s" + "%s" info = dict( wm=[['fa_masking', subject_ID, '_mask_wm.nii']], seeds_left=[['fa_masking', subject_ID, '_interface_left_voxels.txt']], seeds_right=[['fa_masking', subject_ID, '_interface_right_voxels.txt']], index_left=[['fa_masking', subject_ID, '_interface_left_index.nii']], index_right=[['fa_masking', subject_ID, '_interface_right_index.nii']], fa=[['fa_masking', subject_ID, '_fa_masked.nii']], t1=[['anatomy', subject_ID, '_t1_masked.nii']], inv_flirt_mat=[['anatomy', '', 'flirt_t1_2_fa_inv.mat']], warp=[['anatomy', '', 'ants_fa_2_regt1_Warp.nii.gz']]) datasource = pe.Node(interface=io.DataGrabber(outfields=info.keys()), name='datasource') datasource.inputs.template = data_template datasource.inputs.base_directory = output_dir datasource.inputs.template_args = info datasource.inputs.sort_filelist = True datasource.run_without_submitting = True tracts_left_source = pe.Node( interface=io.DataGrabber(outfields=['tracts_left']), name='tracts_left_source') tracts_left_source.inputs.template = subject_ID + '/raw_tracts/lh/probtract_*.nii' tracts_left_source.inputs.base_directory = output_dir tracts_left_source.inputs.sort_filelist = True tracts_left_source.run_without_submitting = True tracts_right_source = pe.Node( interface=io.DataGrabber(outfields=['tracts_right']), name='tracts_right_source') tracts_right_source.inputs.template = subject_ID + '/raw_tracts/rh/probtract_*.nii' tracts_right_source.inputs.base_directory = output_dir tracts_right_source.inputs.sort_filelist = True tracts_right_source.run_without_submitting = True """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """ The input node declared here will be the main conduits for the raw data to the rest of the processing pipeline. """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" inputnode = pe.Node(interface=util.IdentityInterface(fields=[ "wm", "seeds_left", "seeds_right", "index_left", "index_right", "fa", "t1", "inv_flirt_mat", "warp", "tracts_left", "tracts_right" ]), name="inputnode") """ read seed coordinates """ interface_voxels_left = pe.Node(interface=Function( input_names=["seed_file", "use_sample"], output_names=["seed_list"], function=read_voxels), name='70_interface_voxels_left') interface_voxels_left.inputs.use_sample = use_sample dmripipeline.connect(inputnode, "seeds_left", interface_voxels_left, "seed_file") interface_voxels_right = interface_voxels_left.clone( name='70_interface_voxels_right') dmripipeline.connect(inputnode, "seeds_right", interface_voxels_right, "seed_file") """ Get the direct connectivity matrix """ connectivity_matrix = pe.Node(interface=Function( input_names=[ "tract_list_left", "tract_list_right", "voxel_list_left", "voxel_list_right", "max_value" ], output_names=[ "submatrix_left_left", "submatrix_left_right", "submatrix_right_left", "submatrix_right_right", "exclusion_list" ], function=get_connectivity_matrix), name='71_direct_connect_array') connectivity_matrix.inputs.max_value = tract_number connectivity_matrix.run_without_submitting = True # connectivity_matrix.plugin_args={'override_specs': 'requirements = Machine == "kalifornien.cbs.mpg.de"'} dmripipeline.connect(inputnode, "tracts_left", connectivity_matrix, "tract_list_left") dmripipeline.connect(inputnode, "tracts_right", connectivity_matrix, "tract_list_right") dmripipeline.connect(interface_voxels_left, "seed_list", connectivity_matrix, "voxel_list_left") dmripipeline.connect(interface_voxels_right, "seed_list", connectivity_matrix, "voxel_list_right") tract_exclusion_mask = pe.Node(interface=Function( input_names=["voxel_list", "ref_image", "outfile"], output_names=["outfile"], function=voxels2nii), name='72_tract_exclusion_mask') tract_exclusion_mask.inputs.outfile = subject_ID + '_tractseed_exclusion_mask.nii' dmripipeline.connect(inputnode, "wm", tract_exclusion_mask, "ref_image") dmripipeline.connect(connectivity_matrix, "exclusion_list", tract_exclusion_mask, "voxel_list") submatrix_left_left = pe.Node(interface=Function( input_names=["in_array", "max_value", "outfile_prefix"], output_names=[ "mat_matrix_nat", "mat_matrix_log", "nii_matrix_nat", "nii_matrix_log" ], function=normalize_matrix), name='73_submatrix_left_left') submatrix_left_left.run_without_submitting = True submatrix_left_left.inputs.max_value = tract_number submatrix_left_left.inputs.outfile_prefix = 'directconnect_left_left' dmripipeline.connect(connectivity_matrix, "submatrix_left_left", submatrix_left_left, "in_array") submatrix_left_right = submatrix_left_left.clone( name='73_submatrix_left_right') submatrix_left_right.inputs.outfile_prefix = 'directconnect_left_right' dmripipeline.connect(connectivity_matrix, "submatrix_left_right", submatrix_left_right, "in_array") submatrix_right_left = submatrix_left_left.clone( name='73_submatrix_right_left') submatrix_right_left.inputs.outfile_prefix = 'directconnect_right_left' dmripipeline.connect(connectivity_matrix, "submatrix_right_left", submatrix_right_left, "in_array") submatrix_right_right = submatrix_left_left.clone( name='73_submatrix_right_right') submatrix_right_right.inputs.outfile_prefix = 'directconnect_right_right' dmripipeline.connect(connectivity_matrix, "submatrix_right_right", submatrix_right_right, "in_array") # full_matrix_nat = pe.Node(interface=Function(input_names=["sm_left_left", "sm_left_right","sm_right_left", "sm_right_right", "out_filename"], output_names=["out_file"], function=merge_matrices), name='73_full_matrix_nat') # full_matrix_nat.inputs.out_filename = 'directconnect_full_nat.mat' # full_matrix_nat.run_without_submitting = True # dmripipeline.connect(submatrix_left_left, "nii_matrix_nat", full_matrix_nat, "sm_left_left") # dmripipeline.connect(submatrix_left_right, "nii_matrix_nat", full_matrix_nat, "sm_left_right") # dmripipeline.connect(submatrix_right_left, "nii_matrix_nat", full_matrix_nat, "sm_right_left") # dmripipeline.connect(submatrix_right_right, "nii_matrix_nat", full_matrix_nat, "sm_right_right") # # full_matrix_log = full_matrix_nat.clone(name='73_full_matrix_log') # full_matrix_log.inputs.out_filename = 'directconnect_full_log.mat' # full_matrix_log.run_without_submitting = True # dmripipeline.connect(submatrix_left_left, "nii_matrix_log", full_matrix_log, "sm_left_left") # dmripipeline.connect(submatrix_left_right, "nii_matrix_log", full_matrix_log, "sm_left_right") # dmripipeline.connect(submatrix_right_left, "nii_matrix_log", full_matrix_log, "sm_right_left") # dmripipeline.connect(submatrix_right_right, "nii_matrix_log", full_matrix_log, "sm_right_right") """ # invert and binarize tract exclusion mask and remove those voxels from the index interfaces """ tract_denoise_mask = pe.Node(interface=fsl.maths.MathsCommand(), name='74_tract_denoise_mask') tract_denoise_mask.inputs.args = '-binv' tract_denoise_mask.run_without_submitting = True dmripipeline.connect(tract_exclusion_mask, "outfile", tract_denoise_mask, "in_file") index_pruned_left = pe.Node(interface=fsl.maths.ApplyMask(), name='75_interface_pruned_left') index_pruned_left.inputs.out_file = subject_ID + '_interface_pruned_left.nii' index_pruned_left.run_without_submitting = True dmripipeline.connect(inputnode, "index_left", index_pruned_left, "in_file") dmripipeline.connect(tract_denoise_mask, "out_file", index_pruned_left, "mask_file") index_pruned_right = index_pruned_left.clone( name='75_interface_pruned_right') index_pruned_right.inputs.out_file = subject_ID + '_interface_pruned_right.nii' dmripipeline.connect(inputnode, "index_right", index_pruned_right, "in_file") dmripipeline.connect(tract_denoise_mask, "out_file", index_pruned_right, "mask_file") """ # warp index image to t1 space """ index_warped_2_t1_left = pe.Node(interface=ants.WarpImageMultiTransform(), name='76_index_warped_2_t1_left') index_warped_2_t1_left.inputs.use_nearest = True index_warped_2_t1_left.run_without_submitting = True dmripipeline.connect([(index_pruned_left, index_warped_2_t1_left, [('out_file', 'input_image')])]) dmripipeline.connect([(inputnode, index_warped_2_t1_left, [('fa', 'reference_image')])]) dmripipeline.connect([(inputnode, index_warped_2_t1_left, [('warp', 'transformation_series')])]) index_warped_2_t1_right = index_warped_2_t1_left.clone( name='76_index_warped_2_t1_right') dmripipeline.connect([(index_pruned_right, index_warped_2_t1_right, [('out_file', 'input_image')])]) dmripipeline.connect([(inputnode, index_warped_2_t1_right, [('fa', 'reference_image')])]) dmripipeline.connect([(inputnode, index_warped_2_t1_right, [('warp', 'transformation_series')])]) index_final_2_t1_left = pe.Node(interface=fsl.ApplyXfm(), name='77_index_final_2_t1_left') index_final_2_t1_left.inputs.apply_xfm = True index_final_2_t1_left.run_without_submitting = True index_final_2_t1_left.inputs.interp = 'nearestneighbour' index_final_2_t1_left.inputs.out_file = subject_ID + '_index_seedt1_left.nii' dmripipeline.connect([(index_warped_2_t1_left, index_final_2_t1_left, [("output_image", "in_file")])]) dmripipeline.connect([(inputnode, index_final_2_t1_left, [("inv_flirt_mat", "in_matrix_file")])]) dmripipeline.connect([(inputnode, index_final_2_t1_left, [("t1", "reference")])]) index_final_2_t1_right = index_final_2_t1_left.clone( name='77_index_final_2_t1_right') index_final_2_t1_right.inputs.out_file = subject_ID + '_index_seedt1_right.nii' dmripipeline.connect([(index_warped_2_t1_right, index_final_2_t1_right, [("output_image", "in_file")])]) dmripipeline.connect([(inputnode, index_final_2_t1_right, [("inv_flirt_mat", "in_matrix_file")])]) dmripipeline.connect([(inputnode, index_final_2_t1_right, [("t1", "reference")])]) """ extra processing """ index_vol2surf_left = pe.Node(interface=fsurf.SampleToSurface(), name='78_index_vol2surf_left') index_vol2surf_left.inputs.hemi = 'lh' index_vol2surf_left.inputs.subject_id = subject_ID index_vol2surf_left.inputs.reg_header = True index_vol2surf_left.inputs.interp_method = 'nearest' index_vol2surf_left.inputs.sampling_method = 'point' index_vol2surf_left.inputs.sampling_range = 0 index_vol2surf_left.inputs.sampling_units = 'frac' index_vol2surf_left.inputs.surface = 'orig' #index_vol2surf_left.inputs.cortex_mask = True index_vol2surf_left.inputs.terminal_output = 'file' index_vol2surf_left.inputs.out_file = subject_ID + '_index_seedt1_2surf_left.mgz' index_vol2surf_left.run_without_submitting = True dmripipeline.connect([(index_final_2_t1_left, index_vol2surf_left, [('out_file', 'source_file')])]) index_vol2surf_right = index_vol2surf_left.clone( name='78_index_vol2surf_right') index_vol2surf_right.inputs.hemi = 'rh' index_vol2surf_right.inputs.out_file = subject_ID + '_index_seedt1_2surf_right.mgz' dmripipeline.connect([(index_final_2_t1_right, index_vol2surf_right, [('out_file', 'source_file')])]) index_2_t1_reorient_left = pe.Node(interface=fsl.Reorient2Std(), name='79_next_2_t1_reorient_left') index_2_t1_reorient_left.inputs.out_file = subject_ID + '_index_seedt1_reorient_left.nii' index_2_t1_reorient_left.run_without_submitting = True dmripipeline.connect(index_final_2_t1_left, 'out_file', index_2_t1_reorient_left, 'in_file') index_2_t1_reorient_right = index_2_t1_reorient_left.clone( name='79_next_2_t1_reorient_right') index_2_t1_reorient_right.inputs.out_file = subject_ID + '_index_seedt1_reorient_right.nii' dmripipeline.connect(index_final_2_t1_right, 'out_file', index_2_t1_reorient_right, 'in_file') index_interface2surf_left = pe.Node(interface=Function( input_names=[ "interface_image", "surface_file", "cortex_label", "ref_mgz", "out_file" ], output_names=["out_file"], function=interface2surf), name='80_index_interface2surf_left') index_interface2surf_left.inputs.surface_file = subjects_dir + '/' + subject_ID + '/surf/lh.orig' index_interface2surf_left.inputs.cortex_label = subjects_dir + '/' + subject_ID + '/label/lh.cortex.label' index_interface2surf_left.inputs.out_file = subject_ID + '_index_seedt1_2surf_left.mgz' dmripipeline.connect(index_2_t1_reorient_left, 'out_file', index_interface2surf_left, 'interface_image') dmripipeline.connect(index_vol2surf_left, 'out_file', index_interface2surf_left, 'ref_mgz') index_interface2surf_right = index_interface2surf_left.clone( name='80_index_interface2surf_right') index_interface2surf_right.inputs.surface_file = subjects_dir + '/' + subject_ID + '/surf/rh.orig' index_interface2surf_right.inputs.cortex_label = subjects_dir + '/' + subject_ID + '/label/rh.cortex.label' index_interface2surf_right.inputs.out_file = subject_ID + '_index_seedt1_2surf_right.mgz' dmripipeline.connect(index_2_t1_reorient_right, 'out_file', index_interface2surf_right, 'interface_image') dmripipeline.connect(index_vol2surf_right, 'out_file', index_interface2surf_right, 'ref_mgz') fs_indexlist_left = pe.Node(interface=Function( input_names=["in_surface_values", "cortex_label", "out_file"], output_names=["out_file"], function=surf2file), name='81_index_fsnative_left') fs_indexlist_left.inputs.cortex_label = op.join( freesurfer_dir, subject_ID + '/label/lh.cortex.label') fs_indexlist_left.inputs.out_file = subject_ID + '_seed_index_fsnative_left.txt' fs_indexlist_left.run_without_submitting = True dmripipeline.connect([(index_interface2surf_left, fs_indexlist_left, [("out_file", "in_surface_values")])]) fs_indexlist_right = fs_indexlist_left.clone( name='81_index_fsnative_right') fs_indexlist_right.inputs.cortex_label = op.join( freesurfer_dir, subject_ID + '/label/rh.cortex.label') fs_indexlist_right.inputs.out_file = subject_ID + '_seed_index_fsnative_right.txt' dmripipeline.connect([(index_interface2surf_right, fs_indexlist_right, [("out_file", "in_surface_values")])]) """""" """""" """""" """""" """ """ """""" """""" """""" """""" index_fsaverage5_left = pe.Node(interface=fsurf.SurfaceTransform(), name='81_index_fsaverage5_left') index_fsaverage5_left.inputs.hemi = 'lh' index_fsaverage5_left.inputs.source_subject = subject_ID index_fsaverage5_left.inputs.target_subject = 'fsaverage5' index_fsaverage5_left.inputs.args = '--mapmethod nnf --label-src lh.cortex.label --label-trg lh.cortex.label' index_fsaverage5_left.inputs.out_file = subject_ID + '_index_seedt1_fsaverage5_left.mgz' #index_fsaverage5_left.run_without_submitting = True dmripipeline.connect([(index_interface2surf_left, index_fsaverage5_left, [('out_file', 'source_file')])]) index_fsaverage5_right = index_fsaverage5_left.clone( name='81_index_fsaverage5_right') index_fsaverage5_right.inputs.hemi = 'rh' index_fsaverage5_left.inputs.args = '--mapmethod nnf --label-src rh.cortex.label --label-trg rh.cortex.label' index_fsaverage5_right.inputs.out_file = subject_ID + '_index_seedt1_fsaverage5_right.mgz' dmripipeline.connect([(index_interface2surf_right, index_fsaverage5_right, [('out_file', 'source_file')])]) fs5_indexlist_left = pe.Node(interface=Function( input_names=["in_surface_values", "cortex_label", "out_file"], output_names=["out_file"], function=surf2file), name='82_index_fsav5_left') fs5_indexlist_left.inputs.cortex_label = op.join( freesurfer_dir, 'fsaverage5/label/lh.cortex.label') fs5_indexlist_left.inputs.out_file = subject_ID + '_seed_index_fs5_left.txt' #fs5_indexlist_left.run_without_submitting = True dmripipeline.connect([(index_fsaverage5_left, fs5_indexlist_left, [("out_file", "in_surface_values")])]) fs5_indexlist_right = fs5_indexlist_left.clone(name='82_index_fsav5_right') fs5_indexlist_right.inputs.cortex_label = op.join( freesurfer_dir, 'fsaverage5/label/rh.cortex.label') fs5_indexlist_right.inputs.out_file = subject_ID + '_seed_index_fs5_right.txt' dmripipeline.connect([(index_fsaverage5_right, fs5_indexlist_right, [("out_file", "in_surface_values")])]) index_fsaverage4_left = pe.Node(interface=fsurf.SurfaceTransform(), name='81_index_fsaverage4_left') index_fsaverage4_left.inputs.hemi = 'lh' index_fsaverage4_left.inputs.source_subject = subject_ID index_fsaverage4_left.inputs.target_subject = 'fsaverage4' index_fsaverage4_left.inputs.args = '--mapmethod nnf --label-src lh.cortex.label --label-trg lh.cortex.label' index_fsaverage4_left.inputs.out_file = subject_ID + '_index_seedt1_fsaverage4_left.mgz' #index_fsaverage4_left.run_without_submitting = True dmripipeline.connect([(index_interface2surf_left, index_fsaverage4_left, [('out_file', 'source_file')])]) index_fsaverage4_right = index_fsaverage4_left.clone( name='81_index_fsaverage4_right') index_fsaverage4_right.inputs.hemi = 'rh' index_fsaverage4_left.inputs.args = '--mapmethod nnf --label-src rh.cortex.label --label-trg rh.cortex.label' index_fsaverage4_right.inputs.out_file = subject_ID + '_index_seedt1_fsaverage4_right.mgz' dmripipeline.connect([(index_interface2surf_right, index_fsaverage4_right, [('out_file', 'source_file')])]) fs4_indexlist_left = pe.Node(interface=Function( input_names=["in_surface_values", "cortex_label", "out_file"], output_names=["out_file"], function=surf2file), name='82_index_fsav4_left') fs4_indexlist_left.inputs.cortex_label = op.join( freesurfer_dir, 'fsaverage4/label/lh.cortex.label') fs4_indexlist_left.inputs.out_file = subject_ID + '_seed_index_fs4_left.txt' #fs4_indexlist_left.run_without_submitting = True dmripipeline.connect([(index_fsaverage4_left, fs4_indexlist_left, [("out_file", "in_surface_values")])]) fs4_indexlist_right = fs4_indexlist_left.clone(name='82_index_fsav4_right') fs4_indexlist_right.inputs.cortex_label = op.join( freesurfer_dir, 'fsaverage4/label/rh.cortex.label') fs4_indexlist_right.inputs.out_file = subject_ID + '_seed_index_fs4_right.txt' dmripipeline.connect([(index_fsaverage4_right, fs4_indexlist_right, [("out_file", "in_surface_values")])]) """ downsample matrices according to fsaverage projections """ if (not use_sample): connect_mat_fs4_nat_left_left = pe.Node( interface=Function(input_names=[ "index_row_file", "index_col_file", "matrix_file", "out_prefix", "dist2sim" ], output_names=["out_mat", "out_nii"], function=downsample_matrix), name='83_connect_mat_fs4_nat_left_left') connect_mat_fs4_nat_left_left.inputs.out_prefix = subject_ID + '_connect_fs4_nat_left_left' connect_mat_fs4_nat_left_left.inputs.dist2sim = False dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_nat_left_left, "index_row_file") dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_nat_left_left, "index_col_file") dmripipeline.connect(submatrix_left_left, "mat_matrix_nat", connect_mat_fs4_nat_left_left, "matrix_file") connect_mat_fs4_nat_left_right = connect_mat_fs4_nat_left_left.clone( name='83_connect_mat_fs4_nat_left_right') connect_mat_fs4_nat_left_right.inputs.out_prefix = subject_ID + '_connect_fs4_nat_left_right' dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_nat_left_right, "index_row_file") dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_nat_left_right, "index_col_file") dmripipeline.connect(submatrix_left_right, "mat_matrix_nat", connect_mat_fs4_nat_left_right, "matrix_file") connect_mat_fs4_nat_right_left = connect_mat_fs4_nat_left_left.clone( name='83_connect_mat_fs4_nat_right_left') connect_mat_fs4_nat_right_left.inputs.out_prefix = subject_ID + '_connect_fs4_nat_right_left' dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_nat_right_left, "index_row_file") dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_nat_right_left, "index_col_file") dmripipeline.connect(submatrix_right_left, "mat_matrix_nat", connect_mat_fs4_nat_right_left, "matrix_file") connect_mat_fs4_nat_right_right = connect_mat_fs4_nat_left_left.clone( name='83_connect_mat_fs4_nat_right_right') connect_mat_fs4_nat_right_right.inputs.out_prefix = subject_ID + '_connect_fs4_nat_right_right' dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_nat_right_right, "index_row_file") dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_nat_right_right, "index_col_file") dmripipeline.connect(submatrix_right_right, "mat_matrix_nat", connect_mat_fs4_nat_right_right, "matrix_file") connect_mat_fs4_log_left_left = connect_mat_fs4_nat_left_left.clone( name='83_connect_mat_fs4_log_left_left') connect_mat_fs4_log_left_left.inputs.out_prefix = subject_ID + '_connect_fs4_log_left_left' dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_log_left_left, "index_row_file") dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_log_left_left, "index_col_file") dmripipeline.connect(submatrix_left_left, "mat_matrix_log", connect_mat_fs4_log_left_left, "matrix_file") connect_mat_fs4_log_left_right = connect_mat_fs4_log_left_left.clone( name='83_connect_mat_fs4_log_left_right') connect_mat_fs4_log_left_right.inputs.out_prefix = subject_ID + '_connect_fs4_log_left_right' dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_log_left_right, "index_row_file") dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_log_left_right, "index_col_file") dmripipeline.connect(submatrix_left_right, "mat_matrix_log", connect_mat_fs4_log_left_right, "matrix_file") connect_mat_fs4_log_right_left = connect_mat_fs4_log_left_left.clone( name='83_connect_mat_fs4_log_right_left') connect_mat_fs4_log_right_left.inputs.out_prefix = subject_ID + '_connect_fs4_log_right_left' dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_log_right_left, "index_row_file") dmripipeline.connect(fs4_indexlist_left, "out_file", connect_mat_fs4_log_right_left, "index_col_file") dmripipeline.connect(submatrix_right_left, "mat_matrix_log", connect_mat_fs4_log_right_left, "matrix_file") connect_mat_fs4_log_right_right = connect_mat_fs4_log_left_left.clone( name='83_connect_mat_fs4_log_right_right') connect_mat_fs4_log_right_right.inputs.out_prefix = subject_ID + '_connect_fs4_log_right_right' dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_log_right_right, "index_row_file") dmripipeline.connect(fs4_indexlist_right, "out_file", connect_mat_fs4_log_right_right, "index_col_file") dmripipeline.connect(submatrix_right_right, "mat_matrix_log", connect_mat_fs4_log_right_right, "matrix_file") # connect_mat_fs4_nat_full = pe.Node(interface=Function(input_names=["sm_left_left", "sm_left_right","sm_right_left", "sm_right_right", "out_filename"], output_names=["out_file"], function=merge_matrices), name='83_connect_mat_fs4_nat_full') # connect_mat_fs4_nat_full.inputs.out_filename = subject_ID + '_connect_fs4_nat_full.mat' # connect_mat_fs4_nat_full.run_without_submitting = True # dmripipeline.connect(connect_mat_fs4_nat_left_left, "out_nii", connect_mat_fs4_nat_full, "sm_left_left") # dmripipeline.connect(connect_mat_fs4_nat_left_right, "out_nii", connect_mat_fs4_nat_full, "sm_left_right") # dmripipeline.connect(connect_mat_fs4_nat_right_left, "out_nii", connect_mat_fs4_nat_full, "sm_right_left") # dmripipeline.connect(connect_mat_fs4_nat_right_right, "out_nii", connect_mat_fs4_nat_full, "sm_right_right") # # connect_mat_fs4_log_full = connect_mat_fs4_nat_full.clone(name='83_connect_mat_fs4_log_full') # connect_mat_fs4_log_full.inputs.outfile_prefix = subject_ID + '_connect_fs4_log_full.mat' # connect_mat_fs4_log_full.run_without_submitting = True # dmripipeline.connect(connect_mat_fs4_log_left_left, "out_nii", connect_mat_fs4_log_full, "sm_left_left") # dmripipeline.connect(connect_mat_fs4_log_left_right, "out_nii", connect_mat_fs4_log_full, "sm_left_right") # dmripipeline.connect(connect_mat_fs4_log_right_left, "out_nii", connect_mat_fs4_log_full, "sm_right_left") # dmripipeline.connect(connect_mat_fs4_log_right_right, "out_nii", connect_mat_fs4_log_full, "sm_right_right") connect_mat_fs5_nat_left_left = connect_mat_fs4_nat_left_left.clone( name='83_connect_mat_fs5_nat_left_left') connect_mat_fs5_nat_left_left.inputs.out_prefix = subject_ID + '_connect_fs5_nat_left_left' dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_nat_left_left, "index_row_file") dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_nat_left_left, "index_col_file") dmripipeline.connect(submatrix_left_left, "mat_matrix_nat", connect_mat_fs5_nat_left_left, "matrix_file") connect_mat_fs5_nat_left_right = connect_mat_fs5_nat_left_left.clone( name='83_connect_mat_fs5_nat_left_right') connect_mat_fs5_nat_left_right.inputs.out_prefix = subject_ID + '_connect_fs5_nat_left_right' dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_nat_left_right, "index_row_file") dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_nat_left_right, "index_col_file") dmripipeline.connect(submatrix_left_right, "mat_matrix_nat", connect_mat_fs5_nat_left_right, "matrix_file") connect_mat_fs5_nat_right_left = connect_mat_fs5_nat_left_left.clone( name='83_connect_mat_fs5_nat_right_left') connect_mat_fs5_nat_right_left.inputs.out_prefix = subject_ID + '_connect_fs5_nat_right_left' dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_nat_right_left, "index_row_file") dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_nat_right_left, "index_col_file") dmripipeline.connect(submatrix_right_left, "mat_matrix_nat", connect_mat_fs5_nat_right_left, "matrix_file") connect_mat_fs5_nat_right_right = connect_mat_fs5_nat_left_left.clone( name='83_connect_mat_fs5_nat_right_right') connect_mat_fs5_nat_right_right.inputs.out_prefix = subject_ID + '_connect_fs5_nat_right_right' dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_nat_right_right, "index_row_file") dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_nat_right_right, "index_col_file") dmripipeline.connect(submatrix_right_right, "mat_matrix_nat", connect_mat_fs5_nat_right_right, "matrix_file") connect_mat_fs5_log_left_left = connect_mat_fs5_nat_left_left.clone( name='83_connect_mat_fs5_log_left_left') connect_mat_fs5_log_left_left.inputs.out_prefix = subject_ID + '_connect_fs5_log_left_left' dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_log_left_left, "index_row_file") dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_log_left_left, "index_col_file") dmripipeline.connect(submatrix_left_left, "mat_matrix_log", connect_mat_fs5_log_left_left, "matrix_file") connect_mat_fs5_log_left_right = connect_mat_fs5_log_left_left.clone( name='83_connect_mat_fs5_log_left_right') connect_mat_fs5_log_left_right.inputs.out_prefix = subject_ID + '_connect_fs5_log_left_right' dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_log_left_right, "index_row_file") dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_log_left_right, "index_col_file") dmripipeline.connect(submatrix_left_right, "mat_matrix_log", connect_mat_fs5_log_left_right, "matrix_file") connect_mat_fs5_log_right_left = connect_mat_fs5_log_left_left.clone( name='83_connect_mat_fs5_log_right_left') connect_mat_fs5_log_right_left.inputs.out_prefix = subject_ID + '_connect_fs5_log_right_left' dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_log_right_left, "index_row_file") dmripipeline.connect(fs5_indexlist_left, "out_file", connect_mat_fs5_log_right_left, "index_col_file") dmripipeline.connect(submatrix_right_left, "mat_matrix_log", connect_mat_fs5_log_right_left, "matrix_file") connect_mat_fs5_log_right_right = connect_mat_fs5_log_left_left.clone( name='83_connect_mat_fs5_log_right_right') connect_mat_fs5_log_right_right.inputs.out_prefix = subject_ID + '_connect_fs5_log_right_right' dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_log_right_right, "index_row_file") dmripipeline.connect(fs5_indexlist_right, "out_file", connect_mat_fs5_log_right_right, "index_col_file") dmripipeline.connect(submatrix_right_right, "mat_matrix_log", connect_mat_fs5_log_right_right, "matrix_file") # connect_mat_fs5_nat_full = connect_mat_fs4_nat_full.clone(name='83_connect_mat_fs5_nat_full') # connect_mat_fs5_nat_full.inputs.outfile_prefix = subject_ID + '_connect_fs5_nat_full.mat' # connect_mat_fs5_nat_full.run_without_submitting = True # dmripipeline.connect(connect_mat_fs5_nat_left_left, "out_nii", connect_mat_fs5_nat_full, "sm_left_left") # dmripipeline.connect(connect_mat_fs5_nat_left_right, "out_nii", connect_mat_fs5_nat_full, "sm_left_right") # dmripipeline.connect(connect_mat_fs5_nat_right_left, "out_nii", connect_mat_fs5_nat_full, "sm_right_left") # dmripipeline.connect(connect_mat_fs5_nat_right_right, "out_nii", connect_mat_fs5_nat_full, "sm_right_right") # # connect_mat_fs5_log_full = connect_mat_fs5_nat_full.clone(name='83_connect_mat_fs5_log_full') # connect_mat_fs5_log_full.inputs.out_filename = subject_ID + '_connect_fs5_log_full.mat' # connect_mat_fs5_log_full.run_without_submitting = True # dmripipeline.connect(connect_mat_fs5_log_left_left, "out_nii", connect_mat_fs5_log_full, "sm_left_left") # dmripipeline.connect(connect_mat_fs5_log_left_right, "out_nii", connect_mat_fs5_log_full, "sm_left_right") # dmripipeline.connect(connect_mat_fs5_log_right_left, "out_nii", connect_mat_fs5_log_full, "sm_right_left") # dmripipeline.connect(connect_mat_fs5_log_right_right, "out_nii", connect_mat_fs5_log_full, "sm_right_right") # """ use a sink to save outputs """ datasink = pe.Node(io.DataSink(), name='99_datasink') datasink.inputs.base_directory = output_dir datasink.inputs.container = subject_ID datasink.inputs.parameterization = True #datasink.run_without_submitting = True dmripipeline.connect(index_pruned_left, 'out_file', datasink, 'interface_index.@3') dmripipeline.connect(index_pruned_right, 'out_file', datasink, 'interface_index.@4') dmripipeline.connect(index_final_2_t1_left, 'out_file', datasink, 'interface_index.@5') dmripipeline.connect(index_final_2_t1_right, 'out_file', datasink, 'interface_index.@6') dmripipeline.connect(index_interface2surf_left, 'out_file', datasink, 'interface_index.@7') dmripipeline.connect(index_interface2surf_right, 'out_file', datasink, 'interface_index.@8') dmripipeline.connect(index_fsaverage5_left, 'out_file', datasink, 'interface_index.@9') dmripipeline.connect(index_fsaverage5_right, 'out_file', datasink, 'interface_index.@10') dmripipeline.connect(fs5_indexlist_left, 'out_file', datasink, 'interface_index.@11') dmripipeline.connect(fs5_indexlist_right, 'out_file', datasink, 'interface_index.@12') dmripipeline.connect(index_fsaverage4_left, 'out_file', datasink, 'interface_index.@13') dmripipeline.connect(index_fsaverage4_right, 'out_file', datasink, 'interface_index.@14') dmripipeline.connect(fs4_indexlist_left, 'out_file', datasink, 'interface_index.@15') dmripipeline.connect(fs4_indexlist_right, 'out_file', datasink, 'interface_index.@16') dmripipeline.connect(fs_indexlist_left, 'out_file', datasink, 'interface_index.@17') dmripipeline.connect(fs_indexlist_right, 'out_file', datasink, 'interface_index.@18') dmripipeline.connect(tract_exclusion_mask, 'outfile', datasink, 'interface_index.@19') # dmripipeline.connect(submatrix_left_left, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat') # dmripipeline.connect(submatrix_left_left, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@2') dmripipeline.connect(submatrix_left_left, 'nii_matrix_nat', datasink, 'connect_matrix.native.@3') dmripipeline.connect(submatrix_left_left, 'nii_matrix_log', datasink, 'connect_matrix.native.@4') # dmripipeline.connect(submatrix_right_right, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat.@5') # dmripipeline.connect(submatrix_right_right, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@6') dmripipeline.connect(submatrix_right_right, 'nii_matrix_nat', datasink, 'connect_matrix.native.@7') dmripipeline.connect(submatrix_right_right, 'nii_matrix_log', datasink, 'connect_matrix.native.@8') # dmripipeline.connect(submatrix_left_right, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat') # dmripipeline.connect(submatrix_left_right, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@2') dmripipeline.connect(submatrix_left_right, 'nii_matrix_nat', datasink, 'connect_matrix.native.@9') dmripipeline.connect(submatrix_left_right, 'nii_matrix_log', datasink, 'connect_matrix.native.@10') # dmripipeline.connect(submatrix_right_left, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat') # dmripipeline.connect(submatrix_right_left, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@2') dmripipeline.connect(submatrix_right_left, 'nii_matrix_nat', datasink, 'connect_matrix.native.@11') dmripipeline.connect(submatrix_right_left, 'nii_matrix_log', datasink, 'connect_matrix.native.@12') # dmripipeline.connect(full_matrix_nat, 'out_file', datasink, 'connect_matrix.native.@9') # dmripipeline.connect(full_matrix_log, 'out_file', datasink, 'connect_matrix.native.@11') if (not use_sample): # dmripipeline.connect(connect_mat_fs4_nat_left_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@1') # dmripipeline.connect(connect_mat_fs4_log_left_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@2') # dmripipeline.connect(connect_mat_fs4_nat_right_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@3') # dmripipeline.connect(connect_mat_fs4_log_right_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@4') # dmripipeline.connect(connect_mat_fs4_nat_left_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@5') # dmripipeline.connect(connect_mat_fs4_log_left_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@6') # dmripipeline.connect(connect_mat_fs4_nat_right_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@7') # dmripipeline.connect(connect_mat_fs4_log_right_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@8') dmripipeline.connect(connect_mat_fs4_nat_left_left, 'out_nii', datasink, 'connect_matrix.fs4.@1') dmripipeline.connect(connect_mat_fs4_log_left_left, 'out_nii', datasink, 'connect_matrix.fs4.@2') dmripipeline.connect(connect_mat_fs4_nat_right_right, 'out_nii', datasink, 'connect_matrix.fs4.@3') dmripipeline.connect(connect_mat_fs4_log_right_right, 'out_nii', datasink, 'connect_matrix.fs4.@4') dmripipeline.connect(connect_mat_fs4_nat_left_right, 'out_nii', datasink, 'connect_matrix.fs4.@5') dmripipeline.connect(connect_mat_fs4_log_left_right, 'out_nii', datasink, 'connect_matrix.fs4.@6') dmripipeline.connect(connect_mat_fs4_nat_right_left, 'out_nii', datasink, 'connect_matrix.fs4.@7') dmripipeline.connect(connect_mat_fs4_log_right_left, 'out_nii', datasink, 'connect_matrix.fs4.@8') # dmripipeline.connect(connect_mat_fs4_nat_full, 'out_file', datasink, 'connect_matrix.@28') # dmripipeline.connect(connect_mat_fs4_log_full, 'out_file', datasink, 'connect_matrix.@30') # dmripipeline.connect(connect_mat_fs5_nat_left_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@1') # dmripipeline.connect(connect_mat_fs5_log_left_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@2') # dmripipeline.connect(connect_mat_fs5_nat_right_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@3') # dmripipeline.connect(connect_mat_fs5_log_right_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@4') # dmripipeline.connect(connect_mat_fs5_nat_left_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@5') # dmripipeline.connect(connect_mat_fs5_log_left_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@6') # dmripipeline.connect(connect_mat_fs5_nat_right_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@7') # dmripipeline.connect(connect_mat_fs5_log_right_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@8') dmripipeline.connect(connect_mat_fs5_nat_left_left, 'out_nii', datasink, 'connect_matrix.fs5.@1') dmripipeline.connect(connect_mat_fs5_log_left_left, 'out_nii', datasink, 'connect_matrix.fs5.@2') dmripipeline.connect(connect_mat_fs5_nat_right_right, 'out_nii', datasink, 'connect_matrix.fs5.@3') dmripipeline.connect(connect_mat_fs5_log_right_right, 'out_nii', datasink, 'connect_matrix.fs5.@4') dmripipeline.connect(connect_mat_fs5_nat_left_right, 'out_nii', datasink, 'connect_matrix.fs5.@5') dmripipeline.connect(connect_mat_fs5_log_left_right, 'out_nii', datasink, 'connect_matrix.fs5.@6') dmripipeline.connect(connect_mat_fs5_nat_right_left, 'out_nii', datasink, 'connect_matrix.fs5.@7') dmripipeline.connect(connect_mat_fs5_log_right_left, 'out_nii', datasink, 'connect_matrix.fs5.@8') # dmripipeline.connect(connect_mat_fs5_nat_full, 'out_file', datasink, 'connect_matrix.@40') # dmripipeline.connect(connect_mat_fs5_log_full, 'out_file', datasink, 'connect_matrix.@42') """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """ =============================================================================== Connecting the workflow =============================================================================== """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """ Create a higher-level workflow ------------------------------ Finally, we create another higher-level workflow to connect our dmripipeline workflow with the info and datagrabbing nodes declared at the beginning. Our tutorial is now extensible to any arbitrary number of subjects by simply adding their names to the subject list and their data to the proper folders. """ connectprepro = pe.Workflow(name="dmri_pipe3_projection") connectprepro.base_dir = op.abspath(workflow_dir + "/workflow_" + subject_ID) connectprepro.connect([(datasource, dmripipeline, [('wm', 'inputnode.wm'), ('seeds_left', 'inputnode.seeds_left'), ('seeds_right', 'inputnode.seeds_right'), ('t1', 'inputnode.t1'), ('warp', 'inputnode.warp'), ('inv_flirt_mat', 'inputnode.inv_flirt_mat'), ('fa', 'inputnode.fa'), ('index_left', 'inputnode.index_left'), ('index_right', 'inputnode.index_right')]), (tracts_left_source, dmripipeline, [('tracts_left', 'inputnode.tracts_left')]), (tracts_right_source, dmripipeline, [('tracts_right', 'inputnode.tracts_right')])]) return connectprepro
def susceptibility_distortion_correction_using_t1( name='susceptibility_distortion_correction_using_t1'): """ Susceptibility distortion correction using the T1w image. This workflow allows to correct for echo-planar induced susceptibility artifacts without fieldmap (e.g. ADNI Database) by elastically register DWIs to their respective baseline T1-weighted structural scans using an inverse consistent registration algorithm with a mutual information cost function (SyN algorithm). Args: name (Optional[str]): Name of the workflow. Inputnode: in_t1 (str): T1w image. in_dwi (str): DWI dataset Outputnode: out_dwi (str): Corrected DWI dataset out_warp (str): Out warp allowing DWI to T1 registration and susceptibilty induced artifacts correction out_b0_to_t1_rigid_body_matrix (str): B0 to T1 image FLIRT rigid body FSL coregistration matrix out_t1_to_b0_rigid_body_matrix (str): T1 to B0 image FLIRT rigid body FSL coregistration matrix out_t1_coregistered_to_b0 (str): T1 image rigid body coregistered to the B0 image out_b0_to_t1_syn_deformation_field (str): B0 to T1 image ANTs SyN ITK warp out_b0_to_t1_affine_matrix (str): B0 to T1 image ANTs affine ITK coregistration matrix References: .. Nir et al. (Neurobiology of Aging 2015): Connectivity network measures predict volumetric atrophy in mild cognitive impairment .. Leow et al. (IEEE Trans Med Imaging 2007): Statistical Properties of Jacobian Maps and the Realization of Unbiased Large Deformation Nonlinear Image Registration Returns: The workflow Example: >>> epi = susceptibility_distortion_correction_using_t1() >>> epi.inputs.inputnode.in_dwi = 'dwi.nii' >>> epi.inputs.inputnode.in_t1 = 'T1w.nii' >>> epi.run() # doctest: +SKIP """ import nipype import nipype.pipeline.engine as pe import nipype.interfaces.utility as niu import nipype.interfaces.fsl as fsl import clinica.pipelines.dwi_preprocessing_using_t1.dwi_preprocessing_using_t1_utils as utils def expend_matrix_list(in_matrix, in_bvec): import numpy as np bvecs = np.loadtxt(in_bvec).T out_matrix_list = [in_matrix] out_matrix_list = out_matrix_list * len(bvecs) return out_matrix_list def rotate_bvecs(in_bvec, in_matrix): """ Rotates the input bvec file accordingly with a list of matrices. .. note:: the input affine matrix transforms points in the destination image to their corresponding coordinates in the original image. Therefore, this matrix should be inverted first, as we want to know the target position of :math:`\\vec{r}`. """ import os import numpy as np name, fext = os.path.splitext(os.path.basename(in_bvec)) if fext == '.gz': name, _ = os.path.splitext(name) out_file = os.path.abspath('%s_rotated.bvec' % name) bvecs = np.loadtxt( in_bvec).T # Warning, bvecs.txt are not in the good configuration, need to put '.T' new_bvecs = [] if len(bvecs) != len(in_matrix): raise RuntimeError(('Number of b-vectors (%d) and rotation ' 'matrices (%d) should match.') % (len(bvecs), len(in_matrix))) for bvec, mat in zip(bvecs, in_matrix): if np.all(bvec == 0.0): new_bvecs.append(bvec) else: invrot = np.linalg.inv(np.loadtxt(mat))[:3, :3] newbvec = invrot.dot(bvec) new_bvecs.append((newbvec / np.linalg.norm(newbvec))) np.savetxt(out_file, np.array(new_bvecs).T, fmt='%0.15f') return out_file inputnode = pe.Node( niu.IdentityInterface(fields=['in_t1', 'in_dwi', 'in_bvec']), name='inputnode') split = pe.Node(fsl.Split(dimension='t'), name='SplitDWIs') pick_ref = pe.Node(niu.Select(), name='Pick_b0') pick_ref.inputs.index = [0] flirt_b0_to_t1 = pe.Node(interface=fsl.FLIRT(dof=6), name='flirt_b0_to_t1') flirt_b0_to_t1.inputs.interp = "spline" flirt_b0_to_t1.inputs.cost = 'normmi' flirt_b0_to_t1.inputs.cost_func = 'normmi' if nipype.__version__.split('.') < ['0', '13', '0']: apply_xfm = pe.Node(interface=fsl.ApplyXfm(), name='apply_xfm') else: apply_xfm = pe.Node(interface=fsl.ApplyXFM(), name='apply_xfm') apply_xfm.inputs.apply_xfm = True expend_matrix = pe.Node( interface=niu.Function(input_names=['in_matrix', 'in_bvec'], output_names=['out_matrix_list'], function=expend_matrix_list), name='expend_matrix') rot_bvec = pe.Node(niu.Function(input_names=['in_matrix', 'in_bvec'], output_names=['out_file'], function=rotate_bvecs), name='Rotate_Bvec') ants_registration_syn_quick = pe.Node(interface=niu.Function( input_names=['fix_image', 'moving_image'], output_names=['image_warped', 'affine_matrix', 'warp', 'inverse_warped', 'inverse_warp'], function=utils.ants_registration_syn_quick), name='ants_registration_syn_quick') merge_transform = pe.Node(niu.Merge(2), name='MergeTransforms') combine_warp = pe.Node(interface=niu.Function( input_names=['in_file', 'transforms_list', 'reference'], output_names=['out_warp'], function=utils.ants_combine_transform), name='combine_warp') coeffs = pe.Node(fsl.WarpUtils(out_format='spline'), name='CoeffComp') fsl_transf = pe.Node(fsl.WarpUtils(out_format='field'), name='fsl_transf') warp_epi = pe.Node(fsl.ConvertWarp(), name='warp_epi') apply_warp = pe.MapNode(interface=fsl.ApplyWarp(), iterfield=['in_file'], name='apply_warp') apply_warp.inputs.interp = 'spline' thres = pe.MapNode(fsl.Threshold(thresh=0.0), iterfield=['in_file'], name='RemoveNegative') merge = pe.Node(fsl.Merge(dimension='t'), name='MergeDWIs') outputnode = pe.Node(niu.IdentityInterface( fields=['dwi_to_t1_coregistration_matrix', 'itk_dwi_t1_coregistration_matrix', 'epi_correction_deformation_field', 'epi_correction_affine_transform', 'merge_epi_transform', 'out_dwi', 'out_warp', 'out_bvec']), name='outputnode') wf = pe.Workflow(name=name) wf.connect([ (inputnode, split, [('in_dwi', 'in_file')]), # noqa (split, pick_ref, [('out_files', 'inlist')]), # noqa (pick_ref, flirt_b0_to_t1, [('out', 'in_file')]), # noqa (inputnode, flirt_b0_to_t1, [('in_t1', 'reference')]), # noqa (flirt_b0_to_t1, expend_matrix, [('out_matrix_file', 'in_matrix')]), # noqa (inputnode, expend_matrix, [('in_bvec', 'in_bvec')]), # noqa (inputnode, rot_bvec, [('in_bvec', 'in_bvec')]), # noqa (expend_matrix, rot_bvec, [('out_matrix_list', 'in_matrix')]), # noqa (inputnode, ants_registration_syn_quick, [('in_t1', 'fix_image')]), # noqa (flirt_b0_to_t1, ants_registration_syn_quick, [('out_file', 'moving_image')]), # noqa (ants_registration_syn_quick, merge_transform, [('affine_matrix', 'in2'), # noqa ('warp', 'in1')]), # noqa (flirt_b0_to_t1, combine_warp, [('out_file', 'in_file')]), # noqa (merge_transform, combine_warp, [('out', 'transforms_list')]), # noqa (inputnode, combine_warp, [('in_t1', 'reference')]), # noqa (inputnode, coeffs, [('in_t1', 'reference')]), # noqa (combine_warp, coeffs, [('out_warp', 'in_file')]), # noqa (coeffs, fsl_transf, [('out_file', 'in_file')]), # noqa (inputnode, fsl_transf, [('in_t1', 'reference')]), # noqa (inputnode, warp_epi, [('in_t1', 'reference')]), # noqa (flirt_b0_to_t1, warp_epi, [('out_matrix_file', 'premat')]), # noqa (fsl_transf, warp_epi, [('out_file', 'warp1')]), # noqa (warp_epi, apply_warp, [('out_file', 'field_file')]), # noqa (split, apply_warp, [('out_files', 'in_file')]), # noqa (inputnode, apply_warp, [('in_t1', 'ref_file')]), # noqa (apply_warp, thres, [('out_file', 'in_file')]), # noqa (thres, merge, [('out_file', 'in_files')]), # noqa # Outputnode (merge, outputnode, [('merged_file', 'out_dwi')]), # noqa (flirt_b0_to_t1, outputnode, [('out_matrix_file', 'dwi_to_t1_coregistration_matrix')]), # noqa (ants_registration_syn_quick, outputnode, [('warp', 'epi_correction_deformation_field'), # noqa ('affine_matrix', 'epi_correction_affine_transform')]), # noqa (warp_epi, outputnode, [('out_file', 'out_warp')]), # noqa (rot_bvec, outputnode, [('out_file', 'out_bvec')]), # noqa ]) return wf
moco = pe.Node(fsl.MCFLIRT(cost='normmi'), name="mcflirt") extractb0 = pe.Node(fsl.ExtractROI(t_size=1, t_min=1), name = "extractb0") bet = pe.Node(fsl.BET(frac=0.1, mask=True), name="bet_func") bet2 = pe.Node(fsl.BET(frac=0.1), name="bet_struc") segment = pe.Node(fsl.FAST(out_basename='fast_'), name="fastSeg") flirting = pe.Node(fsl.FLIRT(cost_func='normmi', dof=7, searchr_x=[-180, 180], searchr_y=[-180, 180], searchr_z=[-180,180]), name="struc_2_func") applyxfm = pe.MapNode(fsl.ApplyXfm(apply_xfm = True), name="MaskEPI", iterfield=['in_file']) erosion = pe.MapNode(fsl.ErodeImage(), name="erode_masks", iterfield=['in_file']) regcheckoverlay = pe.Node(fsl.Overlay(auto_thresh_bg=True, stat_thresh=(100,500)), name='OverlayCoreg') regcheck = pe.Node(fsl.Slicer(), name='CheckCoreg') #filterfeeder = pe.MapNode(fsl.ImageMeants(eig=True, )) datasink = pe.Node(nio.DataSink(), name='datasink') datasink.inputs.base_directory = "/Users/Katie/Dropbox/Data/habenula/derivatives/hb_test" # Connect alllllll the nodes!! hb_test_wf.connect(subj_iterable, 'subject_id', DataGrabber, 'subject_id')
def func_preproc_fsl(wf_name='func_preproc'): featpreproc = pe.Workflow(name=wf_name) """ Set up a node to define all inputs required for the preprocessing workflow """ inputnode = pe.Node(interface=util.IdentityInterface( fields=['in_file', 'anat_brain'], mandatory_inputs=True), name='inputspec') # preprocessed_func: upscaled, brain-extracted and motion corrected functional data outputnode = pe.Node(interface=util.IdentityInterface( fields=[ 'preprocessed_func', 'example_func', 'func_brain_mask', 'motion_plots', 'func2anat_mat' ], mandatory_inputs=True), name='outputspec') """ Reorient data to match Paxinos """ reorient = pe.MapNode(interface=fsl.utils.SwapDimensions(new_dims=("RL", "AP", "IS")), name='reorient', iterfield=['in_file']) featpreproc.connect(inputnode, 'in_file', reorient, 'in_file') """ Upscale data to human range """ upscaler = mine.upscale() featpreproc.connect(reorient, 'out_file', upscaler, 'inputspec.in_file') """ Convert functional images to float representation. Since there can be more than one functional run we use a MapNode to convert each run. """ img2float = pe.MapNode(interface=fsl.ImageMaths(out_data_type='float', op_string='', suffix='_dtype'), iterfield=['in_file'], name='img2float') featpreproc.connect(upscaler, 'outputspec.out_file', img2float, 'in_file') """ Extract the first volume of the first run as the reference """ extract_ref = pe.MapNode(interface=fsl.ExtractROI(t_size=1), iterfield=['in_file', 't_min'], name='extractref') featpreproc.connect(img2float, 'out_file', extract_ref, 'in_file') featpreproc.connect(img2float, ('out_file', pickmiddle), extract_ref, 't_min') featpreproc.connect(extract_ref, 'roi_file', outputnode, 'example_func') """ Realign the functional runs to the reference (1st volume of first run) """ motion_correct = pe.MapNode(interface=fsl.MCFLIRT(save_mats=True, save_plots=True), name='motioncorr', iterfield=['in_file', 'ref_file']) featpreproc.connect(img2float, 'out_file', motion_correct, 'in_file') featpreproc.connect(extract_ref, 'roi_file', motion_correct, 'ref_file') featpreproc.connect(motion_correct, 'par_file', outputnode, 'motion_parameters') featpreproc.connect(motion_correct, 'out_file', outputnode, 'realigned_files') """ Plot the estimated motion parameters """ plot_motion = pe.MapNode(interface=fsl.PlotMotionParams(in_source='fsl'), name='plot_motion', iterfield=['in_file']) plot_motion.iterables = ('plot_type', ['displacement', 'rotations', 'translations']) featpreproc.connect(motion_correct, 'par_file', plot_motion, 'in_file') featpreproc.connect(plot_motion, 'out_file', outputnode, 'motion_plots') """ Extract the mean volume of the first functional run """ meanfunc = pe.MapNode(interface=fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), iterfield=['in_file'], name='meanfunc') featpreproc.connect(motion_correct, 'out_file', meanfunc, 'in_file') """ estimate func2anat matrix """ f2a = pe.MapNode(util.Function(input_names=['in_file', 'like'], output_names=['out_mat'], function=myfsl.utils.run_resample), name='func2anat', iterfield=['in_file', 'like']) featpreproc.connect(meanfunc, 'out_file', f2a, 'in_file') featpreproc.connect(inputnode, 'anat_brain', f2a, 'like') featpreproc.connect(f2a, 'out_mat', outputnode, 'func2anat_mat') """ Invert func2anat matrix """ invertmat = pe.MapNode(interface=fsl.ConvertXFM(invert_xfm=True), iterfield=['in_file'], name='invertmat') featpreproc.connect(f2a, 'out_mat', invertmat, 'in_file') """ Resample the anatomical brain mask to the space of functional image """ resamplemask = pe.MapNode( interface=fsl.ApplyXfm(interp='nearestneighbour'), iterfield=['reference', 'in_file', 'in_matrix_file'], name='resamplemask') featpreproc.connect(inputnode, 'anat_brain', resamplemask, 'in_file') featpreproc.connect(meanfunc, 'out_file', resamplemask, 'reference') featpreproc.connect(invertmat, 'out_file', resamplemask, 'in_matrix_file') """ Mask the functional runs with the resampled mask """ maskfunc = pe.MapNode(interface=fsl.ImageMaths(suffix='_bet', op_string='-mas'), iterfield=['in_file', 'in_file2'], name='maskfunc') featpreproc.connect(motion_correct, 'out_file', maskfunc, 'in_file') featpreproc.connect(resamplemask, 'out_file', maskfunc, 'in_file2') """ Determine the 2nd and 98th percentile intensities of each functional run """ getthresh = pe.MapNode(interface=fsl.ImageStats(op_string='-p 2 -p 98'), iterfield=['in_file'], name='getthreshold') featpreproc.connect(maskfunc, 'out_file', getthresh, 'in_file') """ Threshold the first run of the functional data at 10% of the 98th percentile """ threshold = pe.MapNode(interface=fsl.ImageMaths(out_data_type='char', suffix='_thresh'), iterfield=['in_file', 'op_string'], name='threshold') featpreproc.connect(maskfunc, 'out_file', threshold, 'in_file') """ Define a function to get 10% of the intensity """ featpreproc.connect(getthresh, ('out_stat', getthreshop), threshold, 'op_string') featpreproc.connect(threshold, 'out_file', outputnode, 'func_brain_mask') #""" #Determine the median value of the functional runs using the mask #""" #medianval = pe.MapNode(interface=fsl.ImageStats(op_string='-k %s -p 50'), # iterfield=['in_file', 'mask_file'], # name='medianval') #featpreproc.connect(motion_correct, 'out_file', medianval, 'in_file') #featpreproc.connect(threshold, 'out_file', medianval, 'mask_file') #""" #Dilate the mask #""" #dilatemask = pe.MapNode(interface=fsl.ImageMaths(suffix='_dil', # op_string='-dilF'), # iterfield=['in_file'], # name='dilatemask') #featpreproc.connect(threshold, 'out_file', dilatemask, 'in_file') """ Mask the motion corrected functional runs with the dilated mask """ maskfunc2 = pe.MapNode(interface=fsl.ImageMaths(suffix='_mask', op_string='-mas'), iterfield=['in_file', 'in_file2'], name='maskfunc2') featpreproc.connect(motion_correct, 'out_file', maskfunc2, 'in_file') featpreproc.connect(threshold, 'out_file', maskfunc2, 'in_file2') #featpreproc.connect(dilatemask, 'out_file', maskfunc2, 'in_file2') featpreproc.connect(maskfunc2, 'out_file', outputnode, 'preprocessed_func') return featpreproc
def t1_b0_registration( participant_id, session_id, caps_directory, working_directory=None, name="t1_b0_registration"): """ Perform rigid registration of the T1-weighted image onto the B0 image. Given a subject, this pipelines performs a registration between its T1-weighted image onto its 1mm upsampled B0 image. Once done, the estimated transformation matrix is used to align the binary mask of the segmentation of the white matter (obtained with FSL fast) from the anatomical space to the diffusion space. The same operation is performed on the Desikan and Destrieux parcellation (obtained with FreeSurfer recon-all) except that these latter are not resliced on the B0 image. These steps enable to prepare the data for the DWI processing pipelines. Args: participant_id (str): Subject (participant) ID in a BIDS format ('sub-<participant_label>'). session_id (str): Session ID in a BIDS format ('ses-<session_label>'). caps_directory (str): Directory where the results are stored in a CAPS hierarchy. working_directory (Optional[str]): Directory where the temporary results are stored. If not specified, it is automatically generated (generally in /tmp/). name (Optional[str]): Name of the pipelines. Inputnode: in_bias_corrected_bet_t1 (str): File containing the bias corrected brain extracted T1-weighted image. It corresponds to the out_brain_extracted file from FSL-T1 pipelines. in_preprocessed_dwi (str): File containing the preprocessed DWI dataset. It assumes that the reference b0 is the first volume in the dataset (which is the case if you are using Clinica). in_b0_mask (str): File containing the mask of the b0 image. It assumes that `in_b0_mask` has the same header as `in_preprocessed_dwi` (which is the case if you are using Clinica). in_white_matter_binary_mask (str): File containing the binary segmentation of the white matter (obtained with FSL fast). You can use the one generated by FreeSurfer recon-all but you must convert your image in FreeSurfer space to Native space first. in_desikan_parcellation (str): File containing the Desikan parcellation (obtained with FreeSurfer recon-all). The file is usually located in ${participant_id}/mri/aparc+aseg.mgz. in_destrieux_parcellation (str): File containing the Destrieux parcellation (obtained with FreeSurfer recon-all). The file is usually located in ${participant_id}/mri/aparc.a2009s+aseg.mgz. Outputnode: out_registered_t1 (str): File containing the registration of the T1-weighted image onto the diffusion space. out_flirt_matrix (str): File containing the transformation matrix estimated by FSL flirt. out_wm_mask_in_diffusion_space (str): File containing the segmentation of the white matter in diffusion space. out_mrtrix_matrix (str): File containing the transformation matrix in MRtrix format (can be used with the mrtransform command). out_desikan_in_diffusion_space (str): File containing the Desikan parcellation in diffusion space. out_destrieux_in_diffusion_space (str): File containing the Desikan parcellation in diffusion space. Example: >>> from clinica.pipelines.dwi.dwi_registration import t1_b0_registration_pipeline >>> t1_b0_registration = t1_b0_registration_pipeline(participant_id='sub-CLNC01', session_id='ses-M00', caps_directory='/path/to/output/results') >>> t1_b0_registration.inputs.inputnode.in_bias_corrected_bet_t1 = 'sub-CLNC01_ses-M00_bias_corrected_brain_extracted_t1.nii' >>> t1_b0_registration.inputs.inputnode.in_preprocessed_dwi = 'sub-CLNC01_ses-M00_preprocessed_dwi.nii' >>> t1_b0_registration.inputs.inputnode.in_b0_mask = 'sub-CLNC01_ses-M00_b0_mask.nii' >>> t1_b0_registration.inputs.inputnode.in_white_matter_binary_mask = 'sub-CLNC01_ses-M00_id_wm_mask.nii' >>> t1_b0_registration.inputs.inputnode.in_desikan_parcellation = 'sub-CLNC01_ses-M00/mri/aparc+aseg.mgz' >>> t1_b0_registration.inputs.inputnode.in_destrieux_parcellation = 'sub-CLNC01_ses-M00/mri/aparc.a2009s+aseg.mgz' >>> t1_b0_registration.run() """ from os.path import join import nipype.interfaces.fsl as fsl import nipype.interfaces.io as nio import nipype.interfaces.utility as niu import nipype.pipeline.engine as pe from nipype.interfaces.freesurfer.preprocess import MRIConvert from clinica.utils.freesurfer import freesurfer_volume_to_native_volume from clinica.utils.mri_registration import convert_flirt_transformation_to_mrtrix_transformation from clinica.utils.mri_registration import apply_mrtrix_transform_without_resampling import tempfile from clinica.utils.check_dependency import check_freesurfer, check_fsl, check_mrtrix if working_directory is None: working_directory = tempfile.mkdtemp() check_freesurfer() check_fsl() check_mrtrix() caps_identifier = participant_id + '_' + session_id inputnode = pe.Node(niu.IdentityInterface( fields=['in_bias_corrected_bet_t1', 'in_preprocessed_dwi', 'in_b0_mask', 'in_white_matter_binary_mask', 'in_desikan_parcellation', 'in_destrieux_parcellation']), name='inputnode') get_b0 = pe.Node(fsl.ExtractROI(args='0 1'), name='get_b0') upsample_b0 = pe.Node( MRIConvert(vox_size=(1, 1, 1), out_type='niigz'), name='upsample_b0') upsample_b0_mask = pe.Node( MRIConvert(vox_size=(1, 1, 1), out_type='niigz'), name='upsample_b0_mask') registration_t1_to_b0 = pe.Node(fsl.FLIRT( dof=6, interp='spline', cost='normmi', cost_func='normmi', out_matrix_file=caps_identifier + '_t1-to-b0_withResampling.mat'), name='registration_t1_to_b0') apply_flirt_registration = pe.Node( fsl.ApplyXfm(apply_xfm=True, interp='spline'), name='apply_flirt_registration') apply_flirt_registration.inputs.out_file = \ caps_identifier + '_binarymask-whitematter_reslicedOnDiffusionSpace.nii.gz' convert_flirt_to_mrtrix = pe.Node(interface=niu.Function( input_names=['in_source_image', 'in_reference_image', 'in_flirt_matrix', 'name_output_matrix'], output_names=['out_mrtrix_matrix'], function=convert_flirt_transformation_to_mrtrix_transformation), name='convert_flirt_to_mrtrix') convert_flirt_to_mrtrix.inputs.name_output_matrix = \ caps_identifier + '_t1-to-b0_withoutResampling.mat' desikan_in_native_space = pe.Node(interface=niu.Function( input_names=['freesurfer_volume', 'native_volume', 'name_output_volume'], output_names=['out_volume'], function=freesurfer_volume_to_native_volume), name='desikan_in_native_space') destrieux_in_native_space = pe.Node(interface=niu.Function( input_names=['freesurfer_volume', 'native_volume', 'name_output_volume'], output_names=['out_volume'], function=freesurfer_volume_to_native_volume), name='destrieux_in_native_space') desikan_in_diffusion_space = pe.Node(interface=niu.Function( input_names=['in_image', 'in_mrtrix_matrix', 'name_output_image'], output_names=['out_deformed_image'], function=apply_mrtrix_transform_without_resampling), name='desikan_in_diffusion_space') desikan_in_diffusion_space.inputs.name_output_image = \ caps_identifier + '_parcellation-desikan_onDiffusionSpace.nii.gz' destrieux_in_diffusion_space = pe.Node(interface=niu.Function( input_names=['in_image', 'in_mrtrix_matrix', 'name_output_image'], output_names=['out_deformed_image'], function=apply_mrtrix_transform_without_resampling), name='destrieux_in_diffusion_space') destrieux_in_diffusion_space.inputs.name_output_image = \ caps_identifier + '_parcellation-destrieux_onDiffusionSpace.nii.gz' outputnode = pe.Node(niu.IdentityInterface( fields=['out_registered_t1', 'out_flirt_matrix', 'out_wm_mask_in_diffusion_space', 'out_mrtrix_matrix', 'out_desikan_in_diffusion_space', 'out_destrieux_in_diffusion_space']), name='outputnode') datasink = pe.Node(nio.DataSink(), name='datasink') datasink.inputs.base_directory = join(caps_directory, 'subjects', participant_id, session_id) # datasink.inputs.substitutions = [('fast_pve_0.nii.gz', caps_identifier + '_binary-csf.nii.gz')] wf = pe.Workflow(name=name) wf.base_dir = working_directory wf.connect([ # Get b0 from DWI: (inputnode, get_b0, [('in_preprocessed_dwi', 'in_file')]), # Upsample at 1mm the b0 image: (get_b0, upsample_b0, [('roi_file', 'in_file')]), # Upsample at 1mm the b0 mask: (inputnode, upsample_b0_mask, [('in_b0_mask', 'in_file')]), # Register the T1 image onto the b0: (inputnode, registration_t1_to_b0, [('in_bias_corrected_bet_t1', 'in_file')]), (upsample_b0, registration_t1_to_b0, [('out_file', 'reference')]), (upsample_b0_mask, registration_t1_to_b0, [('out_file', 'ref_weight')]), # Apply flirt registration to WM mask: (inputnode, apply_flirt_registration, [('in_white_matter_binary_mask', 'in_file')]), (upsample_b0, apply_flirt_registration, [('out_file', 'reference')]), (registration_t1_to_b0, apply_flirt_registration, [('out_matrix_file', 'in_matrix_file')]), # Convert flirt matrix to MRtrix matrix: (inputnode, convert_flirt_to_mrtrix, [('in_bias_corrected_bet_t1', 'in_source_image')]), (upsample_b0, convert_flirt_to_mrtrix, [('out_file', 'in_reference_image')]), (registration_t1_to_b0, convert_flirt_to_mrtrix, [('out_matrix_file', 'in_flirt_matrix')]), # Convert FreeSurfer parcellations into native space: (inputnode, desikan_in_native_space, [('in_desikan_parcellation', 'freesurfer_volume'), ('in_bias_corrected_bet_t1', 'native_volume')]), (inputnode, destrieux_in_native_space, [('in_destrieux_parcellation', 'freesurfer_volume'), ('in_bias_corrected_bet_t1', 'native_volume')]), # Apply registration without resampling on Desikan & Destrieux parcellations: (desikan_in_native_space, desikan_in_diffusion_space, [('out_volume', 'in_image')]), # noqa (convert_flirt_to_mrtrix, desikan_in_diffusion_space, [('out_mrtrix_matrix', 'in_mrtrix_matrix')]), # noqa (destrieux_in_native_space, destrieux_in_diffusion_space, [('out_volume', 'in_image')]), # noqa (convert_flirt_to_mrtrix, destrieux_in_diffusion_space, [('out_mrtrix_matrix', 'in_mrtrix_matrix')]), # noqa # Outputnode: (registration_t1_to_b0, outputnode, [('out_file', 'out_registered_t1')]), # noqa (registration_t1_to_b0, outputnode, [('out_matrix_file', 'out_flirt_matrix')]), # noqa (apply_flirt_registration, outputnode, [('out_file', 'out_wm_mask_in_diffusion_space')]), # noqa (convert_flirt_to_mrtrix, outputnode, [('out_mrtrix_matrix', 'out_mrtrix_matrix')]), # noqa (desikan_in_diffusion_space, outputnode, [('out_deformed_image', 'out_desikan_in_diffusion_space')]), # noqa (destrieux_in_diffusion_space, outputnode, [('out_deformed_image', 'out_destrieux_in_diffusion_space')]), # noqa # Datasink: (registration_t1_to_b0, datasink, [('out_file', 'dwi.@out_registered_t1')]), # noqa (registration_t1_to_b0, datasink, [('out_matrix_file', 'dwi.@out_flirt_matrix')]), # noqa (apply_flirt_registration, datasink, [('out_file', 'dwi.@out_wm_mask_in_diffusion_mask')]), # noqa (convert_flirt_to_mrtrix, datasink, [('out_mrtrix_matrix', 'dwi.@out_mrtrix_matrix')]), # noqa (desikan_in_diffusion_space, datasink, [('out_deformed_image', 'dwi.@out_desikan_in_diffusion_space')]), # noqa (destrieux_in_diffusion_space, datasink, [('out_deformed_image', 'dwi.@out_destrieux_in_diffusion_space')]) # noqa ]) return wf
def main(): freesurferLoc = '/Volumes/CCNC_3T_2/kcho/temple/freesurfer' dtiLoc = '/Volumes/CCNC_3T_2/kcho/temple/preprocessed/preprocessedData/' subjectDirs = [x for x in os.listdir(freesurferLoc) if x.endswith('pre') or \ x.endswith('post')] outputFaLoc = os.path.join(freesurferLoc, 'result.csv') roiDict = { 'CC_Posterior': 251, 'CC_Mid_Posterior': 252, 'CC_Central': 253, 'CC_Mid_Anterior': 254, 'CC_Anterior': 255 } subjectDict = {} for subject in subjectDirs: try: #missing data skip print subject subjectLoc = os.path.join(freesurferLoc, subject) nodifBrain = os.path.join(dtiLoc, subject, 'hifi_nodif_brain.nii.gz') fsBrainLoc = os.path.join(subjectLoc, 'mri', 'brain.mgz') fsBrainLocNii = fsBrainLoc[:-4] + '.nii.gz' asegLoc = os.path.join(subjectLoc, 'mri', 'aseg.mgz') fs2dtiMat = os.path.join(subjectLoc, 'fs2dti.mat') convert = fs.MRIConvert(in_file=fsBrainLoc, out_type='niigz', out_file=fsBrainLocNii) if not os.path.isfile(fsBrainLocNii): convert.run() flirt = fsl.FLIRT(in_file=fsBrainLocNii, reference=nodifBrain, interp='nearestneighbour', out_matrix_file=fs2dtiMat) if not os.path.isfile(fs2dtiMat): flirt.run() faDict = {} for roi, roiNum in roiDict.iteritems(): roiLoc = os.path.join(subjectLoc, roi + '.nii.gz') roiLocReg = os.path.join(subjectLoc, roi + '_reg.nii.gz') fa_mean = os.path.join(subjectLoc, roi + '_FA.txt') binarize = fs.Binarize(in_file=asegLoc, match=[roiNum], binary_file=roiLoc) if not os.path.isfile(roiLoc): binarize.run() applyReg = fsl.ApplyXfm(in_file=roiLoc, reference=nodifBrain, in_matrix_file=fs2dtiMat, interp='nearestneighbour', out_file=roiLocReg) if not os.path.isfile(roiLocReg): applyReg.run() #else: #applyReg.run() faFile = os.path.join(dtiLoc, subject, 'dti_FA.nii.gz') faStamp = fsl.ImageStats( op_string='-k {mask} -M'.format(mask=roiLocReg), #mask_file = roiLocReg, in_file=faFile, ) print faStamp.cmdline stats = faStamp.run() meanFA = stats.outputs.out_stat faDict[roi] = meanFA subjectDict[subject] = faDict except: pass df = pd.DataFrame(subjectDict) if not os.path.isfile(outputFaLoc): df.to_csv(outputFaLoc) # output wrangling #df = pd.read_csv(outputFaLoc, index_col = 0) df = df.T df['group'] = df.index.str[:3] df['timeline'] = df.index.str.split('_').str[1] print df.groupby(('group', 'timeline')).describe()
def calc_RSFA(subject, working_dir, data_dir, result_dir, TR_ms, low_hp_cutoff_freq, low_lp_cutoff_freq, high_hp_cutoff_freq, high_lp_cutoff_freq): fsl.FSLCommand.set_default_output_type('NIFTI_GZ') # working_dir = '/scr/kennedy2/lampe/RSFA_ALFF/data/'+subject+'/' #os.makedirs(working_dir) # result_dir = '/scr/kennedy2/lampe/RSFA_ALFF/results/' +subject + '/' # data_dir = '/data/liem-1/LIFE/preprocessed/'+subject+ '/' #os.makedirs(data_dir) ##change this depending on new and old freesurfer## #freesurfer_dir = '/scr/kennedy2/LIFE/freesurfer/subjects/' # #' # ## #resting_dir = '/scr/kennedy2/lampe/RSFA_ALFF/results/'+subject+'/test/' #standard_brain = '/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain.nii.gz' #standard_brain_resampled = '/scr/kennedy2/lampe/RSFA_ALFF/scripts/MNI_resampled.nii' #standard_brain_mask = '/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain_mask.nii.gz' #standard_brain_mask_resampled='/scr/kennedy2/lampe/RSFA_ALFF/scripts/MNI_resampled_brain_mask.nii' mask_dir = '/scr/kennedy2/lampe/Alle_zusammengefasst/' TOADS_lesion_def = '_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg_def.nii.gz' TOADS_lesion = '_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg.nii.gz' TOADS_full_segmentation = '_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_seg.nii.gz' templates = { #'func': 'func/EPI_t2.nii', #'fmap_fullwarp' : 'unwarp/B0_ph.nii', #'mat_moco': '', #'transform_ts': 'lemon_resting/transform_timeseries/merge/rest2anat.nii.gz' 'MNI_lesionmask': mask_dir + 'deformed_lesions/' + subject + TOADS_lesion_def, 'ind_lesionmask': mask_dir + 'lesions/' + subject + TOADS_lesion, 'ind_TOADS_segmentation': mask_dir + 'lesions/' + subject + TOADS_full_segmentation, 'ind_flair_TOADS': mask_dir + 'flair_input/' + subject + '_spc_da-fl_irprep_sag_p2_iso_395_clone_transform_clone_reg_calc_N3Corrected_calc_filter.nii.gz', 'ind_t1_TOADS': mask_dir + 't1_input/' + subject + '*.nii.gz', 'anat_head': 'structural/T1.nii.gz', #either with mod or without 'anat_brain': 'structural/brain.nii.gz', #new version with brain_extraction from freesurfer #T1_brain_brain.nii.gz', 'brain_mask': 'structural/T1_brain_mask.nii.gz', #T1_brain_brain_mask.nii.gz', 'ants_affine': 'structural/transforms2mni/transform0GenericAffine.mat', 'ants_warp': 'structural/transforms2mni/transform1Warp.nii.gz', 'transform_ts': 'resting_state/coregister/rest_coregistered_nativespace.nii.gz' #nur coregistered, #McFlirted (motion corrected, alle volumes aligned), #3x3x3 downgesampelt, 5 volumes removed, kein slice time correction #kein denoising gemacht } RSFA = pe.Workflow(name='RSFA') RSFA.base_dir = working_dir RSFA.config['execution']['crashdump_dir'] = RSFA.base_dir + "/crash_files" selectfiles = pe.Node( nio.SelectFiles( templates, base_directory=data_dir ), # data_dir = '/data/liem-1/LIFE/preprocessed/' +subject + '/' set in Metascript runRSFA name="Selectfiles") # TR_ms = 2000 # PARAMETERS CUT OFF low RSFA #low_hp_cutoff_freq = 0.01 #low_lp_cutoff_freq = 0.1 # PARAMETERS CUT OFF high RSFA #high_hp_cutoff_freq = 0.1 #high_lp_cutoff_freq = 0.25 # inputnode = pe.Node(interface=util.IdentityInterface(fields=['subject_id', # 'TR_ms', # 'low_lp_cutoff_freq', # 'low_hp_cutoff_freq', # 'high_lp_cutoff_freq', # 'high_hp_cutoff_freq']), # name='inputnode') #this step is redundant, because Franz has already discarded the first 5 volumes #Workflow to delete first five volume #trim = pe.Node(Trim(), name ='Trim') #trim.inputs.begin_index = 5 # remove 5 first volumes #RSFA.connect(selectfiles, 'transform_ts', trim, 'in_file') # TR CONVERSION def get_TR_in_sec_fct(TR_ms): return TR_ms / 1000.0 get_TR_in_sec = pe.Node(util.Function(input_names=['TR_ms'], output_names=['TR_sec'], function=get_TR_in_sec_fct), name='get_TR_in_sec') get_TR_in_sec.inputs.TR_ms = TR_ms def calc_bp_sigma_fct(TR_sec, cutoff_freq): sigma = 1. / (2 * TR_sec * cutoff_freq) return sigma # calculate low and highpass sigmas calc_low_lp_sigma = pe.Node(util.Function( input_names=['TR_sec', 'cutoff_freq'], output_names=['sigma'], function=calc_bp_sigma_fct), name='calc_low_lp_sigma') calc_low_lp_sigma.inputs.cutoff_freq = low_lp_cutoff_freq RSFA.connect(get_TR_in_sec, 'TR_sec', calc_low_lp_sigma, 'TR_sec') calc_low_hp_sigma = pe.Node(util.Function( input_names=['TR_sec', 'cutoff_freq'], output_names=['sigma'], function=calc_bp_sigma_fct), name='calc_low_hp_sigma') calc_low_hp_sigma.inputs.cutoff_freq = low_hp_cutoff_freq RSFA.connect(get_TR_in_sec, 'TR_sec', calc_low_hp_sigma, 'TR_sec') calc_high_lp_sigma = pe.Node(util.Function( input_names=['TR_sec', 'cutoff_freq'], output_names=['sigma'], function=calc_bp_sigma_fct), name='calc_high_lp_sigma') calc_high_lp_sigma.inputs.cutoff_freq = high_lp_cutoff_freq RSFA.connect(get_TR_in_sec, 'TR_sec', calc_high_lp_sigma, 'TR_sec') calc_high_hp_sigma = pe.Node(util.Function( input_names=['TR_sec', 'cutoff_freq'], output_names=['sigma'], function=calc_bp_sigma_fct), name='calc_high_hp_sigma') calc_high_hp_sigma.inputs.cutoff_freq = high_hp_cutoff_freq RSFA.connect(get_TR_in_sec, 'TR_sec', calc_high_hp_sigma, 'TR_sec') # bp filters tempfilter_low = pe.Node(fsl.maths.TemporalFilter(), name='Low_filter') RSFA.connect(selectfiles, 'transform_ts', tempfilter_low, 'in_file') RSFA.connect(calc_low_lp_sigma, 'sigma', tempfilter_low, 'lowpass_sigma') RSFA.connect(calc_low_hp_sigma, 'sigma', tempfilter_low, 'highpass_sigma') tempfilter_high = pe.Node(fsl.maths.TemporalFilter(), 'High_filter') RSFA.connect(selectfiles, 'transform_ts', tempfilter_high, 'in_file') RSFA.connect(calc_high_lp_sigma, 'sigma', tempfilter_high, 'lowpass_sigma') RSFA.connect(calc_high_hp_sigma, 'sigma', tempfilter_high, 'highpass_sigma') stdev_low = pe.Node(fsl.maths.StdImage(), name='Low_std') RSFA.connect(tempfilter_low, 'out_file', stdev_low, 'in_file') stdev_high = pe.Node(fsl.maths.StdImage(), name='High_std') RSFA.connect(tempfilter_high, 'out_file', stdev_high, 'in_file') # register RSFA to t1 flirt_low = pe.Node(interface=fsl.FLIRT(), name='Flirt_low') flirt_low.inputs.cost_func = 'mutualinfo' flirt_low.inputs.dof = 6 flirt_low.inputs.out_matrix_file = "trans_matrix.mat" #flirt_low.inputs.reference = t1_resampled RSFA.connect(stdev_low, 'out_file', flirt_low, 'in_file') RSFA.connect(selectfiles, 'ind_t1_TOADS', flirt_low, 'reference') flirt_high = pe.Node(interface=fsl.FLIRT(), name='Flirt_high') flirt_high.inputs.cost_func = 'mutualinfo' flirt_high.inputs.dof = 6 flirt_high.inputs.out_matrix_file = "trans_matrix.mat" #flirt_high.inputs.reference = t1_resampled RSFA.connect(stdev_high, 'out_file', flirt_high, 'in_file') RSFA.connect(selectfiles, 'ind_t1_TOADS', flirt_high, 'reference') applyxfm_low = pe.Node(interface=fsl.ApplyXfm(), name='Transfer_low') applyxfm_low.inputs.interp = 'nearestneighbour' applyxfm_low.inputs.apply_xfm = True applyxfm_low.inputs.terminal_output = 'file' #applyxfm_low.inputs.reference = temp_t1 RSFA.connect(stdev_low, 'out_file', applyxfm_low, 'in_file') RSFA.connect(flirt_low, 'out_matrix_file', applyxfm_low, 'in_matrix_file') RSFA.connect(selectfiles, 'ind_t1_TOADS', applyxfm_low, 'reference') applyxfm_high = pe.Node(interface=fsl.ApplyXfm(), name='Transfer_high') applyxfm_high.inputs.interp = 'nearestneighbour' applyxfm_high.inputs.apply_xfm = True applyxfm_high.inputs.terminal_output = 'file' #applyxfm_high.inputs.reference = temp_t1 RSFA.connect(stdev_high, 'out_file', applyxfm_high, 'in_file') RSFA.connect(flirt_high, 'out_matrix_file', applyxfm_high, 'in_matrix_file') RSFA.connect(selectfiles, 'ind_t1_TOADS', applyxfm_high, 'reference') # gray matter gm_mask = pe.Node(fsl.ImageMaths(op_string='-thr 14.5 -uthr 15.5 -bin'), name='GM_mask') RSFA.connect(selectfiles, 'ind_TOADS_segmentation', gm_mask, 'in_file') gm_low = pe.Node(fsl.maths.ApplyMask(), name='GM_low') RSFA.connect(applyxfm_low, 'out_file', gm_low, 'in_file') RSFA.connect(gm_mask, 'out_file', gm_low, 'mask_file') gm_high = pe.Node(fsl.maths.ApplyMask(), name='GM_high') RSFA.connect(applyxfm_high, 'out_file', gm_high, 'in_file') RSFA.connect(gm_mask, 'out_file', gm_high, 'mask_file') gm_low_mean = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='GM_low_mean') RSFA.connect(gm_low, 'out_file', gm_low_mean, 'in_file') gm_high_mean = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='GM_high_mean') RSFA.connect(gm_high, 'out_file', gm_high_mean, 'in_file') #white matter wm_mask = pe.Node(fsl.ImageMaths(op_string='-thr 24.5 -uthr 25.5 -bin'), name='WM_mask') RSFA.connect(selectfiles, 'ind_TOADS_segmentation', wm_mask, 'in_file') wm_low = pe.Node(fsl.maths.ApplyMask(), name='WM_low') RSFA.connect(applyxfm_low, 'out_file', wm_low, 'in_file') RSFA.connect(wm_mask, 'out_file', wm_low, 'mask_file') wm_high = pe.Node(fsl.maths.ApplyMask(), name='WM_high') RSFA.connect(applyxfm_high, 'out_file', wm_high, 'in_file') RSFA.connect(wm_mask, 'out_file', wm_high, 'mask_file') wm_low_mean = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='WM_low_mean') RSFA.connect(wm_low, 'out_file', wm_low_mean, 'in_file') wm_high_mean = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='WM_high_mean') RSFA.connect(wm_high, 'out_file', wm_high_mean, 'in_file') #WMH wmh_low = pe.Node(fsl.maths.ApplyMask(), name='WMH_low') RSFA.connect(applyxfm_low, 'out_file', wmh_low, 'in_file') RSFA.connect(selectfiles, 'ind_lesionmask', wmh_low, 'mask_file') wmh_high = pe.Node(fsl.maths.ApplyMask(), name='WMH_high') RSFA.connect(applyxfm_high, 'out_file', wmh_high, 'in_file') RSFA.connect(selectfiles, 'ind_lesionmask', wmh_high, 'mask_file') wmh_low_mean = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='WMH_low_mean') RSFA.connect(wmh_low, 'out_file', wmh_low_mean, 'in_file') wmh_high_mean = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='WMH_high_mean') RSFA.connect(wmh_high, 'out_file', wmh_high_mean, 'in_file') def store2file(SIC, RSFA_l_wm, RSFA_h_wm, RSFA_l_gm, RSFA_h_gm, RSFA_l_wmh, RSFA_h_wmh): import pandas as pd import csv d = { '0subject': [SIC], '1RSFA_l_wm': [RSFA_l_wm], '2RSFA_h_wm': [RSFA_h_wm], '3RSFA_l_gm': [RSFA_l_gm], '4RSFA_h_gm': [RSFA_h_gm], '5RSFA_l_wmh': [RSFA_l_wmh], '6RSFA_h_wmh': [RSFA_h_wmh] } df = pd.DataFrame(d) with open( '/scr/kennedy2/lampe/RSFA_ALFF/results/txt_files/RSFA_results.csv', 'a') as f: df.to_csv(f, header=False) value_safe = pe.Node(name='RSFA_value_file', interface=Function(input_names=[ 'SIC', 'RSFA_l_wm', 'RSFA_h_wm', 'RSFA_l_gm', 'RSFA_h_gm', 'RSFA_l_wmh', 'RSFA_h_wmh' ], output_names=["out_file"], function=store2file)) value_safe.inputs.SIC = subject RSFA.connect(wm_low_mean, 'out_stat', value_safe, 'RSFA_l_wm') RSFA.connect(wm_high_mean, 'out_stat', value_safe, 'RSFA_h_wm') RSFA.connect(gm_low_mean, 'out_stat', value_safe, 'RSFA_l_gm') RSFA.connect(gm_high_mean, 'out_stat', value_safe, 'RSFA_h_gm') RSFA.connect(wmh_low_mean, 'out_stat', value_safe, 'RSFA_l_wmh') RSFA.connect(wmh_high_mean, 'out_stat', value_safe, 'RSFA_h_wmh') datasink = pe.Node(nio.DataSink(), name='sinker') datasink.inputs.base_directory = result_dir #datasink.remove_dest_dir = True #RSFA.connect(addrow, 'csv_file', datasink, 'container.txt_file') RSFA.connect(gm_low, 'out_file', datasink, 'container.low_freq_GM_mask') RSFA.connect(wmh_low, 'out_file', datasink, 'container.low_freq_lesion_mask') RSFA.connect(wm_low, 'out_file', datasink, 'container.low_freq_WM_mask') RSFA.connect(applyxfm_low, 'out_file', datasink, 'container.low_freq_RSFA') RSFA.connect(gm_high, 'out_file', datasink, 'container.high_freq_GM_mask') RSFA.connect(wmh_high, 'out_file', datasink, 'container.high_freq_lesion_mask') RSFA.connect(wm_high, 'out_file', datasink, 'container.high_freq_WM_mask') RSFA.connect(applyxfm_high, 'out_file', datasink, 'container.high_freq_RSFA') RSFA.run(plugin='CondorDAGMan') #plugin = "CondorDAGMan" 'linear'
def epi_correction(name='epi_correction'): inputnode = pe.Node( utility.IdentityInterface( fields=['fieldmap','fieldmap_mag','fieldmap_mask', 'epi_file','epi_reference','epi_mask', 'echo_time','echo_spacing','unwarp_direction']), name='inputspec') outputnode = pe.Node( utility.IdentityInterface( fields=['unwarped_epi','voxel_shift_map', 'fieldmap2epi','epi2fieldmap', 'fieldmap','epi_sigloss']), name='outputspec') #compute deformation/signal_loss in fieldmap space to warp magnitude for registration #this has to use the epi parameters? n_signal_loss = pe.Node( fsl.SigLoss(), name='signal_loss') n_fieldmap_mag_lossy = pe.Node( interface=fsl.ImageMaths(op_string='-mul', suffix='_lossy', output_type='NIFTI'), name='fieldmap_mag_lossy') n_fm_voxelshiftmap = pe.Node( fsl.FUGUE(forward_warping=True, nokspace=True,), name='fm_voxelshiftmap') #register fieldmap into EPI space n_estimate_warp = pe.Node( fsl.FLIRT(cost='normmi', cost_func='normmi', out_matrix_file='epi_to_b0fm', interp='trilinear', searchr_x=[-5,5], # restrict search as they are acquired searchr_y=[-5,5], # in the same sequence searchr_z=[-5,5], dof=6), name='estimate_warp') n_invert_warp = pe.Node( fsl.ConvertXFM(invert_xfm=True), name='invert_warp') n_warp_fieldmap = pe.Node( fsl.ApplyXfm(apply_xfm=True), name='warp_fieldmap') n_warp_sigloss = pe.Node( fsl.ApplyXfm(apply_xfm=True), name='warp_sigloss') #compute deformation in EPI space n_epi_voxelshiftmap = pe.Node( fsl.FUGUE(shift_out_file='vsm_epi.nii.gz',), name='epi_voxelshiftmap') n_unwarp_epi = pe.Node( fsl.FUGUE(), name='unwarp_epi') w=pe.Workflow(name=name) w.connect([ (inputnode,n_signal_loss, [('fieldmap','in_file'), ('fieldmap_mask','mask_file'), ('echo_time','echo_time')]), (n_signal_loss, n_fieldmap_mag_lossy, [('out_file','in_file2')]), (inputnode, n_fieldmap_mag_lossy, [('fieldmap_mag','in_file')]), (inputnode,n_fm_voxelshiftmap,[('fieldmap','fmap_in_file'), ('echo_spacing','dwell_time'), ('unwarp_direction','unwarp_direction'), ('fieldmap_mask','mask_file')]), (n_fieldmap_mag_lossy, n_fm_voxelshiftmap, [('out_file','in_file')]), (n_signal_loss, n_estimate_warp, [('out_file','ref_weight')]), (n_fm_voxelshiftmap,n_estimate_warp,[('warped_file','reference')]), (inputnode,n_estimate_warp,[('epi_reference','in_file'), ]), #('epi_mask','in_weight')]), (n_estimate_warp,n_invert_warp, [('out_matrix_file','in_file')]), (n_invert_warp,n_warp_fieldmap, [('out_file','in_matrix_file')]), (inputnode,n_warp_fieldmap, [('fieldmap','in_file')]), (inputnode,n_warp_fieldmap, [('epi_reference','reference')]), (n_invert_warp,n_warp_sigloss, [('out_file','in_matrix_file')]), (n_signal_loss,n_warp_sigloss, [('out_file','in_file')]), (inputnode,n_warp_sigloss, [('epi_reference','reference')]), (n_warp_fieldmap,n_epi_voxelshiftmap,[('out_file','fmap_in_file')]), (inputnode, n_epi_voxelshiftmap,[ ('epi_reference','in_file'), ('epi_mask','mask_file'), ('unwarp_direction','unwarp_direction'), ('echo_spacing','dwell_time')]), (n_epi_voxelshiftmap,n_unwarp_epi,[('shift_out_file','shift_in_file')]), (inputnode,n_unwarp_epi,[ ('epi_file','in_file'), ('epi_mask','mask_file')]), (n_estimate_warp,outputnode, [('out_matrix_file','epi2fieldmap')]), (n_invert_warp, outputnode, [('out_file','fieldmap2epi')]), (n_warp_sigloss,outputnode, [('out_file','epi_sigloss')]), (n_warp_fieldmap,outputnode,[('out_file','fieldmap')]), (n_unwarp_epi,outputnode,[('unwarped_file','unwarped_epi')]), (n_epi_voxelshiftmap,outputnode,[('shift_out_file','voxel_shift_map')]), ]) return w
def create_denoise_pipeline(working_dir, ds_dir, name='denoise'): # workflow denoise_wf = Workflow(name=name) denoise_wf.base_dir = os.path.join(working_dir, 'LeiCA_resting', 'rsfMRI_preprocessing') # I/O NODES inputnode = Node(interface=util.IdentityInterface(fields=[ 'subject_id', 'epi', 'mean_epi', 'par_moco', 'struct_2_epi_mat', 'MNI_2_epi_warp', 'lat_ventricle_mask_MNI', 'wm_mask', 'csf_mask', 'brain_mask_epiSpace', 'TR_ms', 'lp_cutoff_freq', 'hp_cutoff_freq' ]), name='inputnode') outputnode = Node(interface=util.IdentityInterface( fields=['outlier_files', 'rs_preprocessed']), name='outputnode') ds = Node(nio.DataSink(base_directory=ds_dir), name='ds') ds.inputs.substitutions = [('_TR_id_', 'TR_')] ######### TRANSFORM MASKS wm_mask_epiSpace = Node(fsl.ApplyXfm(apply_xfm=True, interp='nearestneighbour'), name='wm_mask_epiSpace') wm_mask_epiSpace.inputs.out_file = 'wm_mask_epiSpace.nii.gz' denoise_wf.connect([(inputnode, wm_mask_epiSpace, [('wm_mask', 'in_file'), ('mean_epi', 'reference'), ('struct_2_epi_mat', 'in_matrix_file')])]) denoise_wf.connect(wm_mask_epiSpace, 'out_file', ds, 'masks.wm_mask_epiSpace') csf_mask_epiSpace = Node(fsl.ApplyXfm(apply_xfm=True, interp='nearestneighbour'), name='csf_mask_epiSpace') denoise_wf.connect([(inputnode, csf_mask_epiSpace, [('csf_mask', 'in_file'), ('mean_epi', 'reference'), ('struct_2_epi_mat', 'in_matrix_file')])]) # MOVE LATERAL VENTRICLE MASK INTO EPI SPACE lat_ventricle_mask_epiSpace = Node(fsl.ApplyWarp(interp='nn'), name='lat_ventricle_mask_epiSpace') denoise_wf.connect(inputnode, 'lat_ventricle_mask_MNI', lat_ventricle_mask_epiSpace, 'in_file') denoise_wf.connect(inputnode, 'mean_epi', lat_ventricle_mask_epiSpace, 'ref_file') denoise_wf.connect(inputnode, 'MNI_2_epi_warp', lat_ventricle_mask_epiSpace, 'field_file') # CONFINE INDIVIDUAL CSF MASK TO LATERAL VENTRICLES csf_mask_lat_ventricles_epiSpace = Node( fsl.maths.BinaryMaths(operation='mul'), name='csf_mask_lat_ventricles_epiSpace') csf_mask_lat_ventricles_epiSpace.inputs.out_file = 'csf_mask_epiSpace.nii.gz' denoise_wf.connect(csf_mask_epiSpace, 'out_file', csf_mask_lat_ventricles_epiSpace, 'in_file') denoise_wf.connect(lat_ventricle_mask_epiSpace, 'out_file', csf_mask_lat_ventricles_epiSpace, 'operand_file') denoise_wf.connect(csf_mask_lat_ventricles_epiSpace, 'out_file', ds, 'masks.csf_mask_lat_ventr_epiSpace') # TR CONVERSION def get_TR_in_sec_fct(TR_ms): return TR_ms / 1000.0 get_TR_in_sec = Node(util.Function(input_names=['TR_ms'], output_names=['TR_sec'], function=get_TR_in_sec_fct), name='get_TR_in_sec') denoise_wf.connect(inputnode, 'TR_ms', get_TR_in_sec, 'TR_ms') # RUN ARTIFACT DETECTION artifact = Node(rapidart.ArtifactDetect(save_plot=True, use_norm=True, parameter_source='FSL', mask_type='file', norm_threshold=1, zintensity_threshold=3, use_differences=[True, False]), name='artifact') artifact.plugin_args = {'submit_specs': 'request_memory = 17000'} denoise_wf.connect(inputnode, 'epi', artifact, 'realigned_files') denoise_wf.connect([(inputnode, artifact, [('par_moco', 'realignment_parameters')])]) denoise_wf.connect(inputnode, 'brain_mask_epiSpace', artifact, 'mask_file') denoise_wf.connect([ (artifact, ds, [('norm_files', 'denoise.artefact.@combined_motion'), ('outlier_files', 'denoise.artefact.@outlier'), ('intensity_files', 'denoise.artefact.@intensity'), ('statistic_files', 'denoise.artefact.@outlierstats'), ('plot_files', 'denoise.artefact.@outlierplots')]) ]) denoise_wf.connect(artifact, 'outlier_files', outputnode, 'outlier_files') ############################ def combine_motion_parameters_with_outliers_fct(motion_params, outliers_file, spike_reg): """Adapted from rom https://github.com/nipy/nipype/blob/master/examples/ rsfmri_vol_surface_preprocessing_nipy.py#L261 """ import numpy as np import os if spike_reg: out_params = np.genfromtxt(motion_params) try: outlier_val = np.genfromtxt(outliers_file) except IOError: outlier_val = np.empty((0)) for index in np.atleast_1d(outlier_val): outlier_vector = np.zeros((out_params.shape[0], 1)) outlier_vector[index] = 1 out_params = np.hstack((out_params, outlier_vector)) out_file = os.path.join(os.getcwd(), "motion_outlier_regressor.txt" ) #"filter_regressor%02d.txt" % idx) np.savetxt(out_file, out_params, fmt="%.8f") else: out_file = motion_params return out_file ############################ # COMPUTE MOTION DERIVATIVES (FRISTON24) friston24 = Node(util.Function( input_names=['in_file'], output_names=['friston_par'], function=cpac_generate_motion_statistics.calc_friston_twenty_four), name='friston24') denoise_wf.connect(inputnode, 'par_moco', friston24, 'in_file') # CREATE OUTLIER DUMMY REGRESSOR AND COMBINE WITH FRISTON24 motion_and_outlier_regressor = Node(util.Function( input_names=['motion_params', 'outliers_file', 'spike_reg'], output_names=['out_file'], function=combine_motion_parameters_with_outliers_fct), name='motion_and_outlier_regressor') motion_and_outlier_regressor.inputs.spike_reg = True denoise_wf.connect(friston24, 'friston_par', motion_and_outlier_regressor, 'motion_params') denoise_wf.connect(artifact, 'outlier_files', motion_and_outlier_regressor, 'outliers_file') # EXTRACT SIGNAL FROM WM AND CSF FOR COMPCOR wm_sig = Node(util.Function(input_names=['data_file', 'mask_file'], output_names=['out_file'], function=extract_signal_from_tissue), name='wm_sig') denoise_wf.connect(inputnode, 'epi', wm_sig, 'data_file') denoise_wf.connect(wm_mask_epiSpace, 'out_file', wm_sig, 'mask_file') csf_sig = Node(util.Function(input_names=['data_file', 'mask_file'], output_names=['out_file'], function=extract_signal_from_tissue), name='csf_sig') denoise_wf.connect(inputnode, 'epi', csf_sig, 'data_file') denoise_wf.connect(csf_mask_lat_ventricles_epiSpace, 'out_file', csf_sig, 'mask_file') nuisance_selector = { 'compcor': True, 'wm': False, 'csf': False, 'gm': False, 'global': False, 'pc1': False, 'motion': True, 'linear': True, 'quadratic': True } nuisance_reg = Node(util.Function( input_names=[ 'subject', 'selector', 'wm_sig_file', 'csf_sig_file', 'gm_sig_file', 'motion_file', 'compcor_ncomponents' ], output_names=['residual_file', 'regressors_file'], function=cpac_nuisance.calc_residuals), name='nuisance_reg') nuisance_reg.inputs.compcor_ncomponents = 5 nuisance_reg.inputs.selector = nuisance_selector denoise_wf.connect(inputnode, 'epi', nuisance_reg, 'subject') denoise_wf.connect(wm_sig, 'out_file', nuisance_reg, 'wm_sig_file') denoise_wf.connect(csf_sig, 'out_file', nuisance_reg, 'csf_sig_file') denoise_wf.connect(motion_and_outlier_regressor, 'out_file', nuisance_reg, 'motion_file') denoise_wf.connect(nuisance_reg, 'regressors_file', ds, 'denoise.regression.regressor') denoise_wf.connect(nuisance_reg, 'residual_file', ds, 'epis.01_denoised') ############################ # BANDPASS FILTER # sigma calculation see # https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind1205&L=FSL&P=R57592&1=FSL&9=A&I=-3&J=on&d=No+Match%3BMatch%3BMatches&z=4 def calc_bp_sigma_fct(TR_sec, cutoff_freq): sigma = 1. / (2 * TR_sec * cutoff_freq) return sigma calc_lp_sigma = Node(util.Function(input_names=['TR_sec', 'cutoff_freq'], output_names=['sigma'], function=calc_bp_sigma_fct), name='calc_lp_sigma') denoise_wf.connect(get_TR_in_sec, 'TR_sec', calc_lp_sigma, 'TR_sec') denoise_wf.connect(inputnode, 'lp_cutoff_freq', calc_lp_sigma, 'cutoff_freq') calc_hp_sigma = Node(util.Function(input_names=['TR_sec', 'cutoff_freq'], output_names=['sigma'], function=calc_bp_sigma_fct), name='calc_hp_sigma') denoise_wf.connect(get_TR_in_sec, 'TR_sec', calc_hp_sigma, 'TR_sec') denoise_wf.connect(inputnode, 'hp_cutoff_freq', calc_hp_sigma, 'cutoff_freq') bp_filter = Node(fsl.TemporalFilter(), name='bp_filter') bp_filter.plugin_args = {'submit_specs': 'request_memory = 4000'} denoise_wf.connect(nuisance_reg, 'residual_file', bp_filter, 'in_file') denoise_wf.connect(calc_lp_sigma, 'sigma', bp_filter, 'lowpass_sigma') denoise_wf.connect(calc_hp_sigma, 'sigma', bp_filter, 'highpass_sigma') denoise_wf.connect(bp_filter, 'out_file', ds, 'epis.02_denoised_BP') # TIME-NORMALIZE SCAN normalize_time = Node(util.Function(input_names=['in_file', 'tr'], output_names=['out_file'], function=time_normalizer), name='normalize_time') #fixme req mem needed? #normalize_time.plugin_args = {'submit_specs': 'request_memory = 17000'} denoise_wf.connect(bp_filter, 'out_file', normalize_time, 'in_file') denoise_wf.connect(get_TR_in_sec, 'TR_sec', normalize_time, 'tr') denoise_wf.connect(normalize_time, 'out_file', outputnode, 'rs_preprocessed') denoise_wf.connect(normalize_time, 'out_file', ds, 'epis.03_denoised_BP_tNorm') denoise_wf.write_graph(dotfilename=denoise_wf.name, graph2use='flat', format='pdf') return denoise_wf
def create_denoise_pipeline(name='denoise'): # workflow denoise = Workflow(name='denoise') # Define nodes inputnode = Node(interface=util.IdentityInterface(fields=[ 'anat_brain', 'brain_mask', 'flirt_mat', 'unwarped_mean', 'epi_coreg', 'highpass_sigma', 'tr' ]), name='inputnode') outputnode = Node(interface=util.IdentityInterface(fields=[ 'wmcsf_mask', 'brain2epi', 'wmcsf_mask2epi', 'combined_motion', 'comp_regressor', 'comp_F', 'comp_pF', 'out_betas', 'ts_fullspectrum', 'normalized_file' ]), name='outputnode') # run fast to get tissue probability classes fast = Node(fsl.FAST(), name='fast') denoise.connect([(inputnode, fast, [('anat_brain', 'in_files')])]) # functions to select tissue classes def selectindex(files, idx): import numpy as np from nipype.utils.filemanip import filename_to_list, list_to_filename return list_to_filename( np.array(filename_to_list(files))[idx].tolist()) def selectsingle(files, idx): return files[idx] # binarize tissue classes binarize_tissue = MapNode( fsl.ImageMaths(op_string='-nan -thr 0.99 -ero -bin'), iterfield=['in_file'], name='binarize_tissue') denoise.connect([ (fast, binarize_tissue, [(('partial_volume_files', selectindex, [0, 2]), 'in_file')]), ]) # combine tissue classes to noise mask wmcsf_mask = Node(fsl.BinaryMaths(operation='add', out_file='wmcsf_mask.nii'), name='wmcsf_mask') denoise.connect([(binarize_tissue, wmcsf_mask, [(('out_file', selectsingle, 0), 'in_file'), (('out_file', selectsingle, 1), 'operand_file')]), (wmcsf_mask, outputnode, [('out_file', 'wmcsf_mask')])]) # project wm_csf mask from anatomical to original epi space using inverse FLIRT-matrix invmat = Node(fsl.ConvertXFM(), name='invmat') invmat.inputs.invert_xfm = True apply_inv = Node(fsl.ApplyXfm(), name='apply_inv') apply_inv.inputs.apply_xfm = True denoise.connect([(inputnode, invmat, [('flirt_mat', 'in_file')]), (invmat, apply_inv, [('out_file', 'in_matrix_file')]), (inputnode, apply_inv, [('unwarped_mean', 'reference')]), (wmcsf_mask, apply_inv, [('out_file', 'in_file')]), (apply_inv, outputnode, [('out_file', 'wmcsf_mask2epi')]) ]) #project brain to epi space as a checkup apply_inv_brain = Node(fsl.ApplyXfm(), name='apply_inv_brain') apply_inv_brain.inputs.apply_xfm = True denoise.connect([ (invmat, apply_inv_brain, [('out_file', 'in_matrix_file')]), (inputnode, apply_inv_brain, [('unwarped_mean', 'reference')]), (inputnode, apply_inv_brain, [('anat_brain', 'in_file')]), (apply_inv_brain, outputnode, [('out_file', 'brain2epi')]) ]) #no artifact detection and motion regression done because of AROMA # create filter with compcor components createfilter2 = Node(util.Function(input_names=[ 'realigned_file', 'mask_file', 'num_components', 'extra_regressors' ], output_names=['out_files'], function=extract_noise_components), name='makecompcorfilter') createfilter2.inputs.num_components = 6 createfilter2.inputs.extra_regressors = None createfilter2.plugin_args = {'submit_specs': 'request_memory = 17000'} denoise.connect([ (inputnode, createfilter2, [('epi_coreg', 'realigned_file')]), (apply_inv, createfilter2, [('out_file', 'mask_file')]), (createfilter2, outputnode, [('out_files', 'comp_regressor')]), ]) # regress compcor and other noise components filter2 = Node(fsl.GLM(out_f_name='F_noise.nii.gz', out_pf_name='pF_noise.nii.gz', out_res_name='rest2anat_denoised.nii.gz', output_type='NIFTI_GZ', demean=True), name='filternoise') filter2.plugin_args = {'submit_specs': 'request_memory = 17000'} denoise.connect([(inputnode, filter2, [('epi_coreg', 'in_file')]), (createfilter2, filter2, [('out_files', 'design')]), (inputnode, filter2, [('brain_mask', 'mask')]), (filter2, outputnode, [('out_f', 'comp_F'), ('out_pf', 'comp_pF'), ('out_file', 'out_betas')])]) # write TR into header again (glms remove it) # do not use mri_convert interface as it has a bug (already fixed in niyppe master) fix_tr = Node(util.Function(input_names=['in_file', 'TR_sec'], output_names=['out_file'], function=fix_TR_fs), name='fix_tr') denoise.connect(inputnode, 'tr', fix_tr, 'TR_sec') denoise.connect(filter2, 'out_res', fix_tr, 'in_file') #use only highpass filter (because high-frequency content (otherwise filtered by lowpass is already considered in AROMA)) highpass_filter = Node( fsl.TemporalFilter(out_file='rest_denoised_highpassed.nii'), name='highpass_filter') highpass_filter.plugin_args = {'submit_specs': 'request_memory = 17000'} denoise.connect([(inputnode, highpass_filter, [('highpass_sigma', 'highpass_sigma')]), (fix_tr, highpass_filter, [('out_file', 'in_file')]), (fix_tr, outputnode, [('out_file', 'ts_fullspectrum')])]) # time-normalize scans (could be set to percent change etc. but here NO normalization is used # http://nipy.org/nitime/api/generated/nitime.fmri.io.html) normalize_time = Node(util.Function(input_names=['in_file', 'tr'], output_names=['out_file'], function=time_normalizer), name='normalize_time') normalize_time.plugin_args = {'submit_specs': 'request_memory = 17000'} denoise.connect([ (inputnode, normalize_time, [('tr', 'tr')]), (highpass_filter, normalize_time, [('out_file', 'in_file')]), (normalize_time, outputnode, [('out_file', 'normalized_file')]) ]) return denoise
def anat2func(name='anat2func'): """ Get anat2func transform matrix, csf mask and wm mask in functional space. """ anat2func = pe.Workflow(name=name) # Set up a node to define all inputs and outputs required for the # preprocessing workflow inputnode = pe.Node(interface=util.IdentityInterface( fields=['example_func', 'mask', 'brain', 'highres2standard']), name='inputspec') outputnode = pe.Node(interface=util.IdentityInterface( fields=['anat2funcmtx', 'csfmask', 'wmmask', 'gmmask']), name='outputspec') # Mask the example_func with the extracted mask maskfunc = pe.MapNode(interface=fsl.ImageMaths(suffix='_bet', op_string='-mas'), iterfield=['in_file', 'in_file2'], name='maskfunc') coregister = pe.MapNode(interface=fsl.FLIRT(dof=6, cost='corratio', interp='trilinear'), iterfield=['reference'], name='coregister') # Convert highres2standard matrix to standard2highres matrix xfmconvert = pe.Node(interface=fsl.ConvertXFM(invert_xfm=True), name='xfmconvert') # Create mask for three tissue types. tissuemasks = pe.Node(interface=fsl.FAST(no_pve=True, segments=True, use_priors=True), name='segment') # Transform CSF mask to func space. csf2func = pe.MapNode(interface=fsl.ApplyXfm(apply_xfm=True), iterfield=['reference', 'in_matrix_file'], name='csf2func') # Threshold CSF segmentation mask from .90 to 1 threshcsf = pe.MapNode( interface=fsl.ImageMaths(op_string=' -thr .90 -uthr 1 -bin '), iterfield=['in_file'], name='threshcsf') # Transform WM mask to func wm2func = pe.MapNode(interface=fsl.ApplyXfm(apply_xfm=True), iterfield=['reference', 'in_matrix_file'], name='wm2func') # Threshold WM segmentation mask from .90 to 1 threshwm = pe.MapNode( interface=fsl.ImageMaths(op_string=' -thr .90 -uthr 1 -bin '), iterfield=['in_file'], name='threshwm') # Transform GM mask to func gm2func = pe.MapNode(interface=fsl.ApplyXfm(apply_xfm=True), iterfield=['reference', 'in_matrix_file'], name='gm2func') # Threshold WM segmentation mask from .50 to 1 threshgm = pe.MapNode( interface=fsl.ImageMaths(op_string=' -thr .50 -uthr 1 -bin '), iterfield=['in_file'], name='threshgm') # To get CSF and WM mask in functional space anat2func.connect([ (inputnode, coregister, [('brain', 'in_file')]), (inputnode, maskfunc, [('example_func', 'in_file')]), (inputnode, maskfunc, [('mask', 'in_file2')]), (inputnode, xfmconvert, [('highres2standard', 'in_file')]), (xfmconvert, tissuemasks, [('out_file', 'init_transform')]), (maskfunc, coregister, [('out_file', 'reference')]), (coregister, outputnode, [('out_matrix_file', 'anat2funcmtx')]), (inputnode, tissuemasks, [('brain', 'in_files')]), (tissuemasks, csf2func, [(('tissue_class_files', pickfile, 0), 'in_file')]), (maskfunc, csf2func, [('out_file', 'reference')]), (coregister, csf2func, [('out_matrix_file', 'in_matrix_file')]), (csf2func, threshcsf, [('out_file', 'in_file')]), (tissuemasks, wm2func, [(('tissue_class_files', pickfile, 2), 'in_file')]), (maskfunc, wm2func, [('out_file', 'reference')]), (coregister, wm2func, [('out_matrix_file', 'in_matrix_file')]), (wm2func, threshwm, [('out_file', 'in_file')]), (tissuemasks, gm2func, [(('tissue_class_files', pickfile, 1), 'in_file')]), (maskfunc, gm2func, [('out_file', 'reference')]), (coregister, gm2func, [('out_matrix_file', 'in_matrix_file')]), (gm2func, threshgm, [('out_file', 'in_file')]), (threshcsf, outputnode, [('out_file', 'csfmask')]), (threshwm, outputnode, [('out_file', 'wmmask')]), (threshgm, outputnode, [('out_file', 'gmmask')]), ]) return anat2func
def calculate_overlap(population_a, population_b, workspace_a, workspace_b, voxel_name): #* Retest MRS voxels (STUDY_B) are registered to test MRS voxel (STUDY_A) #* The Sorenson Dice metric between the two voxels is calculated to quantif the agreement between the two visits. ## anat_b is first registered to anat_a; ## affine xfm is then applied to mrs_b ## affines of mrs_a and mrs_ are checked. for subject in population_a and population_b: print '###################################################################################' print ' Running %s MRS voxel registration for subject %s' %(voxel_name, subject) print ' ---------------------------------------------------' print '' anat_a = os.path.join(workspace_a, subject, 'anatomical_original', 'ANATOMICAL.nii') voxel_a = os.path.join(workspace_a, subject, 'svs_voxel_mask', '%sa_%s_RDA_MASK.nii'%(subject,voxel_name)) anat_b = os.path.join(workspace_b, subject, 'anatomical_original', 'ANATOMICAL.nii') voxel_b = os.path.join(workspace_b, subject, 'svs_voxel_mask', '%sb_%s_RDA_MASK.nii'%(subject,voxel_name)) try: os.makedirs(os.path.join(os.path.join(workspace_b, subject, 'dice'))) except OSError: pass dice_dir = os.path.join(os.path.join(workspace_b, subject, 'dice')) if os.path.isfile(os.path.join(dice_dir, 'anat_b2a.nii.gz')): print 'Anatomical registration already completed...moving on' else: print 'Registering anat_b to anat_a' # Running registration anat_a to anat_b import nipype.interfaces.fsl as fsl flirt = fsl.FLIRT ( bins=640, cost_func= 'mutualinfo') flirt.inputs.in_file = anat_b flirt.inputs.reference = anat_a flirt.inputs.out_file = os.path.join(dice_dir, 'anat_b2a.nii.gz') flirt.inputs.out_matrix_file = os.path.join(dice_dir, 'anat_b2a.mat') flirt.run() # apply transform to voxel_b print 'Registering voxe_b to voxel_a' mat = os.path.join(dice_dir, 'anat_b2a.mat') from nipype.interfaces import fsl apply_xfm = fsl.ApplyXfm() apply_xfm.inputs.in_file = voxel_b apply_xfm.inputs.in_matrix_file = mat apply_xfm.inputs.out_file = os.path.join(dice_dir, '%s_b2a.nii.gz'%voxel_name) apply_xfm.inputs.reference = anat_a apply_xfm.inputs.apply_xfm = True apply_xfm.run() voxel_b2a = os.path.join(dice_dir, '%s_b2a.nii.gz'%voxel_name) dice_file = os.path.join(dice_dir, 'dice_%s.txt'%voxel_name) # calculate dice print 'Calculating Dice Metric' dice_val = dice_metric(voxel_b2a, voxel_a) dice_write = open(dice_file, 'w') dice_write.write('%s'%dice_val) dice_write.close()
def fsl_getmask(name): import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe import nipype.interfaces.utility as niu wf = pe.Workflow(name=name) inputspec = pe.Node( niu.IdentityInterface(fields=['functional', 'structural']), name='inputspec') bet = pe.Node(fsl.BET(mask=True, remove_eyes=True), name='bet') flirt = pe.Node(fsl.FLIRT(dof=6), name='flirt') flirt_inv = flirt.clone('func2struct') applyxfm_mask = pe.Node(fsl.ApplyXfm(interp='nearestneighbour', apply_xfm=True), name='applyxfm_mask') applyxfm_seg = pe.MapNode(fsl.ApplyXfm(interp='nearestneighbour', apply_xfm=True), name='applyxfm_seg', iterfield=['in_file']) dilate = pe.Node(fsl.DilateImage(operation='mean'), name='dilate') fast = pe.Node(fsl.FAST(), name='fast') outputspec = pe.Node(niu.IdentityInterface(fields=[ 'mask', 'reg_file', 'segments', 'warped_struct', 'bet_struct', 'inverse_reg' ]), name='outputspec') #create brain mask wf.connect(inputspec, "structural", bet, "in_file") # calculate transfor, struct --> func wf.connect(inputspec, "functional", flirt, "reference") wf.connect(inputspec, "structural", flirt, "in_file") wf.connect(flirt, 'out_matrix_file', outputspec, 'reg_file') wf.connect(flirt, 'out_file', outputspec, 'warped_struct') # Calculate inverse wf.connect(inputspec, "functional", flirt_inv, "in_file") wf.connect(inputspec, "structural", flirt_inv, "reference") wf.connect(flirt_inv, "out_matrix_file", outputspec, "inverse_reg") #dilate brain mask wf.connect(bet, "mask_file", dilate, "in_file") #transform mask to functional space wf.connect(dilate, "out_file", applyxfm_mask, "in_file") wf.connect(inputspec, "functional", applyxfm_mask, "reference") wf.connect(flirt, "out_matrix_file", applyxfm_mask, "in_matrix_file") wf.connect(applyxfm_mask, 'out_file', outputspec, 'mask') #segment with FAST wf.connect(bet, "out_file", fast, "in_files") wf.connect(bet, "out_file", outputspec, "bet_struct") #transform segments wf.connect(fast, "tissue_class_map", applyxfm_seg, "in_file") wf.connect(flirt, 'out_matrix_file', applyxfm_seg, "in_matrix_file") wf.connect(inputspec, "functional", applyxfm_seg, "reference") wf.connect(applyxfm_seg, "out_file", outputspec, "segments") return wf
def create_registration_pipeline(working_dir, freesurfer_dir, ds_dir, name='registration'): """ find transformations between struct, funct, and MNI """ # initiate workflow reg_wf = Workflow(name=name) reg_wf.base_dir = os.path.join(working_dir, 'LeiCA_resting', 'rsfMRI_preprocessing') # set fsl output fsl.FSLCommand.set_default_output_type('NIFTI_GZ') freesurfer.FSCommand.set_default_subjects_dir(freesurfer_dir) # inputnode inputnode = Node(util.IdentityInterface(fields=[ 'initial_mean_epi_moco', 't1w', 't1w_brain', 'subject_id', 'wm_mask_4_bbr', 'struct_brain_mask' ]), name='inputnode') outputnode = Node(util.IdentityInterface(fields=[ 'struct_2_MNI_warp', 'epi_2_struct_mat', 'struct_2_epi_mat', 'epi_2_MNI_warp', 'MNI_2_epi_warp', 'fs_2_struct_mat', 'mean_epi_structSpace', 'mean_epi_MNIspace', 'struct_MNIspace' ]), name='outputnode') ds = Node(nio.DataSink(base_directory=ds_dir), name='ds') ds.inputs.substitutions = [('_TR_id_', 'TR_')] ########################################## # TOC REGISTRATION MATS AND WARPS ########################################## # I. STRUCT -> MNI ## 1. STRUCT -> MNI with FLIRT ## 2. CALC. WARP STRUCT -> MNI with FNIRT # II.EPI -> STRUCT ## 3. calc EPI->STRUCT initial registration ## 4. run EPI->STRUCT via bbr ## 5. INVERT to get: STRUCT -> EPI # III. COMBINE I. & II.: EPI -> MNI ## 6. COMBINE MATS: EPI -> MNI ## 7. MNI -> EPI ########################################## # CREATE REGISTRATION MATS AND WARPS ########################################## # I. STRUCT -> MNI ########################################## # 1. REGISTER STRUCT -> MNI with FLIRT struct_2_MNI_mat = Node(fsl.FLIRT(dof=12), name='struct_2_MNI_mat') struct_2_MNI_mat.inputs.reference = fsl.Info.standard_image( 'MNI152_T1_2mm_brain.nii.gz') reg_wf.connect(inputnode, 't1w_brain', struct_2_MNI_mat, 'in_file') reg_wf.connect(struct_2_MNI_mat, 'out_matrix_file', outputnode, 'struct_2_MNI_mat_flirt') # 2. CALC. WARP STRUCT -> MNI with FNIRT # cf. wrt. 2mm # https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind1311&L=FSL&P=R86108&1=FSL&9=A&J=on&d=No+Match%3BMatch%3BMatches&z=4 struct_2_MNI_warp = Node(fsl.FNIRT(), name='struct_2_MNI_warp') struct_2_MNI_warp.inputs.config_file = 'T1_2_MNI152_2mm' struct_2_MNI_warp.inputs.ref_file = fsl.Info.standard_image( 'MNI152_T1_2mm.nii.gz') struct_2_MNI_warp.inputs.field_file = 'struct_2_MNI_warp.nii.gz' struct_2_MNI_warp.plugin_args = {'submit_specs': 'request_memory = 4000'} reg_wf.connect(inputnode, 't1w', struct_2_MNI_warp, 'in_file') reg_wf.connect(struct_2_MNI_mat, 'out_matrix_file', struct_2_MNI_warp, 'affine_file') reg_wf.connect(struct_2_MNI_warp, 'field_file', ds, 'registration.struct_2_MNI_warp') reg_wf.connect(struct_2_MNI_warp, 'field_file', outputnode, 'struct_2_MNI_warp') reg_wf.connect(struct_2_MNI_warp, 'warped_file', outputnode, 'struct_MNIspace') reg_wf.connect(struct_2_MNI_warp, 'warped_file', ds, 'registration.struct_MNIspace') # II.EPI -> STRUCT (via bbr) ########################################## # 3. calc EPI->STRUCT initial registration with flirt dof=6 and corratio epi_2_struct_flirt6_mat = Node(fsl.FLIRT(dof=6, cost='corratio'), name='epi_2_struct_flirt6_mat') epi_2_struct_flirt6_mat.inputs.out_file = 'epi_structSpace_flirt6.nii.gz' reg_wf.connect(inputnode, 't1w_brain', epi_2_struct_flirt6_mat, 'reference') reg_wf.connect(inputnode, 'initial_mean_epi_moco', epi_2_struct_flirt6_mat, 'in_file') # 4. run EPI->STRUCT via bbr bbr_shedule = os.path.join(os.getenv('FSLDIR'), 'etc/flirtsch/bbr.sch') epi_2_struct_bbr_mat = Node(interface=fsl.FLIRT(dof=6, cost='bbr'), name='epi_2_struct_bbr_mat') epi_2_struct_bbr_mat.inputs.schedule = bbr_shedule epi_2_struct_bbr_mat.inputs.out_file = 'epi_structSpace.nii.gz' reg_wf.connect(inputnode, 'initial_mean_epi_moco', epi_2_struct_bbr_mat, 'in_file') reg_wf.connect(inputnode, 't1w_brain', epi_2_struct_bbr_mat, 'reference') reg_wf.connect(epi_2_struct_flirt6_mat, 'out_matrix_file', epi_2_struct_bbr_mat, 'in_matrix_file') reg_wf.connect(inputnode, 'wm_mask_4_bbr', epi_2_struct_bbr_mat, 'wm_seg') reg_wf.connect(epi_2_struct_bbr_mat, 'out_matrix_file', ds, 'registration.epi_2_struct_mat') reg_wf.connect(epi_2_struct_bbr_mat, 'out_file', outputnode, 'mean_epi_structSpace') # 5. INVERT to get: STRUCT -> EPI struct_2_epi_mat = Node(fsl.ConvertXFM(invert_xfm=True), name='struct_2_epi_mat') reg_wf.connect(epi_2_struct_bbr_mat, 'out_matrix_file', struct_2_epi_mat, 'in_file') reg_wf.connect(struct_2_epi_mat, 'out_file', outputnode, 'struct_2_epi_mat') # III. COMBINE I. & II.: EPI -> MNI ########################################## # 6. COMBINE MATS: EPI -> MNI epi_2_MNI_warp = Node(fsl.ConvertWarp(), name='epi_2_MNI_warp') epi_2_MNI_warp.inputs.reference = fsl.Info.standard_image( 'MNI152_T1_2mm.nii.gz') reg_wf.connect(epi_2_struct_bbr_mat, 'out_matrix_file', epi_2_MNI_warp, 'premat') # epi2struct reg_wf.connect(struct_2_MNI_warp, 'field_file', epi_2_MNI_warp, 'warp1') # struct2mni reg_wf.connect(epi_2_MNI_warp, 'out_file', outputnode, 'epi_2_MNI_warp') reg_wf.connect(epi_2_MNI_warp, 'out_file', ds, 'registration.epi_2_MNI_warp') # output: out_file # 7. MNI -> EPI MNI_2_epi_warp = Node(fsl.InvWarp(), name='MNI_2_epi_warp') MNI_2_epi_warp.inputs.reference = fsl.Info.standard_image( 'MNI152_T1_2mm.nii.gz') reg_wf.connect(epi_2_MNI_warp, 'out_file', MNI_2_epi_warp, 'warp') reg_wf.connect(inputnode, 'initial_mean_epi_moco', MNI_2_epi_warp, 'reference') reg_wf.connect(MNI_2_epi_warp, 'inverse_warp', outputnode, 'MNI_2_epi_warp') # output: inverse_warp ########################################## # TRANSFORM VOLUMES ########################################## # CREATE STRUCT IN EPI SPACE FOR DEBUGGING struct_epiSpace = Node(fsl.ApplyXfm(), name='struct_epiSpace') struct_epiSpace.inputs.out_file = 'struct_brain_epiSpace.nii.gz' reg_wf.connect(inputnode, 't1w_brain', struct_epiSpace, 'in_file') reg_wf.connect(inputnode, 'initial_mean_epi_moco', struct_epiSpace, 'reference') reg_wf.connect(struct_2_epi_mat, 'out_file', struct_epiSpace, 'in_matrix_file') reg_wf.connect(struct_epiSpace, 'out_file', ds, 'QC.struct_brain_epiSpace') # CREATE EPI IN MNI SPACE mean_epi_MNIspace = Node(fsl.ApplyWarp(), name='mean_epi_MNIspace') mean_epi_MNIspace.inputs.ref_file = fsl.Info.standard_image( 'MNI152_T1_2mm_brain.nii.gz') mean_epi_MNIspace.inputs.out_file = 'mean_epi_MNIspace.nii.gz' reg_wf.connect(inputnode, 'initial_mean_epi_moco', mean_epi_MNIspace, 'in_file') reg_wf.connect(epi_2_MNI_warp, 'out_file', mean_epi_MNIspace, 'field_file') reg_wf.connect(mean_epi_MNIspace, 'out_file', ds, 'registration.mean_epi_MNIspace') reg_wf.connect(mean_epi_MNIspace, 'out_file', outputnode, 'mean_epi_MNIspace') # CREATE MNI IN EPI SPACE FOR DEBUGGING MNI_epiSpace = Node(fsl.ApplyWarp(), name='MNI_epiSpace') MNI_epiSpace.inputs.in_file = fsl.Info.standard_image( 'MNI152_T1_2mm_brain.nii.gz') MNI_epiSpace.inputs.out_file = 'MNI_epiSpace.nii.gz' reg_wf.connect(inputnode, 'initial_mean_epi_moco', MNI_epiSpace, 'ref_file') reg_wf.connect(MNI_2_epi_warp, 'inverse_warp', MNI_epiSpace, 'field_file') reg_wf.connect(MNI_epiSpace, 'out_file', ds, 'registration.MNI_epiSpace') reg_wf.write_graph(dotfilename=reg_wf.name, graph2use='flat', format='pdf') return reg_wf
def make_fmap_wkfl(name='make_fieldmap', mapnode=False): klass = pe.Node if mapnode: klass = pe.MapNode inputnode = pe.Node(utility.IdentityInterface( fields=['fieldmap', 'magnitude', 't1_mask', 't1_mag', 'delta_TE']), name='inputspec') outputnode = pe.Node(utility.IdentityInterface(fields=[ 'fieldmap', 'fieldmap_reg', 'fieldmap_magnitude', 'fieldmap_mask' ]), name='outputspec') n_fieldmap2t1_warp = klass( fsl.FLIRT( out_matrix_file='fieldmap2t1.mat', cost='normmi', dof=6, searchr_x=[-5, 5], # restrict search as they are acquired searchr_y=[-5, 5], # in the same sequence searchr_z=[-5, 5], cost_func='normmi'), iterfield=['in_file'], name='fieldmap2t1_warp') n_invert_fieldmap2t1_warp = klass(fsl.ConvertXFM(invert_xfm=True), iterfield=['in_file'], name='invert_fieldmap2t1_warp') n_warp_t1_mask = klass(fsl.ApplyXfm(apply_xfm=True, interp='nearestneighbour', datatype='char'), iterfield=['in_matrix_file', 'reference'], name='warp_t1_mask') n_mask_mag = klass(fsl.ImageMaths(op_string='-mul', suffix='_brain', output_type='NIFTI'), iterfield=['in_file', 'in_file2'], name='mask_mag') n_make_fieldmap = klass( fsl.FUGUE(fmap_out_file='fieldmap.nii.gz', smooth3d=2), iterfield=['fmap_out_file', 'mask_file', 'fmap_in_file'], name='make_fieldmap') w = pe.Workflow(name=name) w.connect([ (inputnode, n_fieldmap2t1_warp, [('t1_mag', 'reference'), ('magnitude', 'in_file')]), (n_fieldmap2t1_warp, n_invert_fieldmap2t1_warp, [('out_matrix_file', 'in_file')]), (n_invert_fieldmap2t1_warp, n_warp_t1_mask, [('out_file', 'in_matrix_file')]), (inputnode, n_warp_t1_mask, [('t1_mask', 'in_file')]), (inputnode, n_warp_t1_mask, [('magnitude', 'reference')]), (inputnode, n_mask_mag, [('magnitude', 'in_file')]), (n_warp_t1_mask, n_mask_mag, [('out_file', 'in_file2')]), (inputnode, n_make_fieldmap, [(('fieldmap', fname_presuffix_basename, '', '_reg', './'), 'fmap_out_file')]), (n_warp_t1_mask, n_make_fieldmap, [('out_file', 'mask_file')]), (inputnode, n_make_fieldmap, [('fieldmap', 'fmap_in_file')]), (inputnode, n_make_fieldmap, [('delta_TE', 'asym_se_time')]), (n_warp_t1_mask, outputnode, [('out_file', 'fieldmap_mask')]), (n_mask_mag, outputnode, [('out_file', 'fieldmap_magnitude')]), (n_make_fieldmap, outputnode, [('fmap_out_file', 'fieldmap')]), (n_make_fieldmap, outputnode, [('fmap_out_file', 'fieldmap_reg')]), ]) return w
def create_precoth_pipeline(name="precoth", tractography_type='probabilistic', reg_pet_T1=True): inputnode = pe.Node( interface=util.IdentityInterface(fields=["subjects_dir", "subject_id", "dwi", "bvecs", "bvals", "fdgpet", "dose", "weight", "delay", "glycemie", "scan_time"]), name="inputnode") nonlinfit_interface = util.Function(input_names=["dwi", "bvecs", "bvals", "base_name"], output_names=["tensor", "FA", "MD", "evecs", "evals", "rgb_fa", "norm", "mode", "binary_mask", "b0_masked"], function=nonlinfit_fn) nonlinfit_node = pe.Node(interface=nonlinfit_interface, name="nonlinfit_node") coregister = pe.Node(interface=fsl.FLIRT(dof=12), name = 'coregister') coregister.inputs.cost = ('normmi') invertxfm = pe.Node(interface=fsl.ConvertXFM(), name = 'invertxfm') invertxfm.inputs.invert_xfm = True WM_to_FA = pe.Node(interface=fsl.ApplyXfm(), name = 'WM_to_FA') WM_to_FA.inputs.interp = 'nearestneighbour' TermMask_to_FA = WM_to_FA.clone("TermMask_to_FA") mni_for_reg = op.join(os.environ["FSL_DIR"],"data","standard","MNI152_T1_1mm.nii.gz") reorientBrain = pe.Node(interface=fsl.FLIRT(dof=6), name = 'reorientBrain') reorientBrain.inputs.reference = mni_for_reg reorientROIs = pe.Node(interface=fsl.ApplyXfm(), name = 'reorientROIs') reorientROIs.inputs.interp = "nearestneighbour" reorientROIs.inputs.reference = mni_for_reg reorientRibbon = reorientROIs.clone("reorientRibbon") reorientRibbon.inputs.interp = "nearestneighbour" reorientT1 = reorientROIs.clone("reorientT1") reorientT1.inputs.interp = "trilinear" fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix') fsl2mrtrix.inputs.invert_y = True erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_firstpass') erode_mask_firstpass.inputs.out_filename = "b0_mask_median3D_erode.nii.gz" erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_secondpass') erode_mask_secondpass.inputs.out_filename = "b0_mask_median3D_erode_secondpass.nii.gz" threshold_FA = pe.Node(interface=fsl.ImageMaths(), name='threshold_FA') threshold_FA.inputs.op_string = "-thr 0.8 -uthr 0.99" threshold_mode = pe.Node(interface=fsl.ImageMaths(), name='threshold_mode') threshold_mode.inputs.op_string = "-thr 0.1 -uthr 0.99" make_termination_mask = pe.Node(interface=fsl.ImageMaths(), name='make_termination_mask') make_termination_mask.inputs.op_string = "-bin" get_wm_mask = pe.Node(interface=fsl.ImageMaths(), name='get_wm_mask') get_wm_mask.inputs.op_string = "-thr 0.1" MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply') MRmultiply.inputs.out_filename = "Eroded_FA.nii.gz" MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge') median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3D') fdgpet_regions = pe.Node(interface=RegionalValues(), name='fdgpet_regions') compute_cmr_glc_interface = util.Function(input_names=["in_file", "dose", "weight", "delay", "glycemie", "scan_time"], output_names=["out_file"], function=CMR_glucose) compute_cmr_glc = pe.Node(interface=compute_cmr_glc_interface, name='compute_cmr_glc') csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') if tractography_type == 'probabilistic': CSDstreamtrack = pe.Node( interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack( ), name='CSDstreamtrack') else: CSDstreamtrack = pe.Node( interface=mrtrix.SphericallyDeconvolutedStreamlineTrack(), name='CSDstreamtrack') #CSDstreamtrack.inputs.desired_number_of_tracks = 10000 CSDstreamtrack.inputs.minimum_tract_length = 50 tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk') extract_PreCoTh_interface = util.Function(input_names=["in_file", "out_filename"], output_names=["out_file"], function=extract_PreCoTh) thalamus2precuneus2cortex_ROIs = pe.Node( interface=extract_PreCoTh_interface, name='thalamus2precuneus2cortex_ROIs') wm_mask_interface = util.Function(input_names=["in_file", "out_filename"], output_names=["out_file"], function=wm_labels_only) make_wm_mask = pe.Node( interface=wm_mask_interface, name='make_wm_mask') write_precoth_data_interface = util.Function(input_names=["dwi_network_file", "fdg_stats_file", "subject_id"], output_names=["out_file"], function=summarize_precoth) write_csv_data = pe.Node( interface=write_precoth_data_interface, name='write_csv_data') thalamus2precuneus2cortex = pe.Node( interface=cmtk.CreateMatrix(), name="thalamus2precuneus2cortex") thalamus2precuneus2cortex.inputs.count_region_intersections = True FreeSurferSource = pe.Node( interface=nio.FreeSurferSource(), name='fssource') mri_convert_Brain = pe.Node( interface=fs.MRIConvert(), name='mri_convert_Brain') mri_convert_Brain.inputs.out_type = 'niigz' mri_convert_Brain.inputs.no_change = True if reg_pet_T1: reg_pet_T1 = pe.Node(interface=fsl.FLIRT(dof=6), name = 'reg_pet_T1') reg_pet_T1.inputs.cost = ('corratio') reslice_fdgpet = mri_convert_Brain.clone("reslice_fdgpet") reslice_fdgpet.inputs.no_change = True mri_convert_Ribbon = mri_convert_Brain.clone("mri_convert_Ribbon") mri_convert_ROIs = mri_convert_Brain.clone("mri_convert_ROIs") mri_convert_T1 = mri_convert_Brain.clone("mri_convert_T1") workflow = pe.Workflow(name=name) workflow.base_output_dir = name workflow.connect( [(inputnode, FreeSurferSource, [("subjects_dir", "subjects_dir")])]) workflow.connect( [(inputnode, FreeSurferSource, [("subject_id", "subject_id")])]) workflow.connect( [(FreeSurferSource, mri_convert_T1, [('T1', 'in_file')])]) workflow.connect( [(mri_convert_T1, reorientT1, [('out_file', 'in_file')])]) workflow.connect( [(FreeSurferSource, mri_convert_Brain, [('brain', 'in_file')])]) workflow.connect( [(mri_convert_Brain, reorientBrain, [('out_file', 'in_file')])]) workflow.connect( [(reorientBrain, reorientROIs, [('out_matrix_file', 'in_matrix_file')])]) workflow.connect( [(reorientBrain, reorientRibbon, [('out_matrix_file', 'in_matrix_file')])]) workflow.connect( [(reorientBrain, reorientT1, [('out_matrix_file', 'in_matrix_file')])]) workflow.connect( [(FreeSurferSource, mri_convert_ROIs, [(('aparc_aseg', select_aparc), 'in_file')])]) workflow.connect( [(mri_convert_ROIs, reorientROIs, [('out_file', 'in_file')])]) workflow.connect( [(reorientROIs, make_wm_mask, [('out_file', 'in_file')])]) workflow.connect( [(FreeSurferSource, mri_convert_Ribbon, [(('ribbon', select_ribbon), 'in_file')])]) workflow.connect( [(mri_convert_Ribbon, reorientRibbon, [('out_file', 'in_file')])]) workflow.connect( [(reorientRibbon, make_termination_mask, [('out_file', 'in_file')])]) workflow.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"), ("bvals", "bval_file")])]) workflow.connect(inputnode, 'dwi', nonlinfit_node, 'dwi') workflow.connect(inputnode, 'subject_id', nonlinfit_node, 'base_name') workflow.connect(inputnode, 'bvecs', nonlinfit_node, 'bvecs') workflow.connect(inputnode, 'bvals', nonlinfit_node, 'bvals') workflow.connect([(inputnode, compute_cmr_glc, [("dose", "dose")])]) workflow.connect([(inputnode, compute_cmr_glc, [("weight", "weight")])]) workflow.connect([(inputnode, compute_cmr_glc, [("delay", "delay")])]) workflow.connect([(inputnode, compute_cmr_glc, [("glycemie", "glycemie")])]) workflow.connect([(inputnode, compute_cmr_glc, [("scan_time", "scan_time")])]) if reg_pet_T1: workflow.connect([(inputnode, reg_pet_T1, [("fdgpet", "in_file")])]) workflow.connect( [(reorientBrain, reg_pet_T1, [("out_file", "reference")])]) workflow.connect( [(reg_pet_T1, reslice_fdgpet, [("out_file", "in_file")])]) workflow.connect( [(reorientROIs, reslice_fdgpet, [("out_file", "reslice_like")])]) workflow.connect( [(reslice_fdgpet, compute_cmr_glc, [("out_file", "in_file")])]) else: workflow.connect([(inputnode, reslice_fdgpet, [("fdgpet", "in_file")])]) workflow.connect( [(reorientROIs, reslice_fdgpet, [("out_file", "reslice_like")])]) workflow.connect( [(reslice_fdgpet, compute_cmr_glc, [("out_file", "in_file")])]) workflow.connect( [(compute_cmr_glc, fdgpet_regions, [("out_file", "in_files")])]) workflow.connect( [(thalamus2precuneus2cortex_ROIs, fdgpet_regions, [("out_file", "segmentation_file")])]) workflow.connect([(nonlinfit_node, coregister,[("FA","in_file")])]) workflow.connect([(make_wm_mask, coregister,[('out_file','reference')])]) workflow.connect([(nonlinfit_node, tck2trk,[("FA","image_file")])]) workflow.connect([(reorientBrain, tck2trk,[("out_file","registration_image_file")])]) workflow.connect([(coregister, tck2trk,[("out_matrix_file","matrix_file")])]) workflow.connect([(coregister, invertxfm,[("out_matrix_file","in_file")])]) workflow.connect([(invertxfm, WM_to_FA,[("out_file","in_matrix_file")])]) workflow.connect([(make_wm_mask, WM_to_FA,[("out_file","in_file")])]) workflow.connect([(nonlinfit_node, WM_to_FA,[("FA","reference")])]) workflow.connect([(invertxfm, TermMask_to_FA,[("out_file","in_matrix_file")])]) workflow.connect([(make_termination_mask, TermMask_to_FA,[("out_file","in_file")])]) workflow.connect([(nonlinfit_node, TermMask_to_FA,[("FA","reference")])]) workflow.connect([(nonlinfit_node, median3d, [("binary_mask", "in_file")])]) workflow.connect( [(median3d, erode_mask_firstpass, [("out_file", "in_file")])]) workflow.connect( [(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])]) workflow.connect([(nonlinfit_node, MRmult_merge, [("FA", "in1")])]) workflow.connect( [(erode_mask_secondpass, MRmult_merge, [("out_file", "in2")])]) workflow.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])]) workflow.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])]) workflow.connect( [(threshold_FA, estimateresponse, [("out_file", "mask_image")])]) workflow.connect([(inputnode, estimateresponse, [("dwi", "in_file")])]) workflow.connect( [(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])]) workflow.connect([(inputnode, csdeconv, [("dwi", "in_file")])]) #workflow.connect( # [(TermMask_to_FA, csdeconv, [("out_file", "mask_image")])]) workflow.connect( [(estimateresponse, csdeconv, [("response", "response_file")])]) workflow.connect( [(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")])]) workflow.connect( [(WM_to_FA, CSDstreamtrack, [("out_file", "seed_file")])]) workflow.connect( [(TermMask_to_FA, CSDstreamtrack, [("out_file", "mask_file")])]) workflow.connect( [(csdeconv, CSDstreamtrack, [("spherical_harmonics_image", "in_file")])]) workflow.connect([(CSDstreamtrack, tck2trk, [("tracked", "in_file")])]) workflow.connect( [(tck2trk, thalamus2precuneus2cortex, [("out_file", "tract_file")])]) workflow.connect( [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_file")])]) workflow.connect( [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_mat_file")])]) workflow.connect( [(reorientROIs, thalamus2precuneus2cortex_ROIs, [("out_file", "in_file")])]) workflow.connect( [(thalamus2precuneus2cortex_ROIs, thalamus2precuneus2cortex, [("out_file", "roi_file")])]) workflow.connect( [(thalamus2precuneus2cortex, fdgpet_regions, [("matrix_file", "resolution_network_file")])]) workflow.connect( [(inputnode, write_csv_data, [("subject_id", "subject_id")])]) workflow.connect( [(fdgpet_regions, write_csv_data, [("stats_file", "fdg_stats_file")])]) workflow.connect( [(thalamus2precuneus2cortex, write_csv_data, [("intersection_matrix_file", "dwi_network_file")])]) output_fields = ["fa", "rgb_fa", "md", "csdeconv", "tracts_tck", "rois", "t1", "t1_brain", "wmmask_dtispace", "fa_t1space", "summary", "filtered_tractographies", "matrix_file", "connectome", "CMR_nodes", "fiber_labels_noorphans", "fiber_length_file", "fiber_label_file", "intersection_matrix_mat_file"] outputnode = pe.Node( interface=util.IdentityInterface(fields=output_fields), name="outputnode") workflow.connect( [(CSDstreamtrack, outputnode, [("tracked", "tracts_tck")]), (csdeconv, outputnode, [("spherical_harmonics_image", "csdeconv")]), (nonlinfit_node, outputnode, [("FA", "fa")]), (coregister, outputnode, [("out_file", "fa_t1space")]), (reorientBrain, outputnode, [("out_file", "t1_brain")]), (reorientT1, outputnode, [("out_file", "t1")]), (thalamus2precuneus2cortex_ROIs, outputnode, [("out_file", "rois")]), (thalamus2precuneus2cortex, outputnode, [("filtered_tractographies", "filtered_tractographies")]), (thalamus2precuneus2cortex, outputnode, [("matrix_file", "connectome")]), (thalamus2precuneus2cortex, outputnode, [("fiber_labels_noorphans", "fiber_labels_noorphans")]), (thalamus2precuneus2cortex, outputnode, [("fiber_length_file", "fiber_length_file")]), (thalamus2precuneus2cortex, outputnode, [("fiber_label_file", "fiber_label_file")]), (thalamus2precuneus2cortex, outputnode, [("intersection_matrix_mat_file", "intersection_matrix_mat_file")]), (fdgpet_regions, outputnode, [("networks", "CMR_nodes")]), (nonlinfit_node, outputnode, [("rgb_fa", "rgb_fa")]), (nonlinfit_node, outputnode, [("MD", "md")]), (write_csv_data, outputnode, [("out_file", "summary")]), ]) return workflow
def create_struct_preproc_pipeline(working_dir, freesurfer_dir, ds_dir, use_fs_brainmask, name='struct_preproc'): """ """ # initiate workflow struct_preproc_wf = Workflow(name=name) struct_preproc_wf.base_dir = os.path.join(working_dir, 'LeiCA_resting', 'rsfMRI_preprocessing') # set fsl output fsl.FSLCommand.set_default_output_type('NIFTI_GZ') # inputnode inputnode = Node(util.IdentityInterface(fields=['t1w', 'subject_id']), name='inputnode') # outputnode outputnode = Node(util.IdentityInterface(fields=[ 't1w_brain', 'struct_brain_mask', 'fast_partial_volume_files', 'wm_mask', 'csf_mask', 'wm_mask_4_bbr', 'gm_mask' ]), name='outputnode') ds = Node(nio.DataSink(base_directory=ds_dir), name='ds') ds.inputs.substitutions = [('_TR_id_', 'TR_')] # CREATE BRAIN MASK if use_fs_brainmask: # brainmask with fs fs_source = Node(interface=nio.FreeSurferSource(), name='fs_source') fs_source.inputs.subjects_dir = freesurfer_dir struct_preproc_wf.connect(inputnode, 'subject_id', fs_source, 'subject_id') # get aparc+aseg from list def get_aparc_aseg(files): for name in files: if 'aparc+aseg' in name: return name aseg = Node(fs.MRIConvert(out_type='niigz', out_file='aseg.nii.gz'), name='aseg') struct_preproc_wf.connect(fs_source, ('aparc_aseg', get_aparc_aseg), aseg, 'in_file') fs_brainmask = Node( fs.Binarize( min=0.5, #dilate=1, out_type='nii.gz'), name='fs_brainmask') struct_preproc_wf.connect(aseg, 'out_file', fs_brainmask, 'in_file') # fill holes in mask, smooth, rebinarize fillholes = Node(fsl.maths.MathsCommand( args='-fillh -s 3 -thr 0.1 -bin', out_file='T1_brain_mask.nii.gz'), name='fillholes') struct_preproc_wf.connect(fs_brainmask, 'binary_file', fillholes, 'in_file') fs_2_struct_mat = Node(util.Function( input_names=['moving_image', 'target_image'], output_names=['fsl_file'], function=tkregister2_fct), name='fs_2_struct_mat') struct_preproc_wf.connect([(fs_source, fs_2_struct_mat, [('T1', 'moving_image'), ('rawavg', 'target_image')])]) struct_brain_mask = Node(fsl.ApplyXfm(interp='nearestneighbour'), name='struct_brain_mask_fs') struct_preproc_wf.connect(fillholes, 'out_file', struct_brain_mask, 'in_file') struct_preproc_wf.connect(inputnode, 't1w', struct_brain_mask, 'reference') struct_preproc_wf.connect(fs_2_struct_mat, 'fsl_file', struct_brain_mask, 'in_matrix_file') struct_preproc_wf.connect(struct_brain_mask, 'out_file', outputnode, 'struct_brain_mask') struct_preproc_wf.connect(struct_brain_mask, 'out_file', ds, 'struct_prep.struct_brain_mask') # multiply t1w with fs brain mask t1w_brain = Node(fsl.maths.BinaryMaths(operation='mul'), name='t1w_brain') struct_preproc_wf.connect(inputnode, 't1w', t1w_brain, 'in_file') struct_preproc_wf.connect(struct_brain_mask, 'out_file', t1w_brain, 'operand_file') struct_preproc_wf.connect(t1w_brain, 'out_file', outputnode, 't1w_brain') struct_preproc_wf.connect(t1w_brain, 'out_file', ds, 'struct_prep.t1w_brain') else: # use bet t1w_brain = Node(fsl.BET(mask=True, outline=True, surfaces=True), name='t1w_brain') struct_preproc_wf.connect(inputnode, 't1w', t1w_brain, 'in_file') struct_preproc_wf.connect(t1w_brain, 'out_file', outputnode, 't1w_brain') def struct_brain_mask_bet_fct(in_file): return in_file struct_brain_mask = Node(util.Function( input_names=['in_file'], output_names=['out_file'], function=struct_brain_mask_bet_fct), name='struct_brain_mask') struct_preproc_wf.connect(t1w_brain, 'mask_file', struct_brain_mask, 'in_file') struct_preproc_wf.connect(struct_brain_mask, 'out_file', outputnode, 'struct_brain_mask') struct_preproc_wf.connect(struct_brain_mask, 'out_file', ds, 'struct_prep.struct_brain_mask') # SEGMENTATION WITH FAST fast = Node(fsl.FAST(), name='fast') struct_preproc_wf.connect(t1w_brain, 'out_file', fast, 'in_files') struct_preproc_wf.connect(fast, 'partial_volume_files', outputnode, 'fast_partial_volume_files') struct_preproc_wf.connect(fast, 'partial_volume_files', ds, 'struct_prep.fast') # functions to select tissue classes def selectindex(files, idx): import numpy as np from nipype.utils.filemanip import filename_to_list, list_to_filename return list_to_filename( np.array(filename_to_list(files))[idx].tolist()) def selectsingle(files, idx): return files[idx] # pve0: CSF # pve1: GM # pve2: WM # binarize tissue classes binarize_tissue = MapNode( fsl.ImageMaths(op_string='-nan -thr 0.99 -ero -bin'), iterfield=['in_file'], name='binarize_tissue') struct_preproc_wf.connect(fast, ('partial_volume_files', selectindex, [0, 2]), binarize_tissue, 'in_file') # OUTPUT WM AND CSF MASKS FOR CPAC DENOISING struct_preproc_wf.connect([(binarize_tissue, outputnode, [(('out_file', selectsingle, 0), 'csf_mask'), (('out_file', selectsingle, 1), 'wm_mask')])]) # WRITE WM MASK WITH P > .5 FOR FSL BBR # use threshold of .5 like FSL's epi_reg script wm_mask_4_bbr = Node(fsl.ImageMaths(op_string='-thr 0.5 -bin'), name='wm_mask_4_bbr') struct_preproc_wf.connect(fast, ('partial_volume_files', selectindex, [2]), wm_mask_4_bbr, 'in_file') struct_preproc_wf.connect(wm_mask_4_bbr, 'out_file', outputnode, 'wm_mask_4_bbr') struct_preproc_wf.write_graph(dotfilename=struct_preproc_wf.name, graph2use='flat', format='pdf') return struct_preproc_wf
def create_precoth_pipeline_step1(name="precoth_step1", reg_pet_T1=True, auto_reorient=True): inputnode = pe.Node( interface=util.IdentityInterface(fields=["subjects_dir", "subject_id", "dwi", "bvecs", "bvals", "fdgpet"]), name="inputnode") nonlinfit_interface = util.Function(input_names=["dwi", "bvecs", "bvals", "base_name"], output_names=["tensor", "FA", "MD", "evecs", "evals", "rgb_fa", "norm", "mode", "binary_mask", "b0_masked"], function=nonlinfit_fn) nonlinfit_node = pe.Node(interface=nonlinfit_interface, name="nonlinfit_node") erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_firstpass') erode_mask_firstpass.inputs.out_filename = "b0_mask_median3D_erode.nii.gz" erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_secondpass') erode_mask_secondpass.inputs.out_filename = "b0_mask_median3D_erode_secondpass.nii.gz" threshold_FA = pe.Node(interface=fsl.ImageMaths(), name='threshold_FA') threshold_FA.inputs.op_string = "-thr 0.8 -uthr 0.99" threshold_mode = pe.Node(interface=fsl.ImageMaths(), name='threshold_mode') threshold_mode.inputs.op_string = "-thr 0.9 -fmedian -fmedian" make_termination_mask = pe.Node(interface=fsl.ImageMaths(), name='make_termination_mask') make_termination_mask.inputs.op_string = "-bin" fast_seg_T1 = pe.Node(interface=fsl.FAST(), name='fast_seg_T1') fast_seg_T1.inputs.segments = True fast_seg_T1.inputs.probability_maps = True fix_wm_mask = pe.Node(interface=fsl.MultiImageMaths(), name='fix_wm_mask') fix_wm_mask.inputs.op_string = "-mul %s" fix_termination_mask = pe.Node(interface=fsl.MultiImageMaths(), name='fix_termination_mask') fix_termination_mask.inputs.op_string = "-binv -mul %s" wm_mask_interface = util.Function(input_names=["in_file", "out_filename"], output_names=["out_file"], function=wm_labels_only) make_wm_mask = pe.Node(interface=wm_mask_interface, name='make_wm_mask') MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply') MRmultiply.inputs.out_filename = "Eroded_FA.nii.gz" MultFAbyMode = pe.Node(interface=mrtrix.MRMultiply(), name='MultFAbyMode') MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge') MultFAbyMode_merge = pe.Node(interface=util.Merge(2), name='MultFAbyMode_merge') median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3D') FreeSurferSource = pe.Node( interface=nio.FreeSurferSource(), name='fssource') mri_convert_Brain = pe.Node( interface=fs.MRIConvert(), name='mri_convert_Brain') mri_convert_Brain.inputs.out_type = 'nii' mri_convert_Brain.inputs.no_change = True mri_convert_Ribbon = mri_convert_Brain.clone("mri_convert_Ribbon") mri_convert_ROIs = mri_convert_Brain.clone("mri_convert_ROIs") mri_convert_T1 = mri_convert_Brain.clone("mri_convert_T1") mni_for_reg = op.join(os.environ["FSL_DIR"],"data","standard","MNI152_T1_1mm.nii.gz") if auto_reorient: reorientBrain = pe.Node(interface=fsl.FLIRT(dof=6), name = 'reorientBrain') reorientBrain.inputs.reference = mni_for_reg reorientROIs = pe.Node(interface=fsl.ApplyXfm(), name = 'reorientROIs') reorientROIs.inputs.interp = "nearestneighbour" reorientROIs.inputs.reference = mni_for_reg reorientRibbon = reorientROIs.clone("reorientRibbon") reorientRibbon.inputs.interp = "nearestneighbour" reorientT1 = reorientROIs.clone("reorientT1") reorientT1.inputs.interp = "trilinear" if reg_pet_T1: reg_pet_T1 = pe.Node(interface=fsl.FLIRT(dof=6), name = 'reg_pet_T1') reg_pet_T1.inputs.cost = ('corratio') reslice_fdgpet = mri_convert_Brain.clone("reslice_fdgpet") reslice_fdgpet.inputs.no_change = True extract_PreCoTh_interface = util.Function(input_names=["in_file", "out_filename"], output_names=["out_file"], function=extract_PreCoTh) thalamus2precuneus2cortex_ROIs = pe.Node( interface=extract_PreCoTh_interface, name='thalamus2precuneus2cortex_ROIs') workflow = pe.Workflow(name=name) workflow.base_output_dir = name workflow.connect( [(inputnode, FreeSurferSource, [("subjects_dir", "subjects_dir")])]) workflow.connect( [(inputnode, FreeSurferSource, [("subject_id", "subject_id")])]) workflow.connect( [(FreeSurferSource, mri_convert_T1, [('T1', 'in_file')])]) workflow.connect( [(FreeSurferSource, mri_convert_Brain, [('brain', 'in_file')])]) if auto_reorient: workflow.connect( [(mri_convert_T1, reorientT1, [('out_file', 'in_file')])]) workflow.connect( [(mri_convert_Brain, reorientBrain, [('out_file', 'in_file')])]) workflow.connect( [(reorientBrain, reorientROIs, [('out_matrix_file', 'in_matrix_file')])]) workflow.connect( [(reorientBrain, reorientRibbon, [('out_matrix_file', 'in_matrix_file')])]) workflow.connect( [(reorientBrain, reorientT1, [('out_matrix_file', 'in_matrix_file')])]) workflow.connect( [(FreeSurferSource, mri_convert_ROIs, [(('aparc_aseg', select_aparc), 'in_file')])]) if auto_reorient: workflow.connect( [(mri_convert_ROIs, reorientROIs, [('out_file', 'in_file')])]) workflow.connect( [(reorientROIs, make_wm_mask, [('out_file', 'in_file')])]) workflow.connect( [(reorientROIs, thalamus2precuneus2cortex_ROIs, [("out_file", "in_file")])]) else: workflow.connect( [(mri_convert_ROIs, make_wm_mask, [('out_file', 'in_file')])]) workflow.connect( [(mri_convert_ROIs, thalamus2precuneus2cortex_ROIs, [("out_file", "in_file")])]) workflow.connect( [(FreeSurferSource, mri_convert_Ribbon, [(('ribbon', select_ribbon), 'in_file')])]) if auto_reorient: workflow.connect( [(mri_convert_Ribbon, reorientRibbon, [('out_file', 'in_file')])]) workflow.connect( [(reorientRibbon, make_termination_mask, [('out_file', 'in_file')])]) else: workflow.connect( [(mri_convert_Ribbon, make_termination_mask, [('out_file', 'in_file')])]) if auto_reorient: workflow.connect( [(reorientBrain, fast_seg_T1, [('out_file', 'in_files')])]) else: workflow.connect( [(mri_convert_Brain, fast_seg_T1, [('out_file', 'in_files')])]) workflow.connect( [(inputnode, fast_seg_T1, [("subject_id", "out_basename")])]) workflow.connect([(fast_seg_T1, fix_termination_mask, [(('tissue_class_files', select_CSF), 'in_file')])]) workflow.connect([(fast_seg_T1, fix_wm_mask, [(('tissue_class_files', select_WM), 'in_file')])]) workflow.connect( [(make_termination_mask, fix_termination_mask, [('out_file', 'operand_files')])]) workflow.connect( [(make_wm_mask, fix_wm_mask, [('out_file', 'operand_files')])]) workflow.connect(inputnode, 'dwi', nonlinfit_node, 'dwi') workflow.connect(inputnode, 'subject_id', nonlinfit_node, 'base_name') workflow.connect(inputnode, 'bvecs', nonlinfit_node, 'bvecs') workflow.connect(inputnode, 'bvals', nonlinfit_node, 'bvals') if reg_pet_T1: workflow.connect([(inputnode, reg_pet_T1, [("fdgpet", "in_file")])]) if auto_reorient: workflow.connect( [(reorientBrain, reg_pet_T1, [("out_file", "reference")])]) workflow.connect( [(reorientROIs, reslice_fdgpet, [("out_file", "reslice_like")])]) else: workflow.connect( [(mri_convert_Brain, reg_pet_T1, [("out_file", "reference")])]) workflow.connect( [(mri_convert_ROIs, reslice_fdgpet, [("out_file", "reslice_like")])]) workflow.connect( [(reg_pet_T1, reslice_fdgpet, [("out_file", "in_file")])]) else: workflow.connect([(inputnode, reslice_fdgpet, [("fdgpet", "in_file")])]) if auto_reorient: workflow.connect( [(reorientROIs, reslice_fdgpet, [("out_file", "reslice_like")])]) else: workflow.connect( [(mri_convert_ROIs, reslice_fdgpet, [("out_file", "reslice_like")])]) workflow.connect([(nonlinfit_node, median3d, [("binary_mask", "in_file")])]) workflow.connect( [(median3d, erode_mask_firstpass, [("out_file", "in_file")])]) workflow.connect( [(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])]) workflow.connect([(nonlinfit_node, MRmult_merge, [("FA", "in1")])]) workflow.connect( [(erode_mask_secondpass, MRmult_merge, [("out_file", "in2")])]) workflow.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])]) workflow.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])]) workflow.connect([(nonlinfit_node, threshold_mode, [("mode", "in_file")])]) workflow.connect([(threshold_mode, MultFAbyMode_merge, [("out_file", "in1")])]) workflow.connect([(threshold_FA, MultFAbyMode_merge, [("out_file", "in2")])]) workflow.connect([(MultFAbyMode_merge, MultFAbyMode, [("out", "in_files")])]) workflow.connect([(inputnode, MultFAbyMode, [(('subject_id', add_subj_name_to_sfmask), 'out_filename')])]) workflow.connect([(inputnode, reslice_fdgpet, [(('subject_id', add_subj_name_to_fdgpet), 'out_file')])]) workflow.connect([(inputnode, make_wm_mask, [(('subject_id', add_subj_name_to_wmmask), 'out_filename')])]) workflow.connect([(inputnode, fix_wm_mask, [(('subject_id', add_subj_name_to_wmmask), 'out_file')])]) workflow.connect([(inputnode, fix_termination_mask, [(('subject_id', add_subj_name_to_termmask), 'out_file')])]) workflow.connect([(inputnode, thalamus2precuneus2cortex_ROIs, [(('subject_id', add_subj_name_to_rois), 'out_filename')])]) if auto_reorient: workflow.connect([(inputnode, reorientT1, [(('subject_id', add_subj_name_to_T1), 'out_file')])]) workflow.connect([(inputnode, reorientBrain, [(('subject_id', add_subj_name_to_T1brain), 'out_file')])]) else: workflow.connect([(inputnode, mri_convert_T1, [(('subject_id', add_subj_name_to_T1), 'out_file')])]) workflow.connect([(inputnode, mri_convert_Brain, [(('subject_id', add_subj_name_to_T1brain), 'out_file')])]) output_fields = ["single_fiber_mask", "fa", "rgb_fa", "md", "t1", "t1_brain", "wm_mask", "term_mask", "fdgpet", "rois","mode", "tissue_class_files", "probability_maps"] outputnode = pe.Node( interface=util.IdentityInterface(fields=output_fields), name="outputnode") workflow.connect([(fast_seg_T1, outputnode, [("tissue_class_files", "tissue_class_files")])]) workflow.connect([(fast_seg_T1, outputnode, [("probability_maps", "probability_maps")])]) workflow.connect([ (nonlinfit_node, outputnode, [("FA", "fa")]), (nonlinfit_node, outputnode, [("rgb_fa", "rgb_fa")]), (nonlinfit_node, outputnode, [("MD", "md")]), (nonlinfit_node, outputnode, [("mode", "mode")]), (MultFAbyMode, outputnode, [("out_file", "single_fiber_mask")]), (fix_wm_mask, outputnode, [("out_file", "wm_mask")]), (fix_termination_mask, outputnode, [("out_file", "term_mask")]), (reslice_fdgpet, outputnode, [("out_file", "fdgpet")]), (thalamus2precuneus2cortex_ROIs, outputnode, [("out_file", "rois")]), ]) if auto_reorient: workflow.connect([ (reorientBrain, outputnode, [("out_file", "t1_brain")]), (reorientT1, outputnode, [("out_file", "t1")]), ]) else: workflow.connect([ (mri_convert_Brain, outputnode, [("out_file", "t1_brain")]), (mri_convert_T1, outputnode, [("out_file", "t1")]), ]) return workflow
def coreg_without_resample(name="highres_coreg"): inputnode = pe.Node(interface=util.IdentityInterface( fields=["fixed_image", "moving_image", "interp"]), name="inputnode") outputnode = pe.Node(interface=util.IdentityInterface(fields=[ "out_file", "lowres_matrix_file", "highres_matrix_file", "resampled_fixed_image" ]), name="outputnode") coregister_moving_to_fixed = pe.Node(interface=fsl.FLIRT(dof=12), name='coregister_moving_to_fixed') resample_fixed_to_moving = pe.Node(interface=fs.MRIConvert(), name='resample_fixed_to_moving') rewrite_mat_interface = util.Function( input_names=[ "in_matrix", "orig_img", "target_img", "shape", "vox_size" ], output_names=["out_image", "out_matrix_file"], function=rewrite_mat_for_applyxfm) fix_FOV_in_matrix = pe.Node(interface=rewrite_mat_interface, name='fix_FOV_in_matrix') apply_fixed_matrix = pe.Node(interface=fsl.ApplyXfm(), name='apply_fixed_matrix') final_rigid_reg_to_fixed = pe.Node(interface=fsl.FLIRT(dof=6), name='final_rigid_reg_to_fixed') create_highres_xfm = pe.Node(interface=fsl.ConvertXFM(), name='create_highres_xfm') create_highres_xfm.inputs.concat_xfm = True workflow = pe.Workflow(name=name) workflow.connect([(inputnode, coregister_moving_to_fixed, [("moving_image", "in_file")])]) workflow.connect([(inputnode, coregister_moving_to_fixed, [("fixed_image", "reference")])]) workflow.connect([(coregister_moving_to_fixed, fix_FOV_in_matrix, [("out_matrix_file", "in_matrix")])]) workflow.connect([(inputnode, fix_FOV_in_matrix, [("moving_image", "orig_img")])]) workflow.connect([(inputnode, fix_FOV_in_matrix, [("fixed_image", "target_img")])]) workflow.connect([(inputnode, apply_fixed_matrix, [("moving_image", "in_file")])]) workflow.connect([(inputnode, apply_fixed_matrix, [("interp", "interp")])]) workflow.connect([(fix_FOV_in_matrix, apply_fixed_matrix, [("out_matrix_file", "in_matrix_file")])]) workflow.connect([(fix_FOV_in_matrix, apply_fixed_matrix, [("out_image", "reference")])]) workflow.connect([(inputnode, resample_fixed_to_moving, [('fixed_image', 'in_file')])]) workflow.connect([(inputnode, resample_fixed_to_moving, [('moving_image', 'reslice_like')])]) workflow.connect([(resample_fixed_to_moving, final_rigid_reg_to_fixed, [('out_file', 'reference')])]) workflow.connect([(apply_fixed_matrix, final_rigid_reg_to_fixed, [('out_file', 'in_file')])]) workflow.connect([(inputnode, final_rigid_reg_to_fixed, [('interp', 'interp')])]) workflow.connect([(final_rigid_reg_to_fixed, create_highres_xfm, [('out_matrix_file', 'in_file2')])]) workflow.connect([(fix_FOV_in_matrix, create_highres_xfm, [('out_matrix_file', 'in_file')])]) workflow.connect([(coregister_moving_to_fixed, outputnode, [('out_matrix_file', 'lowres_matrix_file')])]) workflow.connect([(create_highres_xfm, outputnode, [('out_file', 'highres_matrix_file')])]) workflow.connect([(resample_fixed_to_moving, outputnode, [('out_file', 'resampled_fixed_image')])]) workflow.connect([(final_rigid_reg_to_fixed, outputnode, [('out_file', 'out_file')])]) return workflow
def create_precoth_pipeline_step2(name="precoth_step2", tractography_type='probabilistic'): inputnode = pe.Node( interface=util.IdentityInterface(fields=["subjects_dir", "subject_id", "dwi", "bvecs", "bvals", "fdgpet", "dose", "weight", "delay", "glycemie", "scan_time", "single_fiber_mask", "fa", "rgb_fa", "md", "t1_brain", "t1", "wm_mask", "term_mask", "rois", ]), name="inputnode") coregister = pe.Node(interface=fsl.FLIRT(dof=12), name = 'coregister') coregister.inputs.cost = ('normmi') invertxfm = pe.Node(interface=fsl.ConvertXFM(), name = 'invertxfm') invertxfm.inputs.invert_xfm = True WM_to_FA = pe.Node(interface=fsl.ApplyXfm(), name = 'WM_to_FA') WM_to_FA.inputs.interp = 'nearestneighbour' TermMask_to_FA = WM_to_FA.clone("TermMask_to_FA") rgb_fa_t1space = pe.Node(interface=fsl.ApplyXfm(), name = 'rgb_fa_t1space') md_to_T1 = pe.Node(interface=fsl.ApplyXfm(), name = 'md_to_T1') t1_dtispace = pe.Node(interface=fsl.ApplyXfm(), name = 't1_dtispace') fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix') fsl2mrtrix.inputs.invert_y = True fdgpet_regions = pe.Node(interface=RegionalValues(), name='fdgpet_regions') compute_cmr_glc_interface = util.Function(input_names=["in_file", "dose", "weight", "delay", "glycemie", "scan_time"], output_names=["out_file"], function=CMR_glucose) compute_cmr_glc = pe.Node(interface=compute_cmr_glc_interface, name='compute_cmr_glc') csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') if tractography_type == 'probabilistic': CSDstreamtrack = pe.Node( interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack( ), name='CSDstreamtrack') else: CSDstreamtrack = pe.Node( interface=mrtrix.SphericallyDeconvolutedStreamlineTrack(), name='CSDstreamtrack') CSDstreamtrack.inputs.minimum_tract_length = 50 CSDstreamtrack.inputs.desired_number_of_tracks = 10000 tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk') write_precoth_data_interface = util.Function(input_names=["dwi_network_file", "fdg_stats_file", "subject_id"], output_names=["out_file"], function=summarize_precoth) write_csv_data = pe.Node( interface=write_precoth_data_interface, name='write_csv_data') thalamus2precuneus2cortex = pe.Node( interface=cmtk.CreateMatrix(), name="thalamus2precuneus2cortex") thalamus2precuneus2cortex.inputs.count_region_intersections = True workflow = pe.Workflow(name=name) workflow.base_output_dir = name workflow.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"), ("bvals", "bval_file")])]) workflow.connect([(inputnode, fdgpet_regions, [("rois", "segmentation_file")])]) workflow.connect([(inputnode, compute_cmr_glc, [("fdgpet", "in_file")])]) workflow.connect([(inputnode, compute_cmr_glc, [("dose", "dose")])]) workflow.connect([(inputnode, compute_cmr_glc, [("weight", "weight")])]) workflow.connect([(inputnode, compute_cmr_glc, [("delay", "delay")])]) workflow.connect([(inputnode, compute_cmr_glc, [("glycemie", "glycemie")])]) workflow.connect([(inputnode, compute_cmr_glc, [("scan_time", "scan_time")])]) workflow.connect([(compute_cmr_glc, fdgpet_regions, [("out_file", "in_files")])]) workflow.connect([(inputnode, coregister,[("fa","in_file")])]) workflow.connect([(inputnode, coregister,[('wm_mask','reference')])]) workflow.connect([(inputnode, tck2trk,[("fa","image_file")])]) workflow.connect([(inputnode, tck2trk,[("wm_mask","registration_image_file")])]) workflow.connect([(coregister, tck2trk,[("out_matrix_file","matrix_file")])]) workflow.connect([(coregister, invertxfm,[("out_matrix_file","in_file")])]) workflow.connect([(inputnode, t1_dtispace,[("t1","in_file")])]) workflow.connect([(invertxfm, t1_dtispace,[("out_file","in_matrix_file")])]) workflow.connect([(inputnode, t1_dtispace,[("fa","reference")])]) workflow.connect([(inputnode, rgb_fa_t1space,[("rgb_fa","in_file")])]) workflow.connect([(coregister, rgb_fa_t1space,[("out_matrix_file","in_matrix_file")])]) workflow.connect([(inputnode, rgb_fa_t1space,[('wm_mask','reference')])]) workflow.connect([(inputnode, md_to_T1,[("md","in_file")])]) workflow.connect([(coregister, md_to_T1,[("out_matrix_file","in_matrix_file")])]) workflow.connect([(inputnode, md_to_T1,[('wm_mask','reference')])]) workflow.connect([(invertxfm, WM_to_FA,[("out_file","in_matrix_file")])]) workflow.connect([(inputnode, WM_to_FA,[("wm_mask","in_file")])]) workflow.connect([(inputnode, WM_to_FA,[("fa","reference")])]) workflow.connect([(invertxfm, TermMask_to_FA,[("out_file","in_matrix_file")])]) workflow.connect([(inputnode, TermMask_to_FA,[("term_mask","in_file")])]) workflow.connect([(inputnode, TermMask_to_FA,[("fa","reference")])]) workflow.connect([(inputnode, estimateresponse, [("single_fiber_mask", "mask_image")])]) workflow.connect([(inputnode, estimateresponse, [("dwi", "in_file")])]) workflow.connect( [(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])]) workflow.connect([(inputnode, csdeconv, [("dwi", "in_file")])]) #workflow.connect( # [(TermMask_to_FA, csdeconv, [("out_file", "mask_image")])]) workflow.connect( [(estimateresponse, csdeconv, [("response", "response_file")])]) workflow.connect( [(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")])]) workflow.connect( [(WM_to_FA, CSDstreamtrack, [("out_file", "seed_file")])]) workflow.connect( [(TermMask_to_FA, CSDstreamtrack, [("out_file", "mask_file")])]) workflow.connect( [(csdeconv, CSDstreamtrack, [("spherical_harmonics_image", "in_file")])]) workflow.connect([(CSDstreamtrack, tck2trk, [("tracked", "in_file")])]) workflow.connect( [(tck2trk, thalamus2precuneus2cortex, [("out_file", "tract_file")])]) workflow.connect( [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_file")])]) workflow.connect( [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_mat_file")])]) workflow.connect( [(inputnode, thalamus2precuneus2cortex, [("rois", "roi_file")])]) workflow.connect( [(thalamus2precuneus2cortex, fdgpet_regions, [("intersection_matrix_file", "resolution_network_file")])]) workflow.connect( [(inputnode, write_csv_data, [("subject_id", "subject_id")])]) workflow.connect( [(fdgpet_regions, write_csv_data, [("stats_file", "fdg_stats_file")])]) workflow.connect( [(thalamus2precuneus2cortex, write_csv_data, [("intersection_matrix_file", "dwi_network_file")])]) output_fields = ["csdeconv", "tracts_tck", "summary", "filtered_tractographies", "matrix_file", "connectome", "CMR_nodes", "cmr_glucose", "fiber_labels_noorphans", "fiber_length_file", "fiber_label_file", "fa_t1space", "rgb_fa_t1space", "md_t1space", "fa_t1xform", "t1_dtispace", "intersection_matrix_mat_file", "dti_stats"] outputnode = pe.Node( interface=util.IdentityInterface(fields=output_fields), name="outputnode") workflow.connect( [(CSDstreamtrack, outputnode, [("tracked", "tracts_tck")]), (csdeconv, outputnode, [("spherical_harmonics_image", "csdeconv")]), (coregister, outputnode, [("out_file", "fa_t1space")]), (rgb_fa_t1space, outputnode, [("out_file", "rgb_fa_t1space")]), (md_to_T1, outputnode, [("out_file", "md_t1space")]), (t1_dtispace, outputnode, [("out_file", "t1_dtispace")]), (coregister, outputnode, [("out_matrix_file", "fa_t1xform")]), (thalamus2precuneus2cortex, outputnode, [("filtered_tractographies", "filtered_tractographies")]), (thalamus2precuneus2cortex, outputnode, [("matrix_file", "connectome")]), (thalamus2precuneus2cortex, outputnode, [("fiber_labels_noorphans", "fiber_labels_noorphans")]), (thalamus2precuneus2cortex, outputnode, [("fiber_length_file", "fiber_length_file")]), (thalamus2precuneus2cortex, outputnode, [("fiber_label_file", "fiber_label_file")]), (thalamus2precuneus2cortex, outputnode, [("intersection_matrix_mat_file", "intersection_matrix_mat_file")]), (thalamus2precuneus2cortex, outputnode, [("stats_file", "dti_stats")]), (fdgpet_regions, outputnode, [("networks", "CMR_nodes")]), (write_csv_data, outputnode, [("out_file", "summary")]), (compute_cmr_glc, outputnode, [("out_file", "cmr_glucose")]), ]) return workflow
def convert2epi(file2transform, reg_dir, out_dir=None, interpolation='trilinear', suffix='epi'): """ Transforms a nifti from mni152 (2mm) to EPI (native) format. Assuming that reg_dir is a directory with transformation-files (warps) including standard2example_func warps, this function uses nipype's fsl interface to flirt a nifti to EPI format. Parameters ---------- file2transform : str or list Absolute path(s) to nifti file(s) that needs to be transformed reg_dir : str Absolute path to registration directory with warps out_dir : str Absolute path to desired out directory. Default is same directory as the to-be transformed file. interpolation : str Interpolation used by flirt. Default is 'trilinear'. Returns ------- out_all : list Absolute path(s) to newly transformed file(s). """ if type(file2transform) == str: file2transform = [file2transform] out_all = [] for f in file2transform: if out_dir is None: out_dir = op.dirname(f) if suffix is not None: out_name = op.basename(f).split('.')[0] + '_%s.nii.gz' % suffix else: out_name = op.basename(f) out_file = op.join(out_dir, out_name) if op.exists(out_file): out_all.append(out_file) continue if not op.isdir(out_dir): os.makedirs(out_dir) if not op.isdir(out_dir): os.makedirs(out_dir) out_matrix_file = op.join(op.dirname(out_file), 'tmp_flirt') ref_file = op.join(reg_dir, 'example_func.nii.gz') matrix_file = op.join(reg_dir, 'standard2example_func.mat') apply_xfm = fsl.ApplyXfm() apply_xfm.inputs.in_file = f apply_xfm.inputs.reference = ref_file apply_xfm.inputs.in_matrix_file = matrix_file apply_xfm.inputs.out_matrix_file = out_matrix_file apply_xfm.interp = interpolation apply_xfm.inputs.out_file = out_file apply_xfm.inputs.apply_xfm = True apply_xfm.run() if op.exists(out_matrix_file): os.remove(out_matrix_file) out_all.append(out_file) if len(out_all) == 1: out_all = out_all[0] return out_all
pipe = pe.Workflow('testworkflow') pipe.base_dir = '/opt/shared2/nipype-test/' # node for gems anatproc = wf.bet.ratbet.anatproc() anatproc.inputs.inputspec.in_file = in_gems # dti2anat dti2anat = wf.bet.ratbet.reg2anat(onlyResample=False) dti2anat.inputs.inputspec.in_file = in_dti # fslroi -> 3D # node for mask resampling resample = pe.MapNode(interface=fsl.ApplyXfm(), name='resample_mask', iterfield=['in_file', 'in_matrix_file']) resample.inputs.reference = in_dti # fslroi -> 3D # node for dti dti = wf.dti.ratdti.ratdti() dti.inputs.inputspec.in_file = in_dti dti.inputs.inputspec.in_bvals = in_bvals dti.inputs.inputspec.in_bvecs = in_bvecs # data sink to save brain extracted image and mask datasink = pe.Node(nio.DataSink(), name="sinker") datasink.base_directory = "/opt/shared2/nipype-test/dti_2015052601_m0_ctr_a4_11/" # filebase(in_gems)
def create_epidewarp_pipeline(name='epidewarp', fieldmap_registration=False): """ Replaces the epidewarp.fsl script (http://www.nmr.mgh.harvard.edu/~greve/fbirn/b0/epidewarp.fsl) for susceptibility distortion correction of dMRI & fMRI acquired with EPI sequences and the fieldmap information (Jezzard et al., 1995) using FSL's FUGUE. The registration to the (warped) fieldmap (strictly following the original script) is available using fieldmap_registration=True. .. warning:: This workflow makes use of ``epidewarp.fsl`` a script of FSL deprecated long time ago. The use of this workflow is not recommended, use :func:`nipype.workflows.dmri.preprocess.epi.sdc_fmb` instead. Example ------- >>> nipype_epicorrect = create_epidewarp_pipeline('nipype_epidewarp', fieldmap_registration=False) >>> nipype_epicorrect.inputs.inputnode.in_file = 'diffusion.nii' >>> nipype_epicorrect.inputs.inputnode.fieldmap_mag = 'magnitude.nii' >>> nipype_epicorrect.inputs.inputnode.fieldmap_pha = 'phase.nii' >>> nipype_epicorrect.inputs.inputnode.te_diff = 2.46 >>> nipype_epicorrect.inputs.inputnode.epi_echospacing = 0.77 >>> nipype_epicorrect.inputs.inputnode.epi_rev_encoding = False >>> nipype_epicorrect.inputs.inputnode.ref_num = 0 >>> nipype_epicorrect.inputs.inputnode.pi_accel_factor = 1.0 >>> nipype_epicorrect.run() # doctest: +SKIP Inputs:: inputnode.in_file - The volume acquired with EPI sequence inputnode.fieldmap_mag - The magnitude of the fieldmap inputnode.fieldmap_pha - The phase difference of the fieldmap inputnode.te_diff - Time difference between TE in ms. inputnode.epi_echospacing - The echo spacing (aka dwell time) in the EPI sequence inputnode.epi_ph_encoding_dir - The phase encoding direction in EPI acquisition (default y) inputnode.epi_rev_encoding - True if it is acquired with reverse encoding inputnode.pi_accel_factor - Acceleration factor used for EPI parallel imaging (GRAPPA) inputnode.vsm_sigma - Sigma value of the gaussian smoothing filter applied to the vsm (voxel shift map) inputnode.ref_num - The reference volume (B=0 in dMRI or a central frame in fMRI) Outputs:: outputnode.epi_corrected Optional arguments:: fieldmap_registration - True if registration to fieldmap should be done (default False) """ warnings.warn(('This workflow reproduces a deprecated FSL script.'), DeprecationWarning) inputnode = pe.Node(niu.IdentityInterface(fields=[ 'in_file', 'fieldmap_mag', 'fieldmap_pha', 'te_diff', 'epi_echospacing', 'epi_ph_encoding_dir', 'epi_rev_encoding', 'pi_accel_factor', 'vsm_sigma', 'ref_num', 'unwarp_direction' ]), name='inputnode') pipeline = pe.Workflow(name=name) # Keep first frame from magnitude select_mag = pe.Node(fsl.utils.ExtractROI(t_size=1, t_min=0), name='select_magnitude') # mask_brain mask_mag = pe.Node(fsl.BET(mask=True), name='mask_magnitude') mask_mag_dil = pe.Node(niu.Function(input_names=['in_file'], output_names=['out_file'], function=_dilate_mask), name='mask_dilate') # Compute dwell time dwell_time = pe.Node(niu.Function( input_names=['dwell_time', 'pi_factor', 'is_reverse_encoding'], output_names=['dwell_time'], function=_compute_dwelltime), name='dwell_time') # Normalize phase diff to be [-pi, pi) norm_pha = pe.Node(niu.Function(input_names=['in_file'], output_names=['out_file'], function=_prepare_phasediff), name='normalize_phasediff') # Execute FSL PRELUDE: prelude -p %s -a %s -o %s -f -v -m %s prelude = pe.Node(fsl.PRELUDE(process3d=True), name='phase_unwrap') fill_phase = pe.Node(niu.Function(input_names=['in_file'], output_names=['out_file'], function=_fill_phase), name='fill_phasediff') # to assure that vsm is same dimension as mag. The input only affects the output dimension. # The content of the input has no effect on the vsm. The de-warped mag volume is # meaningless and will be thrown away # fugue -i %s -u %s -p %s --dwell=%s --asym=%s --mask=%s --saveshift=%s % # ( mag_name, magdw_name, ph_name, esp, tediff, mask_name, vsmmag_name) vsm = pe.Node(fsl.FUGUE(save_shift=True), name='generate_vsm') vsm_mean = pe.Node(niu.Function( input_names=['in_file', 'mask_file', 'in_unwarped'], output_names=['out_file'], function=_vsm_remove_mean), name='vsm_mean_shift') # fugue_epi dwi_split = pe.Node(niu.Function(input_names=['in_file'], output_names=['out_files'], function=_split_dwi), name='dwi_split') # 'fugue -i %s -u %s --loadshift=%s --mask=%s' % ( vol_name, out_vol_name, vsm_name, mask_name ) dwi_applyxfm = pe.MapNode(fsl.FUGUE(icorr=True, save_shift=False), iterfield=['in_file'], name='dwi_fugue') # Merge back all volumes dwi_merge = pe.Node(fsl.utils.Merge(dimension='t'), name='dwi_merge') outputnode = pe.Node(niu.IdentityInterface(fields=['epi_corrected']), name='outputnode') pipeline.connect([ (inputnode, dwell_time, [('epi_echospacing', 'dwell_time'), ('pi_accel_factor', 'pi_factor'), ('epi_rev_encoding', 'is_reverse_encoding')]), (inputnode, select_mag, [('fieldmap_mag', 'in_file')]), (inputnode, norm_pha, [('fieldmap_pha', 'in_file')]), (select_mag, mask_mag, [('roi_file', 'in_file')]), (mask_mag, mask_mag_dil, [('mask_file', 'in_file')]), (select_mag, prelude, [('roi_file', 'magnitude_file')]), (norm_pha, prelude, [('out_file', 'phase_file')]), (mask_mag_dil, prelude, [('out_file', 'mask_file')]), (prelude, fill_phase, [('unwrapped_phase_file', 'in_file')]), (inputnode, vsm, [('fieldmap_mag', 'in_file')]), (fill_phase, vsm, [('out_file', 'phasemap_in_file')]), (inputnode, vsm, [(('te_diff', _ms2sec), 'asym_se_time'), ('vsm_sigma', 'smooth2d')]), (dwell_time, vsm, [(('dwell_time', _ms2sec), 'dwell_time')]), (mask_mag_dil, vsm, [('out_file', 'mask_file')]), (mask_mag_dil, vsm_mean, [('out_file', 'mask_file')]), (vsm, vsm_mean, [('unwarped_file', 'in_unwarped'), ('shift_out_file', 'in_file')]), (inputnode, dwi_split, [('in_file', 'in_file')]), (dwi_split, dwi_applyxfm, [('out_files', 'in_file')]), (dwi_applyxfm, dwi_merge, [('unwarped_file', 'in_files')]), (dwi_merge, outputnode, [('merged_file', 'epi_corrected')]) ]) if fieldmap_registration: """ Register magfw to example epi. There are some parameters here that may need to be tweaked. Should probably strip the mag Pre-condition: forward warp the mag in order to reg with func. What does mask do here? """ # Select reference volume from EPI (B0 in dMRI and a middle frame in # fMRI) select_epi = pe.Node(fsl.utils.ExtractROI(t_size=1), name='select_epi') # fugue -i %s -w %s --loadshift=%s --mask=%s % ( mag_name, magfw_name, # vsmmag_name, mask_name ), log ) # Forward Map vsm_fwd = pe.Node(fsl.FUGUE(forward_warping=True), name='vsm_fwd') vsm_reg = pe.Node(fsl.FLIRT(bins=256, cost='corratio', dof=6, interp='spline', searchr_x=[-10, 10], searchr_y=[-10, 10], searchr_z=[-10, 10]), name='vsm_registration') # 'flirt -in %s -ref %s -out %s -init %s -applyxfm' % ( vsmmag_name, ref_epi, vsmmag_name, magfw_mat_out ) vsm_applyxfm = pe.Node(fsl.ApplyXfm(interp='spline'), name='vsm_apply_xfm') # 'flirt -in %s -ref %s -out %s -init %s -applyxfm' % ( mask_name, ref_epi, mask_name, magfw_mat_out ) msk_applyxfm = pe.Node(fsl.ApplyXfm(interp='nearestneighbour'), name='msk_apply_xfm') pipeline.connect([ (inputnode, select_epi, [('in_file', 'in_file'), ('ref_num', 't_min')]), (select_epi, vsm_reg, [('roi_file', 'reference')]), (vsm, vsm_fwd, [('shift_out_file', 'shift_in_file')]), (mask_mag_dil, vsm_fwd, [('out_file', 'mask_file')]), (inputnode, vsm_fwd, [('fieldmap_mag', 'in_file')]), (vsm_fwd, vsm_reg, [('warped_file', 'in_file')]), (vsm_reg, msk_applyxfm, [('out_matrix_file', 'in_matrix_file')]), (select_epi, msk_applyxfm, [('roi_file', 'reference')]), (mask_mag_dil, msk_applyxfm, [('out_file', 'in_file')]), (vsm_reg, vsm_applyxfm, [('out_matrix_file', 'in_matrix_file')]), (select_epi, vsm_applyxfm, [('roi_file', 'reference')]), (vsm_mean, vsm_applyxfm, [('out_file', 'in_file')]), (msk_applyxfm, dwi_applyxfm, [('out_file', 'mask_file')]), (vsm_applyxfm, dwi_applyxfm, [('out_file', 'shift_in_file')]) ]) else: pipeline.connect([ (mask_mag_dil, dwi_applyxfm, [('out_file', 'mask_file')]), (vsm_mean, dwi_applyxfm, [('out_file', 'shift_in_file')]) ]) return pipeline
def freesufer_create_tissues(population, workspace_dir, freesurfer_dir): #1. get aseg files #2. convert asegs to niftis #3. swaps dims to SPM orientation #4. register freesurfer files to spm space #5. create tissue masks from labels #subject = population[subject_index] count = 0 for subject in population: count += 1 print '========================================================================================' print '%s- Grabbing FREESURFER reconall for subject %s_%s' % ( count, subject, workspace_dir[-1]) subject_dir = os.path.join(workspace_dir, subject) anatomical_dir = os.path.join(subject_dir, 'anatomical_original') anatomical_file = os.path.join(anatomical_dir, 'ANATOMICAL.nii') # check if the file exists if os.path.isfile(anatomical_file): print '..' if os.path.isfile( os.path.join(freesurfer_dir, subject, 'mri', 'aseg.mgz')): print 'Brain already segmented .......................... moving on' #print 'check data here ---> %s' %(os.path.join(freesurfer_dir, subject)) else: print 'Run reconall for GTS_control_%s and then come back to me' % subject else: print 'anatomical file for subject %s not found' % subject '============================================================================================' ' Convert Freesurfer MGZs to Nifti' '============================================================================================' seg_dir = os.path.join(freesurfer_dir, subject) t1_mgz = os.path.join(seg_dir, 'mri', 'T1.mgz') # T1 image in freesurfer orientation aseg_mgz = os.path.join(seg_dir, 'mri', 'aseg.mgz') # freesurfer segmentation file if os.path.isfile( os.path.join(workspace_dir, subject, 'segmentation_freesurfer', 'aseg.nii')): print 'MGZs already converted to NIFTI .................. moving on' else: print 'converting Freesurfer MGZ files to NIFTI......' try: os.makedirs( os.path.join(workspace_dir, subject, 'segmentation_freesurfer')) except OSError: out_fs_dir = str( os.path.join(workspace_dir, subject, 'segmentation_freesurfer')) out_fs_dir = str( os.path.join(workspace_dir, subject, 'segmentation_freesurfer')) #convert T1 to nifti anat2nii = fs.MRIConvert() anat2nii.inputs.in_file = t1_mgz anat2nii.inputs.out_file = '%s/T1.nii' % out_fs_dir anat2nii.inputs.out_type = 'nii' anat2nii.run() #convert seg to nifti seg2nii = fs.MRIConvert() seg2nii.inputs.in_file = aseg_mgz seg2nii.inputs.out_file = '%s/aseg.nii' % out_fs_dir seg2nii.inputs.out_type = 'nii' seg2nii.run() '============================================================================================' ' SWAP dims to SPM orientation -- AP IS LR -- ' '============================================================================================' out_fs_dir = str( os.path.join(workspace_dir, subject, 'segmentation_freesurfer')) if os.path.isfile(os.path.join(out_fs_dir, 'aseg_swapdim.nii.gz')): print 'Dimensions already swapped ....................... moving on' else: print 'Swapping dimensions of freesurfer files to AIL' fs_t1_nii = os.path.join(out_fs_dir, 'T1.nii') fs_aseg_nii = os.path.join(out_fs_dir, 'aseg.nii') swapdim_t1 = fsl.SwapDimensions() swapdim_t1.inputs.in_file = fs_t1_nii swapdim_t1.inputs.new_dims = ('AP', 'IS', 'LR') swapdim_t1.inputs.out_file = '%s/T1_swapdim.nii.gz' % out_fs_dir swapdim_t1.inputs.output_type = 'NIFTI_GZ' swapdim_t1.run() swapdim_aseg = fsl.SwapDimensions() swapdim_aseg.inputs.in_file = fs_aseg_nii swapdim_aseg.inputs.new_dims = ('AP', 'IS', 'LR') swapdim_aseg.inputs.out_file = '%s/aseg_swapdim.nii.gz' % out_fs_dir swapdim_aseg.inputs.output_type = 'NIFTI_GZ' swapdim_aseg.run() '============================================================================================' ' Registration ' '============================================================================================' if os.path.isfile( os.path.join(out_fs_dir, 'freesurfer_aseg_2spm.nii.gz')): print 'Freesurfer to SPM affine already calculated....... moving on' else: print 'Registring freesurfer affines to SPM space ..........' anat_spm = os.path.join(workspace_dir, subject, 'anatomical_original', 'ANATOMICAL.nii') fs_t1_swapdim = os.path.join(out_fs_dir, 'T1_swapdim.nii.gz') fs_aseg_swapdim = os.path.join(out_fs_dir, 'aseg_swapdim.nii.gz') #register freesurfer T1 to SPM space anat_flirt = fsl.FLIRT() anat_flirt.inputs.in_file = fs_t1_swapdim anat_flirt.inputs.reference = anat_spm anat_flirt.inputs.output_type = "NIFTI" anat_flirt.inputs.bins = 256 anat_flirt.inputs.cost = 'mutualinfo' anat_flirt.inputs.searchr_x = [-90, 90] anat_flirt.inputs.searchr_y = [-90, 90] anat_flirt.inputs.searchr_z = [-90, 90] #anat_flirt.inputs.dof = 6 anat_flirt.inputs.interp = 'nearestneighbour' anat_flirt.inputs.out_file = '%s/freesurfer_T1_2spm.nii' % out_fs_dir anat_flirt.inputs.out_matrix_file = '%s/freesurfer_T1_2spm_xfm.mat' % out_fs_dir anat_flirt.run() # Apply fs2spm xfm to aseg file fs2spm_xfm = '%s/freesurfer_T1_2spm_xfm.mat' % out_fs_dir aseg_applyxfm = fsl.ApplyXfm() aseg_applyxfm.inputs.in_file = fs_aseg_swapdim aseg_applyxfm.inputs.reference = anat_spm aseg_applyxfm.inputs.interp = 'nearestneighbour' aseg_applyxfm.inputs.in_matrix_file = fs2spm_xfm aseg_applyxfm.inputs.apply_xfm = True aseg_applyxfm.inputs.out_file = '%s/freesurfer_aseg_2spm.nii.gz' % out_fs_dir aseg_applyxfm.run() '============================================================================================' ' Create Tissue Masks ' '============================================================================================' if os.path.isfile(os.path.join(out_fs_dir, 'freesurfer_GM_mask.nii.gz')): print 'Tissues already extracted as nifti files.......... moving on' else: print 'Extracting Tissue classes from Labels and saving as a nifti file' aseg = str( os.path.join(workspace_dir, subject, 'segmentation_freesurfer', 'freesurfer_aseg_2spm.nii.gz')) aseg_data = nb.load(aseg).get_data() aseg_affine = nb.load(aseg).get_affine() wm_data = np.zeros(aseg_data.shape) gm_data = np.zeros(aseg_data.shape) csf_data = np.zeros(aseg_data.shape) for data, labels in zip([wm_data, gm_data, csf_data], [wm_labels, gm_labels, csf_labels]): for label in labels: data[np.where(aseg_data == label)] = 1 wm_img = nb.Nifti1Image(wm_data, aseg_affine) gm_img = nb.Nifti1Image(gm_data, aseg_affine) csf_img = nb.Nifti1Image(csf_data, aseg_affine) nb.save(wm_img, '%s/freesurfer_WM_mask.nii.gz' % out_fs_dir) nb.save(gm_img, '%s/freesurfer_GM_mask.nii.gz' % out_fs_dir) nb.save(csf_img, '%s/freesurfer_CSF_mask.nii.gz' % out_fs_dir)