Exemple #1
0
def mask2surf(name='MaskToSurface', use_ras_coord=True):
    inputnode = pe.Node(niu.IdentityInterface(
        fields=['in_file', 'norm', 'in_filled', 'out_name']),
                        name='inputnode')
    outputnode = pe.Node(niu.IdentityInterface(fields=['out_surf']),
                         name='outputnode')
    binarize = pe.Node(fs.Binarize(min=0.1), name='binarize')
    fill = pe.Node(FillMask(), name='FillMask')
    pretess = pe.Node(fs.MRIPretess(label=1), name='PreTess')
    tess = pe.Node(fs.MRITessellate(label_value=1,
                                    use_real_RAS_coordinates=use_ras_coord),
                   name='tess')
    smooth = pe.Node(fs.SmoothTessellation(disable_estimates=True),
                     name='mris_smooth')
    rename = pe.Node(niu.Rename(keep_ext=False), name='rename')
    togii = pe.Node(fs.MRIsConvert(out_datatype='gii'), name='toGIFTI')

    wf = pe.Workflow(name=name)
    wf.connect([
        (inputnode, binarize, [('in_file', 'in_file')]),
        (inputnode, pretess, [('norm', 'in_norm')]),
        (inputnode, fill, [('in_filled', 'in_filled')]),
        (inputnode, rename, [('out_name', 'format_string')]),
        (binarize, fill, [('binary_file', 'in_file')]),
        (fill, pretess, [('out_file', 'in_filled')]),
        (pretess, tess, [('out_file', 'in_file')]),
        (tess, smooth, [('surface', 'in_file')]),
        (smooth, rename, [('surface', 'in_file')]),
        (rename, togii, [('out_file', 'in_file')]),
        (togii, outputnode, [('converted', 'out_surf')]),
    ])
    return wf
Exemple #2
0
def makeAsc(freesurferLoc):
    for side in ['lh', 'rh']:
        thickSurf = os.path.join(freesurferLoc, 'surf', side + '.thickness')
        whiteSurf = os.path.join(freesurferLoc, 'surf', side + '.white')
        output = os.path.join(freesurferLoc, 'tmp', side + '.thickness.asc')

        toAsc = fs.MRIsConvert(
            scalarcurv_file=thickSurf,
            in_file=whiteSurf,
            out_datatype='ico',
            #out_file = output,
        )
        command = 'mris_convert -c {thickF} {whiteF} {outF}'.format(
            thickF=thickSurf, whiteF=whiteSurf, outF=output)

        out = os.popen(command).read()
Exemple #3
0
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
Exemple #4
0
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
Exemple #5
0
def surface_32k(name='surface_32k',
                templates_dir='/home/bpinsard/data/src/Pipelines'):
    w = pe.Workflow(name=name)

    fs_templates = dict(
        white=[['subject', 'surf', '?h.white']],
        pial=[['subject', 'surf', '?h.pial']],
        sphere=[['subject', 'surf', '?h.sphere.reg']],
        finalsurf=[['subject', 'mri', 'brain.finalsurfs.mgz']],
        aparc_a2009s_annot=[['subject', 'label', '?h.aparc.a2009s.annot']],
        ba_annot=[['subject', 'label', '?h.BA_exvivo.annot']],
        ba_thresh_annot=[['subject', 'label', '?h.BA_exvivo.thresh.annot']])

    n_fs_source = pe.Node(nio.DataGrabber(infields=['subject'],
                                          outfields=fs_templates.keys(),
                                          raise_on_empty=False,
                                          sort_filelist=True,
                                          template='%s/%s/%s'),
                          run_without_submitting=True,
                          name='fs_source')
    n_fs_source.inputs.template_args = fs_templates

    n_c_ras = pe.Node(utility.Function(input_names=['mgz_file'],
                                       output_names=['c_ras'],
                                       function=get_c_ras),
                      run_without_submitting=True,
                      name='c_ras')

    n_white_to_gifti = pe.MapNode(freesurfer.MRIsConvert(out_datatype='gii'),
                                  iterfield=['in_file'],
                                  name='white_to_gifti')
    n_pial_to_gifti = n_white_to_gifti.clone('pial_to_gifti')
    n_sphere_to_gifti = n_white_to_gifti.clone('sphere_to_gifti')

    n_sphere_project_unproject = pe.MapNode(
        utility.Function(input_names=[
            'sphere_in', 'sphere_project_to', 'sphere_unproject_from', 'suffix'
        ],
                         output_names=['out_file'],
                         function=wb_command_sphere_project_unproject),
        iterfield=['sphere_in', 'sphere_project_to', 'sphere_unproject_from'],
        name='sphere_project_unproject')

    n_sphere_project_unproject.inputs.sphere_project_to = [
        os.path.join(
            templates_dir,
            'global/templates/standard_mesh_atlases/fs_%s/fsaverage.%s.sphere.164k_fs_%s.surf.gii'
            % (h, h, h)) for h in 'LR'
    ]
    n_sphere_project_unproject.inputs.sphere_unproject_from = [
        os.path.join(
            templates_dir,
            'global/templates/standard_mesh_atlases/fs_%s/fs_%s-to-fs_LR_fsaverage.%s_LR.spherical_std.164k_fs_%s.surf.gii'
            % (h, h, h, h)) for h in 'LR'
    ]
    n_sphere_project_unproject.inputs.suffix = '.proj_unproj'

    n_labels_to_gifti = pe.MapNode(freesurfer.MRIsConvert(out_datatype='gii'),
                                   iterfield=['annot_file', 'in_file'],
                                   name='labels_to_gifti')
    n_ba_to_gifti = n_labels_to_gifti.clone('ba_to_gifti')
    n_ba_thresh_to_gifti = n_labels_to_gifti.clone('ba_thresh_to_gifti')

    n_white_apply_affine = pe.MapNode(utility.Function(
        input_names=['in_file', 'c_ras'],
        output_names=['out_file'],
        function=wb_command_surface_apply_affine),
                                      iterfield=['in_file'],
                                      name='white_apply_affine')

    n_pial_apply_affine = n_white_apply_affine.clone('pial_apply_affine')

    n_white_resample_surf = pe.MapNode(
        utility.Function(
            input_names=['in_file', 'sphere_in', 'sphere_out', 'suffix'],
            output_names=['out_file'],
            function=wb_command_surface_resample),
        iterfield=['in_file', 'sphere_in', 'sphere_out'],
        name='white_resample_surf')
    n_white_resample_surf.inputs.suffix = '.32k'
    n_white_resample_surf.inputs.sphere_out = [
        os.path.join(
            templates_dir,
            'global/templates/standard_mesh_atlases/%s.sphere.32k_fs_LR.surf.gii'
            % h) for h in 'LR'
    ]
    n_pial_resample_surf = n_white_resample_surf.clone('pial_resample_surf')

    n_label_resample = pe.MapNode(
        utility.Function(
            input_names=['in_file', 'sphere_in', 'sphere_out', 'suffix'],
            output_names=['out_file'],
            function=wb_command_label_resample),
        iterfield=['in_file', 'sphere_in', 'sphere_out'],
        name='label_resample')
    n_label_resample.inputs.suffix = '.32k'
    n_label_resample.inputs.sphere_out = [
        os.path.join(
            templates_dir,
            'global/templates/standard_mesh_atlases/%s.sphere.32k_fs_LR.surf.gii'
            % h) for h in 'LR'
    ]

    n_ba_resample = n_label_resample.clone('BA_resample')
    n_ba_thresh_resample = n_label_resample.clone('BA_thresh_resample')

    w.connect([
        (n_fs_source, n_c_ras, [('finalsurf', 'mgz_file')]),
        (n_fs_source, n_white_to_gifti, [('white', 'in_file')]),
        (n_fs_source, n_labels_to_gifti, [('white', 'in_file'),
                                          ('aparc_a2009s_annot', 'annot_file')
                                          ]),
        (n_fs_source, n_ba_to_gifti, [('white', 'in_file'),
                                      ('ba_annot', 'annot_file')]),
        (n_fs_source, n_ba_thresh_to_gifti, [('white', 'in_file'),
                                             ('ba_thresh_annot', 'annot_file')
                                             ]),
        (n_fs_source, n_pial_to_gifti, [('pial', 'in_file')]),
        (n_fs_source, n_sphere_to_gifti, [('sphere', 'in_file')]),
        (n_sphere_to_gifti, n_sphere_project_unproject, [('converted',
                                                          'sphere_in')]),
        (n_white_to_gifti, n_white_apply_affine, [('converted', 'in_file')]),
        (n_pial_to_gifti, n_pial_apply_affine, [('converted', 'in_file')]),
        (n_c_ras, n_white_apply_affine, [('c_ras', ) * 2]),
        (n_c_ras, n_pial_apply_affine, [('c_ras', ) * 2]),

        #           (n_white_to_gifti,n_white_resample_surf,[('converted','in_file')]),
        #           (n_pial_to_gifti,n_pial_resample_surf,[('converted','in_file')]),
        (n_white_apply_affine, n_white_resample_surf, [('out_file', 'in_file')]
         ),
        (n_pial_apply_affine, n_pial_resample_surf, [('out_file', 'in_file')]),
        (n_sphere_project_unproject, n_white_resample_surf, [('out_file',
                                                              'sphere_in')]),
        (n_sphere_project_unproject, n_pial_resample_surf, [('out_file',
                                                             'sphere_in')]),
        (n_sphere_project_unproject, n_label_resample, [('out_file',
                                                         'sphere_in')]),
        (n_labels_to_gifti, n_label_resample, [('converted', 'in_file')]),
        (n_sphere_project_unproject, n_ba_resample, [('out_file', 'sphere_in')
                                                     ]),
        (n_sphere_project_unproject, n_ba_thresh_resample, [('out_file',
                                                             'sphere_in')]),
        (n_ba_to_gifti, n_ba_resample, [('converted', 'in_file')]),
        (n_ba_thresh_to_gifti, n_ba_thresh_resample, [('converted', 'in_file')
                                                      ]),
    ])
    return w
Exemple #6
0
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
Exemple #7
0
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 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_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
"""
"""
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::
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
Exemple #12
0
def create_bem_flow(name='bem', out_format='stl'):
    """Uses MNE's Watershed algorithm to create Boundary Element Meshes (BEM)
     for a subject's brain, inner/outer skull, and skin. The surfaces are
     returned in the desired (by default, stereolithic .stl) format.

    Example
    -------
    >>> from nipype.workflows.smri.freesurfer import create_bem_flow
    >>> bemflow = create_bem_flow()
    >>> bemflow.inputs.inputspec.subject_id = 'subj1'
    >>> bemflow.inputs.inputspec.subjects_dir = '.'
    >>> bemflow.run()  # doctest: +SKIP


    Inputs::

           inputspec.subject_id : freesurfer subject id
           inputspec.subjects_dir : freesurfer subjects directory

    Outputs::

           outputspec.meshes : output boundary element meshes in (by default) stereolithographic (.stl) format
    """

    """
    Initialize the workflow
    """

    bemflow = pe.Workflow(name=name)

    """
    Define the inputs to the workflow.
    """

    inputnode = pe.Node(niu.IdentityInterface(fields=['subject_id',
                                                      'subjects_dir']),
                        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

    """

    watershed_bem = pe.Node(interface=mne.WatershedBEM(), name='WatershedBEM')

    surfconvert = pe.MapNode(fs.MRIsConvert(out_datatype=out_format),
                          iterfield=['in_file'],
                          name='surfconvert')

    """
    Connect the nodes
    """

    bemflow.connect([
            (inputnode, watershed_bem, [('subject_id', 'subject_id'),
                                   ('subjects_dir', 'subjects_dir')]),
            (watershed_bem, surfconvert, [('mesh_files', 'in_file')]),
            ])

    """
    Setup an outputnode that defines relevant inputs of the workflow.
    """

    outputnode = pe.Node(niu.IdentityInterface(fields=["meshes"]),
                         name="outputspec")
    bemflow.connect([
            (surfconvert, outputnode, [("converted", "meshes")]),
            ])
    return bemflow
Exemple #13
0
mls = mls2020
from fsto3d import *
import nipype.interfaces.freesurfer as fs
for stage in stages:
    parc = subtype+'SubtypeStage'+str(stage)
    ctab = os.path.join(wd,"aparc_"+parc+".annot.ctab")
    if os.path.exists(ctab):
        #* Output folder
        outp = os.path.join(wd,parc)
        os.makedirs(outp,exist_ok=True)
        #* Prep work on FreeSurfer model brain
        #* Convert ctab to better format with python utilities
        ctab_24bit = ctab.replace(".ctab",".24bit.ctab")
        convert_ctab(ctab, ctab_24bit)
        #* Convert surface(s) to ASCII format with color integer values
        mris = fs.MRIsConvert()
        mris.inputs.parcstats_file = ctab_24bit
        for hemisphere in ['lh','rh']:
            pial = os.path.join(fs_model,"%s.pial" % hemisphere)
            pial_asc = pial + ".asc"
            pial_asc_custom = os.path.join(outp,"%s.pial.%s_%s.asc" % (hemisphere,parc,cmap_name))
            pial_asc_custom2 = pial_asc_custom.replace("asc","combined.asc")
            pial_asc_custom_obj = pial_asc_custom2.replace(".asc",".obj")
            x3d = pial_asc_custom_obj.replace(".obj",".x3d")
            annot = os.path.join(fs_model,"%s.aparc.annot" % hemisphere)
            mris.inputs.annot_file     = annot.encode('unicode-escape').decode()
            mris.inputs.in_file        = pial.encode('unicode-escape').decode()
            mris.inputs.out_file       = pial_asc_custom.encode('unicode-escape').decode()
            mris.run()
            #* Paste together the two ASCII files to get both vertex/face info and color info
            combine_asc_color(pial_asc,pial_asc_custom,pial_asc_custom2)
Exemple #14
0
def extract_surfaces(name='GenSurface',
                     normalize=True,
                     use_ras_coord=True,
                     brainmask=False):
    """
    A nipype workflow for surface extraction from ``labels`` in a segmentation.

    .. note :: References used to implement this code:

        * <https://github.com/nipy/nipype/issues/307>
        * <https://mail.nmr.mgh.harvard.edu/pipermail/\
freesurfer/2011-November/021391.html>
        * <http://brainder.org/2012/05/08/importing-\
freesurfer-subcortical-structures-into-blender/>
        * <https://mail.nmr.mgh.harvard.edu/pipermail/\
freesurfer/2013-June/030586.html>
    """
    inputnode = pe.Node(niu.IdentityInterface(fields=[
        'aseg', 'norm', 'in_filled', 'brainmask', 't1_2_fsnative_invxfm',
        'model_name'
    ],
                                              mandatory_inputs=False),
                        name='inputnode')
    outputnode = pe.Node(
        niu.IdentityInterface(fields=['out_surf', 'out_binary']),
        name='outputnode')

    surfnode = pe.Node(niu.IdentityInterface(fields=['out_surf']),
                       name='surfnode')

    get_mod = pe.Node(niu.Function(function=_read_model,
                                   output_names=['name', 'labels']),
                      name='GetModel')

    binarize = pe.MapNode(Binarize(),
                          name='BinarizeLabels',
                          iterfield=['match'])

    fill = pe.MapNode(FillMask(), name='FillMask', iterfield=['in_file'])
    pretess = pe.MapNode(fs.MRIPretess(label=1),
                         name='PreTess',
                         iterfield=['in_filled'])
    tess = pe.MapNode(fs.MRITessellate(label_value=1,
                                       use_real_RAS_coordinates=use_ras_coord),
                      name='tess',
                      iterfield=['in_file'])
    smooth = pe.MapNode(fs.SmoothTessellation(disable_estimates=True),
                        name='mris_smooth',
                        iterfield=['in_file'])
    rename = pe.MapNode(niu.Rename(keep_ext=False),
                        name='rename',
                        iterfield=['in_file', 'format_string'])

    togii = pe.MapNode(fs.MRIsConvert(out_datatype='gii'),
                       iterfield='in_file',
                       name='toGIFTI')

    wf = pe.Workflow(name=name)
    wf.connect([
        (inputnode, get_mod, [('model_name', 'model_name')]),
        (inputnode, binarize, [('aseg', 'in_file')]),
        (get_mod, binarize, [('labels', 'match')]),
        (inputnode, pretess, [('norm', 'in_norm')]),
        (inputnode, fill, [('in_filled', 'in_filled')]),
        (binarize, fill, [('out_file', 'in_file')]),
        (fill, pretess, [('out_file', 'in_filled')]),
        (pretess, tess, [('out_file', 'in_file')]),
        (tess, smooth, [('surface', 'in_file')]),
        (smooth, rename, [('surface', 'in_file')]),
        (get_mod, rename, [('name', 'format_string')]),
        (rename, togii, [('out_file', 'in_file')]),
        (fill, outputnode, [('out_file', 'out_binary')]),
    ])

    if brainmask:
        bmsk_wf = mask2surf(use_ras_coord=use_ras_coord)
        bmsk_wf.inputs.inputnode.out_name = 'brain.surf'
        merge = pe.Node(niu.Merge(2), name='mergebmask')
        wf.connect([
            (inputnode, bmsk_wf, [('brainmask', 'inputnode.in_file'),
                                  ('norm', 'inputnode.norm'),
                                  ('in_filled', 'inputnode.in_filled')]),
            (togii, merge, [('converted', 'in1')]),
            (bmsk_wf, merge, [('outputnode.out_surf', 'in2')]),
            (merge, surfnode, [('out', 'out_surf')]),
        ])
    else:
        wf.connect(togii, 'converted', surfnode, 'out_surf')

    if normalize:
        fixgii = pe.MapNode(NormalizeSurf(),
                            iterfield='in_file',
                            name='fixGIFTI')
        wf.connect([
            (inputnode, fixgii, [('t1_2_fsnative_invxfm', 'transform_file')]),
            (surfnode, fixgii, [('out_surf', 'in_file')]),
            (fixgii, outputnode, [('out_file', 'out_surf')]),
        ])
    else:
        wf.connect([
            (surfnode, outputnode, [('out_surf', 'out_surf')]),
        ])

    return wf
Exemple #15
0
def create_fsconnectivity_pipeline(name="fsconnectivity",
                                   manual_seg_rois=False,
                                   parcellation_name="scale33"):
    inputfields = [
        "subjects_dir", "subject_id", "dwi", "bvecs", "bvals",
        "resolution_network_file"
    ]

    inputnode = pe.Node(interface=util.IdentityInterface(fields=inputfields),
                        name="inputnode")

    outputnode = pe.Node(
        interface=util.IdentityInterface(
            fields=[  # Outputs from the DWI workflow
                "single_fiber_mask",
                "fa",
                "rgb_fa",
                "md",
                "mode",
                "t1",
                "t1_brain",
                "wm_mask",
                "term_mask",
                "aparc_aseg",
                "tissue_class_files",
                "gm_prob",
                "wm_prob",
                "csf_prob",

                # Outputs from registration and labelling
                "rois_to_dwi",
                "wmmask_to_dwi",
                "termmask_to_dwi",
                "dwi_to_t1_matrix",
                "highres_t1_to_dwi_matrix",

                # T1 in DWI space for reference
                "t1_to_dwi",

                # Outputs from tracking
                "fiber_odfs",
                "fiber_tracks_tck_dwi",
                "fiber_tracks_trk_t1",

                # Outputs from connectivity mapping
                "connectome",
                "nxstatscff",
                "nxmatlab",
                "nxcsv",
                "cmatrix",
                "matrix_file",
            ]),
        name="outputnode")

    t1_to_dwi = pe.Node(interface=fsl.ApplyXfm(), name='t1_to_dwi')

    termmask_to_dwi = t1_to_dwi.clone("termmask_to_dwi")

    dtiproc = damaged_brain_dti_processing("dtiproc", use_FAST_masks=True)
    reg_label = create_reg_and_label_wf("reg_label", manual_seg_rois=True)

    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_convertLHlabels = mris_convertLH.clone('mris_convertLHlabels')
    mris_convertRHlabels = mris_convertLH.clone('mris_convertRHlabels')
    """
    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(6), 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()))

    workflow = pe.Workflow(name=name)
    workflow.base_output_dir = name

    workflow.connect([(inputnode, dtiproc,
                       [("subjects_dir", "inputnode.subjects_dir"),
                        ("subject_id", "inputnode.subject_id"),
                        ("dwi", "inputnode.dwi"), ("bvecs", "inputnode.bvecs"),
                        ("bvals", "inputnode.bvals")])])

    workflow.connect([(inputnode, reg_label, [("subject_id",
                                               "inputnode.subject_id")])])
    #workflow.connect([(mri_convert_ROI_scale500, reg_label, [("out_file", "inputnode.manual_seg_rois")])])
    workflow.connect([(dtiproc, reg_label, [("outputnode.aparc_aseg",
                                             "inputnode.manual_seg_rois")])])

    workflow.connect([(dtiproc, reg_label, [
        ("outputnode.wm_mask", "inputnode.wm_mask"),
        ("outputnode.term_mask", "inputnode.termination_mask"),
        ("outputnode.fa", "inputnode.fa"),
        ("outputnode.aparc_aseg", "inputnode.aparc_aseg"),
    ])])

    workflow.connect([(reg_label, t1_to_dwi, [("outputnode.t1_to_dwi_matrix",
                                               "in_matrix_file")])])
    workflow.connect([(dtiproc, t1_to_dwi, [("outputnode.t1", "in_file")])])
    workflow.connect([(dtiproc, t1_to_dwi, [("outputnode.fa", "reference")])])
    workflow.connect([(inputnode, t1_to_dwi, [
        (('subject_id', add_subj_name_to_T1_dwi), 'out_file')
    ])])

    workflow.connect([(reg_label, termmask_to_dwi,
                       [("outputnode.t1_to_dwi_matrix", "in_matrix_file")])])
    workflow.connect([(dtiproc, termmask_to_dwi, [("outputnode.term_mask",
                                                   "in_file")])])
    workflow.connect([(dtiproc, termmask_to_dwi, [("outputnode.fa",
                                                   "reference")])])
    '''
    Connect outputnode
    '''

    workflow.connect([(t1_to_dwi, outputnode, [("out_file", "t1_to_dwi")])])

    workflow.connect([(dtiproc, outputnode, [
        ("outputnode.t1", "t1"),
        ("outputnode.wm_prob", "wm_prob"),
        ("outputnode.gm_prob", "gm_prob"),
        ("outputnode.csf_prob", "csf_prob"),
        ("outputnode.single_fiber_mask", "single_fiber_mask"),
        ("outputnode.fa", "fa"),
        ("outputnode.rgb_fa", "rgb_fa"),
        ("outputnode.md", "md"),
        ("outputnode.mode", "mode"),
        ("outputnode.t1_brain", "t1_brain"),
        ("outputnode.wm_mask", "wm_mask"),
        ("outputnode.term_mask", "term_mask"),
        ("outputnode.aparc_aseg", "aparc_aseg"),
        ("outputnode.tissue_class_files", "tissue_class_files"),
    ])])

    workflow.connect([(reg_label, outputnode, [
        ("outputnode.rois_to_dwi", "rois_to_dwi"),
        ("outputnode.wmmask_to_dwi", "wmmask_to_dwi"),
        ("outputnode.termmask_to_dwi", "termmask_to_dwi"),
        ("outputnode.dwi_to_t1_matrix", "dwi_to_t1_matrix"),
        ("outputnode.highres_t1_to_dwi_matrix", "highres_t1_to_dwi_matrix"),
    ])])

    workflow.connect([(dtiproc, outputnode, [("outputnode.aparc_aseg", "rois")
                                             ])])

    tracking = anatomically_constrained_tracking("tracking")

    workflow.connect([(inputnode, tracking, [
        ("subject_id", "inputnode.subject_id"),
        ("dwi", "inputnode.dwi"),
        ("bvecs", "inputnode.bvecs"),
        ("bvals", "inputnode.bvals"),
    ])])

    workflow.connect([(reg_label, tracking, [
        ("outputnode.wmmask_to_dwi", "inputnode.wm_mask"),
        ("outputnode.termmask_to_dwi", "inputnode.termination_mask"),
        ("outputnode.dwi_to_t1_matrix", "inputnode.registration_matrix_file"),
    ])])

    workflow.connect([(dtiproc, tracking, [
        ("outputnode.t1", "inputnode.registration_image_file")
    ])])

    workflow.connect([(dtiproc, tracking, [("outputnode.single_fiber_mask",
                                            "inputnode.single_fiber_mask")])])

    workflow.connect([(tracking, outputnode, [
        ("outputnode.fiber_odfs", "fiber_odfs"),
        ("outputnode.fiber_tracks_tck_dwi", "fiber_tracks_tck_dwi"),
        ("outputnode.fiber_tracks_trk_t1", "fiber_tracks_trk_t1"),
    ])])

    workflow.connect([(tracking, creatematrix,
                       [("outputnode.fiber_tracks_trk_t1", "tract_file")])])

    workflow.connect([(inputnode, FreeSurferSource, [("subjects_dir",
                                                      "subjects_dir")])])
    workflow.connect([(inputnode, FreeSurferSource, [("subject_id",
                                                      "subject_id")])])

    workflow.connect([(inputnode, FreeSurferSourceLH, [("subjects_dir",
                                                        "subjects_dir")])])
    workflow.connect([(inputnode, FreeSurferSourceLH, [("subject_id",
                                                        "subject_id")])])

    workflow.connect([(inputnode, FreeSurferSourceRH, [("subjects_dir",
                                                        "subjects_dir")])])
    workflow.connect([(inputnode, FreeSurferSourceRH, [("subject_id",
                                                        "subject_id")])])

    workflow.connect([(inputnode, parcellate, [("subjects_dir", "subjects_dir")
                                               ])])
    workflow.connect([(inputnode, parcellate, [("subject_id", "subject_id")])])
    workflow.connect([(parcellate, mri_convert_ROI_scale500, [('roi_file',
                                                               'in_file')])])
    """
    Surface conversions to GIFTI (pial, white, inflated, and sphere for both hemispheres)
    """

    workflow.connect([(FreeSurferSourceLH, mris_convertLH, [('pial', 'in_file')
                                                            ])])
    workflow.connect([(FreeSurferSourceRH, mris_convertRH, [('pial', 'in_file')
                                                            ])])
    workflow.connect([(FreeSurferSourceLH, mris_convertLHwhite,
                       [('white', 'in_file')])])
    workflow.connect([(FreeSurferSourceRH, mris_convertRHwhite,
                       [('white', 'in_file')])])
    workflow.connect([(FreeSurferSourceLH, mris_convertLHinflated,
                       [('inflated', 'in_file')])])
    workflow.connect([(FreeSurferSourceRH, mris_convertRHinflated,
                       [('inflated', '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.
    """

    workflow.connect([(FreeSurferSourceLH, mris_convertLHlabels,
                       [('pial', 'in_file')])])
    workflow.connect([(FreeSurferSourceRH, mris_convertRHlabels,
                       [('pial', 'in_file')])])
    workflow.connect([(FreeSurferSourceLH, mris_convertLHlabels,
                       [(('annot', select_aparc_annot), 'annot_file')])])
    workflow.connect([(FreeSurferSourceRH, mris_convertRHlabels,
                       [(('annot', select_aparc_annot), 'annot_file')])])

    workflow.connect(inputnode, 'resolution_network_file', creatematrix,
                     'resolution_network_file')
    workflow.connect([(inputnode, creatematrix, [("subject_id",
                                                  "out_matrix_file")])])
    workflow.connect([(inputnode, creatematrix, [("subject_id",
                                                  "out_matrix_mat_file")])])
    workflow.connect([(parcellate, creatematrix, [("roi_file", "roi_file")])])

    workflow.connect([(creatematrix, fiberDataArrays, [("endpoint_file", "in1")
                                                       ])])
    workflow.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm",
                                                        "in2")])])
    workflow.connect([(creatematrix, fiberDataArrays, [("fiber_length_file",
                                                        "in3")])])
    workflow.connect([(creatematrix, fiberDataArrays, [("fiber_label_file",
                                                        "in4")])])

    workflow.connect([(mris_convertLH, giftiSurfaces, [("converted", "in1")])])
    workflow.connect([(mris_convertRH, giftiSurfaces, [("converted", "in2")])])
    workflow.connect([(mris_convertLHwhite, giftiSurfaces, [("converted",
                                                             "in3")])])
    workflow.connect([(mris_convertRHwhite, giftiSurfaces, [("converted",
                                                             "in4")])])
    workflow.connect([(mris_convertLHinflated, giftiSurfaces, [("converted",
                                                                "in5")])])
    workflow.connect([(mris_convertRHinflated, giftiSurfaces, [("converted",
                                                                "in6")])])

    workflow.connect([(mris_convertLHlabels, giftiLabels, [("converted", "in1")
                                                           ])])
    workflow.connect([(mris_convertRHlabels, giftiLabels, [("converted", "in2")
                                                           ])])

    workflow.connect([(giftiSurfaces, CFFConverter, [("out", "gifti_surfaces")
                                                     ])])
    workflow.connect([(giftiLabels, CFFConverter, [("out", "gifti_labels")])])
    workflow.connect([(creatematrix, CFFConverter, [("matrix_files",
                                                     "gpickled_networks")])])
    workflow.connect([(fiberDataArrays, CFFConverter, [("out", "data_files")])
                      ])
    workflow.connect([(inputnode, CFFConverter, [("subject_id", "title")])])
    workflow.connect([(inputnode, CFFConverter, [
        (('subject_id', add_subj_name_to_Connectome), 'out_file')
    ])])
    """
    The graph theoretical metrics which have been generated are placed into another CFF file.
    """

    workflow.connect([(inputnode, networkx, [("subject_id",
                                              "inputnode.extra_field")])])
    workflow.connect([(creatematrix, networkx, [("intersection_matrix_file",
                                                 "inputnode.network_file")])])

    workflow.connect([(networkx, NxStatsCFFConverter,
                       [("outputnode.network_files", "gpickled_networks")])])
    workflow.connect([(giftiSurfaces, NxStatsCFFConverter,
                       [("out", "gifti_surfaces")])])
    workflow.connect([(giftiLabels, NxStatsCFFConverter, [("out",
                                                           "gifti_labels")])])
    workflow.connect([(fiberDataArrays, NxStatsCFFConverter,
                       [("out", "data_files")])])
    workflow.connect([(inputnode, NxStatsCFFConverter, [("subject_id", "title")
                                                        ])])
    workflow.connect([(inputnode, NxStatsCFFConverter, [
        (('subject_id', add_subj_name_to_nxConnectome), 'out_file')
    ])])

    workflow.connect([(CFFConverter, outputnode, [("connectome_file",
                                                   "connectome")])])
    workflow.connect([(NxStatsCFFConverter, outputnode, [("connectome_file",
                                                          "nxstatscff")])])
    workflow.connect([(creatematrix, outputnode, [("intersection_matrix_file",
                                                   "matrix_file")])])
    workflow.connect([(creatematrix, outputnode, [("matrix_mat_file",
                                                   "cmatrix")])])
    workflow.connect([(networkx, outputnode, [("outputnode.csv_files", "nxcsv")
                                              ])])
    return workflow