Esempio n. 1
0
def init_smooth_wf(fwhm=None, memcalc=MemoryCalculator(), name="smooth_wf"):
    """
    Smooths a volume within a mask while correcting for the mask edge
    """
    workflow = pe.Workflow(name=name)

    inputnode = pe.Node(
        interface=niu.IdentityInterface(
            fields=["in_file", "mask_file", "fwhm"]),
        name="inputnode",
    )

    if fwhm is not None:
        assert isinstance(fwhm, float)
        inputnode.inputs.fwhm = fwhm

    smooth = pe.Node(afni.BlurInMask(preserve=True,
                                     float_out=True,
                                     out_file="blur.nii.gz"),
                     name="smooth")

    workflow.connect([
        (
            inputnode,
            smooth,
            [("in_file", "in_file"), ("mask_file", "mask"), ("fwhm", "fwhm")],
        ),
    ])

    outputnode = pe.Node(interface=niu.IdentityInterface(fields=["out_file"]),
                         name="outputnode")
    workflow.connect(smooth, "out_file", outputnode, "out_file")

    return workflow
Esempio n. 2
0
            ref_file=cf_files['standard'],
            out_file = cf_files['masked'],
            mask_file = cf_files['standard_mask']
        ), name = 'masker')
        #inputmask.inputs.mask_file = cf_files['standard_mask']
    else:
        masker = Node(maths.ApplyMask(
            in_file=cf_files['bold'],
            out_file=cf_files['masked'],
            mask_file=cf_files['standard_mask']
            ), name='masker')


    bim = Node(afni.BlurInMask(
        out_file=cf_files['smoothed'],
        mask = cf_files['standard_mask'],
        fwhm=5.0
    ), name='bim')

    l1 = Node(SpecifyModel(
        event_files=EVfiles,
        realignment_parameters=confoundsfile,
        input_units='secs',
        time_repetition=2,
        high_pass_filter_cutoff=100
    ), name='l1')

    l1model = Node(Level1Design(
        interscan_interval=2,
        bases={'dgamma': {'derivs': True}},
        model_serial_correlations=True,
Esempio n. 3
0
def FUNCPIPE():
	#--- 1)  Import modules

	import os                                    # system functions
	os.system('clear')
	import nipype.interfaces.dcm2nii as dcm2nii
	import nipype.interfaces.io as nio           # Data i/o
	import nipype.interfaces.fsl as fsl          # fsl
	import nipype.interfaces.utility as util     # utility
	import nipype.pipeline.engine as pe          # pypeline engine
	import nipype.interfaces.fsl.utils as fslu
	import nipype.interfaces.fsl.preprocess as fslp
	from nipype.interfaces import afni as afni
	from nipype.interfaces.utility import Function
	import matplotlib
	from nilearn import plotting
	from nilearn import image
	import os
	import nipype.interfaces.fsl as fsl          # fsl
	import nipype.interfaces.utility as util     # utility
	import nipype.pipeline.engine as pe          # pypeline engine
	import nipype.interfaces.freesurfer as fs    # freesurfer


	tolist = lambda x: [x]
	highpass_operand = lambda x:'-bptf %.10f -1'%x

	#--- 2) Prompt user for directory containing DICOM FILES

	INITDIR=os.getcwd();

	#--- 3) Prompt user for inputs.

	DICOMDIR=raw_input('Please drag in the directory of\nDICOM files you wish to pre-process\n(ensure there is no blank space at the end)\n')
	os.system('clear')
	print ('---\n')
	DICOMDIR=DICOMDIR.strip('\'"')
	frac=float(input('Please enter the fractional anisotropy threshold [0 - 1] \n'))
	os.system('clear')
	print ('---\n')
	grad=float(input('Please enter the threshold gradient [-1 - 1] \n'))
	os.system('clear')
	print ('---\n')
	FWHM=float(input('Please enter the FWHM of the smoother (mm) \n'))
	os.system('clear')
	print ('---\n')
	HIGHPASS=float(input('Please enter the High Pass filter cutoff (s)\n'))
	os.system('clear')
	print ('---\n')
	TR=float(input('Please enter the TR (s)\n'))
	os.system('clear')
	print ('---\n')





	#--- 4) Define workflow and input node.

	workflow = pe.Workflow(name='FUNCPIPE')
	inputnode = pe.Node(interface=util.IdentityInterface(fields=['fwhm','highpass','TR']),name='inputspec')

	inputnode.inputs.fwhm=FWHM
	inputnode.inputs.TR=TR
	inputnode.inputs.highpass=float(HIGHPASS/(inputnode.inputs.TR*2.5))


	#--- 5) Move to directory
	os.chdir(DICOMDIR)


	#--- 6) Set up converter node for conversion to nifti
	converter=pe.Node(interface=dcm2nii.Dcm2nii(),name='CONVERTED')
	converter.inputs.source_dir=DICOMDIR
	converter.inputs.gzip_output=bool(1)


	#--- 7) Set up realigner node to match orientation of MNI 152
	realigner=pe.Node(interface=fslu.Reorient2Std(),name='REORIENTED')
	realigner.inputs.output_type='NIFTI_GZ'

	workflow.connect(converter,'converted_files',realigner,'in_file')


	#--- 8) Set up a slice timing node
	slicetimer=pe.Node(interface=fslp.SliceTimer(),name='SLICETIMED')
	slicetimer.inputs.interleaved = True

	workflow.connect(inputnode, 'TR', slicetimer, 'time_repetition')
	workflow.connect(realigner, 'out_file', slicetimer, 'in_file')


	#--- 9) Convert to float.
	img2float = pe.Node(interface=fsl.ImageMaths(out_data_type='float',op_string='',suffix='_dtype'),name='IMG2FLOATED')

	workflow.connect(slicetimer,'slice_time_corrected_file',img2float,'in_file')

	#--- 10) Motion correct.
	motion_correct = pe.Node(interface=fsl.MCFLIRT(save_mats=True,save_plots=True,interpolation='spline'),name='MCORRECTED')

	workflow.connect(img2float, 'out_file', motion_correct, 'in_file')


	#--- 11) Despike
	despiker=pe.Node(interface=afni.Despike(),name='DESPIKED')
	despiker.inputs.outputtype = 'NIFTI_GZ'

	workflow.connect(motion_correct,'out_file',despiker,'in_file')

	#--- 12) Plot motion.
	plot_motion = pe.Node(interface=fsl.PlotMotionParams(in_source='fsl'),name='MOTIONPLOTTED')
	plot_motion.iterables = ('plot_type', ['rotations', 'translations'])

	workflow.connect(motion_correct, 'par_file', plot_motion, 'in_file')

	#--- 13) Extract
	extracter=pe.Node(interface=fsl.BET(),name='EXTRACTED')
	extracter.inputs.frac=float(frac)
	extracter.inputs.vertical_gradient=float(grad)
	extracter.inputs.mask=bool(1)
	extracter.inputs.functional=bool(1)

	workflow.connect(despiker, 'out_file', extracter, 'in_file')


	#--- 14) Smooth
	smoother=pe.MapNode(interface=afni.BlurInMask(),name='SMOOTHED',iterfield=['fwhm'])
	smoother.inputs.outputtype='NIFTI_GZ'

	workflow.connect(inputnode, 'fwhm', smoother, 'fwhm')
	workflow.connect(extracter, 'out_file', smoother, 'in_file')
	workflow.connect(extracter, 'mask_file', smoother, 'mask')


	#--- 15) Highpass filter

	# Filtering node
	highpass = pe.MapNode(interface=fsl.ImageMaths(suffix='_tempfilt'),name='HIGHPASSED',iterfield=['in_file'])

	workflow.connect(inputnode, ('highpass', highpass_operand), highpass, 'op_string')
	workflow.connect(smoother, 'out_file', highpass, 'in_file')

	#--- 16) Mean functional volume
	# Need to add back the mean removed by FSL
	meanfunc = pe.MapNode(interface=fsl.ImageMaths(op_string='-Tmean',suffix='_mean'),name='meanfunc',iterfield=['in_file'])
	workflow.connect(smoother, 'out_file', meanfunc, 'in_file')

	#--- 17) Add mean back to highpassed data (FINAL OUTPUT)
	addmean = pe.MapNode(interface=fsl.BinaryMaths(operation='add'),name='PREPROCESSED',iterfield=['in_file','operand_file'])

	workflow.connect(highpass, 'out_file', addmean, 'in_file')
	workflow.connect(meanfunc, 'out_file', addmean, 'operand_file')

	outputnode = pe.Node(interface=util.IdentityInterface(fields=['highpassed_files']),name='outputnode')

	workflow.connect(addmean, 'out_file', outputnode, 'highpassed_files')



	# Utility function for plotting extraction
	def bplot(in_file,in_file2,in_file3):
		from nilearn import image
		from nilearn import plotting
		import matplotlib
		niftifiledim=len(image.load_img(in_file).shape)
		firstim=image.index_img(in_file, 0)
		firstim2=image.index_img(in_file2, 0)
		display=plotting.plot_anat(firstim2)	
		display.add_contours(firstim,filled=True, alpha=0.5,levels=[0.2], colors='b')
		display.add_edges(in_file3)
		matplotlib.pyplot.show()
		return niftifiledim

	#--- 18) Show extraction
	showextract= pe.Node(Function(input_names=['in_file','in_file2','in_file3'],output_names=['niftifiledim'],function=bplot),name='SHOWEXTRACT')

	workflow.connect(despiker,'out_file', showextract,'in_file2')
	workflow.connect(extracter,'out_file', showextract,'in_file')
	workflow.connect(extracter,'mask_file', showextract,'in_file3')

	# Utility function for plotting extraction
	def splot(in_file):
		from nilearn import image
		from nilearn import plotting
		import matplotlib
		niftifiledim=len(image.load_img(in_file).shape)
		firstim=image.index_img(in_file, 0)
		display=plotting.plot_anat(firstim,display_mode='z',cut_coords=10)
		matplotlib.pyplot.show()	
		return niftifiledim

	#--- 19) Show smoothing
	showsmooth= pe.MapNode(Function(input_names=['in_file'],output_names=['niftifiledim'],function=splot),iterfield=['in_file'],name='SHOWSMOOTH')

	workflow.connect(smoother,'out_file', showsmooth,'in_file')



	#--- 20) Mean functional volume (for plotting stats)
	meanfunc2 = pe.Node(interface=fsl.ImageMaths(op_string='-Tmean',suffix='_mean'),name='MEANFUNCTIONAL')
	workflow.connect(extracter, 'out_file', meanfunc2, 'in_file')
	workflow.connect(meanfunc2, 'out_file', outputnode, 'mean_functional_volume')

	#--- 21) Plot workflow
	workflow.base_dir = DICOMDIR
	workflow.write_graph(graph2use='exec')

	#--- 22) Plot workflow
	result=workflow.run()

	#--- 23) Show plots
	

	#--- 24) Return to initial working directory
	print ("Workflow completed. Returning to intital directory\n")
	os.chdir(INITDIR)
Esempio n. 4
0
def SMOOTHER():

    #--- 1)  Import modules
    import nipype.pipeline.engine as pe
    import os
    os.system('clear')
    from glob import glob
    import nipype.interfaces.fsl.preprocess as fslp
    from nipype.interfaces import afni as afni
    import nipype.interfaces.utility as util
    from nipype.interfaces.utility import Function

    #--- 2)  Record intial working directory

    INITDIR = os.getcwd()

    #--- 3) Prompt user for nifti file

    NIFTIFILE = raw_input(
        'Please drag in the functional volume\n(ensure there is no blank space at the end)\n'
    )
    os.system('clear')
    print '---\n'
    NIFTIMASK = raw_input(
        'Please drag in the mask\n for the functional volume\n(ensure there is no blank space at the end)\n'
    )
    os.system('clear')
    print '---\n'
    FWHM = input('Please enter the FWHM (mm) of the smoother\n')
    os.system('clear')
    print '---\n'

    NIFTIFILE = NIFTIFILE.strip('\'"')
    NIFTIDIR = os.path.split(NIFTIFILE)[0]

    #--- 3) Move to directory

    os.chdir(NIFTIDIR)

    #--- 4) Set up input node
    inputnode = pe.Node(interface=util.IdentityInterface(fields=['fwhm']),
                        name='inputspec')
    inputnode.inputs.fwhm = FWHM

    #--- 5) Set up smoothing node
    smoother = pe.MapNode(interface=afni.BlurInMask(),
                          name='SMOOTHED',
                          iterfield=['fwhm'])
    smoother.inputs.outputtype = 'NIFTI_GZ'
    smoother.inputs.in_file = NIFTIFILE
    smoother.inputs.mask = NIFTIMASK

    #--- 6) Function for plotting result
    def splot(in_file):
        from nilearn import image
        from nilearn import plotting
        import matplotlib
        niftifiledim = len(image.load_img(in_file).shape)
        firstim = image.index_img(in_file, 0)
        display = plotting.plot_anat(firstim, display_mode='z', cut_coords=10)
        matplotlib.pyplot.show()
        return niftifiledim

    #--- 7) Node for plotting smoothing
    showsmooth = pe.MapNode(Function(input_names=['in_file'],
                                     output_names=['niftifiledim'],
                                     function=splot),
                            iterfield=['in_file'],
                            name='SHOWSMOOTH')

    #--- 8) Set up workflow
    workflow = pe.Workflow(name='SMOOTHER')
    workflow.base_dir = NIFTIDIR

    #--- 9) Connect nodes.
    workflow.connect(inputnode, 'fwhm', smoother, 'fwhm')
    workflow.connect(smoother, 'out_file', showsmooth, 'in_file')

    workflow.write_graph(graph2use='exec')

    #--- 10) Run workflow

    result = workflow.run()

    print "Node completed. Returning to intital directory\n"

    os.chdir(INITDIR)
Esempio n. 5
0
def first_level_wf(pipeline, subject_id, task_id, output_dir):
    """
    First level workflow
    """
    workflow = pe.Workflow(name='_'.join((pipeline, subject_id, task_id)))

    inputnode = pe.Node(niu.IdentityInterface(fields=[
        'bold_preproc', 'contrasts', 'confounds', 'brainmask', 'events_file'
    ]),
                        name='inputnode')

    outputnode = pe.Node(
        niu.IdentityInterface(fields=['sigma_pre', 'sigma_post', 'out_stats']),
        name='outputnode')

    conf2movpar = pe.Node(niu.Function(function=_confounds2movpar),
                          name='conf2movpar')
    masker = pe.Node(fsl.ApplyMask(), name='masker')
    bim = pe.Node(afni.BlurInMask(fwhm=5.0, outputtype='NIFTI_GZ'),
                  name='bim',
                  mem_gb=20)

    ev = pe.Node(EventsFilesForTask(task=task_id), name='events')

    l1 = pe.Node(SpecifyModel(
        input_units='secs',
        time_repetition=2,
        high_pass_filter_cutoff=100,
        parameter_source='FSL',
    ),
                 name='l1')

    l1model = pe.Node(fsl.Level1Design(interscan_interval=2,
                                       bases={'dgamma': {
                                           'derivs': True
                                       }},
                                       model_serial_correlations=True),
                      name='l1design')

    l1featmodel = pe.Node(fsl.FEATModel(), name='l1model')
    l1estimate = pe.Node(fsl.FEAT(), name='l1estimate', mem_gb=40)

    pre_smooth_afni = pe.Node(afni.FWHMx(combine=True,
                                         detrend=True,
                                         args='-ShowMeClassicFWHM'),
                              name='smooth_pre_afni',
                              mem_gb=20)
    post_smooth_afni = pe.Node(afni.FWHMx(combine=True,
                                          detrend=True,
                                          args='-ShowMeClassicFWHM'),
                               name='smooth_post_afni',
                               mem_gb=20)

    pre_smooth = pe.Node(fsl.SmoothEstimate(), name='smooth_pre', mem_gb=20)
    post_smooth = pe.Node(fsl.SmoothEstimate(), name='smooth_post', mem_gb=20)

    def _resels(val):
        return val**(1 / 3.)

    def _fwhm(fwhm):
        from numpy import mean
        return float(mean(fwhm, dtype=float))

    workflow.connect([
        (inputnode, masker, [('bold_preproc', 'in_file'),
                             ('brainmask', 'mask_file')]),
        (inputnode, ev, [('events_file', 'in_file')]),
        (inputnode, l1model, [('contrasts', 'contrasts')]),
        (inputnode, conf2movpar, [('confounds', 'in_confounds')]),
        (inputnode, bim, [('brainmask', 'mask')]),
        (masker, bim, [('out_file', 'in_file')]),
        (bim, l1, [('out_file', 'functional_runs')]),
        (ev, l1, [('event_files', 'event_files')]),
        (conf2movpar, l1, [('out', 'realignment_parameters')]),
        (l1, l1model, [('session_info', 'session_info')]),
        (ev, l1model, [('orthogonalization', 'orthogonalization')]),
        (l1model, l1featmodel, [('fsf_files', 'fsf_file'),
                                ('ev_files', 'ev_files')]),
        (l1model, l1estimate, [('fsf_files', 'fsf_file')]),
        # Smooth
        (inputnode, pre_smooth, [('bold_preproc', 'zstat_file'),
                                 ('brainmask', 'mask_file')]),
        (bim, post_smooth, [('out_file', 'zstat_file')]),
        (inputnode, post_smooth, [('brainmask', 'mask_file')]),
        (pre_smooth, outputnode, [(('resels', _resels), 'sigma_pre')]),
        (post_smooth, outputnode, [(('resels', _resels), 'sigma_post')]),

        # Smooth with AFNI
        (inputnode, pre_smooth_afni, [('bold_preproc', 'in_file'),
                                      ('brainmask', 'mask')]),
        (bim, post_smooth_afni, [('out_file', 'in_file')]),
        (inputnode, post_smooth_afni, [('brainmask', 'mask')]),
    ])

    # Writing outputs
    csv = pe.Node(AddCSVRow(in_file=str(output_dir / 'smoothness.csv')),
                  name='addcsv_%s_%s' % (subject_id, pipeline))
    csv.inputs.sub_id = subject_id
    csv.inputs.pipeline = pipeline

    # Datasinks
    ds_stats = pe.Node(niu.Function(function=_feat_stats), name='ds_stats')
    ds_stats.inputs.subject_id = subject_id
    ds_stats.inputs.task_id = task_id
    ds_stats.inputs.variant = pipeline
    ds_stats.inputs.out_path = output_dir
    setattr(ds_stats.interface, '_always_run', True)

    workflow.connect([
        (outputnode, csv, [('sigma_pre', 'smooth_pre'),
                           ('sigma_post', 'smooth_post')]),
        (pre_smooth_afni, csv, [(('fwhm', _fwhm), 'fwhm_pre')]),
        (post_smooth_afni, csv, [(('fwhm', _fwhm), 'fwhm_post')]),
        (l1estimate, ds_stats, [('feat_dir', 'feat_dir')]),
        (ds_stats, outputnode, [('out', 'out_stats')]),
    ])
    return workflow
Esempio n. 6
0
def base_preproc2(trim_realign=True,name='rsfmri_base_preproc'):

    inputnode = pe.Node(
        utility.IdentityInterface(
            fields=['fmri','fmri_mask']),
        name='inputspec')
    outputnode = pe.Node(
        utility.IdentityInterface(
            fields=['preprocessed','mean','motion']),
        name='outputspec')

#    n_trim = pe.Node(
#        interface=nipypp.Trim(begin_index=3),
#        name='trim')
    
    n_realign = pe.Node(
        fsl.MCFLIRT(ref_vol=0,
                    save_plots=True,
                    save_rms=True,
                    save_mats=True,
                    stats_imgs=True,),
        name='realign')

    n_mean = pe.Node(fsl.MeanImage(),name='mean')

    n_mask_mean = pe.Node(
        interface=fsl.ImageMaths(op_string='-mul', suffix='_brain',
                                 output_type='NIFTI'),
        name='mask_mean')

    #linear with shear/scale in phase direction

    n_smooth = pe.Node(
        afni.BlurInMask(fwhm=5.0, out_file='%s_smooth', float_out=True),
        name = 'smooth')    

    n_bandpass_smooth = pe.Node(
        afni.Bandpass(highpass=0.005, lowpass=999999,
                      despike=True,
                      blur=5.0, normalize=False, out_file='%s_filt.nii.gz'),
        name='bandpass_smooth')

    n_motion_filter = pe.Node(
        interface = nipypp.RegressOutMotion(
            motion_source='fsl',
            regressors_type='voxelwise_translation',
            global_signal = False,
            prefix = 'mfilt_',
            regressors_transform='original+bw_derivatives'),
        name = 'motion_filter')


    n_motion_estimates = pe.Node(
        nipyutils.MotionEstimate(motion_source='fsl'),
        name='motion_estimates')    

    w=pe.Workflow(name=name)

    if trim_realign:
        w.connect([
                (inputnode, n_realign, [('fmri','in_file')]),
                (n_realign, n_motion_filter, [('out_file','in_file'),
                                              ('par_file','motion')]),
                (inputnode, n_motion_filter,[('fmri_mask','mask')]),
                (n_motion_filter, n_bandpass_smooth, [('out_file','in_file')]),
                (n_realign, n_mask_mean,  [('mean_img', 'in_file')]),
                (n_realign, n_motion_estimates,[('par_file','motion')]),
                (inputnode, n_motion_estimates,[('fmri_mask','mask')]),
                (n_realign, outputnode, [('par_file','motion')]),
                ])
    else:
        w.connect([
                (inputnode, n_bandpass_smooth, [('fmri','in_file')]),
                (inputnode, n_mean, [('fmri','in_file')]),
                (n_mean, n_mask_mean, [('out_file', 'in_file')]),
                ])

    w.connect([
        (inputnode, n_mask_mean,  [('fmri_mask', 'in_file2')]),
        (inputnode, n_bandpass_smooth, [('fmri_mask','mask')]),
        (n_bandpass_smooth, outputnode, [('out_file','preprocessed')]),
        (n_mask_mean, outputnode, [('out_file','mean')]),

      ])
    return w
Esempio n. 7
0
def base_preproc(trim_realign=True,name='rsfmri_base_preproc'):

    inputnode = pe.Node(
        utility.IdentityInterface(
            fields=['fmri','t1','t1_mask']),
        name='inputspec')
    outputnode = pe.Node(
        utility.IdentityInterface(
            fields=['preprocessed','mask','mean','motion']),
        name='outputspec')

#    n_trim = pe.Node(
#        interface=nipypp.Trim(begin_index=3),
#        name='trim')
    
    n_realign = pe.Node(
        fsl.MCFLIRT(ref_vol=0,
                    mean_vol=True,
                    save_plots=True,
                    save_rms=True,
                    save_mats=True,
                    stats_imgs=True,),
        name='realign')

    n_mean = pe.Node(fsl.MeanImage(),name='mean')

    n_mask = pe.Node(
        interface=afni.Automask(
            out_file='%s_mask.nii',
#            brain_file=Undefined,
            outputtype='NIFTI'),
        name='mask')

    n_mask_mean = pe.Node(
        interface=fsl.ImageMaths(op_string='-mul', suffix='_brain',
                                 output_type='NIFTI'),
        name='mask_mean')

    n_segment_epi = pe.Node(
        fsl.FAST(
            img_type=2,
            number_classes=3,
            probability_maps=True,
            segments=True),
        name='segment_epi')

    #linear with shear/scale in phase direction
    n_coregister_linear = pe.Node(
        afni.Allineate(epi=True, args='-float',cost='nmi',
                       out_param_file='params.1D',
                       out_matrix='coregister.mat'),
        name='coregister_linear')

    n_coregister_gray_linear = pe.Node(
        afni.Allineate(epi=True, args='-float',cost='nmi',
                       out_param_file='params.1D',
                       out_matrix='coregister.mat'),
        name='coregister_gray_linear')

    n_smooth = pe.Node(
        afni.BlurInMask(fwhm=5.0, out_file='%s_smooth', float_out=True),
        name = 'smooth')    

    n_bandpass_smooth = pe.Node(
        afni.Bandpass(highpass=0.005, lowpass=999999,
                      despike=True,
                      blur=5.0, normalize=False, out_file='%s_filt.nii.gz'),
        name='bandpass_smooth')

    n_motion_filter = pe.Node(
        interface = nipypp.RegressOutMotion(
            motion_source='fsl',
            regressors_type='voxelwise_translation',
            global_signal = False,
            prefix = 'mfilt_',
            regressors_transform='original+bw_derivatives'),
        name = 'motion_filter')


#    spm_path = spm.Info().version()['path']
#    epi_tpl = os.path.join(spm_path, 'templates/EPI.nii')
    """
    n_normalize = pe.Node(
        spm.Normalize(template=epi_tpl,
                      source_image_smoothing=8,
                      template_image_smoothing=0,
                      DCT_period_cutoff=25,
                      affine_regularization_type='mni',
                      jobtype='est'),
        name='normalize')
        """

    n_motion_estimates = pe.Node(
        nipyutils.MotionEstimate(motion_source='fsl'),
        name='motion_estimates')    

    w=pe.Workflow(name=name)

    if trim_realign:
        w.connect([
#                (inputnode, n_trim, [('fmri','in_file')]),
#                (inputnode, n_trim, [('fmri','in_file_a'),
#                                     (('fmri',n_volumes,-1),'stop_idx')]),
#                (n_trim, n_realign, [('out_file','in_file')]),
                (inputnode, n_realign, [('fmri','in_file')]),
#                (inputnode, n_realign, [('fmri','in_file')]),
                (n_realign, n_motion_filter, [('out_file','in_file'),
                                              ('par_file','motion')]),
                (n_mask, n_motion_filter,[('out_file','mask')]),
                (n_motion_filter, n_bandpass_smooth, [('out_file','in_file')]),
                (n_realign, n_mask, [('out_file','in_file')]),                
                (n_realign, n_mask_mean,  [('mean_img', 'in_file')]),
                (n_realign, n_motion_estimates,[('par_file','motion')]),
                (n_mask, n_motion_estimates,[('out_file','mask')]),
                (n_realign, outputnode, [('par_file','motion')]),
                ])
    else:
        w.connect([
                (inputnode, n_bandpass_smooth, [('fmri','in_file')]),
                (inputnode, n_mean, [('fmri','in_file')]),
                (inputnode, n_mask, [('fmri','in_file')]),                
                (n_mean, n_mask_mean, [('out_file', 'in_file')]),
                ])

    w.connect([
        (n_mask, n_mask_mean,  [('out_file', 'in_file2')]),
        (n_mask, n_bandpass_smooth, [('out_file','mask')]),
#        (n_mask_mean, n_segment_epi, [('out_file','in_files')]),
#        (n_mask_mean, n_normalize, [('out_file','source')]),
        
#        (n_detrend, n_smooth, [('out_file','in_file')]),
#        (n_mask, n_smooth,  [('out_file', 'mask')]),


#        (n_smooth, outputnode, [('out_file','preprocessed')]),
        (n_bandpass_smooth, outputnode, [('out_file','preprocessed')]),
        (n_mask, outputnode, [('out_file','mask')]),
        (n_mask_mean, outputnode, [('out_file','mean')]),

      ])
    return w