示例#1
0
def test_flirt():
    # setup
    tmpdir, infile, reffile = setup_flirt()

    flirter = fsl.FLIRT()
    yield assert_equal, flirter.cmd, 'flirt'

    flirter.inputs.bins = 256
    flirter.inputs.cost = 'mutualinfo'

    flirted = fsl.FLIRT(in_file=infile,
                        reference=reffile,
                        out_file='outfile',
                        out_matrix_file='outmat.mat',
                        bins=256,
                        cost='mutualinfo')
    flirt_est = fsl.FLIRT(in_file=infile,
                          reference=reffile,
                          out_matrix_file='outmat.mat',
                          bins=256,
                          cost='mutualinfo')
    yield assert_not_equal, flirter.inputs, flirted.inputs
    yield assert_not_equal, flirted.inputs, flirt_est.inputs

    yield assert_equal, flirter.inputs.bins, flirted.inputs.bins
    yield assert_equal, flirter.inputs.cost, flirt_est.inputs.cost
    realcmd = 'flirt -in %s -ref %s -out outfile -omat outmat.mat ' \
        '-bins 256 -cost mutualinfo' % (infile, reffile)
    yield assert_equal, flirted.cmdline, realcmd

    flirter = fsl.FLIRT()
    # infile not specified
    yield assert_raises, ValueError, flirter.run
    flirter.inputs.in_file = infile
    # reference not specified
    yield assert_raises, ValueError, flirter.run
    flirter.inputs.reference = reffile
    # Generate outfile and outmatrix
    pth, fname, ext = split_filename(infile)
    outfile = fsl_name(flirter, '%s_flirt' % fname)
    outmat = '%s_flirt.mat' % fname
    realcmd = 'flirt -in %s -ref %s -out %s -omat %s' % (infile, reffile,
                                                         outfile, outmat)
    yield assert_equal, flirter.cmdline, realcmd

    _, tmpfile = tempfile.mkstemp(suffix='.nii', dir=tmpdir)
    # Loop over all inputs, set a reasonable value and make sure the
    # cmdline is updated correctly.
    for key, trait_spec in sorted(fsl.FLIRT.input_spec().traits().items()):
        # Skip mandatory inputs and the trait methods
        if key in ('trait_added', 'trait_modified', 'in_file', 'reference',
                   'environ', 'output_type', 'out_file', 'out_matrix_file',
                   'in_matrix_file', 'apply_xfm', 'ignore_exception',
                   'terminal_output', 'out_log', 'save_log'):
            continue
        param = None
        value = None
        if key == 'args':
            param = '-v'
            value = '-v'
        elif isinstance(trait_spec.trait_type, File):
            value = tmpfile
            param = trait_spec.argstr % value
        elif trait_spec.default is False:
            param = trait_spec.argstr
            value = True
        elif key in ('searchr_x', 'searchr_y', 'searchr_z'):
            value = [-45, 45]
            param = trait_spec.argstr % ' '.join(str(elt) for elt in value)
        else:
            value = trait_spec.default
            param = trait_spec.argstr % value
        cmdline = 'flirt -in %s -ref %s' % (infile, reffile)
        # Handle autogeneration of outfile
        pth, fname, ext = split_filename(infile)
        outfile = fsl_name(fsl.FLIRT(), '%s_flirt' % fname)
        outfile = ' '.join(['-out', outfile])
        # Handle autogeneration of outmatrix
        outmatrix = '%s_flirt.mat' % fname
        outmatrix = ' '.join(['-omat', outmatrix])
        # Build command line
        cmdline = ' '.join([cmdline, outfile, outmatrix, param])
        flirter = fsl.FLIRT(in_file=infile, reference=reffile)
        setattr(flirter.inputs, key, value)
        yield assert_equal, flirter.cmdline, cmdline

    # Test OutputSpec
    flirter = fsl.FLIRT(in_file=infile, reference=reffile)
    pth, fname, ext = split_filename(infile)
    flirter.inputs.out_file = ''.join(['foo', ext])
    flirter.inputs.out_matrix_file = ''.join(['bar', ext])
    outs = flirter._list_outputs()
    yield assert_equal, outs['out_file'], \
        os.path.join(os.getcwd(), flirter.inputs.out_file)
    yield assert_equal, outs['out_matrix_file'], \
        os.path.join(os.getcwd(), flirter.inputs.out_matrix_file)

    teardown_flirt(tmpdir)
示例#2
0
文件: workflows.py 项目: MichlF/misc
def create_B0_workflow(name='b0_unwarping', scanner='philips'):
    """ Does B0 field unwarping

    Example
    -------
    >>> nipype_epicorrect = create_unwarping_workflow('unwarp',)
    >>> unwarp.inputs.input_node.in_file = 'subj1_run1_bold.nii.gz'
    >>> unwarp.inputs.input_node.fieldmap_mag = 'subj1_run1_mag.nii.gz'
    >>> unwarp.inputs.input_node.fieldmap_pha = 'subj1_run1_phas.nii.gz'
    >>> unwarp.inputs.input_node.wfs = 12.223
    >>> unwarp.inputs.input_node.epi_factor = 35.0
    >>> unwarp.inputs.input_node.acceleration = 3.0
    >>> unwarp.inputs.input_node.te_diff = 0.005
    >>> unwarp.inputs.input_node.phase_encoding_direction = 'y'
    >>> nipype_epicorrect.run()

    Inputs::
        input_node.in_file - Volume acquired with EPI sequence
        input_node.fieldmap_mag - Magnitude of the fieldmap
        input_node.fieldmap_pha - Phase difference of the fieldmap
        input_node.wfs - Water-fat-shift in pixels
        input_node.epi_factor - EPI factor
        input_node.acceleration - Acceleration factor used for EPI parallel imaging (SENSE)
        input_node.te_diff - Time difference between TE in seconds.
        input_node.phase_encoding_direction - Unwarp direction (default should be "y")
    Outputs::
        outputnode.epi_corrected
    """

    # Nodes:
    # ------

    # Define input and workflow:
    input_node = pe.Node(name='inputspec',
                         interface=IdentityInterface(fields=[
                             'in_files', 'fieldmap_mag', 'fieldmap_pha', 'wfs',
                             'epi_factor', 'acceleration', 'echo_spacing',
                             'te_diff', 'phase_encoding_direction'
                         ]))

    # Normalize phase difference of the fieldmap phase to be [-pi, pi)
    norm_pha = pe.Node(interface=Prepare_phasediff, name='normalize_phasediff')

    # Mask the magnitude of the fieldmap
    mask_mag = pe.Node(fsl.BET(mask=True), name='mask_magnitude')
    mask_mag_dil = pe.Node(interface=Dilate_mask, name='mask_dilate')

    # Unwrap fieldmap phase using FSL PRELUDE
    prelude = pe.Node(fsl.PRELUDE(process3d=True), name='phase_unwrap')

    # Convert unwrapped fieldmap phase to radials per second:
    radials_per_second = pe.Node(interface=Radials_per_second,
                                 name='radials_ps')

    # in case of SIEMENS scanner:
    prepare_fieldmap = pe.Node(PrepareFieldmap(), name='prepare_fieldmap')

    # Register unwrapped fieldmap (rad/s) to epi, using the magnitude of the fieldmap
    registration = pe.MapNode(fsl.FLIRT(bins=256,
                                        cost='corratio',
                                        dof=6,
                                        interp='trilinear',
                                        searchr_x=[-10, 10],
                                        searchr_y=[-10, 10],
                                        searchr_z=[-10, 10]),
                              iterfield=['reference'],
                              name='registration')

    # transform unwrapped fieldmap (rad/s)
    applyxfm = pe.MapNode(fsl.ApplyXFM(interp='trilinear'),
                          iterfield=['reference', 'in_matrix_file'],
                          name='apply_xfm')

    # compute effective echospacing:
    echo_spacing_philips = pe.Node(interface=Compute_echo_spacing_philips,
                                   name='echo_spacing_philips')
    echo_spacing_siemens = pe.Node(interface=Compute_echo_spacing_siemens,
                                   name='echo_spacing_siemens')
    te_diff_in_ms = pe.Node(interface=TE_diff_ms, name='te_diff_in_ms')

    # Unwarp with FSL Fugue
    fugue = pe.MapNode(interface=fsl.FUGUE(median_2dfilter=True),
                       iterfield=['in_file', 'unwarped_file', 'fmap_in_file'],
                       name='fugue')

    # Convert unwrapped fieldmap phase to radials per second:
    out_file = pe.MapNode(interface=Make_output_filename,
                          iterfield=['in_file'],
                          name='out_file')

    # Define output node
    outputnode = pe.Node(
        IdentityInterface(fields=['out_files', 'field_coefs']),
        name='outputspec')

    # Workflow:
    # ---------

    unwarp_workflow = pe.Workflow(name=name)
    unwarp_workflow.connect(input_node, 'in_files', out_file, 'in_file')

    # registration:
    unwarp_workflow.connect(input_node, 'fieldmap_mag', mask_mag, 'in_file')
    unwarp_workflow.connect(mask_mag, 'mask_file', mask_mag_dil, 'in_file')
    unwarp_workflow.connect(mask_mag, 'out_file', registration, 'in_file')
    unwarp_workflow.connect(input_node, 'in_files', registration, 'reference')

    if scanner == 'philips':

        # prepare fieldmap:
        unwarp_workflow.connect(input_node, 'fieldmap_pha', norm_pha,
                                'in_file')
        unwarp_workflow.connect(input_node, 'fieldmap_mag', prelude,
                                'magnitude_file')
        unwarp_workflow.connect(norm_pha, 'out_file', prelude, 'phase_file')
        unwarp_workflow.connect(mask_mag_dil, 'out_file', prelude, 'mask_file')
        unwarp_workflow.connect(prelude, 'unwrapped_phase_file',
                                radials_per_second, 'in_file')
        unwarp_workflow.connect(input_node, 'te_diff', radials_per_second,
                                'asym')

        # transform fieldmap:
        unwarp_workflow.connect(radials_per_second, 'out_file', applyxfm,
                                'in_file')
        unwarp_workflow.connect(registration, 'out_matrix_file', applyxfm,
                                'in_matrix_file')
        unwarp_workflow.connect(input_node, 'in_files', applyxfm, 'reference')

        # compute echo spacing:
        unwarp_workflow.connect(input_node, 'wfs', echo_spacing_philips, 'wfs')
        unwarp_workflow.connect(input_node, 'epi_factor', echo_spacing_philips,
                                'epi_factor')
        unwarp_workflow.connect(input_node, 'acceleration',
                                echo_spacing_philips, 'acceleration')
        unwarp_workflow.connect(echo_spacing_philips, 'echo_spacing', fugue,
                                'dwell_time')

    elif scanner == 'siemens':

        unwarp_workflow.connect(input_node, 'te_diff', te_diff_in_ms,
                                'te_diff')

        # prepare fieldmap:
        unwarp_workflow.connect(mask_mag, 'out_file', prepare_fieldmap,
                                'in_magnitude')
        unwarp_workflow.connect(input_node, 'fieldmap_pha', prepare_fieldmap,
                                'in_phase')
        unwarp_workflow.connect(te_diff_in_ms, 'te_diff', prepare_fieldmap,
                                'delta_TE')

        # transform fieldmap:
        unwarp_workflow.connect(prepare_fieldmap, 'out_fieldmap', applyxfm,
                                'in_file')
        unwarp_workflow.connect(registration, 'out_matrix_file', applyxfm,
                                'in_matrix_file')
        unwarp_workflow.connect(input_node, 'in_files', applyxfm, 'reference')

        # compute echo spacing:
        unwarp_workflow.connect(input_node, 'acceleration',
                                echo_spacing_siemens, 'acceleration')
        unwarp_workflow.connect(input_node, 'echo_spacing',
                                echo_spacing_siemens, 'echo_spacing')
        unwarp_workflow.connect(echo_spacing_siemens, 'echo_spacing', fugue,
                                'dwell_time')

    unwarp_workflow.connect(input_node, 'in_files', fugue, 'in_file')
    unwarp_workflow.connect(out_file, 'out_file', fugue, 'unwarped_file')
    unwarp_workflow.connect(applyxfm, 'out_file', fugue, 'fmap_in_file')
    unwarp_workflow.connect(input_node, 'te_diff', fugue, 'asym_se_time')
    unwarp_workflow.connect(input_node, 'phase_encoding_direction', fugue,
                            'unwarp_direction')
    unwarp_workflow.connect(fugue, 'unwarped_file', outputnode, 'out_files')
    unwarp_workflow.connect(applyxfm, 'out_file', outputnode, 'field_coefs')

    # # Connect
    # unwarp_workflow.connect(input_node, 'in_files', out_file, 'in_file')
    # unwarp_workflow.connect(input_node, 'fieldmap_pha', norm_pha, 'in_file')
    # unwarp_workflow.connect(input_node, 'fieldmap_mag', mask_mag, 'in_file')
    # unwarp_workflow.connect(mask_mag, 'mask_file', mask_mag_dil, 'in_file')
    # unwarp_workflow.connect(input_node, 'fieldmap_mag', prelude, 'magnitude_file')
    # unwarp_workflow.connect(norm_pha, 'out_file', prelude, 'phase_file')
    # unwarp_workflow.connect(mask_mag_dil, 'out_file', prelude, 'mask_file')
    # unwarp_workflow.connect(prelude, 'unwrapped_phase_file', radials_per_second, 'in_file')
    # unwarp_workflow.connect(input_node, 'te_diff', radials_per_second, 'asym')
    # unwarp_workflow.connect(mask_mag, 'out_file', registration, 'in_file')
    # unwarp_workflow.connect(input_node, 'in_files', registration, 'reference')
    # unwarp_workflow.connect(radials_per_second, 'out_file', applyxfm, 'in_file')
    # unwarp_workflow.connect(registration, 'out_matrix_file', applyxfm, 'in_matrix_file')
    # unwarp_workflow.connect(input_node, 'in_files', applyxfm, 'reference')
    # if compute_echo_spacing:
    #     unwarp_workflow.connect(input_node, 'wfs', echo_spacing, 'wfs')
    #     unwarp_workflow.connect(input_node, 'epi_factor', echo_spacing, 'epi_factor')
    #     unwarp_workflow.connect(input_node, 'acceleration', echo_spacing, 'acceleration')
    #     unwarp_workflow.connect(echo_spacing, 'echo_spacing', fugue, 'dwell_time')
    # else:
    #     unwarp_workflow.connect(input_node, 'echo_spacing', fugue, 'dwell_time')
    # unwarp_workflow.connect(input_node, 'in_files', fugue, 'in_file')
    # unwarp_workflow.connect(out_file, 'out_file', fugue, 'unwarped_file')
    # unwarp_workflow.connect(applyxfm, 'out_file', fugue, 'fmap_in_file')
    # unwarp_workflow.connect(input_node, 'te_diff', fugue, 'asym_se_time')
    # unwarp_workflow.connect(input_node, 'phase_encoding_direction', fugue, 'unwarp_direction')
    # unwarp_workflow.connect(fugue, 'unwarped_file', outputnode, 'out_files')
    # unwarp_workflow.connect(applyxfm, 'out_file', outputnode, 'field_coefs')

    return unwarp_workflow
示例#3
0
def create_register_structural_to_diff(name='structural_to_diff'):
    """Co-register images using an affine transformation.

    Example
    -------

    >>> from tn_image_processing.workflows import registration
    >>> registration = registration.create_affine_registration()
    >>> registration.inputs.inputnode.structural = ['sub
    >>> registration.inputs.inputnode.dwi = ['DTI.nii.gz']

    Inputs::

        [Mandatory]
        inputnode.structural_list: list of hi-resolution structural
                                   images
        inputnode.dwi_list: list of 4dim diffusion volumes

    Outputs::

        outputnode.struct_to_b0: structural image registered to b0
                                 space
        outputnode.struct_to_b0_mat: affine matrix used to register
                                     structural image to b0 space

    """

    # Define the inputnode
    inputnode = pe.Node(interface=util.IdentityInterface(
        fields=["structural_list", "dwi_list"]),
                        name="inputnode")

    # Get first volume from 4d diffusion image (we assume this is b0)
    extract_b0 = pe.MapNode(interface=fslutil.ExtractROI(
        roi_file='DTI_first.nii.gz', t_min=0, t_size=1),
                            iterfield=['in_file'],
                            name='extract_b0')

    # Align structural image to b0
    flirt = pe.MapNode(interface=fslpre.FLIRT(dof=6,
                                              cost='mutualinfo',
                                              usesqform=True,
                                              out_file="T1_to_b0.nii.gz",
                                              out_matrix_file="T1_to_b0.mat"),
                       iterfield=['in_file', 'ref_file'],
                       name="flirt")

    # Define this workflow
    structural_to_diff = pe.Workflow(name=name)

    # Connect components of this workflow
    structural_to_diff.connect([
        (inputnode, extract_b0, [("dwi", "in_file")]),
        (inputnode, flirt, [("structural", "in_file")]),
        (extract_b0, flirt, [("roi_file", "ref_file")]),
    ])

    # Define the outputnode
    outputnode = pe.Node(interface=util.IdentityInterface(
        fields=['struct_to_b0', 'struct_to_b0_mat']))

    # Connect the output
    structural_to_diff.connect([
        (flirt, outputnode, [('out_file', 'struct_to_b0'),
                             ('out_matrix_file', 'struct_to_b0_mat')]),
    ])

    return structural_to_diff
示例#4
0
def create_registration(name='registration'):
    """Create a workflow designed to register structural image to dwi.

    Example
    -------
    >>> import tn_image_processing.workflows as pipes
    >>> registration = pipes.create_registration()
    >>> registration.inputnode.dwi_image = ['path/to/dwi/image']
    >>> registration.inputnode.struct_image = ['path/to/struct/image']
    >>> registration.run()

    Inputs::

      [mandatory]
      inputnode.dwi_image
      inputnode.structural_image
      inputnode.working_dir

    Outputs::

      outputnode.dwi_first
      outputnode.dwi_resampled
      outputnode.struct_to_dwi_image
      outputnode.struct_to_dwi_mat

    """
    import nipype.pipeline.engine as pe
    import nipype.interfaces.utility as util
    import nipype.interfaces.fsl.utils as fslutil
    import nipype.interfaces.fsl.preprocess as fslpre

    # Setup input node
    inputnode = pe.Node(interface=util.IdentityInterface(
        fields=['dwi_image', 'structural_image']),
                        name='inputnode')
    # Get first volume from 4d diffusion image (we assume this is b0)
    extract_b0 = pe.Node(interface=fslutil.ExtractROI(t_min=0, t_size=1),
                         name='extract_b0')
    # TODO: debug runtime error caused when specifying name of output roi file
    # extract_b0.inputs.roi_file = 'DTI_first.nii.gz'
    #
    # Resample b0 to voxel size of 1mm
    import nipype.interfaces.freesurfer.preprocess as fspre
    resample_b0 = pe.Node(interface=fspre.Resample(), name='resample_b0')
    resample_b0.inputs.voxel_size = tuple((1., 1., 1.))
    # resample_b0.inputs.resampled_file = 'Diffusion_b0_resampled.nii.gz'
    # Align structural image to b0
    flirt = pe.Node(interface=fslpre.FLIRT(dof=6,
                                           cost='mutualinfo',
                                           uses_qform=True),
                    name="flirt")
    # flirt.inputs.out_file = 'T1-TO-b0.nii.gz'
    # flirt.inputs.out_matrix_file = 'T1-TO-b0.mat'
    # Setup output node
    outputnode = pe.Node(interface=util.IdentityInterface(fields=[
        'dwi_first', 'dwi_resampled', 'struct_to_dwi_image',
        'struct_to_dwi_mat'
    ]),
                         name='outputnode')

    # Create workflow
    this_workflow = pe.Workflow(name=name)
    # Connect workflow
    this_workflow.connect(inputnode, "dwi_image", extract_b0, "in_file")
    this_workflow.connect(inputnode, "structural_image", flirt, "in_file")
    this_workflow.connect(extract_b0, "roi_file", resample_b0, "in_file")
    this_workflow.connect(resample_b0, "resampled_file", flirt, "reference")
    this_workflow.connect(extract_b0, "roi_file", outputnode, "dwi_first")
    this_workflow.connect(resample_b0, "resampled_file", outputnode,
                          "dwi_resampled")
    this_workflow.connect(flirt, "out_file", outputnode, "struct_to_dwi_image")
    this_workflow.connect(flirt, "out_matrix_file", outputnode,
                          "struct_to_dwi_mat")
    # Return workflow
    return this_workflow
示例#5
0
def NORMPIPE():
    #--- 1)  Import modules
    from nipype.interfaces.ants import Registration, ApplyTransforms
    import nipype.pipeline.engine as pe
    import matplotlib
    import os
    from glob import glob
    from nilearn import plotting
    from nilearn import image
    from nipype.interfaces.utility import Function
    import nipype.interfaces.fsl.preprocess as fsl
    import nipype.interfaces.fsl as fslbase
    import nipype.interfaces.fsl.utils as fslu
    from nipype.interfaces.fsl import Info
    import nipype.interfaces.utility as util

    INITDIR = os.getcwd()

    #--- 2)  Define input node
    template = Info.standard_image('MNI152_T1_2mm_brain.nii.gz')
    inputnode = pe.Node(interface=util.IdentityInterface(fields=['standard']),
                        name='inputspec')
    inputnode.inputs.standard = template

    #--- 3)  Get inputs and define node for registering EPI to structural.
    alsonorm = bool(input('Also normalise?\n'))
    epireg = pe.Node(interface=fslbase.EpiReg(), name='EPIREG')

    t1_brain = raw_input(
        'Please drag in the brain-extracted structural volume\n')
    t1_head = raw_input(
        'Please drag in the non-brain extracted structural volume\n')
    epi = raw_input('Please drag in the mean functional volume.\n')

    epireg.inputs.t1_brain = t1_brain.strip('\'"')
    epireg.inputs.t1_head = t1_head.strip('\'"')
    epireg.inputs.epi = epi.strip('\'"')
    NIFTIDIR = os.path.split(epireg.inputs.t1_brain)[0]

    #--- 4)  Register the T1 to the MNI
    registerT12S = pe.Node(interface=fsl.FLIRT(), name='REGISTEREDT12MNI')
    registerT12S.inputs.dof = int(12)
    registerT12S.inputs.reference = template
    registerT12S.inputs.in_file = epireg.inputs.t1_brain

    #--- 5)  Concatenate the two transformation matrices from 3 and 4.
    concatxfm = pe.Node(interface=fslbase.ConvertXFM(), name='CONCATMATRICES')
    concatxfm.inputs.concat_xfm = bool(1)

    #--- 6)  Register the EPI to the standard, using the combined transformation matrix
    registerF2S = pe.Node(interface=fsl.ApplyXFM(), name='REGISTEREDF2MNI')
    registerF2S.inputs.reference = template
    registerF2S.inputs.in_file = epireg.inputs.epi

    #--- 7)  Use ANTS to normalise the structural to the MNI
    antsregfast = pe.Node(Registration(
        args='--float',
        collapse_output_transforms=True,
        fixed_image=template,
        initial_moving_transform_com=True,
        output_inverse_warped_image=True,
        output_warped_image=True,
        sigma_units=['vox'] * 3,
        transforms=['Rigid', 'Affine', 'SyN'],
        terminal_output='file',
        winsorize_lower_quantile=0.005,
        winsorize_upper_quantile=0.995,
        convergence_threshold=[1e-08, 1e-08, -0.01],
        convergence_window_size=[20, 20, 5],
        metric=['Mattes', 'Mattes', ['Mattes', 'CC']],
        metric_weight=[1.0, 1.0, [0.5, 0.5]],
        number_of_iterations=[[10000, 11110, 11110], [10000, 11110, 11110],
                              [100, 30, 20]],
        radius_or_number_of_bins=[32, 32, [32, 4]],
        sampling_percentage=[0.3, 0.3, [None, None]],
        sampling_strategy=['Regular', 'Regular', [None, None]],
        shrink_factors=[[3, 2, 1], [3, 2, 1], [4, 2, 1]],
        smoothing_sigmas=[[4.0, 2.0, 1.0], [4.0, 2.0, 1.0], [1.0, 0.5, 0.0]],
        transform_parameters=[(0.1, ), (0.1, ), (0.2, 3.0, 0.0)],
        use_estimate_learning_rate_once=[True] * 3,
        use_histogram_matching=[False, False, True],
        write_composite_transform=True),
                          name='NORMSTRUCT')

    #--- 8)  Apply the same warping to the EPI
    apply2mean = pe.Node(ApplyTransforms(args='--float',
                                         input_image_type=3,
                                         interpolation='Linear',
                                         invert_transform_flags=[False],
                                         num_threads=1,
                                         reference_image=template,
                                         terminal_output='file'),
                         name='NORMFUNC')

    #--- 9)  Also need an outputnode, since otherwise some outputs may be binned.
    outputnode = pe.Node(interface=util.IdentityInterface(fields=[
        'warped', 'structmat', 'funcmat', 'epimat', 'funcreg', 'structreg'
    ]),
                         name='outputnode')

    #--- 10)  Custom plotting functions.
    def bplot(in_file, MNI):
        from nilearn import image
        from nilearn import plotting
        import matplotlib
        niftifiledim = len(image.load_img(in_file).shape)
        display = plotting.plot_anat(template)
        display.add_edges(in_file)
        matplotlib.pyplot.show()
        return niftifiledim

    def bplotN(in_file, MNI):
        from nilearn import image
        from nilearn import plotting
        import matplotlib
        niftifiledim = len(image.load_img(in_file).shape)
        display = plotting.plot_anat(MNI)
        display.add_edges(in_file)
        matplotlib.pyplot.show()
        return niftifiledim

    showregL = pe.Node(Function(input_names=['in_file', 'MNI'],
                                output_names=['niftifiledim'],
                                function=bplot),
                       name='SHOWREG')
    showregNL = pe.Node(Function(input_names=['in_file', 'MNI'],
                                 output_names=['niftifiledim'],
                                 function=bplotN),
                        name='SHOWREG')

    #--- 11)  Setup workflow
    workflow = pe.Workflow(name='NORMPIPE')
    workflow.base_dir = NIFTIDIR

    #--- 12)  Connect nodes, depending on whether we want to do normalisation too.
    if alsonorm == bool(0):
        workflow.connect(epireg, 'epi2str_mat', outputnode, 'epimat')
        workflow.connect(epireg, 'epi2str_mat', concatxfm, 'in_file')
        workflow.connect(registerT12S, 'out_matrix_file', concatxfm,
                         'in_file2')
        workflow.connect(concatxfm, 'out_file', registerF2S, 'in_matrix_file')
        workflow.connect(registerT12S, 'out_matrix_file', outputnode,
                         'structmat')
        workflow.connect(registerF2S, 'out_matrix_file', outputnode, 'funcmat')
        workflow.connect(registerF2S, 'out_file', outputnode, 'funcreg')
        workflow.connect(registerT12S, 'out_file', outputnode, 'structreg')
        workflow.connect(registerT12S, 'out_file', showregL, 'in_file')
        workflow.connect(inputnode, 'standard', showregL, 'MNI')
        workflow.write_graph(graph2use='exec')
        workflow.run()
    elif alsonorm == bool(1):
        workflow.connect(epireg, 'epi2str_mat', outputnode, 'epimat')
        workflow.connect(epireg, 'epi2str_mat', concatxfm, 'in_file')
        workflow.connect(registerT12S, 'out_matrix_file', concatxfm,
                         'in_file2')
        workflow.connect(concatxfm, 'out_file', registerF2S, 'in_matrix_file')
        workflow.connect(registerT12S, 'out_matrix_file', outputnode,
                         'structmat')
        workflow.connect(registerF2S, 'out_matrix_file', outputnode, 'funcmat')
        workflow.connect(registerF2S, 'out_file', outputnode, 'funcreg')
        workflow.connect(registerT12S, 'out_file', outputnode, 'structreg')
        workflow.connect(registerF2S, 'out_file', apply2mean, 'input_image')
        workflow.connect(registerT12S, 'out_file', antsregfast, 'moving_image')
        workflow.connect(antsregfast, 'warped_image', outputnode, 'warped')
        workflow.connect([(antsregfast, apply2mean, [('composite_transform',
                                                      'transforms')])])
        workflow.connect(antsregfast, 'warped_image', showregNL, 'in_file')
        workflow.connect(inputnode, 'standard', showregNL, 'MNI')
        workflow.write_graph(graph2use='exec')
        workflow.run()

    print "Node completed. Returning to intital directory\n"
    os.chdir(INITDIR)