def create_mgzconvert_pipeline(name='mgzconvert'): # workflow mgzconvert = Workflow(name='mgzconvert') # inputnode inputnode = Node( util.IdentityInterface(fields=['fs_subjects_dir', 'fs_subject_id']), name='inputnode') # outputnode outputnode = Node(util.IdentityInterface(fields=[ 'anat_head', 'anat_brain', 'anat_brain_mask', 'wmseg', 'wmedge' ]), name='outputnode') # import files from freesurfer fs_import = Node(interface=nio.FreeSurferSource(), name='fs_import') # convert Freesurfer T1 file to nifti head_convert = Node(fs.MRIConvert(out_type='niigz', out_file='T1.nii.gz'), name='head_convert') # create brainmask from aparc+aseg with single dilation def get_aparc_aseg(files): for name in files: if 'aparc+aseg' in name: return name # create brain by converting only freesurfer output brain_convert = Node(fs.MRIConvert(out_type='niigz', out_file='brain.nii.gz'), name='brain_convert') brain_binarize = Node(fsl.ImageMaths(op_string='-bin -fillh', out_file='T1_brain_mask.nii.gz'), name='brain_binarize') # cortical and cerebellar white matter volumes to construct wm edge # [lh cerebral wm, lh cerebellar wm, rh cerebral wm, rh cerebellar wm, brain stem] wmseg = Node(fs.Binarize(out_type='nii.gz', match=[2, 7, 41, 46, 16], binary_file='T1_brain_wmseg.nii.gz'), name='wmseg') # make edge from wmseg to visualize coregistration quality edge = Node(fsl.ApplyMask(args='-edge -bin', out_file='T1_brain_wmedge.nii.gz'), name='edge') # connections mgzconvert.connect([ (inputnode, fs_import, [('fs_subjects_dir', 'subjects_dir'), ('fs_subject_id', 'subject_id')]), (fs_import, head_convert, [('T1', 'in_file')]), (fs_import, wmseg, [(('aparc_aseg', get_aparc_aseg), 'in_file')]), (fs_import, brain_convert, [('brainmask', 'in_file')]), (wmseg, edge, [('binary_file', 'in_file'), ('binary_file', 'mask_file')]), (head_convert, outputnode, [('out_file', 'anat_head')]), (brain_convert, outputnode, [('out_file', 'anat_brain')]), (brain_convert, brain_binarize, [('out_file', 'in_file')]), (brain_binarize, outputnode, [('out_file', 'anat_brain_mask')]), (wmseg, outputnode, [('binary_file', 'wmseg')]), (edge, outputnode, [('out_file', 'wmedge')]) ]) return mgzconvert
def get_regions(name='get_regions'): import nipype.pipeline.engine as pe import nipype.interfaces.utility as niu import nipype.interfaces.io as nio import nipype.interfaces.freesurfer as fs wf = pe.Workflow(name=name) inputspec = pe.Node(niu.IdentityInterface( fields=["surf_dir", "subject_id", "surface", "reg_file", "mean"]), name='inputspec') l2v = pe.MapNode(fs.Label2Vol(), name="label2vol", iterfield=['hemi', 'annot_file']) l2v.inputs.hemi = ['lh', 'rh'] wf.connect(inputspec, 'surf_dir', l2v, "subjects_dir") wf.connect(inputspec, 'subject_id', l2v, 'subject_id') wf.connect(inputspec, "reg_file", l2v, "reg_file") wf.connect(inputspec, "mean", l2v, "template_file") fssource = pe.MapNode(nio.FreeSurferSource(), name='fssource', iterfield=['hemi']) fssource.inputs.hemi = ['lh', 'rh'] wf.connect(inputspec, 'surf_dir', fssource, "subjects_dir") wf.connect(inputspec, 'subject_id', fssource, 'subject_id') wf.connect(fssource, ('annot', pickfile), l2v, 'annot_file') bin = pe.MapNode(niu.Function( input_names=["in_file", "subject_id", "surf_dir", "hemi"], output_names=["out_files"], function=binarize_and_name), name="binarize_and_name", iterfield=['hemi', "in_file"]) wf.connect(inputspec, "subject_id", bin, "subject_id") wf.connect(inputspec, "surf_dir", bin, "surf_dir") wf.connect(l2v, "vol_label_file", bin, "in_file") bin.inputs.hemi = ['lh', 'rh'] outputspec = pe.Node(niu.IdentityInterface(fields=["ROIs"]), name='outputspec') wf.connect(bin, ("out_files", merge), outputspec, "ROIs") return wf
def create_get_T1_brainmask(name='get_T1_brainmask'): get_T1_brainmask = Workflow(name='get_T1_brainmask') # Define nodes inputnode = Node(util.IdentityInterface(fields=[ 'fs_subjects_dir', 'fs_subject_id', ]), name='inputnode') outputnode = Node( interface=util.IdentityInterface(fields=['T1', 'brain_mask']), name='outputnode') # import files from freesurfer fs_import = Node(interface=nio.FreeSurferSource(), name='fs_import') #transform to nii convert_mask = Node(interface=fs.MRIConvert(), name="convert_mask") convert_mask.inputs.out_type = "niigz" convert_T1 = Node(interface=fs.MRIConvert(), name="convert_T1") convert_T1.inputs.out_type = "niigz" #binarize brain mask (like done in Lemon_Scripts_mod/struct_preproc/mgzconvert.py) brain_binarize = Node(fsl.ImageMaths(op_string='-bin', out_file='T1_brain_mask.nii.gz'), name='brain_binarize') get_T1_brainmask.connect([ (inputnode, fs_import, [('fs_subjects_dir', 'subjects_dir'), ('fs_subject_id', 'subject_id')]), (fs_import, convert_mask, [('brainmask', 'in_file')]), (fs_import, convert_T1, [('T1', 'in_file')]), (convert_mask, brain_binarize, [('out_file', 'in_file')]), (brain_binarize, outputnode, [('out_file', 'brain_mask')]), (convert_T1, outputnode, [('out_file', 'T1')]) ]) return get_T1_brainmask
def create_custom_template(c): import nipype.pipeline.engine as pe #from nipype.interfaces.ants import BuildTemplate import nipype.interfaces.io as nio import nipype.interfaces.utility as niu import nipype.interfaces.freesurfer as fs wf = pe.Workflow(name='create_fs_masked_brains') #temp = pe.Node(BuildTemplate(parallelization=1), name='create_template') fssource = pe.Node(nio.FreeSurferSource(subjects_dir=c.surf_dir), name='fssource') infosource = pe.Node(niu.IdentityInterface(fields=["subject_id"]), name="subject_names") infosource.iterables = ("subject_id", c.subjects) wf.connect(infosource, "subject_id", fssource, "subject_id") sink = pe.Node(nio.DataSink(base_directory=c.sink_dir), name='sinker') applymask = pe.Node(fs.ApplyMask(mask_thresh=0.5), name='applymask') binarize = pe.Node(fs.Binarize(dilate=1, min=0.5, subjects_dir=c.surf_dir), name='binarize') convert = pe.Node(fs.MRIConvert(out_type='niigz'), name='convert') wf.connect(fssource, 'orig', applymask, 'in_file') wf.connect(fssource, ('aparc_aseg', pickaparc), binarize, 'in_file') wf.connect(binarize, 'binary_file', applymask, 'mask_file') wf.connect(applymask, 'out_file', convert, 'in_file') wf.connect(convert, "out_file", sink, "masked_images") def getsubs(subject_id): subs = [] subs.append(('_subject_id_%s/' % subject_id, '%s_' % subject_id)) return subs wf.connect(infosource, ("subject_id", getsubs), sink, "substitutions") #wf.connect(convert,'out_file',temp,'in_files') #wf.connect(temp,'final_template_file',sink,'custom_template.final_template_file') #wf.connect(temp,'subject_outfiles',sink,'custom_template.subject_outfiles') #wf.connect(temp,'template_files',sink,'template_files') return wf
def init_gifti_surface_wf(name="gifti_surface_wf", subjects_dir=getenv("SUBJECTS_DIR", None)): """ Build a Nipype workflow to prepare GIFTI surfaces from FreeSurfer. This workflow prepares GIFTI surfaces from a FreeSurfer subjects directory If midthickness (or graymid) surfaces do not exist, they are generated and saved to the subject directory as ``lh/rh.midthickness``. These, along with the gray/white matter boundary (``lh/rh.smoothwm``), pial sufaces (``lh/rh.pial``) and inflated surfaces (``lh/rh.inflated``) are converted to GIFTI files. Additionally, the vertex coordinates are :py:class:`recentered <smriprep.interfaces.NormalizeSurf>` to align with native T1w space. Workflow Graph .. workflow:: :graph2use: orig :simple_form: yes from niworkflows.anat.freesurfer import init_gifti_surface_wf wf = init_gifti_surface_wf(subjects_dir="/tmp") Parameters ---------- subjects_dir : str FreeSurfer's ``$SUBJECTS_DIR`` environment variable. name : str Name for the workflow hierarchy of Nipype Inputs ------ in_t1w : str original (pre-``recon-all``), reference T1w image. subject_id : str FreeSurfer subject ID Outputs ------- surfaces : list GIFTI surfaces for gray/white matter boundary, pial surface, midthickness (or graymid) surface, and inflated surfaces. surf_norm : list Normalized (re-centered) GIFTI surfaces aligned in native T1w space, corresponding to the ``surfaces`` output. fsnative_to_t1w_xfm : str LTA formatted affine transform file. """ if subjects_dir is None: raise RuntimeError("``$SUBJECTS_DIR`` must be set") workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(["in_t1w", "subject_id"]), name="inputnode") outputnode = pe.Node( niu.IdentityInterface(["surfaces", "surf_norm", "fsnative_to_t1w_xfm"]), name="outputnode", ) fssource = pe.Node( nio.FreeSurferSource(subjects_dir=subjects_dir), name="fssource", run_without_submitting=True, ) fsnative_2_t1_xfm = pe.Node(RobustRegister(auto_sens=True, est_int_scale=True), name="fsnative_2_t1_xfm") midthickness = pe.MapNode( MakeMidthickness(thickness=True, distance=0.5, out_name="midthickness"), iterfield="in_file", name="midthickness", ) save_midthickness = pe.Node( nio.DataSink(parameterization=False, base_directory=subjects_dir), name="save_midthickness", run_without_submitting=True, ) surface_list = pe.Node( niu.Merge(4, ravel_inputs=True), name="surface_list", run_without_submitting=True, ) fs_2_gii = pe.MapNode(fs.MRIsConvert(out_datatype="gii"), iterfield="in_file", name="fs_2_gii") fix_surfs = pe.MapNode(NormalizeSurf(), iterfield="in_file", name="fix_surfs") # fmt: off workflow.connect([ (inputnode, fssource, [("subject_id", "subject_id")]), (inputnode, save_midthickness, [("subject_id", "container")]), # Generate fsnative-to-T1w transform (inputnode, fsnative_2_t1_xfm, [("in_t1w", "target_file")]), (fssource, fsnative_2_t1_xfm, [("orig", "source_file")]), # Generate midthickness surfaces and save to FreeSurfer derivatives (fssource, midthickness, [("smoothwm", "in_file"), ("graymid", "graymid")]), (midthickness, save_midthickness, [("out_file", "surf.@graymid")]), # Produce valid GIFTI surface files (dense mesh) (fssource, surface_list, [ ("smoothwm", "in1"), ("pial", "in2"), ("inflated", "in3"), ]), (save_midthickness, surface_list, [("out_file", "in4")]), (surface_list, fs_2_gii, [("out", "in_file")]), (fs_2_gii, fix_surfs, [("converted", "in_file")]), (fsnative_2_t1_xfm, fix_surfs, [("out_reg_file", "transform_file")]), (fsnative_2_t1_xfm, outputnode, [("out_reg_file", "fsnative_to_t1w_xfm")]), (fix_surfs, outputnode, [("out_file", "surf_norm")]), (fs_2_gii, outputnode, [("converted", "surfaces")]), ]) # fmt: on return workflow
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 init_gifti_surface_wf(name='gifti_surface_wf'): r""" Prepare GIFTI surfaces from a FreeSurfer subjects directory. If midthickness (or graymid) surfaces do not exist, they are generated and saved to the subject directory as ``lh/rh.midthickness``. These, along with the gray/white matter boundary (``lh/rh.smoothwm``), pial sufaces (``lh/rh.pial``) and inflated surfaces (``lh/rh.inflated``) are converted to GIFTI files. Additionally, the vertex coordinates are :py:class:`recentered <smriprep.interfaces.NormalizeSurf>` to align with native T1w space. .. workflow:: :graph2use: orig :simple_form: yes from smriprep.workflows.surfaces import init_gifti_surface_wf wf = init_gifti_surface_wf() **Inputs** subjects_dir FreeSurfer SUBJECTS_DIR subject_id FreeSurfer subject ID fsnative2t1w_xfm LTA formatted affine transform file (inverse) **Outputs** surfaces GIFTI surfaces for gray/white matter boundary, pial surface, midthickness (or graymid) surface, and inflated surfaces """ workflow = Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface( ['subjects_dir', 'subject_id', 'fsnative2t1w_xfm']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface(['surfaces']), name='outputnode') get_surfaces = pe.Node(nio.FreeSurferSource(), name='get_surfaces') midthickness = pe.MapNode(MakeMidthickness(thickness=True, distance=0.5, out_name='midthickness'), iterfield='in_file', name='midthickness') save_midthickness = pe.Node(nio.DataSink(parameterization=False), name='save_midthickness') surface_list = pe.Node(niu.Merge(4, ravel_inputs=True), name='surface_list', run_without_submitting=True) fs2gii = pe.MapNode(fs.MRIsConvert(out_datatype='gii'), iterfield='in_file', name='fs2gii') fix_surfs = pe.MapNode(NormalizeSurf(), iterfield='in_file', name='fix_surfs') workflow.connect([ (inputnode, get_surfaces, [('subjects_dir', 'subjects_dir'), ('subject_id', 'subject_id')]), (inputnode, save_midthickness, [('subjects_dir', 'base_directory'), ('subject_id', 'container')]), # Generate midthickness surfaces and save to FreeSurfer derivatives (get_surfaces, midthickness, [('smoothwm', 'in_file'), ('graymid', 'graymid')]), (midthickness, save_midthickness, [('out_file', 'surf.@graymid')]), # Produce valid GIFTI surface files (dense mesh) (get_surfaces, surface_list, [('smoothwm', 'in1'), ('pial', 'in2'), ('inflated', 'in3')]), (save_midthickness, surface_list, [('out_file', 'in4')]), (surface_list, fs2gii, [('out', 'in_file')]), (fs2gii, fix_surfs, [('converted', 'in_file')]), (inputnode, fix_surfs, [('fsnative2t1w_xfm', 'transform_file')]), (fix_surfs, outputnode, [('out_file', 'surfaces')]), ]) return workflow
def init_gifti_surface_wf(name='gifti_surface_wf', subjects_dir=getenv('SUBJECTS_DIR', None)): """ This workflow prepares GIFTI surfaces from a FreeSurfer subjects directory If midthickness (or graymid) surfaces do not exist, they are generated and saved to the subject directory as ``lh/rh.midthickness``. These, along with the gray/white matter boundary (``lh/rh.smoothwm``), pial sufaces (``lh/rh.pial``) and inflated surfaces (``lh/rh.inflated``) are converted to GIFTI files. Additionally, the vertex coordinates are :py:class:`recentered <smriprep.interfaces.NormalizeSurf>` to align with native T1w space. .. workflow:: :graph2use: orig :simple_form: yes from fmriprep.workflows.anatomical import init_gifti_surface_wf wf = init_gifti_surface_wf() **Parameters** subjects_dir FreeSurfer SUBJECTS_DIR name Name for the workflow hierarchy of Nipype **Inputs** in_t1w original (pre-``recon-all``), reference T1w image. subject_id FreeSurfer subject ID **Outputs** surfaces GIFTI surfaces for gray/white matter boundary, pial surface, midthickness (or graymid) surface, and inflated surfaces. surf_norm Normalized (re-centered) GIFTI surfaces aligned in native T1w space, corresponding to the ``surfaces`` output. fsnative_to_t1w_xfm LTA formatted affine transform file. """ if subjects_dir is None: raise RuntimeError('``$SUBJECTS_DIR`` must be set') workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface( ['in_t1w', 'subject_id']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( ['surfaces', 'surf_norm', 'fsnative_to_t1w_xfm']), name='outputnode') fssource = pe.Node(nio.FreeSurferSource(subjects_dir=subjects_dir), name='fssource', run_without_submitting=True) fsnative_2_t1_xfm = pe.Node(RobustRegister(auto_sens=True, est_int_scale=True), name='fsnative_2_t1_xfm') midthickness = pe.MapNode( MakeMidthickness(thickness=True, distance=0.5, out_name='midthickness'), iterfield='in_file', name='midthickness') save_midthickness = pe.Node(nio.DataSink( parameterization=False, base_directory=subjects_dir), name='save_midthickness', run_without_submitting=True) surface_list = pe.Node(niu.Merge(4, ravel_inputs=True), name='surface_list', run_without_submitting=True) fs_2_gii = pe.MapNode(fs.MRIsConvert(out_datatype='gii'), iterfield='in_file', name='fs_2_gii') fix_surfs = pe.MapNode(NormalizeSurf(), iterfield='in_file', name='fix_surfs') workflow.connect([ (inputnode, fssource, [('subject_id', 'subject_id')]), (inputnode, save_midthickness, [('subject_id', 'container')]), # Generate fsnative-to-T1w transform (inputnode, fsnative_2_t1_xfm, [('in_t1w', 'target_file')]), (fssource, fsnative_2_t1_xfm, [('orig', 'source_file')]), # Generate midthickness surfaces and save to FreeSurfer derivatives (fssource, midthickness, [('smoothwm', 'in_file'), ('graymid', 'graymid')]), (midthickness, save_midthickness, [('out_file', 'surf.@graymid')]), # Produce valid GIFTI surface files (dense mesh) (fssource, surface_list, [('smoothwm', 'in1'), ('pial', 'in2'), ('inflated', 'in3')]), (save_midthickness, surface_list, [('out_file', 'in4')]), (surface_list, fs_2_gii, [('out', 'in_file')]), (fs_2_gii, fix_surfs, [('converted', 'in_file')]), (fsnative_2_t1_xfm, fix_surfs, [('out_reg_file', 'transform_file')]), (fsnative_2_t1_xfm, outputnode, [('out_reg_file', 'fsnative_to_t1w_xfm')]), (fix_surfs, outputnode, [('out_file', 'surf_norm')]), (fs_2_gii, outputnode, [('converted', 'surfaces')]), ]) return workflow
def test_freesurfersource(): fss = nio.FreeSurferSource() assert fss.inputs.hemi == 'both' assert fss.inputs.subject_id == Undefined assert fss.inputs.subjects_dir == Undefined
psb6351_wf.connect(tshifter, 'out_file', Blur, 'in_file') # Added a mapnode to do temporal smoothing # Saving the outputs to the datasink temp_smooth = pe.MapNode(afni.TSmooth(), iterfield=['in_file'], name='temp_smooth') temp_smooth.inputs.adaptive = 5 temp_smooth.inputs.lin = True temp_smooth.inputs.med = True temp_smooth.inputs.outputtype = 'NIFTI_GZ' psb6351_wf.connect(Blur, 'out_file', temp_smooth, 'in_file') # Register a source file to fs space and create a brain mask in source space # The node below creates the Freesurfer source fssource = pe.Node(nio.FreeSurferSource(), name='fssource') fssource.inputs.subject_id = f'sub-{sids[0]}' fssource.inputs.subjects_dir = fs_dir # Extract aparc+aseg brain mask, binarize, and dilate by 1 voxel fs_threshold = pe.Node(fs.Binarize(min=0.5, out_type='nii'), name='fs_threshold') fs_threshold.inputs.dilate = 1 psb6351_wf.connect(fssource, ('aparc_aseg', get_aparc_aseg), fs_threshold, 'in_file') # Transform the binarized aparc+aseg file to the EPI space # use a nearest neighbor interpolation fs_voltransform = pe.Node(fs.ApplyVolTransform(inverse=True), name='fs_transform') fs_voltransform.inputs.subjects_dir = fs_dir
def create_connectivity_pipeline(name="connectivity"): """Creates a pipeline that does the same connectivity processing as in the :ref:`example_dmri_connectivity` example script. Given a subject id (and completed Freesurfer reconstruction) diffusion-weighted image, b-values, and b-vectors, the workflow will return the subject's connectome as a Connectome File Format (CFF) file for use in Connectome Viewer (http://www.cmtk.org). Example ------- >>> from nipype.workflows.dmri.camino.connectivity_mapping import create_connectivity_pipeline >>> conmapper = create_connectivity_pipeline("nipype_conmap") >>> conmapper.inputs.inputnode.subjects_dir = '.' >>> conmapper.inputs.inputnode.subject_id = 'subj1' >>> conmapper.inputs.inputnode.dwi = 'data.nii.gz' >>> conmapper.inputs.inputnode.bvecs = 'bvecs' >>> conmapper.inputs.inputnode.bvals = 'bvals' >>> conmapper.run() # doctest: +SKIP Inputs:: inputnode.subject_id inputnode.subjects_dir inputnode.dwi inputnode.bvecs inputnode.bvals inputnode.resolution_network_file Outputs:: outputnode.connectome outputnode.cmatrix outputnode.gpickled_network outputnode.fa outputnode.struct outputnode.trace outputnode.tracts outputnode.tensors """ inputnode_within = pe.Node(interface=util.IdentityInterface(fields=["subject_id", "dwi", "bvecs", "bvals", "subjects_dir", "resolution_network_file", ]), name="inputnode_within") FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(), name='fssource') FreeSurferSourceLH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceLH') FreeSurferSourceLH.inputs.hemi = 'lh' FreeSurferSourceRH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceRH') FreeSurferSourceRH.inputs.hemi = 'rh' """ Since the b values and b vectors come from the FSL course, we must convert it to a scheme file for use in Camino. """ fsl2scheme = pe.Node(interface=camino.FSL2Scheme(), name="fsl2scheme") fsl2scheme.inputs.usegradmod = True """ FSL's Brain Extraction tool is used to create a mask from the b0 image """ b0Strip = pe.Node(interface=fsl.BET(mask = True), name = 'bet_b0') """ FSL's FLIRT function is used to coregister the b0 mask and the structural image. A convert_xfm node is then used to obtain the inverse of the transformation matrix. FLIRT is used once again to apply the inverse transformation to the parcellated brain image. """ coregister = pe.Node(interface=fsl.FLIRT(dof=6), name = 'coregister') coregister.inputs.cost = ('normmi') convertxfm = pe.Node(interface=fsl.ConvertXFM(), name = 'convertxfm') convertxfm.inputs.invert_xfm = True inverse = pe.Node(interface=fsl.FLIRT(), name = 'inverse') inverse.inputs.interp = ('nearestneighbour') inverse_AparcAseg = pe.Node(interface=fsl.FLIRT(), name = 'inverse_AparcAseg') inverse_AparcAseg.inputs.interp = ('nearestneighbour') """ A number of conversion operations are required to obtain NIFTI files from the FreesurferSource for each subject. Nodes are used to convert the following: * Original structural image to NIFTI * Parcellated white matter image to NIFTI * Parcellated whole-brain image to NIFTI * Pial, white, inflated, and spherical surfaces for both the left and right hemispheres are converted to GIFTI for visualization in ConnectomeViewer * Parcellated annotation files for the left and right hemispheres are also converted to GIFTI """ mri_convert_Brain = pe.Node(interface=fs.MRIConvert(), name='mri_convert_Brain') mri_convert_Brain.inputs.out_type = 'nii' mri_convert_AparcAseg = mri_convert_Brain.clone('mri_convert_AparcAseg') mris_convertLH = pe.Node(interface=fs.MRIsConvert(), name='mris_convertLH') mris_convertLH.inputs.out_datatype = 'gii' mris_convertRH = mris_convertLH.clone('mris_convertRH') mris_convertRHwhite = mris_convertLH.clone('mris_convertRHwhite') mris_convertLHwhite = mris_convertLH.clone('mris_convertLHwhite') mris_convertRHinflated = mris_convertLH.clone('mris_convertRHinflated') mris_convertLHinflated = mris_convertLH.clone('mris_convertLHinflated') mris_convertRHsphere = mris_convertLH.clone('mris_convertRHsphere') mris_convertLHsphere = mris_convertLH.clone('mris_convertLHsphere') mris_convertLHlabels = mris_convertLH.clone('mris_convertLHlabels') mris_convertRHlabels = mris_convertLH.clone('mris_convertRHlabels') """ In this section we create the nodes necessary for diffusion analysis. First, the diffusion image is converted to voxel order, since this is the format in which Camino does its processing. """ image2voxel = pe.Node(interface=camino.Image2Voxel(), name="image2voxel") """ Second, diffusion tensors are fit to the voxel-order data. If desired, these tensors can be converted to a Nifti tensor image using the DT2NIfTI interface. """ dtifit = pe.Node(interface=camino.DTIFit(),name='dtifit') """ Next, a lookup table is generated from the schemefile and the signal-to-noise ratio (SNR) of the unweighted (q=0) data. """ dtlutgen = pe.Node(interface=camino.DTLUTGen(), name="dtlutgen") dtlutgen.inputs.snr = 16.0 dtlutgen.inputs.inversion = 1 """ In this tutorial we implement probabilistic tractography using the PICo algorithm. PICo tractography requires an estimate of the fibre direction and a model of its uncertainty in each voxel; this probabilitiy distribution map is produced using the following node. """ picopdfs = pe.Node(interface=camino.PicoPDFs(), name="picopdfs") picopdfs.inputs.inputmodel = 'dt' """ Finally, tractography is performed. In this tutorial, we will use only one iteration for time-saving purposes. It is important to note that we use the TrackPICo interface here. This interface now expects the files required for PICo tracking (i.e. the output from picopdfs). Similar interfaces exist for alternative types of tracking, such as Bayesian tracking with Dirac priors (TrackBayesDirac). """ track = pe.Node(interface=camino.TrackPICo(), name="track") track.inputs.iterations = 1 """ Currently, the best program for visualizing tracts is TrackVis. For this reason, a node is included to convert the raw tract data to .trk format. Solely for testing purposes, another node is added to perform the reverse. """ camino2trackvis = pe.Node(interface=cam2trk.Camino2Trackvis(), name="camino2trackvis") camino2trackvis.inputs.min_length = 30 camino2trackvis.inputs.voxel_order = 'LAS' trk2camino = pe.Node(interface=cam2trk.Trackvis2Camino(), name="trk2camino") """ Tracts can also be converted to VTK and OOGL formats, for use in programs such as GeomView and Paraview, using the following two nodes. """ vtkstreamlines = pe.Node(interface=camino.VtkStreamlines(), name="vtkstreamlines") procstreamlines = pe.Node(interface=camino.ProcStreamlines(), name="procstreamlines") """ We can easily produce a variety of scalar values from our fitted tensors. The following nodes generate the fractional anisotropy and diffusivity trace maps and their associated headers, and then merge them back into a single .nii file. """ fa = pe.Node(interface=camino.ComputeFractionalAnisotropy(),name='fa') trace = pe.Node(interface=camino.ComputeTensorTrace(),name='trace') dteig = pe.Node(interface=camino.ComputeEigensystem(), name='dteig') analyzeheader_fa = pe.Node(interface=camino.AnalyzeHeader(),name='analyzeheader_fa') analyzeheader_fa.inputs.datatype = 'double' analyzeheader_trace = pe.Node(interface=camino.AnalyzeHeader(),name='analyzeheader_trace') analyzeheader_trace.inputs.datatype = 'double' fa2nii = pe.Node(interface=misc.CreateNifti(),name='fa2nii') trace2nii = fa2nii.clone("trace2nii") """ This section adds the Connectome Mapping Toolkit (CMTK) nodes. These interfaces are fairly experimental and may not function properly. In order to perform connectivity mapping using CMTK, the parcellated structural data is rewritten using the indices and parcellation scheme from the connectome mapper (CMP). This process has been written into the ROIGen interface, which will output a remapped aparc+aseg image as well as a dictionary of label information (i.e. name, display colours) pertaining to the original and remapped regions. These label values are input from a user-input lookup table, if specified, and otherwise the default Freesurfer LUT (/freesurfer/FreeSurferColorLUT.txt). """ roigen = pe.Node(interface=cmtk.ROIGen(), name="ROIGen") roigen_structspace = roigen.clone("ROIGen_structspace") """ The CreateMatrix interface takes in the remapped aparc+aseg image as well as the label dictionary and fiber tracts and outputs a number of different files. The most important of which is the connectivity network itself, which is stored as a 'gpickle' and can be loaded using Python's NetworkX package (see CreateMatrix docstring). Also outputted are various NumPy arrays containing detailed tract information, such as the start and endpoint regions, and statistics on the mean and standard deviation for the fiber length of each connection. These matrices can be used in the ConnectomeViewer to plot the specific tracts that connect between user-selected regions. """ createnodes = pe.Node(interface=cmtk.CreateNodes(), name="CreateNodes") creatematrix = pe.Node(interface=cmtk.CreateMatrix(), name="CreateMatrix") creatematrix.inputs.count_region_intersections = True """ Here we define the endpoint of this tutorial, which is the CFFConverter node, as well as a few nodes which use the Nipype Merge utility. These are useful for passing lists of the files we want packaged in our CFF file. """ CFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="CFFConverter") giftiSurfaces = pe.Node(interface=util.Merge(8), name="GiftiSurfaces") giftiLabels = pe.Node(interface=util.Merge(2), name="GiftiLabels") niftiVolumes = pe.Node(interface=util.Merge(3), name="NiftiVolumes") fiberDataArrays = pe.Node(interface=util.Merge(4), name="FiberDataArrays") gpickledNetworks = pe.Node(interface=util.Merge(1), name="NetworkFiles") """ Since we have now created all our nodes, we can define our workflow and start making connections. """ mapping = pe.Workflow(name='mapping') """ First, we connect the input node to the early conversion functions. FreeSurfer input nodes: """ mapping.connect([(inputnode_within, FreeSurferSource,[("subjects_dir","subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSource,[("subject_id","subject_id")])]) mapping.connect([(inputnode_within, FreeSurferSourceLH,[("subjects_dir","subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSourceLH,[("subject_id","subject_id")])]) mapping.connect([(inputnode_within, FreeSurferSourceRH,[("subjects_dir","subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSourceRH,[("subject_id","subject_id")])]) """ Required conversions for processing in Camino: """ mapping.connect([(inputnode_within, image2voxel, [("dwi", "in_file")]), (inputnode_within, fsl2scheme, [("bvecs", "bvec_file"), ("bvals", "bval_file")]), (image2voxel, dtifit,[['voxel_order','in_file']]), (fsl2scheme, dtifit,[['scheme','scheme_file']]) ]) """ Nifti conversions for the subject's stripped brain image from Freesurfer: """ mapping.connect([(FreeSurferSource, mri_convert_Brain,[('brain','in_file')])]) """ Surface conversions to GIFTI (pial, white, inflated, and sphere for both hemispheres) """ mapping.connect([(FreeSurferSourceLH, mris_convertLH,[('pial','in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRH,[('pial','in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite,[('white','in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite,[('white','in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated,[('inflated','in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated,[('inflated','in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere,[('sphere','in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere,[('sphere','in_file')])]) """ The annotation files are converted using the pial surface as a map via the MRIsConvert interface. One of the functions defined earlier is used to select the lh.aparc.annot and rh.aparc.annot files specifically (rather than i.e. rh.aparc.a2009s.annot) from the output list given by the FreeSurferSource. """ mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels,[('pial','in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels,[('pial','in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) """ This section coregisters the diffusion-weighted and parcellated white-matter / whole brain images. At present the conmap node connection is left commented, as there have been recent changes in Camino code that have presented some users with errors. """ mapping.connect([(inputnode_within, b0Strip,[('dwi','in_file')])]) mapping.connect([(inputnode_within, b0Strip,[('dwi','t2_guided')])]) # Added to improve damaged brain extraction mapping.connect([(b0Strip, coregister,[('out_file','in_file')])]) mapping.connect([(mri_convert_Brain, coregister,[('out_file','reference')])]) mapping.connect([(coregister, convertxfm,[('out_matrix_file','in_file')])]) mapping.connect([(b0Strip, inverse,[('out_file','reference')])]) mapping.connect([(convertxfm, inverse,[('out_file','in_matrix_file')])]) mapping.connect([(mri_convert_Brain, inverse,[('out_file','in_file')])]) """ The tractography pipeline consists of the following nodes. Further information about the tractography can be found in nipype/examples/dmri_camino_dti.py. """ mapping.connect([(b0Strip, track,[("mask_file","seed_file")])]) mapping.connect([(fsl2scheme, dtlutgen,[("scheme","scheme_file")])]) mapping.connect([(dtlutgen, picopdfs,[("dtLUT","luts")])]) mapping.connect([(dtifit, picopdfs,[("tensor_fitted","in_file")])]) mapping.connect([(picopdfs, track,[("pdfs","in_file")])]) """ Connecting the Fractional Anisotropy and Trace nodes is simple, as they obtain their input from the tensor fitting. This is also where our voxel- and data-grabbing functions come in. We pass these functions, along with the original DWI image from the input node, to the header-generating nodes. This ensures that the files will be correct and readable. """ mapping.connect([(dtifit, fa,[("tensor_fitted","in_file")])]) mapping.connect([(fa, analyzeheader_fa,[("fa","in_file")])]) mapping.connect([(inputnode_within, analyzeheader_fa,[(('dwi', get_vox_dims), 'voxel_dims'), (('dwi', get_data_dims), 'data_dims')])]) mapping.connect([(fa, fa2nii,[('fa','data_file')])]) mapping.connect([(inputnode_within, fa2nii,[(('dwi', get_affine), 'affine')])]) mapping.connect([(analyzeheader_fa, fa2nii,[('header', 'header_file')])]) mapping.connect([(dtifit, trace,[("tensor_fitted","in_file")])]) mapping.connect([(trace, analyzeheader_trace,[("trace","in_file")])]) mapping.connect([(inputnode_within, analyzeheader_trace,[(('dwi', get_vox_dims), 'voxel_dims'), (('dwi', get_data_dims), 'data_dims')])]) mapping.connect([(trace, trace2nii,[('trace','data_file')])]) mapping.connect([(inputnode_within, trace2nii,[(('dwi', get_affine), 'affine')])]) mapping.connect([(analyzeheader_trace, trace2nii,[('header', 'header_file')])]) mapping.connect([(dtifit, dteig,[("tensor_fitted","in_file")])]) """ The output tracts are converted to Trackvis format (and back). Here we also use the voxel- and data-grabbing functions defined at the beginning of the pipeline. """ mapping.connect([(track, camino2trackvis, [('tracked','in_file')]), (track, vtkstreamlines,[['tracked','in_file']]), (camino2trackvis, trk2camino,[['trackvis','in_file']]) ]) mapping.connect([(inputnode_within, camino2trackvis,[(('dwi', get_vox_dims), 'voxel_dims'), (('dwi', get_data_dims), 'data_dims')])]) """ Here the CMTK connectivity mapping nodes are connected. The original aparc+aseg image is converted to NIFTI, then registered to the diffusion image and delivered to the ROIGen node. The remapped parcellation, original tracts, and label file are then given to CreateMatrix. """ mapping.connect(inputnode_within, 'resolution_network_file', createnodes, 'resolution_network_file') mapping.connect(createnodes, 'node_network', creatematrix, 'resolution_network_file') mapping.connect([(FreeSurferSource, mri_convert_AparcAseg, [(('aparc_aseg', select_aparc), 'in_file')])]) mapping.connect([(b0Strip, inverse_AparcAseg,[('out_file','reference')])]) mapping.connect([(convertxfm, inverse_AparcAseg,[('out_file','in_matrix_file')])]) mapping.connect([(mri_convert_AparcAseg, inverse_AparcAseg,[('out_file','in_file')])]) mapping.connect([(mri_convert_AparcAseg, roigen_structspace,[('out_file','aparc_aseg_file')])]) mapping.connect([(roigen_structspace, createnodes,[("roi_file","roi_file")])]) mapping.connect([(inverse_AparcAseg, roigen,[("out_file","aparc_aseg_file")])]) mapping.connect([(roigen, creatematrix,[("roi_file","roi_file")])]) mapping.connect([(camino2trackvis, creatematrix,[("trackvis","tract_file")])]) mapping.connect([(inputnode_within, creatematrix,[("subject_id","out_matrix_file")])]) mapping.connect([(inputnode_within, creatematrix,[("subject_id","out_matrix_mat_file")])]) """ The merge nodes defined earlier are used here to create lists of the files which are destined for the CFFConverter. """ mapping.connect([(mris_convertLH, giftiSurfaces,[("converted","in1")])]) mapping.connect([(mris_convertRH, giftiSurfaces,[("converted","in2")])]) mapping.connect([(mris_convertLHwhite, giftiSurfaces,[("converted","in3")])]) mapping.connect([(mris_convertRHwhite, giftiSurfaces,[("converted","in4")])]) mapping.connect([(mris_convertLHinflated, giftiSurfaces,[("converted","in5")])]) mapping.connect([(mris_convertRHinflated, giftiSurfaces,[("converted","in6")])]) mapping.connect([(mris_convertLHsphere, giftiSurfaces,[("converted","in7")])]) mapping.connect([(mris_convertRHsphere, giftiSurfaces,[("converted","in8")])]) mapping.connect([(mris_convertLHlabels, giftiLabels,[("converted","in1")])]) mapping.connect([(mris_convertRHlabels, giftiLabels,[("converted","in2")])]) mapping.connect([(roigen, niftiVolumes,[("roi_file","in1")])]) mapping.connect([(inputnode_within, niftiVolumes,[("dwi","in2")])]) mapping.connect([(mri_convert_Brain, niftiVolumes,[("out_file","in3")])]) mapping.connect([(creatematrix, fiberDataArrays,[("endpoint_file","in1")])]) mapping.connect([(creatematrix, fiberDataArrays,[("endpoint_file_mm","in2")])]) mapping.connect([(creatematrix, fiberDataArrays,[("fiber_length_file","in3")])]) mapping.connect([(creatematrix, fiberDataArrays,[("fiber_label_file","in4")])]) """ This block actually connects the merged lists to the CFF converter. We pass the surfaces and volumes that are to be included, as well as the tracts and the network itself. The currently running pipeline (dmri_connectivity.py) is also scraped and included in the CFF file. This makes it easy for the user to examine the entire processing pathway used to generate the end product. """ CFFConverter.inputs.script_files = op.abspath(inspect.getfile(inspect.currentframe())) mapping.connect([(giftiSurfaces, CFFConverter,[("out","gifti_surfaces")])]) mapping.connect([(giftiLabels, CFFConverter,[("out","gifti_labels")])]) mapping.connect([(creatematrix, CFFConverter,[("matrix_files","gpickled_networks")])]) mapping.connect([(niftiVolumes, CFFConverter,[("out","nifti_volumes")])]) mapping.connect([(fiberDataArrays, CFFConverter,[("out","data_files")])]) mapping.connect([(camino2trackvis, CFFConverter,[("trackvis","tract_files")])]) mapping.connect([(inputnode_within, CFFConverter,[("subject_id","title")])]) """ Finally, we create another higher-level workflow to connect our mapping workflow with the info and datagrabbing nodes declared at the beginning. Our tutorial can 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. """ inputnode = pe.Node(interface=util.IdentityInterface(fields=["subject_id", "dwi", "bvecs", "bvals", "subjects_dir", "resolution_network_file"]), name="inputnode") outputnode = pe.Node(interface = util.IdentityInterface(fields=["fa", "struct", "trace", "tracts", "connectome", "cmatrix", "networks", "rois", "mean_fiber_length", "fiber_length_std", "tensors"]), name="outputnode") connectivity = pe.Workflow(name="connectivity") connectivity.base_output_dir=name connectivity.connect([(inputnode, mapping, [("dwi", "inputnode_within.dwi"), ("bvals", "inputnode_within.bvals"), ("bvecs", "inputnode_within.bvecs"), ("subject_id", "inputnode_within.subject_id"), ("subjects_dir", "inputnode_within.subjects_dir"), ("resolution_network_file", "inputnode_within.resolution_network_file")]) ]) connectivity.connect([(mapping, outputnode, [("camino2trackvis.trackvis", "tracts"), ("CFFConverter.connectome_file", "connectome"), ("CreateMatrix.matrix_mat_file", "cmatrix"), ("CreateMatrix.mean_fiber_length_matrix_mat_file", "mean_fiber_length"), ("CreateMatrix.fiber_length_std_matrix_mat_file", "fiber_length_std"), ("fa2nii.nifti_file", "fa"), ("CreateMatrix.matrix_files", "networks"), ("ROIGen.roi_file", "rois"), ("mri_convert_Brain.out_file", "struct"), ("trace2nii.nifti_file", "trace"), ("dtifit.tensor_fitted", "tensors")]) ]) return connectivity
def init_segs_to_native_wf(*, name="segs_to_native", segmentation="aseg"): """ Get a segmentation from FreeSurfer conformed space into native T1w space. Workflow Graph .. workflow:: :graph2use: orig :simple_form: yes from smriprep.workflows.surfaces import init_segs_to_native_wf wf = init_segs_to_native_wf() Parameters ---------- segmentation The name of a segmentation ('aseg' or 'aparc_aseg' or 'wmparc') Inputs ------ in_file Anatomical, merged T1w image after INU correction subjects_dir FreeSurfer SUBJECTS_DIR subject_id FreeSurfer subject ID fsnative2t1w_xfm LTA-style affine matrix translating from FreeSurfer-conformed subject space to T1w Outputs ------- out_file The selected segmentation, after resampling in native space """ workflow = Workflow(name="%s_%s" % (name, segmentation)) inputnode = pe.Node( niu.IdentityInterface( ["in_file", "subjects_dir", "subject_id", "fsnative2t1w_xfm"] ), name="inputnode", ) outputnode = pe.Node(niu.IdentityInterface(["out_file"]), name="outputnode") # Extract the aseg and aparc+aseg outputs fssource = pe.Node(nio.FreeSurferSource(), name="fs_datasource") # Resample from T1.mgz to T1w.nii.gz, applying any offset in fsnative2t1w_xfm, # and convert to NIfTI while we're at it resample = pe.Node( fs.ApplyVolTransform(transformed_file="seg.nii.gz", interp="nearest"), name="resample", ) if segmentation.startswith("aparc"): if segmentation == "aparc_aseg": def _sel(x): return [parc for parc in x if "aparc+" in parc][0] # noqa elif segmentation == "aparc_a2009s": def _sel(x): return [parc for parc in x if "a2009s+" in parc][0] # noqa elif segmentation == "aparc_dkt": def _sel(x): return [parc for parc in x if "DKTatlas+" in parc][0] # noqa segmentation = (segmentation, _sel) # fmt:off workflow.connect([ (inputnode, fssource, [ ('subjects_dir', 'subjects_dir'), ('subject_id', 'subject_id')]), (inputnode, resample, [('in_file', 'target_file'), ('fsnative2t1w_xfm', 'lta_file')]), (fssource, resample, [(segmentation, 'source_file')]), (resample, outputnode, [('transformed_file', 'out_file')]), ]) # fmt:on return workflow
def create_connectivity_pipeline(name="connectivity", parcellation_name='scale500'): inputnode_within = pe.Node(util.IdentityInterface(fields=[ "subject_id", "dwi", "bvecs", "bvals", "subjects_dir", "resolution_network_file" ]), name="inputnode_within") FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(), name='fssource') FreeSurferSourceLH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceLH') FreeSurferSourceLH.inputs.hemi = 'lh' FreeSurferSourceRH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceRH') FreeSurferSourceRH.inputs.hemi = 'rh' """ Creating the workflow's nodes ============================= """ """ Conversion nodes ---------------- """ """ A number of conversion operations are required to obtain NIFTI files from the FreesurferSource for each subject. Nodes are used to convert the following: * Original structural image to NIFTI * Pial, white, inflated, and spherical surfaces for both the left and right hemispheres are converted to GIFTI for visualization in ConnectomeViewer * Parcellated annotation files for the left and right hemispheres are also converted to GIFTI """ mri_convert_Brain = pe.Node(interface=fs.MRIConvert(), name='mri_convert_Brain') mri_convert_Brain.inputs.out_type = 'nii' mri_convert_ROI_scale500 = mri_convert_Brain.clone( 'mri_convert_ROI_scale500') mris_convertLH = pe.Node(interface=fs.MRIsConvert(), name='mris_convertLH') mris_convertLH.inputs.out_datatype = 'gii' mris_convertRH = mris_convertLH.clone('mris_convertRH') mris_convertRHwhite = mris_convertLH.clone('mris_convertRHwhite') mris_convertLHwhite = mris_convertLH.clone('mris_convertLHwhite') mris_convertRHinflated = mris_convertLH.clone('mris_convertRHinflated') mris_convertLHinflated = mris_convertLH.clone('mris_convertLHinflated') mris_convertRHsphere = mris_convertLH.clone('mris_convertRHsphere') mris_convertLHsphere = mris_convertLH.clone('mris_convertLHsphere') mris_convertLHlabels = mris_convertLH.clone('mris_convertLHlabels') mris_convertRHlabels = mris_convertLH.clone('mris_convertRHlabels') """ Diffusion processing nodes -------------------------- .. seealso:: dmri_mrtrix_dti.py Tutorial that focuses solely on the MRtrix diffusion processing http://www.brain.org.au/software/mrtrix/index.html MRtrix's online documentation """ """ b-values and b-vectors stored in FSL's format are converted into a single encoding file for MRTrix. """ fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix') """ Distortions induced by eddy currents are corrected prior to fitting the tensors. The first image is used as a reference for which to warp the others. """ eddycorrect = create_eddy_correct_pipeline(name='eddycorrect') eddycorrect.inputs.inputnode.ref_num = 1 """ Tensors are fitted to each voxel in the diffusion-weighted image and from these three maps are created: * Major eigenvector in each voxel * Apparent diffusion coefficient * Fractional anisotropy """ dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(), name='dwi2tensor') tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(), name='tensor2vector') tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(), name='tensor2adc') tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(), name='tensor2fa') MRconvert_fa = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert_fa') MRconvert_fa.inputs.extension = 'nii' """ These nodes are used to create a rough brain mask from the b0 image. The b0 image is extracted from the original diffusion-weighted image, put through a simple thresholding routine, and smoothed using a 3x3 median filter. """ MRconvert = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert') MRconvert.inputs.extract_at_axis = 3 MRconvert.inputs.extract_at_coordinate = [0] threshold_b0 = pe.Node(interface=mrtrix.Threshold(), name='threshold_b0') median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3d') """ The brain mask is also used to help identify single-fiber voxels. This is done by passing the brain mask through two erosion steps, multiplying the remaining mask with the fractional anisotropy map, and thresholding the result to obtain some highly anisotropic within-brain voxels. """ erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_firstpass') erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_secondpass') MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply') MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge') threshold_FA = pe.Node(interface=mrtrix.Threshold(), name='threshold_FA') threshold_FA.inputs.absolute_threshold_value = 0.7 """ For whole-brain tracking we also require a broad white-matter seed mask. This is created by generating a white matter mask, given a brainmask, and thresholding it at a reasonably high level. """ bet = pe.Node(interface=fsl.BET(mask=True), name='bet_b0') gen_WM_mask = pe.Node(interface=mrtrix.GenerateWhiteMatterMask(), name='gen_WM_mask') threshold_wmmask = pe.Node(interface=mrtrix.Threshold(), name='threshold_wmmask') threshold_wmmask.inputs.absolute_threshold_value = 0.4 """ The spherical deconvolution step depends on the estimate of the response function in the highly anisotropic voxels we obtained above. .. warning:: For damaged or pathological brains one should take care to lower the maximum harmonic order of these steps. """ estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') estimateresponse.inputs.maximum_harmonic_order = 6 csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') csdeconv.inputs.maximum_harmonic_order = 6 """ Finally, we track probabilistically using the orientation distribution functions obtained earlier. The tracts are then used to generate a tract-density image, and they are also converted to TrackVis format. """ probCSDstreamtrack = pe.Node( interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(), name='probCSDstreamtrack') probCSDstreamtrack.inputs.inputmodel = 'SD_PROB' probCSDstreamtrack.inputs.desired_number_of_tracks = 150000 tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(), name='tracks2prob') tracks2prob.inputs.colour = True MRconvert_tracks2prob = MRconvert_fa.clone(name='MRconvert_tracks2prob') tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk') """ Structural segmentation nodes ----------------------------- """ """ The following node identifies the transformation between the diffusion-weighted image and the structural image. This transformation is then applied to the tracts so that they are in the same space as the regions of interest. """ coregister = pe.Node(interface=fsl.FLIRT(dof=6), name='coregister') coregister.inputs.cost = ('normmi') """ Parcellation is performed given the aparc+aseg image from Freesurfer. The CMTK Parcellation step subdivides these regions to return a higher-resolution parcellation scheme. The parcellation used here is entitled "scale500" and returns 1015 regions. """ parcellate = pe.Node(interface=cmtk.Parcellate(), name="Parcellate") parcellate.inputs.parcellation_name = parcellation_name """ The CreateMatrix interface takes in the remapped aparc+aseg image as well as the label dictionary and fiber tracts and outputs a number of different files. The most important of which is the connectivity network itself, which is stored as a 'gpickle' and can be loaded using Python's NetworkX package (see CreateMatrix docstring). Also outputted are various NumPy arrays containing detailed tract information, such as the start and endpoint regions, and statistics on the mean and standard deviation for the fiber length of each connection. These matrices can be used in the ConnectomeViewer to plot the specific tracts that connect between user-selected regions. Here we choose the Lausanne2008 parcellation scheme, since we are incorporating the CMTK parcellation step. """ creatematrix = pe.Node(interface=cmtk.CreateMatrix(), name="CreateMatrix") creatematrix.inputs.count_region_intersections = True """ Next we define the endpoint of this tutorial, which is the CFFConverter node, as well as a few nodes which use the Nipype Merge utility. These are useful for passing lists of the files we want packaged in our CFF file. The inspect.getfile command is used to package this script into the resulting CFF file, so that it is easy to look back at the processing parameters that were used. """ CFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="CFFConverter") CFFConverter.inputs.script_files = op.abspath( inspect.getfile(inspect.currentframe())) giftiSurfaces = pe.Node(interface=util.Merge(8), name="GiftiSurfaces") giftiLabels = pe.Node(interface=util.Merge(2), name="GiftiLabels") niftiVolumes = pe.Node(interface=util.Merge(3), name="NiftiVolumes") fiberDataArrays = pe.Node(interface=util.Merge(4), name="FiberDataArrays") """ We also create a node to calculate several network metrics on our resulting file, and another CFF converter which will be used to package these networks into a single file. """ networkx = create_networkx_pipeline(name='networkx') cmats_to_csv = create_cmats_to_csv_pipeline(name='cmats_to_csv') nfibs_to_csv = pe.Node(interface=misc.Matlab2CSV(), name='nfibs_to_csv') merge_nfib_csvs = pe.Node(interface=misc.MergeCSVFiles(), name='merge_nfib_csvs') merge_nfib_csvs.inputs.extra_column_heading = 'Subject' merge_nfib_csvs.inputs.out_file = 'fibers.csv' NxStatsCFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="NxStatsCFFConverter") NxStatsCFFConverter.inputs.script_files = op.abspath( inspect.getfile(inspect.currentframe())) """ Connecting the workflow ======================= Here we connect our processing pipeline. """ """ Connecting the inputs, FreeSurfer nodes, and conversions -------------------------------------------------------- """ mapping = pe.Workflow(name='mapping') """ First, we connect the input node to the FreeSurfer input nodes. """ mapping.connect([(inputnode_within, FreeSurferSource, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSource, [("subject_id", "subject_id")])]) mapping.connect([(inputnode_within, FreeSurferSourceLH, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSourceLH, [("subject_id", "subject_id")])]) mapping.connect([(inputnode_within, FreeSurferSourceRH, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSourceRH, [("subject_id", "subject_id")])]) mapping.connect([(inputnode_within, parcellate, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, parcellate, [("subject_id", "subject_id")])]) mapping.connect([(parcellate, mri_convert_ROI_scale500, [('roi_file', 'in_file')])]) """ Nifti conversion for subject's stripped brain image from Freesurfer: """ mapping.connect([(FreeSurferSource, mri_convert_Brain, [('brain', 'in_file')])]) """ Surface conversions to GIFTI (pial, white, inflated, and sphere for both hemispheres) """ mapping.connect([(FreeSurferSourceLH, mris_convertLH, [('pial', 'in_file') ])]) mapping.connect([(FreeSurferSourceRH, mris_convertRH, [('pial', 'in_file') ])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite, [('white', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite, [('white', 'in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated, [('inflated', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated, [('inflated', 'in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere, [('sphere', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere, [('sphere', 'in_file')])]) """ The annotation files are converted using the pial surface as a map via the MRIsConvert interface. One of the functions defined earlier is used to select the lh.aparc.annot and rh.aparc.annot files specifically (rather than e.g. rh.aparc.a2009s.annot) from the output list given by the FreeSurferSource. """ mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [('pial', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [('pial', 'in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) """ Diffusion Processing -------------------- Now we connect the tensor computations: """ mapping.connect([(inputnode_within, fsl2mrtrix, [("bvecs", "bvec_file"), ("bvals", "bval_file")])]) mapping.connect([(inputnode_within, eddycorrect, [("dwi", "inputnode.in_file")])]) mapping.connect([(eddycorrect, dwi2tensor, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file", "encoding_file")])]) mapping.connect([ (dwi2tensor, tensor2vector, [['tensor', 'in_file']]), (dwi2tensor, tensor2adc, [['tensor', 'in_file']]), (dwi2tensor, tensor2fa, [['tensor', 'in_file']]), ]) mapping.connect([(tensor2fa, MRmult_merge, [("FA", "in1")])]) mapping.connect([(tensor2fa, MRconvert_fa, [("FA", "in_file")])]) """ This block creates the rough brain mask to be multiplied, mulitplies it with the fractional anisotropy image, and thresholds it to get the single-fiber voxels. """ mapping.connect([(eddycorrect, MRconvert, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(MRconvert, threshold_b0, [("converted", "in_file")])]) mapping.connect([(threshold_b0, median3d, [("out_file", "in_file")])]) mapping.connect([(median3d, erode_mask_firstpass, [("out_file", "in_file") ])]) mapping.connect([(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])]) mapping.connect([(erode_mask_secondpass, MRmult_merge, [("out_file", "in2") ])]) mapping.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])]) mapping.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])]) """ Here the thresholded white matter mask is created for seeding the tractography. """ mapping.connect([(eddycorrect, bet, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(eddycorrect, gen_WM_mask, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(bet, gen_WM_mask, [("mask_file", "binary_mask")])]) mapping.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file", "encoding_file")])]) mapping.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap", "in_file")])]) """ Next we estimate the fiber response distribution. """ mapping.connect([(eddycorrect, estimateresponse, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])]) mapping.connect([(threshold_FA, estimateresponse, [("out_file", "mask_image")])]) """ Run constrained spherical deconvolution. """ mapping.connect([(eddycorrect, csdeconv, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap", "mask_image")])]) mapping.connect([(estimateresponse, csdeconv, [("response", "response_file")])]) mapping.connect([(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file") ])]) """ Connect the tractography and compute the tract density image. """ mapping.connect([(threshold_wmmask, probCSDstreamtrack, [("out_file", "seed_file")])]) mapping.connect([(csdeconv, probCSDstreamtrack, [("spherical_harmonics_image", "in_file")])]) mapping.connect([(probCSDstreamtrack, tracks2prob, [("tracked", "in_file") ])]) mapping.connect([(eddycorrect, tracks2prob, [("outputnode.eddy_corrected", "template_file")])]) mapping.connect([(tracks2prob, MRconvert_tracks2prob, [("tract_image", "in_file")])]) """ Structural Processing --------------------- First, we coregister the diffusion image to the structural image """ mapping.connect([(eddycorrect, coregister, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(mri_convert_Brain, coregister, [('out_file', 'reference') ])]) """ The MRtrix-tracked fibers are converted to TrackVis format (with voxel and data dimensions grabbed from the DWI). The connectivity matrix is created with the transformed .trk fibers and the parcellation file. """ mapping.connect([(eddycorrect, tck2trk, [("outputnode.eddy_corrected", "image_file")])]) mapping.connect([(mri_convert_Brain, tck2trk, [("out_file", "registration_image_file")])]) mapping.connect([(coregister, tck2trk, [("out_matrix_file", "matrix_file") ])]) mapping.connect([(probCSDstreamtrack, tck2trk, [("tracked", "in_file")])]) mapping.connect([(tck2trk, creatematrix, [("out_file", "tract_file")])]) mapping.connect(inputnode_within, 'resolution_network_file', creatematrix, 'resolution_network_file') mapping.connect([(inputnode_within, creatematrix, [("subject_id", "out_matrix_file")])]) mapping.connect([(inputnode_within, creatematrix, [("subject_id", "out_matrix_mat_file")])]) mapping.connect([(parcellate, creatematrix, [("roi_file", "roi_file")])]) """ The merge nodes defined earlier are used here to create lists of the files which are destined for the CFFConverter. """ mapping.connect([(mris_convertLH, giftiSurfaces, [("converted", "in1")])]) mapping.connect([(mris_convertRH, giftiSurfaces, [("converted", "in2")])]) mapping.connect([(mris_convertLHwhite, giftiSurfaces, [("converted", "in3") ])]) mapping.connect([(mris_convertRHwhite, giftiSurfaces, [("converted", "in4") ])]) mapping.connect([(mris_convertLHinflated, giftiSurfaces, [("converted", "in5")])]) mapping.connect([(mris_convertRHinflated, giftiSurfaces, [("converted", "in6")])]) mapping.connect([(mris_convertLHsphere, giftiSurfaces, [("converted", "in7")])]) mapping.connect([(mris_convertRHsphere, giftiSurfaces, [("converted", "in8")])]) mapping.connect([(mris_convertLHlabels, giftiLabels, [("converted", "in1") ])]) mapping.connect([(mris_convertRHlabels, giftiLabels, [("converted", "in2") ])]) mapping.connect([(parcellate, niftiVolumes, [("roi_file", "in1")])]) mapping.connect([(eddycorrect, niftiVolumes, [("outputnode.eddy_corrected", "in2")])]) mapping.connect([(mri_convert_Brain, niftiVolumes, [("out_file", "in3")])]) mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file", "in1") ])]) mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm", "in2")])]) mapping.connect([(creatematrix, fiberDataArrays, [("fiber_length_file", "in3")])]) mapping.connect([(creatematrix, fiberDataArrays, [("fiber_label_file", "in4")])]) """ This block actually connects the merged lists to the CFF converter. We pass the surfaces and volumes that are to be included, as well as the tracts and the network itself. The currently running pipeline (dmri_connectivity_advanced.py) is also scraped and included in the CFF file. This makes it easy for the user to examine the entire processing pathway used to generate the end product. """ mapping.connect([(giftiSurfaces, CFFConverter, [("out", "gifti_surfaces")]) ]) mapping.connect([(giftiLabels, CFFConverter, [("out", "gifti_labels")])]) mapping.connect([(creatematrix, CFFConverter, [("matrix_files", "gpickled_networks")])]) mapping.connect([(niftiVolumes, CFFConverter, [("out", "nifti_volumes")])]) mapping.connect([(fiberDataArrays, CFFConverter, [("out", "data_files")])]) mapping.connect([(creatematrix, CFFConverter, [("filtered_tractography", "tract_files")])]) mapping.connect([(inputnode_within, CFFConverter, [("subject_id", "title") ])]) """ The graph theoretical metrics which have been generated are placed into another CFF file. """ mapping.connect([(inputnode_within, networkx, [("subject_id", "inputnode.extra_field")])]) mapping.connect([(creatematrix, networkx, [("intersection_matrix_file", "inputnode.network_file")])]) mapping.connect([(networkx, NxStatsCFFConverter, [("outputnode.network_files", "gpickled_networks")])]) mapping.connect([(giftiSurfaces, NxStatsCFFConverter, [("out", "gifti_surfaces")])]) mapping.connect([(giftiLabels, NxStatsCFFConverter, [("out", "gifti_labels")])]) mapping.connect([(niftiVolumes, NxStatsCFFConverter, [("out", "nifti_volumes")])]) mapping.connect([(fiberDataArrays, NxStatsCFFConverter, [("out", "data_files")])]) mapping.connect([(inputnode_within, NxStatsCFFConverter, [("subject_id", "title")])]) mapping.connect([(inputnode_within, cmats_to_csv, [("subject_id", "inputnode.extra_field")])]) mapping.connect([(creatematrix, cmats_to_csv, [ ("matlab_matrix_files", "inputnode.matlab_matrix_files") ])]) mapping.connect([(creatematrix, nfibs_to_csv, [("stats_file", "in_file")]) ]) mapping.connect([(nfibs_to_csv, merge_nfib_csvs, [("csv_files", "in_files") ])]) mapping.connect([(inputnode_within, merge_nfib_csvs, [("subject_id", "extra_field")])]) """ Create a higher-level workflow -------------------------------------- Finally, we create another higher-level workflow to connect our mapping workflow with the info and datagrabbing nodes declared at the beginning. Our tutorial can 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. """ inputnode = pe.Node(interface=util.IdentityInterface( fields=["subject_id", "dwi", "bvecs", "bvals", "subjects_dir"]), name="inputnode") outputnode = pe.Node(interface=util.IdentityInterface(fields=[ "fa", "struct", "tracts", "tracks2prob", "connectome", "nxstatscff", "nxmatlab", "nxcsv", "fiber_csv", "cmatrices_csv", "nxmergedcsv", "cmatrix", "networks", "filtered_tracts", "rois", "odfs", "tdi", "mean_fiber_length", "median_fiber_length", "fiber_length_std" ]), name="outputnode") connectivity = pe.Workflow(name="connectivity") connectivity.base_output_dir = name connectivity.base_dir = name connectivity.connect([(inputnode, mapping, [ ("dwi", "inputnode_within.dwi"), ("bvals", "inputnode_within.bvals"), ("bvecs", "inputnode_within.bvecs"), ("subject_id", "inputnode_within.subject_id"), ("subjects_dir", "inputnode_within.subjects_dir") ])]) connectivity.connect([(mapping, outputnode, [ ("tck2trk.out_file", "tracts"), ("CFFConverter.connectome_file", "connectome"), ("NxStatsCFFConverter.connectome_file", "nxstatscff"), ("CreateMatrix.matrix_mat_file", "cmatrix"), ("CreateMatrix.mean_fiber_length_matrix_mat_file", "mean_fiber_length"), ("CreateMatrix.median_fiber_length_matrix_mat_file", "median_fiber_length"), ("CreateMatrix.fiber_length_std_matrix_mat_file", "fiber_length_std"), ("CreateMatrix.matrix_files", "networks"), ("CreateMatrix.filtered_tractographies", "filtered_tracts"), ("merge_nfib_csvs.csv_file", "fiber_csv"), ("mri_convert_ROI_scale500.out_file", "rois"), ("csdeconv.spherical_harmonics_image", "odfs"), ("mri_convert_Brain.out_file", "struct"), ("MRconvert_fa.converted", "fa"), ("MRconvert_tracks2prob.converted", "tracks2prob") ])]) connectivity.connect([(cmats_to_csv, outputnode, [("outputnode.csv_file", "cmatrices_csv")])]) connectivity.connect([(networkx, outputnode, [("outputnode.csv_files", "nxcsv")])]) return connectivity
def create_epi_t1_nonlinear_pipeline(name='epi_t1_nonlinear'): """Creates a pipeline that performs nonlinear EPI to T1 registration using the antsRegistration tool. Beforehand, the T1 image has to be processed in freesurfer and the EPI timeseries should be realigned. Example ------- >>> nipype_epi_t1_nonlin = create_epi_t1_nonlinear_pipeline('nipype_epi_t1_nonlin') >>> nipype_epi_t1_nonlin.inputs.inputnode.fs_subject_id = '123456' >>> nipype_epi_t1_nonlin.inputs.inputnode.fs_subjects_dir = '/project/data/freesurfer' >>> nipype_epi_t1_nonlin.inputs.inputnode.realigned_epi = 'mcflirt.nii.gz' >>> nipype_epi_t1_nonlin.run() Inputs:: inputnode.fs_subject_id # subject id used in freesurfer inputnode.fs_subjects_dir # path to freesurfer output inputnode.realigned_epi # realigned EPI timeseries Outputs:: outputnode.lin_epi2anat # ITK format outputnode.lin_anat2epi # ITK format outputnode.nonlin_epi2anat # ANTs specific 5D deformation field outputnode.nonlin_anat2epi # ANTs specific 5D deformation field """ nonreg = Workflow(name='epi_t1_nonlinear') # input inputnode = Node(interface=util.IdentityInterface( fields=['fs_subject_id', 'fs_subjects_dir', 'realigned_epi']), name='inputnode') # calculate the temporal mean image of the realigned timeseries tmean = Node(interface=fsl.maths.MeanImage(dimension='T', output_type='NIFTI_GZ'), name='tmean') nonreg.connect(inputnode, 'realigned_epi', tmean, 'in_file') # import brain.mgz and ribbon.mgz from freesurfer directory fs_import = Node(interface=nio.FreeSurferSource(), name='freesurfer_import') nonreg.connect(inputnode, 'fs_subjects_dir', fs_import, 'subjects_dir') nonreg.connect(inputnode, 'fs_subject_id', fs_import, 'subject_id') # convert brain.mgz to niigz mriconvert = Node(interface=fs.MRIConvert(out_type='niigz'), name='mriconvert') nonreg.connect(fs_import, 'brain', mriconvert, 'in_file') # calculate rigid transformation of mean epi to t1 with bbregister bbregister = Node(interface=fs.BBRegister(init='fsl', contrast_type='t2', out_fsl_file=True), name='bbregister') nonreg.connect(inputnode, 'fs_subjects_dir', bbregister, 'subjects_dir') nonreg.connect(inputnode, 'fs_subject_id', bbregister, 'subject_id') nonreg.connect(tmean, 'out_file', bbregister, 'source_file') # convert linear transformation to itk format compatible with ants itk = Node(interface=c3.C3dAffineTool(fsl2ras=True, itk_transform='epi2anat_affine.txt'), name='itk') nonreg.connect(tmean, 'out_file', itk, 'source_file') nonreg.connect(mriconvert, 'out_file', itk, 'reference_file') nonreg.connect(bbregister, 'out_fsl_file', itk, 'transform_file') # get aparc aseg mask # create brainmask from aparc+aseg def get_aparc_aseg(files): for name in files: if 'aparc+aseg' in name: return name aparc_aseg_mask = Node(fs.Binarize(min=0.1, dilate=10, erode=7, out_type='nii.gz', binary_file='aparc_aseg_mask.nii.gz'), name='aparc_aseg_mask') # fill holes in mask fillholes = Node(fsl.maths.MathsCommand(args='-fillh'), name='fillholes') nonreg.connect([(fs_import, aparc_aseg_mask, [ (('aparc_aseg', get_aparc_aseg), 'in_file') ]), (aparc_aseg_mask, fillholes, [('binary_file', 'in_file')])]) #create bounding box mask and rigidly transform into anatomical (fs) space fov = Node(interface=fs.model.Binarize(min=0.0, out_type='nii.gz'), name='fov') nonreg.connect(tmean, 'out_file', fov, 'in_file') fov_trans = Node(interface=ants.resampling.ApplyTransforms( dimension=3, interpolation='NearestNeighbor'), name='fov_trans') nonreg.connect(itk, ('itk_transform', filename_to_list), fov_trans, 'transforms') nonreg.connect(fov, 'binary_file', fov_trans, 'input_image') nonreg.connect(fillholes, 'out_file', fov_trans, 'reference_image') #nonreg.connect(ribbon, 'binary_file', fov_trans, 'reference_image') # intersect both masks intersect = Node(interface=fsl.maths.BinaryMaths(operation='mul'), name='intersect') nonreg.connect(fillholes, 'out_file', intersect, 'in_file') #nonreg.connect(ribbon, 'binary_file', intersect, 'in_file') nonreg.connect(fov_trans, 'output_image', intersect, 'operand_file') # inversly transform mask and mask original epi mask_trans = Node(interface=ants.resampling.ApplyTransforms( dimension=3, interpolation='NearestNeighbor', invert_transform_flags=[True]), name='mask_trans') nonreg.connect(itk, ('itk_transform', filename_to_list), mask_trans, 'transforms') nonreg.connect(intersect, 'out_file', mask_trans, 'input_image') nonreg.connect(tmean, 'out_file', mask_trans, 'reference_image') maskepi = Node(interface=fs.utils.ApplyMask(), name='maskepi') nonreg.connect(mask_trans, 'output_image', maskepi, 'mask_file') nonreg.connect(tmean, 'out_file', maskepi, 'in_file') # mask anatomical image (brain) maskanat = Node(interface=fs.utils.ApplyMask(), name='maskanat') nonreg.connect(intersect, 'out_file', maskanat, 'mask_file') nonreg.connect(mriconvert, 'out_file', maskanat, 'in_file') # invert masked anatomical image anat_min_max = Node(interface=fsl.utils.ImageStats(op_string='-R'), name='anat_min_max') epi_min_max = Node(interface=fsl.utils.ImageStats(op_string='-r'), name='epi_min_max') nonreg.connect(maskanat, 'out_file', anat_min_max, 'in_file') nonreg.connect(tmean, 'out_file', epi_min_max, 'in_file') def calc_inversion(anat_min_max, epi_min_max): mul = -(epi_min_max[1] - epi_min_max[0]) / (anat_min_max[1] - anat_min_max[0]) add = abs(anat_min_max[1] * mul) + epi_min_max[0] return mul, add calcinv = Node(interface=Function( input_names=['anat_min_max', 'epi_min_max'], output_names=['mul', 'add'], function=calc_inversion), name='calcinv') nonreg.connect(anat_min_max, 'out_stat', calcinv, 'anat_min_max') nonreg.connect(epi_min_max, 'out_stat', calcinv, 'epi_min_max') mulinv = Node(interface=fsl.maths.BinaryMaths(operation='mul'), name='mulinv') addinv = Node(interface=fsl.maths.BinaryMaths(operation='add'), name='addinv') nonreg.connect(maskanat, 'out_file', mulinv, 'in_file') nonreg.connect(calcinv, 'mul', mulinv, 'operand_value') nonreg.connect(mulinv, 'out_file', addinv, 'in_file') nonreg.connect(calcinv, 'add', addinv, 'operand_value') # nonlinear transformation of masked anat to masked epi with ants antsreg = Node(interface=ants.registration.Registration( dimension=3, invert_initial_moving_transform=True, metric=['CC'], metric_weight=[1.0], radius_or_number_of_bins=[4], sampling_strategy=['None'], transforms=['SyN'], args='-g .1x1x.1', transform_parameters=[(0.10, 3, 0)], number_of_iterations=[[10, 5]], convergence_threshold=[1e-06], convergence_window_size=[10], shrink_factors=[[2, 1]], smoothing_sigmas=[[1, 0.5]], sigma_units=['vox'], use_estimate_learning_rate_once=[True], use_histogram_matching=[True], collapse_output_transforms=True, output_inverse_warped_image=True, output_warped_image=True), name='antsreg') nonreg.connect(itk, 'itk_transform', antsreg, 'initial_moving_transform') nonreg.connect(maskepi, 'out_file', antsreg, 'fixed_image') nonreg.connect(addinv, 'out_file', antsreg, 'moving_image') # output def second_element(file_list): return file_list[1] def first_element(file_list): return file_list[0] outputnode = Node(interface=util.IdentityInterface(fields=[ 'lin_epi2anat', 'lin_anat2epi', 'nonlin_epi2anat', 'nonlin_anat2epi' ]), name='outputnode') nonreg.connect(itk, 'itk_transform', outputnode, 'lin_epi2anat') nonreg.connect(antsreg, ('forward_transforms', first_element), outputnode, 'lin_anat2epi') nonreg.connect(antsreg, ('forward_transforms', second_element), outputnode, 'nonlin_anat2epi') nonreg.connect(antsreg, ('reverse_transforms', second_element), outputnode, 'nonlin_epi2anat') return nonreg
def create_workflow(func_runs, subject_id, subjects_dir, fwhm, slice_times, highpass_frequency, lowpass_frequency, TR, sink_directory, use_fsl_bp, num_components, whichvol, name='wmaze'): wf = pe.Workflow(name=name) datasource = pe.Node(nio.DataGrabber(infields=['subject_id', 'run'], outfields=['func']), name='datasource') datasource.inputs.subject_id = subject_id datasource.inputs.run = func_runs datasource.inputs.template = '/home/data/madlab/data/mri/wmaze/%s/bold/bold_%03d/bold.nii.gz' datasource.inputs.sort_filelist = True # Rename files in case they are named identically name_unique = pe.MapNode(util.Rename(format_string='wmaze_%(run)02d'), iterfield = ['in_file', 'run'], name='rename') name_unique.inputs.keep_ext = True name_unique.inputs.run = func_runs wf.connect(datasource, 'func', name_unique, 'in_file') # Define the outputs for the preprocessing workflow output_fields = ['reference', 'motion_parameters', 'motion_parameters_plusDerivs', 'motionandoutlier_noise_file', 'noise_components', 'realigned_files', 'motion_plots', 'mask_file', 'smoothed_files', 'bandpassed_files', 'reg_file', 'reg_cost', 'reg_fsl_file', 'artnorm_files', 'artoutlier_files', 'artdisplacement_files', 'tsnr_file'] outputnode = pe.Node(util.IdentityInterface(fields=output_fields), name='outputspec') # Convert functional images to float representation img2float = pe.MapNode(fsl.ImageMaths(out_data_type='float', op_string = '', suffix='_dtype'), iterfield=['in_file'], name='img2float') wf.connect(name_unique, 'out_file', img2float, 'in_file') # Run AFNI's despike. This is always run, however, whether this is fed to # realign depends on the input configuration despiker = pe.MapNode(afni.Despike(outputtype='NIFTI_GZ'), iterfield=['in_file'], name='despike') num_threads = 4 despiker.inputs.environ = {'OMP_NUM_THREADS': '%d' % num_threads} despiker.plugin_args = {'bsub_args': '-n %d' % num_threads} despiker.plugin_args = {'bsub_args': '-R "span[hosts=1]"'} wf.connect(img2float, 'out_file', despiker, 'in_file') # Extract the first volume of the first run as the reference extractref = pe.Node(fsl.ExtractROI(t_size=1), iterfield=['in_file'], name = "extractref") wf.connect(despiker, ('out_file', pickfirst), extractref, 'in_file') wf.connect(despiker, ('out_file', pickvol, 0, whichvol), extractref, 't_min') wf.connect(extractref, 'roi_file', outputnode, 'reference') if slice_times is not None: # Simultaneous motion and slice timing correction with Nipy algorithm motion_correct = pe.Node(nipy.SpaceTimeRealigner(), name='motion_correct') motion_correct.inputs.tr = TR motion_correct.inputs.slice_times = slice_times motion_correct.inputs.slice_info = 2 motion_correct.plugin_args = {'bsub_args': '-n %s' %os.environ['MKL_NUM_THREADS']} motion_correct.plugin_args = {'bsub_args': '-R "span[hosts=1]"'} wf.connect(despiker, 'out_file', motion_correct, 'in_file') wf.connect(motion_correct, 'par_file', outputnode, 'motion_parameters') wf.connect(motion_correct, 'out_file', outputnode, 'realigned_files') else: # Motion correct functional runs to the reference (1st volume of 1st run) motion_correct = pe.MapNode(fsl.MCFLIRT(save_mats = True, save_plots = True, interpolation = 'sinc'), name = 'motion_correct', iterfield = ['in_file']) wf.connect(despiker, 'out_file', motion_correct, 'in_file') wf.connect(extractref, 'roi_file', motion_correct, 'ref_file') wf.connect(motion_correct, 'par_file', outputnode, 'motion_parameters') wf.connect(motion_correct, 'out_file', outputnode, 'realigned_files') # Compute TSNR on realigned data regressing polynomials upto order 2 tsnr = pe.MapNode(TSNR(regress_poly=2), iterfield=['in_file'], name='tsnr') wf.connect(motion_correct, 'out_file', tsnr, 'in_file') wf.connect(tsnr, 'tsnr_file', outputnode, 'tsnr_file') # Plot the estimated motion parameters plot_motion = pe.MapNode(fsl.PlotMotionParams(in_source='fsl'), name='plot_motion', iterfield=['in_file']) plot_motion.iterables = ('plot_type', ['rotations', 'translations']) wf.connect(motion_correct, 'par_file', plot_motion, 'in_file') wf.connect(plot_motion, 'out_file', outputnode, 'motion_plots') # Register a source file to fs space and create a brain mask in source space fssource = pe.Node(nio.FreeSurferSource(), name ='fssource') fssource.inputs.subject_id = subject_id fssource.inputs.subjects_dir = subjects_dir # Extract aparc+aseg brain mask and binarize fs_threshold = pe.Node(fs.Binarize(min=0.5, out_type='nii'), name ='fs_threshold') wf.connect(fssource, ('aparc_aseg', get_aparc_aseg), fs_threshold, 'in_file') # Calculate the transformation matrix from EPI space to FreeSurfer space # using the BBRegister command fs_register = pe.MapNode(fs.BBRegister(init='fsl'), iterfield=['source_file'], name ='fs_register') fs_register.inputs.contrast_type = 't2' fs_register.inputs.out_fsl_file = True fs_register.inputs.subject_id = subject_id fs_register.inputs.subjects_dir = subjects_dir wf.connect(extractref, 'roi_file', fs_register, 'source_file') wf.connect(fs_register, 'out_reg_file', outputnode, 'reg_file') wf.connect(fs_register, 'min_cost_file', outputnode, 'reg_cost') wf.connect(fs_register, 'out_fsl_file', outputnode, 'reg_fsl_file') # Extract wm+csf, brain masks by eroding freesurfer lables wmcsf = pe.MapNode(fs.Binarize(), iterfield=['match', 'binary_file', 'erode'], name='wmcsfmask') #wmcsf.inputs.wm_ven_csf = True wmcsf.inputs.match = [[2, 41], [4, 5, 14, 15, 24, 31, 43, 44, 63]] wmcsf.inputs.binary_file = ['wm.nii.gz', 'csf.nii.gz'] wmcsf.inputs.erode = [2, 2] #int(np.ceil(slice_thickness)) wf.connect(fssource, ('aparc_aseg', get_aparc_aseg), wmcsf, 'in_file') # Now transform the wm and csf masks to 1st volume of 1st run wmcsftransform = pe.MapNode(fs.ApplyVolTransform(inverse=True, interp='nearest'), iterfield=['target_file'], name='wmcsftransform') wmcsftransform.inputs.subjects_dir = subjects_dir wf.connect(extractref, 'roi_file', wmcsftransform, 'source_file') wf.connect(fs_register, ('out_reg_file', pickfirst), wmcsftransform, 'reg_file') wf.connect(wmcsf, 'binary_file', wmcsftransform, 'target_file') # Transform the binarized aparc+aseg file to the 1st volume of 1st run space fs_voltransform = pe.MapNode(fs.ApplyVolTransform(inverse=True), iterfield = ['source_file', 'reg_file'], name='fs_transform') fs_voltransform.inputs.subjects_dir = subjects_dir wf.connect(extractref, 'roi_file', fs_voltransform, 'source_file') wf.connect(fs_register, 'out_reg_file', fs_voltransform, 'reg_file') wf.connect(fs_threshold, 'binary_file', fs_voltransform, 'target_file') # Dilate the binarized mask by 1 voxel that is now in the EPI space fs_threshold2 = pe.MapNode(fs.Binarize(min=0.5, out_type='nii'), iterfield=['in_file'], name='fs_threshold2') fs_threshold2.inputs.dilate = 1 wf.connect(fs_voltransform, 'transformed_file', fs_threshold2, 'in_file') wf.connect(fs_threshold2, 'binary_file', outputnode, 'mask_file') # Use RapidART to detect motion/intensity outliers art = pe.MapNode(ra.ArtifactDetect(use_differences = [True, False], use_norm = True, zintensity_threshold = 3, norm_threshold = 1, bound_by_brainmask=True, mask_type = "file"), iterfield=["realignment_parameters","realigned_files"], name="art") if slice_times is not None: art.inputs.parameter_source = "NiPy" else: art.inputs.parameter_source = "FSL" wf.connect(motion_correct, 'par_file', art, 'realignment_parameters') wf.connect(motion_correct, 'out_file', art, 'realigned_files') wf.connect(fs_threshold2, ('binary_file', pickfirst), art, 'mask_file') wf.connect(art, 'norm_files', outputnode, 'artnorm_files') wf.connect(art, 'outlier_files', outputnode, 'artoutlier_files') wf.connect(art, 'displacement_files', outputnode, 'artdisplacement_files') # Compute motion regressors (save file with 1st and 2nd derivatives) motreg = pe.Node(util.Function(input_names=['motion_params', 'order', 'derivatives'], output_names=['out_files'], function=motion_regressors, imports=imports), name='getmotionregress') wf.connect(motion_correct, 'par_file', motreg, 'motion_params') wf.connect(motreg, 'out_files', outputnode, 'motion_parameters_plusDerivs') # Create a filter text file to remove motion (+ derivatives), art confounds, # and 1st, 2nd, and 3rd order legendre polynomials. createfilter1 = pe.Node(util.Function(input_names=['motion_params', 'comp_norm', 'outliers', 'detrend_poly'], output_names=['out_files'], function=build_filter1, imports=imports), name='makemotionbasedfilter') createfilter1.inputs.detrend_poly = 3 wf.connect(motreg, 'out_files', createfilter1, 'motion_params') wf.connect(art, 'norm_files', createfilter1, 'comp_norm') wf.connect(art, 'outlier_files', createfilter1, 'outliers') wf.connect(createfilter1, 'out_files', outputnode, 'motionandoutlier_noise_file') # Create a filter to remove noise components based on white matter and CSF createfilter2 = pe.MapNode(util.Function(input_names=['realigned_file', 'mask_file', 'num_components', 'extra_regressors'], output_names=['out_files'], function=extract_noise_components, imports=imports), iterfield=['realigned_file', 'extra_regressors'], name='makecompcorrfilter') createfilter2.inputs.num_components = num_components wf.connect(createfilter1, 'out_files', createfilter2, 'extra_regressors') wf.connect(motion_correct, 'out_file', createfilter2, 'realigned_file') wf.connect(wmcsftransform, 'transformed_file', createfilter2, 'mask_file') wf.connect(createfilter2, 'out_files', outputnode, 'noise_components') # Mask the functional runs with the extracted mask maskfunc = pe.MapNode(fsl.ImageMaths(suffix='_bet', op_string='-mas'), iterfield=['in_file'], name = 'maskfunc') wf.connect(motion_correct, 'out_file', maskfunc, 'in_file') wf.connect(fs_threshold2, ('binary_file', pickfirst), maskfunc, 'in_file2') # Smooth each run using SUSAn with the brightness threshold set to 75% # of the median value for each run and a mask constituting the mean functional smooth_median = pe.MapNode(fsl.ImageStats(op_string='-k %s -p 50'), iterfield = ['in_file'], name='smooth_median') wf.connect(maskfunc, 'out_file', smooth_median, 'in_file') wf.connect(fs_threshold2, ('binary_file', pickfirst), smooth_median, 'mask_file') smooth_meanfunc = pe.MapNode(fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), iterfield=['in_file'], name='smooth_meanfunc') wf.connect(maskfunc, 'out_file', smooth_meanfunc, 'in_file') smooth_merge = pe.Node(util.Merge(2, axis='hstack'), name='smooth_merge') wf.connect(smooth_meanfunc, 'out_file', smooth_merge, 'in1') wf.connect(smooth_median, 'out_stat', smooth_merge, 'in2') smooth = pe.MapNode(fsl.SUSAN(), iterfield=['in_file', 'brightness_threshold', 'usans'], name='smooth') smooth.inputs.fwhm=fwhm wf.connect(maskfunc, 'out_file', smooth, 'in_file') wf.connect(smooth_median, ('out_stat', getbtthresh), smooth, 'brightness_threshold') wf.connect(smooth_merge, ('out', getusans), smooth, 'usans') # Mask the smoothed data with the dilated mask maskfunc2 = pe.MapNode(fsl.ImageMaths(suffix='_mask', op_string='-mas'), iterfield=['in_file'], name='maskfunc2') wf.connect(smooth, 'smoothed_file', maskfunc2, 'in_file') wf.connect(fs_threshold2, ('binary_file', pickfirst), maskfunc2, 'in_file2') wf.connect(maskfunc2, 'out_file', outputnode, 'smoothed_files') # Band-pass filter the timeseries if use_fsl_bp == 'True': determine_bp_sigmas = pe.Node(util.Function(input_names=['tr', 'highpass_freq', 'lowpass_freq'], output_names = ['out_sigmas'], function=calc_fslbp_sigmas), name='determine_bp_sigmas') determine_bp_sigmas.inputs.tr = float(TR) determine_bp_sigmas.inputs.highpass_freq = float(highpass_frequency) determine_bp_sigmas.inputs.lowpass_freq = float(lowpass_frequency) bandpass = pe.MapNode(fsl.ImageMaths(suffix='_tempfilt'), iterfield=["in_file"], name="bandpass") wf.connect(determine_bp_sigmas, ('out_sigmas', highpass_operand), bandpass, 'op_string') wf.connect(maskfunc2, 'out_file', bandpass, 'in_file') wf.connect(bandpass, 'out_file', outputnode, 'bandpassed_files') else: bandpass = pe.Node(util.Function(input_names=['files', 'lowpass_freq', 'highpass_freq', 'fs'], output_names=['out_files'], function=bandpass_filter, imports=imports), name='bandpass') bandpass.inputs.fs = 1./TR if highpass_frequency < 0: bandpass.inputs.highpass_freq = -1 else: bandpass.inputs.highpass_freq = highpass_frequency if lowpass_frequency < 0: bandpass.inputs.lowpass_freq = -1 else: bandpass.inputs.lowpass_freq = lowpass_frequency wf.connect(maskfunc2, 'out_file', bandpass, 'files') wf.connect(bandpass, 'out_files', outputnode, 'bandpassed_files') # Save the relevant data into an output directory datasink = pe.Node(nio.DataSink(), name="datasink") datasink.inputs.base_directory = sink_directory datasink.inputs.container = subject_id wf.connect(outputnode, 'reference', datasink, 'ref') wf.connect(outputnode, 'motion_parameters', datasink, 'motion') wf.connect(outputnode, 'realigned_files', datasink, 'func.realigned') wf.connect(outputnode, 'motion_plots', datasink, 'motion.@plots') wf.connect(outputnode, 'mask_file', datasink, 'ref.@mask') wf.connect(outputnode, 'smoothed_files', datasink, 'func.smoothed_fullspectrum') wf.connect(outputnode, 'bandpassed_files', datasink, 'func.smoothed_bandpassed') wf.connect(outputnode, 'reg_file', datasink, 'bbreg.@reg') wf.connect(outputnode, 'reg_cost', datasink, 'bbreg.@cost') wf.connect(outputnode, 'reg_fsl_file', datasink, 'bbreg.@regfsl') wf.connect(outputnode, 'artnorm_files', datasink, 'art.@norm_files') wf.connect(outputnode, 'artoutlier_files', datasink, 'art.@outlier_files') wf.connect(outputnode, 'artdisplacement_files', datasink, 'art.@displacement_files') wf.connect(outputnode, 'motion_parameters_plusDerivs', datasink, 'noise.@motionplusDerivs') wf.connect(outputnode, 'motionandoutlier_noise_file', datasink, 'noise.@motionplusoutliers') wf.connect(outputnode, 'noise_components', datasink, 'compcor') wf.connect(outputnode, 'tsnr_file', datasink, 'tsnr') return wf
def create_confound_removal_workflow(workflow_name="confound_removal"): inputnode = pe.Node(util.IdentityInterface( fields=["subject_id", "timeseries", "reg_file", "motion_parameters"]), name="inputs") # Get the Freesurfer aseg volume from the Subjects Directory getaseg = pe.Node(io.FreeSurferSource(subjects_dir=fs.Info.subjectsdir()), name="getaseg") # Binarize the Aseg to use as a whole brain mask asegmask = pe.Node(fs.Binarize(min=0.5, dilate=2), name="asegmask") # Extract and erode a mask of the deep cerebral white matter extractwm = pe.Node(fs.Binarize(match=[2, 41], erode=3), name="extractwm") # Extract and erode a mask of the ventricles and CSF extractcsf = pe.Node(fs.Binarize(match=[4, 5, 14, 15, 24, 31, 43, 44, 63], erode=1), name="extractcsf") # Mean the timeseries across the fourth dimension meanfunc = pe.MapNode(fsl.MeanImage(), iterfield=["in_file"], name="meanfunc") # Invert the anatomical coregistration and resample the masks regwm = pe.MapNode(fs.ApplyVolTransform(inverse=True, interp="nearest"), iterfield=["source_file", "reg_file"], name="regwm") regcsf = pe.MapNode(fs.ApplyVolTransform(inverse=True, interp="nearest"), iterfield=["source_file", "reg_file"], name="regcsf") regbrain = pe.MapNode(fs.ApplyVolTransform(inverse=True, interp="nearest"), iterfield=["source_file", "reg_file"], name="regbrain") # Convert to Nifti for FSL tools convertwm = pe.MapNode(fs.MRIConvert(out_type="niigz"), iterfield=["in_file"], name="convertwm") convertcsf = pe.MapNode(fs.MRIConvert(out_type="niigz"), iterfield=["in_file"], name="convertcsf") convertbrain = pe.MapNode(fs.MRIConvert(out_type="niigz"), iterfield=["in_file"], name="convertbrain") # Add the mask images together for a report image addconfmasks = pe.MapNode(fsl.ImageMaths(suffix="conf", op_string="-mul 2 -add", out_data_type="char"), iterfield=["in_file", "in_file2"], name="addconfmasks") # Overlay and slice the confound mask overlaied on mean func for reporting confoverlay = pe.MapNode(fsl.Overlay(auto_thresh_bg=True, stat_thresh=(.7, 2)), iterfield=["background_image", "stat_image"], name="confoverlay") confslice = pe.MapNode(fsl.Slicer(image_width=800, label_slices=False), iterfield=["in_file"], name="confslice") confslice.inputs.sample_axial = 2 # Extract the mean signal from white matter and CSF masks wmtcourse = pe.MapNode(fs.SegStats(exclude_id=0, avgwf_txt_file=True), iterfield=["segmentation_file", "in_file"], name="wmtcourse") csftcourse = pe.MapNode(fs.SegStats(exclude_id=0, avgwf_txt_file=True), iterfield=["segmentation_file", "in_file"], name="csftcourse") # Extract the mean signal from over the whole brain globaltcourse = pe.MapNode(fs.SegStats(exclude_id=0, avgwf_txt_file=True), iterfield=["segmentation_file", "in_file"], name="globaltcourse") # Build the confound design matrix conf_inputs = [ "motion_params", "global_waveform", "wm_waveform", "csf_waveform" ] confmatrix = pe.MapNode(util.Function(input_names=conf_inputs, output_names=["confound_matrix"], function=make_confound_matrix), iterfield=conf_inputs, name="confmatrix") # Regress the confounds out of the timeseries confregress = pe.MapNode(fsl.FilterRegressor(filter_all=True), iterfield=["in_file", "design_file", "mask"], name="confregress") # Rename the confound mask png renamepng = pe.MapNode(util.Rename(format_string="confound_sources.png"), iterfield=["in_file"], name="renamepng") # Define the outputs outputnode = pe.Node( util.IdentityInterface(fields=["timeseries", "confound_sources"]), name="outputs") # Define and connect the confound workflow confound = pe.Workflow(name=workflow_name) confound.connect([ (inputnode, meanfunc, [("timeseries", "in_file")]), (inputnode, getaseg, [("subject_id", "subject_id")]), (getaseg, extractwm, [("aseg", "in_file")]), (getaseg, extractcsf, [("aseg", "in_file")]), (getaseg, asegmask, [("aseg", "in_file")]), (extractwm, regwm, [("binary_file", "target_file")]), (extractcsf, regcsf, [("binary_file", "target_file")]), (asegmask, regbrain, [("binary_file", "target_file")]), (meanfunc, regwm, [("out_file", "source_file")]), (meanfunc, regcsf, [("out_file", "source_file")]), (meanfunc, regbrain, [("out_file", "source_file")]), (inputnode, regwm, [("reg_file", "reg_file")]), (inputnode, regcsf, [("reg_file", "reg_file")]), (inputnode, regbrain, [("reg_file", "reg_file")]), (regwm, convertwm, [("transformed_file", "in_file")]), (regcsf, convertcsf, [("transformed_file", "in_file")]), (regbrain, convertbrain, [("transformed_file", "in_file")]), (convertwm, addconfmasks, [("out_file", "in_file")]), (convertcsf, addconfmasks, [("out_file", "in_file2")]), (addconfmasks, confoverlay, [("out_file", "stat_image")]), (meanfunc, confoverlay, [("out_file", "background_image")]), (confoverlay, confslice, [("out_file", "in_file")]), (confslice, renamepng, [("out_file", "in_file")]), (regwm, wmtcourse, [("transformed_file", "segmentation_file")]), (inputnode, wmtcourse, [("timeseries", "in_file")]), (regcsf, csftcourse, [("transformed_file", "segmentation_file")]), (inputnode, csftcourse, [("timeseries", "in_file")]), (regbrain, globaltcourse, [("transformed_file", "segmentation_file")]), (inputnode, globaltcourse, [("timeseries", "in_file")]), (inputnode, confmatrix, [("motion_parameters", "motion_params")]), (wmtcourse, confmatrix, [("avgwf_txt_file", "wm_waveform")]), (csftcourse, confmatrix, [("avgwf_txt_file", "csf_waveform")]), (globaltcourse, confmatrix, [("avgwf_txt_file", "global_waveform")]), (confmatrix, confregress, [("confound_matrix", "design_file")]), (inputnode, confregress, [("timeseries", "in_file")]), (convertbrain, confregress, [("out_file", "mask")]), (confregress, outputnode, [("out_file", "timeseries")]), (renamepng, outputnode, [("out_file", "confound_sources")]), ]) return confound
def create_bbregister_workflow(name="bbregister", contrast_type="t2"): # Define the workflow inputs inputnode = pe.Node( util.IdentityInterface(fields=["subject_id", "source_file"]), name="inputs") # Estimate the registration to Freesurfer conformed space func2anat = pe.MapNode(fs.BBRegister(contrast_type=contrast_type, init="fsl", epi_mask=True, registered_file=True, out_fsl_file=True), iterfield=["source_file"], name="func2anat") # Set up a node to grab the target from the subjects directory fssource = pe.Node(io.FreeSurferSource(subjects_dir=fs.Info.subjectsdir()), name="fssource") # Always overwrite the grab; shouldn't cascade unless the underlying image changes fssource.overwrite = True # Convert the target to nifti convert = pe.Node(fs.MRIConvert(out_type="niigz"), name="convertbrain") # Swap dimensions so stuff looks nice in the report flipbrain = pe.Node(fsl.SwapDimensions(new_dims=("RL", "PA", "IS")), name="flipbrain") flipfunc = pe.MapNode(fsl.SwapDimensions(new_dims=("RL", "PA", "IS")), iterfield=["in_file"], name="flipfunc") # Slice up the registration func2anatpng = pe.MapNode(fsl.Slicer(middle_slices=True, show_orientation=False, scaling=.6, label_slices=False), iterfield=["in_file"], name="func2anatpng") # Rename some files pngname = pe.MapNode(util.Rename(format_string="func2anat.png"), iterfield=["in_file"], name="pngname") costname = pe.MapNode(util.Rename(format_string="func2anat_cost.dat"), iterfield=["in_file"], name="costname") tkregname = pe.MapNode(util.Rename(format_string="func2anat_tkreg.dat"), iterfield=["in_file"], name="tkregname") flirtname = pe.MapNode(util.Rename(format_string="func2anat_flirt.mat"), iterfield=["in_file"], name="flirtname") # Merge the slicer png and cost file into a report list report = pe.Node(util.Merge(2, axis="hstack"), name="report") # Define the workflow outputs outputnode = pe.Node( util.IdentityInterface(fields=["tkreg_mat", "flirt_mat", "report"]), name="outputs") bbregister = pe.Workflow(name=name) # Connect the registration bbregister.connect([ (inputnode, func2anat, [("subject_id", "subject_id"), ("source_file", "source_file")]), (inputnode, fssource, [("subject_id", "subject_id")]), (func2anat, flipfunc, [("registered_file", "in_file")]), (flipfunc, func2anatpng, [("out_file", "in_file")]), (fssource, convert, [("brain", "in_file")]), (convert, flipbrain, [("out_file", "in_file")]), (flipbrain, func2anatpng, [("out_file", "image_edges")]), (func2anatpng, pngname, [("out_file", "in_file")]), (func2anat, tkregname, [("out_reg_file", "in_file")]), (func2anat, flirtname, [("out_fsl_file", "in_file")]), (func2anat, costname, [("min_cost_file", "in_file")]), (costname, report, [("out_file", "in1")]), (pngname, report, [("out_file", "in2")]), (tkregname, outputnode, [("out_file", "tkreg_mat")]), (flirtname, outputnode, [("out_file", "flirt_mat")]), (report, outputnode, [("out", "report")]), ]) return bbregister
art.inputs.mask_type = 'file' art.inputs.parameter_source = 'SPM' """ Use :class:`nipype.interfaces.freesurfer.BBRegister` to coregister the mean functional image generated by realign to the subjects' surfaces. """ surfregister = pe.Node(interface=fs.BBRegister(), name='surfregister') surfregister.inputs.init = 'fsl' surfregister.inputs.contrast_type = 't2' """ Use :class:`nipype.interfaces.io.FreeSurferSource` to retrieve various image files that are automatically generated by the recon-all process. """ FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(), name='fssource') """ Use :class:`nipype.interfaces.freesurfer.ApplyVolTransform` to convert the brainmask generated by freesurfer into the realigned functional space. """ ApplyVolTransform = pe.Node(interface=fs.ApplyVolTransform(), name='applyreg') ApplyVolTransform.inputs.inverse = True """ Use :class:`nipype.interfaces.freesurfer.Binarize` to extract a binary brain mask. """ Threshold = pe.Node(interface=fs.Binarize(), name='threshold') Threshold.inputs.min = 10 Threshold.inputs.out_type = 'nii'
def create_tessellation_flow(name='tessellate', out_format='stl'): """Tessellates the input subject's aseg.mgz volume and returns the surfaces for each region in stereolithic (.stl) format Example ------- >>> from nipype.workflows.smri.freesurfer import create_tessellation_flow >>> tessflow = create_tessellation_flow() >>> tessflow.inputs.inputspec.subject_id = 'subj1' >>> tessflow.inputs.inputspec.subjects_dir = '.' >>> tessflow.inputs.inputspec.lookup_file = 'FreeSurferColorLUT.txt' # doctest: +SKIP >>> tessflow.run() # doctest: +SKIP Inputs:: inputspec.subject_id : freesurfer subject id inputspec.subjects_dir : freesurfer subjects directory inputspec.lookup_file : lookup file from freesurfer directory Outputs:: outputspec.meshes : output region meshes in (by default) stereolithographic (.stl) format """ """ Initialize the workflow """ tessflow = pe.Workflow(name=name) """ Define the inputs to the workflow. """ inputnode = pe.Node(niu.IdentityInterface( fields=['subject_id', 'subjects_dir', 'lookup_file']), name='inputspec') """ Define all the nodes of the workflow: fssource: used to retrieve aseg.mgz mri_convert : converts aseg.mgz to aseg.nii tessellate : tessellates regions in aseg.mgz surfconvert : converts regions to stereolithographic (.stl) format smoother: smooths the tessellated regions """ fssource = pe.Node(nio.FreeSurferSource(), name='fssource') volconvert = pe.Node(fs.MRIConvert(out_type='nii'), name='volconvert') tessellate = pe.MapNode(fs.MRIMarchingCubes(), iterfield=['label_value', 'out_file'], name='tessellate') surfconvert = pe.MapNode(fs.MRIsConvert(out_datatype='stl'), iterfield=['in_file'], name='surfconvert') smoother = pe.MapNode(mf.MeshFix(), iterfield=['in_file1'], name='smoother') if out_format == 'gii': stl_to_gifti = pe.MapNode(fs.MRIsConvert(out_datatype=out_format), iterfield=['in_file'], name='stl_to_gifti') smoother.inputs.save_as_stl = True smoother.inputs.laplacian_smoothing_steps = 1 region_list_from_volume_interface = Function( input_names=["in_file"], output_names=["region_list"], function=region_list_from_volume) id_list_from_lookup_table_interface = Function( input_names=["lookup_file", "region_list"], output_names=["id_list"], function=id_list_from_lookup_table) region_list_from_volume_node = pe.Node( interface=region_list_from_volume_interface, name='region_list_from_volume_node') id_list_from_lookup_table_node = pe.Node( interface=id_list_from_lookup_table_interface, name='id_list_from_lookup_table_node') """ Connect the nodes """ tessflow.connect([ (inputnode, fssource, [('subject_id', 'subject_id'), ('subjects_dir', 'subjects_dir')]), (fssource, volconvert, [('aseg', 'in_file')]), (volconvert, region_list_from_volume_node, [('out_file', 'in_file')]), (region_list_from_volume_node, tessellate, [('region_list', 'label_value')]), (region_list_from_volume_node, id_list_from_lookup_table_node, [('region_list', 'region_list')]), (inputnode, id_list_from_lookup_table_node, [('lookup_file', 'lookup_file')]), (id_list_from_lookup_table_node, tessellate, [('id_list', 'out_file') ]), (fssource, tessellate, [('aseg', 'in_file')]), (tessellate, surfconvert, [('surface', 'in_file')]), (surfconvert, smoother, [('converted', 'in_file1')]), ]) """ Setup an outputnode that defines relevant inputs of the workflow. """ outputnode = pe.Node(niu.IdentityInterface(fields=["meshes"]), name="outputspec") if out_format == 'gii': tessflow.connect([ (smoother, stl_to_gifti, [("mesh_file", "in_file")]), ]) tessflow.connect([ (stl_to_gifti, outputnode, [("converted", "meshes")]), ]) else: tessflow.connect([ (smoother, outputnode, [("mesh_file", "meshes")]), ]) return tessflow
def create_coreg_pipeline(name='coreg'): # fsl output type fsl.FSLCommand.set_default_output_type('NIFTI_GZ') # initiate workflow coreg = Workflow(name='coreg') #inputnode inputnode = Node(util.IdentityInterface(fields=[ 'epi_median', 'fs_subjects_dir', 'fs_subject_id', 'uni_highres', ]), name='inputnode') # outputnode outputnode = Node(util.IdentityInterface(fields=[ 'uni_lowres', 'epi2lowres', 'epi2lowres_mat', 'epi2lowres_dat', 'highres2lowres', 'highres2lowres_mat', 'highres2lowres_dat', 'epi2highres_lin', 'epi2highres_lin_mat', 'epi2highres_lin_itk' ]), name='outputnode') # convert mgz head file for reference fs_import = Node(interface=nio.FreeSurferSource(), name='fs_import') brain_convert = Node(fs.MRIConvert(out_type='niigz', out_file='uni_lowres.nii.gz'), name='brain_convert') coreg.connect([(inputnode, fs_import, [('fs_subjects_dir', 'subjects_dir'), ('fs_subject_id', 'subject_id')]), (fs_import, brain_convert, [('brain', 'in_file')]), (brain_convert, outputnode, [('out_file', 'uni_lowres')])]) # linear registration epi median to lowres mp2rage with bbregister bbregister_epi = Node(fs.BBRegister(contrast_type='t2', out_fsl_file='epi2lowres.mat', out_reg_file='epi2lowres.dat', registered_file='epi2lowres.nii.gz', init='fsl', epi_mask=True), name='bbregister_epi') coreg.connect([ (inputnode, bbregister_epi, [('fs_subjects_dir', 'subjects_dir'), ('fs_subject_id', 'subject_id'), ('epi_median', 'source_file')]), (bbregister_epi, outputnode, [('out_fsl_file', 'epi2lowres_mat'), ('out_reg_file', 'epi2lowres_dat'), ('registered_file', 'epi2lowres')]) ]) # linear register highres mp2rage to lowres mp2rage bbregister_anat = Node(fs.BBRegister( contrast_type='t1', out_fsl_file='highres2lowres.mat', out_reg_file='highres2lowres.dat', registered_file='highres2lowres.nii.gz', init='fsl'), name='bbregister_anat') coreg.connect([ (inputnode, bbregister_anat, [('fs_subjects_dir', 'subjects_dir'), ('fs_subject_id', 'subject_id'), ('uni_highres', 'source_file')]), (bbregister_anat, outputnode, [('out_fsl_file', 'highres2lowres_mat'), ('out_reg_file', 'highres2lowres_dat'), ('registered_file', 'highres2lowres')]) ]) # invert highres2lowres transform invert = Node(fsl.ConvertXFM(invert_xfm=True), name='invert') coreg.connect([(bbregister_anat, invert, [('out_fsl_file', 'in_file')])]) # concatenate epi2highres transforms concat = Node(fsl.ConvertXFM(concat_xfm=True, out_file='epi2highres_lin.mat'), name='concat') coreg.connect([(bbregister_epi, concat, [('out_fsl_file', 'in_file')]), (invert, concat, [('out_file', 'in_file2')]), (concat, outputnode, [('out_file', 'epi2higres_lin_mat')])]) # convert epi2highres transform into itk format itk = Node(interface=c3.C3dAffineTool(fsl2ras=True, itk_transform='epi2highres_lin.txt'), name='itk') coreg.connect([(inputnode, itk, [('epi_median', 'source_file'), ('uni_highres', 'reference_file')]), (concat, itk, [('out_file', 'transform_file')]), (itk, outputnode, [('itk_transform', 'epi2highres_lin_itk') ])]) # transform epi to highres epi2highres = Node(ants.ApplyTransforms( dimension=3, output_image='epi2highres_lin.nii.gz', interpolation='BSpline', ), name='epi2highres') coreg.connect([ (inputnode, epi2highres, [('uni_highres', 'reference_image'), ('epi_median', 'input_image')]), (itk, epi2highres, [('itk_transform', 'transforms')]), (epi2highres, outputnode, [('output_image', 'epi2highres_lin')]) ]) return coreg
def init_gifti_surface_wf(name='gifti_surface_wf'): workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityInterface(['subjects_dir', 'subject_id']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface(['surfaces']), name='outputnode') get_surfaces = pe.Node(nio.FreeSurferSource(), name='get_surfaces') midthickness = pe.MapNode(MakeMidthickness(thickness=True, distance=0.5, out_name='midthickness'), iterfield='in_file', name='midthickness') save_midthickness = pe.Node(nio.DataSink(parameterization=False), name='save_midthickness') surface_list = pe.Node(niu.Merge(4, ravel_inputs=True), name='surface_list', run_without_submitting=True) fs_2_gii = pe.MapNode(fs.MRIsConvert(out_datatype='gii'), iterfield='in_file', name='fs_2_gii') def normalize_surfs(in_file): """ Re-center GIFTI coordinates to fit align to native T1 space For midthickness surfaces, add MidThickness metadata Coordinate update based on: https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91 and https://github.com/Washington-University/Pipelines/blob/ae69b9a/PostFreeSurfer/scripts/FreeSurfer2CaretConvertAndRegisterNonlinear.sh#L147 """ import os import numpy as np import nibabel as nib img = nib.load(in_file) pointset = img.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0] coords = pointset.data c_ras_keys = ('VolGeomC_R', 'VolGeomC_A', 'VolGeomC_S') ras = np.array([float(pointset.metadata[key]) for key in c_ras_keys]) # Apply C_RAS translation to coordinates pointset.data = (coords + ras).astype(coords.dtype) secondary = nib.gifti.GiftiNVPairs('AnatomicalStructureSecondary', 'MidThickness') geom_type = nib.gifti.GiftiNVPairs('GeometricType', 'Anatomical') has_ass = has_geo = False for nvpair in pointset.meta.data: # Remove C_RAS translation from metadata to avoid double-dipping in FreeSurfer if nvpair.name in c_ras_keys: nvpair.value = '0.000000' # Check for missing metadata elif nvpair.name == secondary.name: has_ass = True elif nvpair.name == geom_type.name: has_geo = True fname = os.path.basename(in_file) # Update metadata for MidThickness/graymid surfaces if 'midthickness' in fname.lower() or 'graymid' in fname.lower(): if not has_ass: pointset.meta.data.insert(1, secondary) if not has_geo: pointset.meta.data.insert(2, geom_type) img.to_filename(fname) return os.path.abspath(fname) fix_surfs = pe.MapNode(niu.Function(function=normalize_surfs), iterfield='in_file', name='fix_surfs') workflow.connect([ (inputnode, get_surfaces, [('subjects_dir', 'subjects_dir'), ('subject_id', 'subject_id')]), (inputnode, save_midthickness, [('subjects_dir', 'base_directory'), ('subject_id', 'container')]), # Generate midthickness surfaces and save to FreeSurfer derivatives (get_surfaces, midthickness, [('smoothwm', 'in_file'), ('graymid', 'graymid')]), (midthickness, save_midthickness, [('out_file', 'surf.@graymid')]), # Produce valid GIFTI surface files (dense mesh) (get_surfaces, surface_list, [('smoothwm', 'in1'), ('pial', 'in2'), ('inflated', 'in3')]), (save_midthickness, surface_list, [('out_file', 'in4')]), (surface_list, fs_2_gii, [('out', 'in_file')]), (fs_2_gii, fix_surfs, [('converted', 'in_file')]), (fix_surfs, outputnode, [('out', 'surfaces')]), ]) return workflow
def test_freesurfersource_incorrectdir(): fss = nio.FreeSurferSource() with pytest.raises(TraitError) as err: fss.inputs.subjects_dir = 'path/to/no/existing/directory'
def damaged_brain_dti_processing(name="dwi_preproc", use_FAST_masks=True): ''' Uses both Freesurfer and FAST to mask the white matter because neither works sufficiently well in patients ''' ''' Define inputs and outputs of the workflow ''' inputnode = pe.Node( interface=util.IdentityInterface(fields=["subjects_dir", "subject_id", "dwi", "bvecs", "bvals"]), name="inputnode") outputnode = pe.Node( interface=util.IdentityInterface(fields=["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"]), name="outputnode") ''' Define the nodes ''' 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" 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 if not use_FAST_masks: fix_wm_mask = pe.Node(interface=fsl.MultiImageMaths(), name='fix_wm_mask') fix_wm_mask.inputs.op_string = "-mul %s" if use_FAST_masks: make_termination_mask = pe.Node( interface=fsl.MultiImageMaths(), name='make_termination_mask') make_termination_mask.inputs.op_string = "-add %s -bin" else: make_termination_mask = pe.Node( interface=fsl.ImageMaths(), name='make_termination_mask') make_termination_mask.inputs.op_string = "-bin" 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") ''' Connect the workflow ''' workflow = pe.Workflow(name=name) workflow.base_dir = name ''' Structural processing to create seed and termination masks ''' 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')])]) 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')])]) workflow.connect( [(mri_convert_Brain, fast_seg_T1, [('out_file', 'in_files')])]) workflow.connect( [(inputnode, fast_seg_T1, [("subject_id", "out_basename")])]) workflow.connect( [(FreeSurferSource, mri_convert_ROIs, [(('aparc_aseg', select_aparc), 'in_file')])]) workflow.connect( [(inputnode, mri_convert_ROIs, [(('subject_id', add_subj_name_to_aparc), 'out_file')])]) if use_FAST_masks: workflow.connect( [(fast_seg_T1, outputnode, [(('tissue_class_files', select_WM), 'wm_mask')])]) workflow.connect( [(fast_seg_T1, make_termination_mask, [(('tissue_class_files', select_GM), 'in_file')])]) workflow.connect( [(fast_seg_T1, make_termination_mask, [(('tissue_class_files', select_WM), 'operand_files')])]) workflow.connect( [(inputnode, make_termination_mask, [(('subject_id', add_subj_name_to_termmask), 'out_file')])]) workflow.connect( [(make_termination_mask, outputnode, [("out_file", "term_mask")])]) else: workflow.connect( [(mri_convert_ROIs, make_wm_mask, [('out_file', 'in_file')])]) workflow.connect( [(make_wm_mask, fix_wm_mask, [('out_file', 'operand_files')])]) workflow.connect( [(fast_seg_T1, fix_wm_mask, [(('tissue_class_files', select_WM), 'in_file')])]) workflow.connect( [(FreeSurferSource, mri_convert_Ribbon, [(('ribbon', select_ribbon), 'in_file')])]) workflow.connect( [(mri_convert_Ribbon, make_termination_mask, [('out_file', 'in_file')])]) workflow.connect( [(make_termination_mask, fix_termination_mask, [('out_file', 'operand_files')])]) workflow.connect( [(fast_seg_T1, fix_termination_mask, [(('tissue_class_files', select_CSF), 'in_file')])]) ''' Diffusion processing ''' workflow.connect(inputnode, 'subject_id', nonlinfit_node, 'base_name') workflow.connect(inputnode, 'dwi', nonlinfit_node, 'dwi') workflow.connect(inputnode, 'bvecs', nonlinfit_node, 'bvecs') workflow.connect(inputnode, 'bvals', nonlinfit_node, 'bvals') 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")])]) ''' Create a single fiber mask ''' 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")])]) ''' Fix output names with subject ID ''' workflow.connect( [(inputnode, MultFAbyMode, [(('subject_id', add_subj_name_to_sfmask), 'out_filename')])]) if not use_FAST_masks: 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')])]) ''' Connect outputnode ''' workflow.connect( [(fast_seg_T1, outputnode, [("tissue_class_files", "tissue_class_files")])]) workflow.connect( [(fast_seg_T1, outputnode, [(('probability_maps', select_GM), 'gm_prob')])]) workflow.connect( [(fast_seg_T1, outputnode, [(('probability_maps', select_WM), 'wm_prob')])]) workflow.connect( [(fast_seg_T1, outputnode, [(('probability_maps', select_CSF), 'csf_prob')])]) workflow.connect([ (mri_convert_ROIs, outputnode, [("out_file", "aparc_aseg")]), (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")]), (mri_convert_Brain, outputnode, [("out_file", "t1_brain")]), (mri_convert_T1, outputnode, [("out_file", "t1")]), ]) if not use_FAST_masks: workflow.connect( [(fix_wm_mask, outputnode, [("out_file", "wm_mask")])]) workflow.connect( [(fix_termination_mask, outputnode, [("out_file", "term_mask")])]) return workflow
def create_getmask_flow(name='getmask', dilate_mask=True): """Registers a source file to freesurfer space and create a brain mask in source space Requires fsl tools for initializing registration Parameters ---------- name : string name of workflow dilate_mask : boolean indicates whether to dilate mask or not Example ------- >>> getmask = create_getmask_flow() >>> getmask.inputs.inputspec.source_file = 'mean.nii' >>> getmask.inputs.inputspec.subject_id = 's1' >>> getmask.inputs.inputspec.subjects_dir = '.' >>> getmask.inputs.inputspec.contrast_type = 't2' Inputs:: inputspec.source_file : reference image for mask generation inputspec.subject_id : freesurfer subject id inputspec.subjects_dir : freesurfer subjects directory inputspec.contrast_type : MR contrast of reference image Outputs:: outputspec.mask_file : binary mask file in reference image space outputspec.reg_file : registration file that maps reference image to freesurfer space outputspec.reg_cost : cost of registration (useful for detecting misalignment) """ import nipype.pipeline.engine as pe import nipype.interfaces.utility as niu import nipype.interfaces.freesurfer as fs import nipype.interfaces.io as nio """ Initialize the workflow """ getmask = pe.Workflow(name=name) """ Define the inputs to the workflow. """ inputnode = pe.Node(niu.IdentityInterface(fields=['source_file', 'subject_id', 'subjects_dir', 'contrast_type']), name='inputspec') """ Define all the nodes of the workflow: fssource: used to retrieve aseg.mgz threshold : binarize aseg register : coregister source file to freesurfer space voltransform: convert binarized aseg to source file space """ fssource = pe.Node(nio.FreeSurferSource(), name = 'fssource') threshold = pe.Node(fs.Binarize(min=0.5, out_type='nii'), name='threshold') register = pe.MapNode(fs.BBRegister(init='fsl'), iterfield=['source_file'], name='register') voltransform = pe.MapNode(fs.ApplyVolTransform(inverse=True), iterfield=['source_file', 'reg_file'], name='transform') """ Connect the nodes """ getmask.connect([ (inputnode, fssource, [('subject_id','subject_id'), ('subjects_dir','subjects_dir')]), (inputnode, register, [('source_file', 'source_file'), ('subject_id', 'subject_id'), ('subjects_dir', 'subjects_dir'), ('contrast_type', 'contrast_type')]), (inputnode, voltransform, [('subjects_dir', 'subjects_dir'), ('source_file', 'source_file')]), (fssource, threshold, [(('aparc_aseg', get_aparc_aseg), 'in_file')]), (register, voltransform, [('out_reg_file','reg_file')]), (threshold, voltransform, [('binary_file','target_file')]) ]) """ Add remaining nodes and connections dilate : dilate the transformed file in source space threshold2 : binarize transformed file """ threshold2 = pe.MapNode(fs.Binarize(min=0.5, out_type='nii'), iterfield=['in_file'], name='threshold2') if dilate_mask: threshold2.inputs.dilate = 1 getmask.connect([ (voltransform, threshold2, [('transformed_file', 'in_file')]) ]) """ Setup an outputnode that defines relevant inputs of the workflow. """ outputnode = pe.Node(niu.IdentityInterface(fields=["mask_file", "reg_file", "reg_cost" ]), name="outputspec") getmask.connect([ (register, outputnode, [("out_reg_file", "reg_file")]), (register, outputnode, [("min_cost_file", "reg_cost")]), (threshold2, outputnode, [("binary_file", "mask_file")]), ]) return getmask
# Calculate the transformation matrix from EPI space to FreeSurfer space # using the BBRegister command coregister = pe.Node(fs.BBRegister(subjects_dir=subjects_dir, contrast_type='t2', init='fsl', out_fsl_file=True), name='coregister') preproc_wf.connect(subj_iterable, 'subject_id', coregister, 'subject_id') preproc_wf.connect(motion_correct, ('out_file', pickfirst), coregister, 'source_file') preproc_wf.connect(coregister, 'out_reg_file', outputspec, 'reg_file') preproc_wf.connect(coregister, 'out_fsl_file', outputspec, 'fsl_reg_file') preproc_wf.connect(coregister, 'min_cost_file', outputspec, 'reg_cost') # Register a source file to fs space fssource = pe.Node(nio.FreeSurferSource(subjects_dir=subjects_dir), name='fssource') preproc_wf.connect(subj_iterable, 'subject_id', fssource, 'subject_id') # Extract aparc+aseg brain mask and binarize fs_threshold = pe.Node(fs.Binarize(min=0.5, out_type='nii'), name='fs_threshold') preproc_wf.connect(fssource, ('aparc_aseg', get_aparc_aseg), fs_threshold, 'in_file') # Transform the binarized aparc+aseg file to the 1st volume of 1st run space fs_voltransform = pe.MapNode(fs.ApplyVolTransform(inverse=True, subjects_dir=subjects_dir), iterfield=['source_file', 'reg_file'], name='fs_transform') preproc_wf.connect(extractref, 'roi_file', fs_voltransform, 'source_file')
def init_segs_to_native_wf(name='segs_to_native', segmentation='aseg'): """ Get a segmentation from FreeSurfer conformed space into native T1w space. .. workflow:: :graph2use: orig :simple_form: yes from smriprep.workflows.surfaces import init_segs_to_native_wf wf = init_segs_to_native_wf() **Parameters** segmentation The name of a segmentation ('aseg' or 'aparc_aseg' or 'wmparc') **Inputs** in_file Anatomical, merged T1w image after INU correction subjects_dir FreeSurfer SUBJECTS_DIR subject_id FreeSurfer subject ID **Outputs** out_file The selected segmentation, after resampling in native space """ workflow = Workflow(name='%s_%s' % (name, segmentation)) inputnode = pe.Node(niu.IdentityInterface( ['in_file', 'subjects_dir', 'subject_id']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface(['out_file']), name='outputnode') # Extract the aseg and aparc+aseg outputs fssource = pe.Node(nio.FreeSurferSource(), name='fs_datasource') tonative = pe.Node(fs.Label2Vol(), name='tonative') tonii = pe.Node(fs.MRIConvert(out_type='niigz', resample_type='nearest'), name='tonii') if segmentation.startswith('aparc'): if segmentation == 'aparc_aseg': def _sel(x): return [parc for parc in x if 'aparc+' in parc][0] elif segmentation == 'aparc_a2009s': def _sel(x): return [parc for parc in x if 'a2009s+' in parc][0] elif segmentation == 'aparc_dkt': def _sel(x): return [parc for parc in x if 'DKTatlas+' in parc][0] segmentation = (segmentation, _sel) workflow.connect([ (inputnode, fssource, [('subjects_dir', 'subjects_dir'), ('subject_id', 'subject_id')]), (inputnode, tonii, [('in_file', 'reslice_like')]), (fssource, tonative, [(segmentation, 'seg_file'), ('rawavg', 'template_file'), ('aseg', 'reg_header')]), (tonative, tonii, [('vol_label_file', 'in_file')]), (tonii, outputnode, [('out_file', 'out_file')]), ]) return workflow
def test_freesurfersource(): fss = nio.FreeSurferSource() yield assert_equal, fss.inputs.hemi, 'both' yield assert_equal, fss.inputs.subject_id, Undefined yield assert_equal, fss.inputs.subjects_dir, Undefined
sp_blur.inputs.automask = True sp_blur.inputs.outputtype = 'NIFTI_GZ' psb6351_wf.connect(tshifter, 'out_file', sp_blur, 'in_file') #### Temporal Smoothing tmp_smooth = pe.MapNode(afni.TSmooth(), iterfield=['in_file'], name = 'tmp_smooth') tmp_smooth.inputs.adaptive = 5 tmp_smooth.inputs.lin = True tmp_smooth.inputs.outputtype = 'NIFTI_GZ' psb6351_wf.connect(sp_blur, 'out_file', tmp_smooth, 'in_file') # Register a source file to fs space and create a brain mask in source space # The node below creates the Freesurfer source fssource = pe.Node(nio.FreeSurferSource(), name ='fssource') fssource.inputs.subject_id = f'sub-{sids[0]}' fssource.inputs.subjects_dir = fs_dir # Extract aparc+aseg brain mask, binarize, and dilate by 1 voxel fs_threshold = pe.Node(fs.Binarize(min=0.5, out_type='nii'), name ='fs_threshold') fs_threshold.inputs.dilate = 1 psb6351_wf.connect(fssource, ('aparc_aseg', get_aparc_aseg), fs_threshold, 'in_file') # Transform the binarized aparc+aseg file to the EPI space # use a nearest neighbor interpolation fs_voltransform = pe.Node(fs.ApplyVolTransform(inverse=True), name='fs_transform') fs_voltransform.inputs.subjects_dir = fs_dir
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