Beispiel #1
0
def head_motion_correction(name='motion_correction'):
    workflow = Workflow(name)

    input_node = Node(
        niu.IdentityInterface(fields=['bold_file', 'raw_ref_image']),
        name='input')
    output_node = Node(niu.IdentityInterface(fields=['xforms', 'movpar_file']),
                       name='outputnode')

    mcflirt = Node(fsl.MCFLIRT(save_mats=True, save_plots=True),
                   name='mcflirt')

    fsl2itk = Node(MCFLIRT2ITK(), name='fsl2itk')

    normalize_motion = Node(NormalizeMotionParams(format='FSL'),
                            name="normalize_motion")

    workflow.connect([
        (input_node, mcflirt, [('raw_ref_image', 'ref_file'),
                               ('bold_file', 'in_file')]),
        (input_node, fsl2itk, [('raw_ref_image', 'in_source'),
                               ('raw_ref_image', 'in_reference')]),
        (mcflirt, fsl2itk, [('mat_file', 'in_files')]),
        (mcflirt, normalize_motion, [('par_file', 'in_file')]),
        (fsl2itk, output_node, [('out_file', 'xforms')]),
        (normalize_motion, output_node, [('out_file', 'movpar_file')]),
    ])

    return workflow
Beispiel #2
0
def MCORRECTOR():
	#--- 1)  Import modules
	import nipype.pipeline.engine as pe
	import os
	os.system('clear')
	from glob import glob
	import nipype.interfaces.fsl as fsl
	import nipype.interfaces.utility as util

	#--- 2)  Record intial working directory

	INITDIR=os.getcwd();

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

	NIFTIFILE=raw_input('Please drag in the nifti\n file you wish to motion correct\n(ensure there is no blank space at the end)\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 motion correction node

	motion_correct = pe.Node(interface=fsl.MCFLIRT(save_mats=True,save_plots=True,interpolation='spline'),name='MCORRECTED')
	motion_correct.inputs.in_file=NIFTIFILE

	#--- 5) Set up plotting node
	plot_motion = pe.Node(interface=fsl.PlotMotionParams(in_source='fsl'),name='PLOTTED')
	plot_motion.iterables = ('plot_type', ['rotations', 'translations'])

	#--- 5) Utility output node
	outputnode = pe.Node(interface=util.IdentityInterface(fields=['mcorrected_files']),name='outputnode')

	
	#--- 6) Set up workflow

	workflow = pe.Workflow(name='MCORRECTOR')
	workflow.base_dir = NIFTIDIR


	#--- 7) Connect nodes.

	workflow.connect(motion_correct, 'par_file', plot_motion, 'in_file')
	workflow.connect(motion_correct,'out_file', outputnode,'mcorrected_files')


	workflow.write_graph(graph2use='exec')

	#--- 8) Run workflow

	result=workflow.run()


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

	os.chdir(INITDIR)
Beispiel #3
0
    def intrascan_alignment_pipeline(self, **kwargs):

        # inputs=[FilesetSpec('preproc', nifti_gz_format)],
        #   outputs=[FilesetSpec('moco', nifti_gz_format),
        #            FilesetSpec('align_mats', directory_format),
        #            FilesetSpec('moco_par', par_format)],

        pipeline = self.new_pipeline(name='MCFLIRT_pipeline',
                                     desc=("Intra-epi volumes alignment."),
                                     citations=[fsl_cite],
                                     **kwargs)
        mcflirt = pipeline.add('mcflirt',
                               fsl.MCFLIRT(),
                               requirements=[fsl_req.v('5.0.9')])
        mcflirt.inputs.ref_vol = 0
        mcflirt.inputs.save_mats = True
        mcflirt.inputs.save_plots = True
        mcflirt.inputs.output_type = 'NIFTI_GZ'
        mcflirt.inputs.out_file = 'moco.nii.gz'
        pipeline.connect_input('preproc', mcflirt, 'in_file')
        pipeline.connect_output('moco', mcflirt, 'out_file')
        pipeline.connect_output('moco_par', mcflirt, 'par_file')

        merge = pipeline.add('merge', MergeListMotionMat())
        pipeline.connect(mcflirt, 'mat_file', merge, 'file_list')
        pipeline.connect_output('align_mats', merge, 'out_dir')

        return pipeline
Beispiel #4
0
def fsl_realign_opt(name='fsl_realign_opt'):

    inputnode = pe.Node(
        utility.IdentityInterface(
            fields=['fmri','reference','mask']),
        name='inputspec')

    n_flirt_epi2t1 = pe.Node(
        fsl.FLIRT(out_matrix_file='flirt_epi2t1.mat',
                  cost='normmi', # as in fcon1000 preproc, why??
                  searchr_x=[-10,10],searchr_y=[-10,10],searchr_z=[-10,10],
                  dof=6),
        name='flirt_epi2t1')
    
    n_mcflirt_spline = pe.Node(
        fsl.MCFLIRT(interpolation='spline',
                    ref_vol=0,
                    save_plots=True,
                    save_rms=True,
                    save_mats=True,
                    stats_imgs=True,
                    dof=6),
        name='mcflirt_spline')

    w=pe.Workflow(name=name)
    w.connect([
            (inputnode,n_flirt_epi2t1,[('fmri','in_file'),
                                       ('reference','reference')]),
            (inputnode,n_mcflirt_spline,[('fmri','in_file'),]),
            (n_flirt_epi2t1,n_mcflirt_spline,[('out_matrix_file','init')])
            ])
    return w
Beispiel #5
0
    def intrascan_alignment_pipeline(self, **name_maps):

        pipeline = self.new_pipeline(
            name='MCFLIRT_pipeline',
            desc=("Intra-epi volumes alignment."),
            citations=[fsl_cite],
            name_maps=name_maps)

        mcflirt = pipeline.add(
            'mcflirt',
            fsl.MCFLIRT(
                ref_vol=0,
                save_mats=True,
                save_plots=True,
                output_type='NIFTI_GZ',
                out_file='moco.nii.gz'),
            inputs={
                'in_file': ('mag_preproc', nifti_gz_format)},
            outputs={
                'moco': ('out_file', nifti_gz_format),
                'moco_par': ('par_file', par_format)},
            requirements=[fsl_req.v('5.0.9')])

        pipeline.add(
            'merge',
            MergeListMotionMat(),
            inputs={
                'file_list': (mcflirt, 'mat_file')},
            outputs={
                'align_mats': ('out_dir', motion_mats_format)})

        return pipeline
Beispiel #6
0
def hmc_mcflirt(name='fMRI_HMC_mcflirt'):
    """
    An :abbr:`HMC (head motion correction)` for functional scans
    using FSL MCFLIRT
    """

    workflow = pe.Workflow(name=name)

    inputnode = pe.Node(niu.IdentityInterface(
        fields=['in_file', 'fd_radius', 'start_idx', 'stop_idx']), name='inputnode')

    outputnode = pe.Node(niu.IdentityInterface(
        fields=['out_file', 'out_fd']), name='outputnode')

    mcflirt = pe.Node(fsl.MCFLIRT(save_plots=True, save_rms=True, save_mats=True),
                      name='MCFLIRT')
    fdnode = pe.Node(nac.FramewiseDisplacement(normalize=False), name='ComputeFD')

    workflow.connect([
        (inputnode, mcflirt, [('in_file', 'in_file')]),
        (inputnode, fdnode, [('fd_radius', 'radius')]),
        (mcflirt, fdnode, [('par_file', 'in_plots')]),
        (mcflirt, outputnode, [('out_file', 'out_file')]),
        (fdnode, outputnode, [('out_file', 'out_fd')]),
    ])

    return workflow
Beispiel #7
0
    def intrascan_alignment_pipeline(self, **kwargs):

        pipeline = self.create_pipeline(
            name='MCFLIRT_pipeline',
            inputs=[DatasetSpec('preproc', nifti_gz_format)],
            outputs=[
                DatasetSpec('moco', nifti_gz_format),
                DatasetSpec('align_mats', directory_format),
                DatasetSpec('moco_par', par_format)
            ],
            desc=("Intra-epi volumes alignment."),
            version=1,
            citations=[fsl_cite],
            **kwargs)
        mcflirt = pipeline.create_node(fsl.MCFLIRT(),
                                       name='mcflirt',
                                       requirements=[fsl509_req])
        mcflirt.inputs.ref_vol = 0
        mcflirt.inputs.save_mats = True
        mcflirt.inputs.save_plots = True
        mcflirt.inputs.output_type = 'NIFTI_GZ'
        mcflirt.inputs.out_file = 'moco.nii.gz'
        pipeline.connect_input('preproc', mcflirt, 'in_file')
        pipeline.connect_output('moco', mcflirt, 'out_file')
        pipeline.connect_output('moco_par', mcflirt, 'par_file')

        merge = pipeline.create_node(MergeListMotionMat(), name='merge')
        pipeline.connect(mcflirt, 'mat_file', merge, 'file_list')
        pipeline.connect_output('align_mats', merge, 'out_dir')

        return pipeline
Beispiel #8
0
def create_bet_mask_from_dwi(name, do_realignment=True):
    wf = Workflow(name=name)

    inputnode = Node(interface=IdentityInterface(fields=["dwi", "bvec", "bval"]),
                     name="inputnode")

    b0s = Node(DwiextractB0(), "b0s")
    wf.connect(inputnode, "dwi", b0s, "in_file")
    wf.connect(inputnode, "bvec", b0s, "bvec")
    wf.connect(inputnode, "bval", b0s, "bval")

    meanb0 = Node(fsl.ImageMaths(op_string='-Tmean', suffix='_mean'), name="meanb0")
    wf.connect(b0s, "out_file", meanb0, "in_file")

    mcflirt = Node(fsl.MCFLIRT(), "mcflirt")

    bet = Node(fsl.BET(), "bet")
    bet.inputs.frac = 0.3
    bet.inputs.robust = True
    bet.inputs.mask = True

    if do_realignment:
        wf.connect(meanb0, "out_file", mcflirt, "in_file")
        wf.connect(mcflirt, "out_file", bet, "in_file")
    else:
        wf.connect(meanb0, "out_file", bet, "in_file")

    outputnode = Node(interface=IdentityInterface(fields=["mask_file"]), name="outputnode")
    wf.connect(bet, "mask_file", outputnode, "mask_file")

    return wf
Beispiel #9
0
    def _run_interface(self, runtime):
        in_files = self.inputs.in_files
        if not isinstance(in_files, list):
            in_files = [self.inputs.in_files]

        # Generate output average name early
        self._results['out_avg'] = fname_presuffix(self.inputs.in_files[0],
                                                   suffix='_avg',
                                                   newpath=runtime.cwd)

        if self.inputs.to_ras:
            in_files = [reorient(inf, newpath=runtime.cwd) for inf in in_files]

        if len(in_files) == 1:
            filenii = nb.load(in_files[0])
            filedata = filenii.get_data()

            # magnitude files can have an extra dimension empty
            if filedata.ndim == 5:
                sqdata = np.squeeze(filedata)
                if sqdata.ndim == 5:
                    raise RuntimeError('Input image (%s) is 5D' % in_files[0])
                else:
                    in_files = [
                        fname_presuffix(in_files[0],
                                        suffix='_squeezed',
                                        newpath=runtime.cwd)
                    ]
                    nb.Nifti1Image(sqdata, filenii.affine,
                                   filenii.header).to_filename(in_files[0])

            if np.squeeze(nb.load(in_files[0]).get_data()).ndim < 4:
                self._results['out_file'] = in_files[0]
                self._results['out_avg'] = in_files[0]
                # TODO: generate identity out_mats and zero-filled out_movpar
                return runtime
            in_files = in_files[0]
        else:
            magmrg = fsl.Merge(dimension='t', in_files=self.inputs.in_files)
            in_files = magmrg.run().outputs.merged_file
        mcflirt = fsl.MCFLIRT(cost='normcorr',
                              save_mats=True,
                              save_plots=True,
                              ref_vol=0,
                              in_file=in_files)
        mcres = mcflirt.run()
        self._results['out_mats'] = mcres.outputs.mat_file
        self._results['out_movpar'] = mcres.outputs.par_file
        self._results['out_file'] = mcres.outputs.out_file

        hmcnii = nb.load(mcres.outputs.out_file)
        hmcdat = hmcnii.get_data().mean(axis=3)
        if self.inputs.zero_based_avg:
            hmcdat -= hmcdat.min()

        nb.Nifti1Image(hmcdat, hmcnii.affine,
                       hmcnii.header).to_filename(self._results['out_avg'])

        return runtime
def create_moco_pipeline(name='motion_correction'):
    # initiate workflow
    moco = Workflow(name='motion_correction')
    # set fsl output
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')
    # inputnode
    inputnode = Node(util.IdentityInterface(fields=['epi']), name='inputnode')
    # outputnode
    outputnode = Node(util.IdentityInterface(fields=[
        'epi_moco', 'par_moco', 'mat_moco', 'rms_moco', 'epi_mean', 'rotplot',
        'transplot', 'dispplots', 'tsnr_file'
    ]),
                      name='outputnode')
    # mcflirt motion correction to 1st volume
    mcflirt = Node(fsl.MCFLIRT(save_mats=True,
                               save_plots=True,
                               save_rms=True,
                               ref_vol=1,
                               out_file='rest_realigned.nii.gz'),
                   name='mcflirt')
    # plot motion parameters
    rotplotter = Node(fsl.PlotMotionParams(in_source='fsl',
                                           plot_type='rotations',
                                           out_file='rotation_plot.png'),
                      name='rotplotter')
    transplotter = Node(fsl.PlotMotionParams(in_source='fsl',
                                             plot_type='translations',
                                             out_file='translation_plot.png'),
                        name='transplotter')
    dispplotter = MapNode(interface=fsl.PlotMotionParams(
        in_source='fsl',
        plot_type='displacement',
    ),
                          name='dispplotter',
                          iterfield=['in_file'])
    dispplotter.iterables = ('plot_type', ['displacement'])
    # calculate tmean
    tmean = Node(fsl.maths.MeanImage(dimension='T',
                                     out_file='rest_realigned_mean.nii.gz'),
                 name='tmean')
    # calculate tsnr
    tsnr = Node(confounds.TSNR(), name='tsnr')
    # create connections
    moco.connect([(inputnode, mcflirt, [('epi', 'in_file')]),
                  (mcflirt, tmean, [('out_file', 'in_file')]),
                  (mcflirt, rotplotter, [('par_file', 'in_file')]),
                  (mcflirt, transplotter, [('par_file', 'in_file')]),
                  (mcflirt, dispplotter, [('rms_files', 'in_file')]),
                  (tmean, outputnode, [('out_file', 'epi_mean')]),
                  (mcflirt, outputnode, [('out_file', 'epi_moco'),
                                         ('par_file', 'par_moco'),
                                         ('mat_file', 'mat_moco'),
                                         ('rms_files', 'rms_moco')]),
                  (rotplotter, outputnode, [('out_file', 'rotplot')]),
                  (transplotter, outputnode, [('out_file', 'transplot')]),
                  (dispplotter, outputnode, [('out_file', 'dispplots')]),
                  (mcflirt, tsnr, [('out_file', 'in_file')]),
                  (tsnr, outputnode, [('tsnr_file', 'tsnr_file')])])
    return moco
Beispiel #11
0
 def init_params(self, in_file: str, out_file: str):
     mcflt = fsl.MCFLIRT()
     mcflt.inputs.in_file = in_file
     mcflt.inputs.out_file = out_file
     # mcflt.inputs.save_mats = True
     # mcflt.inputs.save_plots = True
     # mcflt.inputs.save_rms = True
     # mcflt.inputs.stats_imgs = True
     return mcflt
Beispiel #12
0
    def _run_interface(self, runtime):
        ref_name = self.inputs.in_file
        ref_nii = nb.load(ref_name)
        n_volumes_to_discard = _get_vols_to_discard(ref_nii)

        self._results["n_volumes_to_discard"] = n_volumes_to_discard

        out_ref_fname = os.path.join(runtime.cwd, "ref_bold.nii.gz")
        if isdefined(self.inputs.sbref_file):
            out_ref_fname = os.path.join(runtime.cwd, "ref_sbref.nii.gz")
            ref_name = self.inputs.sbref_file
            ref_nii = nb.squeeze_image(nb.load(ref_name))

            # If reference is only 1 volume, return it directly
            if len(ref_nii.shape) == 3:
                ref_nii.header.extensions.clear()
                ref_nii.to_filename(out_ref_fname)
                self._results['ref_image'] = out_ref_fname
                return runtime
            else:
                # Reset this variable as it no longer applies
                # and value for the output is stored in self._results
                n_volumes_to_discard = 0

        # Slicing may induce inconsistencies with shape-dependent values in extensions.
        # For now, remove all. If this turns out to be a mistake, we can select extensions
        # that don't break pipeline stages.
        ref_nii.header.extensions.clear()

        if n_volumes_to_discard == 0:
            if ref_nii.shape[-1] > 40:
                ref_name = os.path.join(runtime.cwd, "slice.nii.gz")
                nb.Nifti1Image(ref_nii.dataobj[:, :, :, 20:40], ref_nii.affine,
                               ref_nii.header).to_filename(ref_name)

            if self.inputs.mc_method == "AFNI":
                res = afni.Volreg(in_file=ref_name,
                                  args='-Fourier -twopass',
                                  zpad=4,
                                  outputtype='NIFTI_GZ').run()
            elif self.inputs.mc_method == "FSL":
                res = fsl.MCFLIRT(in_file=ref_name,
                                  ref_vol=0,
                                  interpolation='sinc').run()
            mc_slice_nii = nb.load(res.outputs.out_file)

            median_image_data = np.median(mc_slice_nii.get_fdata(), axis=3)
        else:
            median_image_data = np.median(
                ref_nii.dataobj[:, :, :, :n_volumes_to_discard], axis=3)

        nb.Nifti1Image(median_image_data, ref_nii.affine,
                       ref_nii.header).to_filename(out_ref_fname)

        self._results["ref_image"] = out_ref_fname

        return runtime
Beispiel #13
0
def motion_correct(in_file: Path, out_file: Path):
    """
    Perform motion correction using FSL's MCFLIRT
    Arguments:
        in_file {Path} -- [4D nifti path]
        out_file {Path} -- [4D nifti output path]
    """
    mcflt = fsl.MCFLIRT()
    mcflt.inputs.in_file = in_file
    mcflt.inputs.out_file = out_file
    return mcflt
Beispiel #14
0
def mcflirt(launcher, in_file, out_file):
    mcflt = flsi.MCFLIRT()
    mcflt.inputs.in_file = in_file  # Low Space Resolution, High time resolution 64x64x32x150
    mcflt.inputs.cost = 'mutualinfo'
    mcflt.inputs.out_file = out_file
    mcflt.inputs.save_plots = True
    mcflt.cmdline

    # 'mcflirt -in rest.nii.gz -plot -cost mutualinfo -out rest'
    # >>> res = mcflt.run()  # doctest: +SKIP
    launcher.run(mcflt.cmdline)
Beispiel #15
0
def create_realign_flow(name='realign'):
    """Realign a time series to the middle volume using spline interpolation

    Uses MCFLIRT to realign the time series and ApplyWarp to apply the rigid
    body transformations using spline interpolation (unknown order).

    Example
    -------

    >>> wf = create_realign_flow()
    >>> wf.inputs.inputspec.func = 'f3.nii'
    >>> wf.run() # doctest: +SKIP

    """
    realignflow = pe.Workflow(name=name)
    inputnode = pe.Node(interface=util.IdentityInterface(fields=[
        'func',
    ]),
                        name='inputspec')
    outputnode = pe.Node(interface=util.IdentityInterface(
        fields=['realigned_file', 'rms_files', 'par_file']),
                         name='outputspec')
    start_dropper = pe.Node(util.Function(
        input_names=['in_vol_fn', 'n_frames'],
        output_names=['out_fn'],
        function=remove_first_n_frames),
                            name='start_dropper')
    start_dropper.inputs.n_frames = 5

    realigner = pe.Node(fsl.MCFLIRT(save_mats=True,
                                    stats_imgs=True,
                                    save_rms=True,
                                    save_plots=True),
                        name='realigner')

    splitter = pe.Node(fsl.Split(dimension='t'), name='splitter')
    warper = pe.MapNode(fsl.ApplyWarp(interp='spline'),
                        iterfield=['in_file', 'premat'],
                        name='warper')
    joiner = pe.Node(fsl.Merge(dimension='t'), name='joiner')

    realignflow.connect(inputnode, 'func', start_dropper, 'in_vol_fn')
    realignflow.connect(start_dropper, 'out_fn', realigner, 'in_file')
    realignflow.connect(start_dropper, ('out_fn', select_volume, 'middle'),
                        realigner, 'ref_vol')
    realignflow.connect(realigner, 'out_file', splitter, 'in_file')
    realignflow.connect(realigner, 'mat_file', warper, 'premat')
    realignflow.connect(realigner, 'variance_img', warper, 'ref_file')
    realignflow.connect(splitter, 'out_files', warper, 'in_file')
    realignflow.connect(warper, 'out_file', joiner, 'in_files')
    realignflow.connect(joiner, 'merged_file', outputnode, 'realigned_file')
    realignflow.connect(realigner, 'rms_files', outputnode, 'rms_files')
    realignflow.connect(realigner, 'par_file', outputnode, 'par_file')
    return realignflow
Beispiel #16
0
 def motion(file_to_realign, ref_vol):
     print "running realignment"
     realign = fsl.MCFLIRT(interpolation='spline', ref_file=ref_vol)
     realign.inputs.save_plots = True
     realign.inputs.save_mats = True
     realign.inputs.mean_vol = True
     realign.inputs.in_file = file_to_realign
     realign.inputs.out_file = 'fsl_corr_' +\
                               os.path.split(file_to_realign)[1]
     Realign_res = realign.run()
     out_file = Realign_res.outputs.out_file
     par_file = Realign_res.outputs.par_file
     return out_file, par_file
Beispiel #17
0
def cbf_cl_preprocessing_initialize():
    """ 1) Extracts control/label pairs from raw pCASL data
        2) Motion correction with mcflirt
        3) Control/Label pairwise subtraction
    """

    cl_preproc = pe.Workflow(name='cl_preproc')
    cl_preproc.base_dir = (os.getcwd())

    cl_inputnode = pe.Node(
        interface=util.IdentityInterface(fields=['func', 'm0', 'm0_mask']),
        name='cl_inputnode')

    print(cl_inputnode.inputs)

    cl_datasink = pe.Node(nio.DataSink(), name='cl_sinker')
    cl_datasink.inputs.base_directory = results_dir

    # Extract Control Label Pairs
    cl_fslroi = pe.Node(fsl.ExtractROI(roi_file='cl.nii.gz',
                                       t_min=1,
                                       t_size=-1),
                        name='cl_fslroi')

    # Align Control/Label Pairs to M0 image
    cl_mcflirt = pe.Node(fsl.MCFLIRT(save_mats=True, save_plots=True),
                         name='cl_mcflirt')

    # Mask Control Label Pairs
    cl_mask = pe.Node(fsl.ApplyMask(), name="cl_mask")

    cl_outputnode = pe.Node(interface=util.IdentityInterface(
        fields=['cl', 'cl_brain', 'cl_mcf', 'cl_mcf_par']),
                            name='cl_outputnode')

    cl_preproc.connect([
        (cl_inputnode, cl_fslroi, [('func', 'in_file')]),
        (cl_fslroi, cl_mcflirt, [['roi_file', 'in_file']]),
        (cl_inputnode, cl_mcflirt, [['m0', 'ref_file']]),
        (cl_mcflirt, cl_mask, [('out_file', 'in_file')]),
        (cl_inputnode, cl_mask, [('m0_mask', 'mask_file')]),
        (cl_fslroi, cl_datasink, [['roi_file', 'results.@cl']]),
        (cl_mcflirt, cl_datasink, [['out_file', 'results.@mcfcl']]),
        (cl_mask, cl_datasink, [['out_file', 'results.@cl_mask']]),
        (cl_fslroi, cl_outputnode, [['roi_file', 'cl']]),
        (cl_mcflirt, cl_outputnode, [['par_file', 'cl_mcf_par']]),
        (cl_mcflirt, cl_outputnode, [['out_file', 'cl_mcf']]),
        (cl_mask, cl_outputnode, [['out_file', 'cl_brain']])
    ])

    return cl_preproc
def preporcessFMRI():
    global nii_file, preproc_status

    # skull stripping
    btr = fsl.BET()
    btr.inputs.in_file = nii_file
    btr.inputs.frac = 0.7
    btr.inputs.out_file = nii_file
    btr.cmdline
    res = btr.run()
    preproc_status = 20

    # segmentation and bias correction
    fastr = fsl.FAST()
    fastr.inputs.in_files = nii_file
    fastr.cmdline
    out = fastr.run()
    preproc_status = 40

    # coregistration
    flt = fsl.FLIRT(bins=640, cost_func='mutualinfo')
    flt.inputs.in_file = nii_file
    flt.inputs.reference = nii_file
    flt.inputs.output_type = "NIFTI_GZ"
    preproc_status = 45
    flt.cmdline
    preproc_status = 50
    res = flt.run()
    preproc_status = 60

    # motion correction
    mcflt = fsl.MCFLIRT()
    mcflt.inputs.in_file = nii_file
    mcflt.inputs.cost = 'mutualinfo'
    mcflt.inputs.out_file = nii_file
    mcflt.cmdline
    res = mcflt.run()
    preproc_status = 80

    # smoothing
    sus = fsl.SUSAN()
    sus.inputs.in_file = nii_file
    sus.inputs.out_file = nii_file
    sus.inputs.brightness_threshold = 2000.0
    sus.inputs.fwhm = 8.0
    result = sus.run()
    preproc_status = 100
Beispiel #19
0
    def _run_interface(self, runtime):
        if isdefined(self.inputs.sbref_file):
            self._results['ref_image'] = self.inputs.sbref_file
            return runtime

        in_nii = nb.load(self.inputs.in_file)
        data_slice = in_nii.dataobj[:, :, :, :50]

        # Slicing may induce inconsistencies with shape-dependent values in extensions.
        # For now, remove all. If this turns out to be a mistake, we can select extensions
        # that don't break pipeline stages.
        in_nii.header.extensions.clear()

        n_volumes_to_discard = _get_vols_to_discard(in_nii)

        out_ref_fname = os.path.join(runtime.cwd, "ref_image.nii.gz")

        if n_volumes_to_discard == 0:
            if in_nii.shape[-1] > 40:
                slice_fname = os.path.join(runtime.cwd, "slice.nii.gz")
                nb.Nifti1Image(data_slice[:, :, :, 20:40], in_nii.affine,
                               in_nii.header).to_filename(slice_fname)
            else:
                slice_fname = self.inputs.in_file

            if self.inputs.mc_method == "AFNI":
                res = afni.Volreg(in_file=slice_fname, args='-Fourier -twopass',
                                  zpad=4, outputtype='NIFTI_GZ').run()
            elif self.inputs.mc_method == "FSL":
                res = fsl.MCFLIRT(in_file=slice_fname,
                                  ref_vol=0, interpolation='sinc').run()
            mc_slice_nii = nb.load(res.outputs.out_file)

            median_image_data = np.median(mc_slice_nii.get_data(), axis=3)
        else:
            median_image_data = np.median(
                data_slice[:, :, :, :n_volumes_to_discard], axis=3)

        nb.Nifti1Image(median_image_data, in_nii.affine,
                       in_nii.header).to_filename(out_ref_fname)

        self._results["ref_image"] = out_ref_fname
        self._results["n_volumes_to_discard"] = n_volumes_to_discard

        return runtime
Beispiel #20
0
    def _run_interface(self, runtime):
        in_nii = nb.load(self.inputs.in_file)
        data_slice = in_nii.dataobj[:, :, :, :50]
        global_signal = data_slice.mean(axis=0).mean(axis=0).mean(axis=0)

        n_volumes_to_discard = is_outlier(global_signal)

        out_ref_fname = os.path.abspath("ref_image.nii.gz")

        if n_volumes_to_discard == 0:
            if in_nii.shape[-1] > 40:
                slice = data_slice[:, :, :, 20:40]
                slice_fname = os.path.abspath("slice.nii.gz")
                nb.Nifti1Image(slice, in_nii.affine,
                               in_nii.header).to_filename(slice_fname)
            else:
                slice_fname = self.inputs.in_file

            if self.inputs.mc_method == "AFNI":
                res = afni.Volreg(in_file=slice_fname,
                                  args='-Fourier -twopass',
                                  zpad=4,
                                  outputtype='NIFTI_GZ').run()
            elif self.inputs.mc_method == "FSL":
                res = fsl.MCFLIRT(in_file=slice_fname,
                                  ref_vol=0,
                                  interpolation='sinc').run()
            mc_slice_nii = nb.load(res.outputs.out_file)

            median_image_data = np.median(mc_slice_nii.get_data(), axis=3)
            nb.Nifti1Image(median_image_data, mc_slice_nii.affine,
                           mc_slice_nii.header).to_filename(out_ref_fname)
        else:
            median_image_data = np.median(
                data_slice[:, :, :, :n_volumes_to_discard], axis=3)
            nb.Nifti1Image(median_image_data, in_nii.affine,
                           in_nii.header).to_filename(out_ref_fname)

        self._results = dict()
        self._results["ref_image"] = out_ref_fname
        self._results["n_volumes_to_discard"] = n_volumes_to_discard

        return runtime
Beispiel #21
0
def create_realignment_workflow(name="realignment"):
    """Motion and slice-time correct the timeseries and summarize."""
    inputnode = Node(IdentityInterface(["timeseries"]), "inputs")

    # Get the middle volume of each run for motion correction
    extractref = MapNode(ExtractRealignmentTarget(), "in_file", "extractref")

    # Motion correct to middle volume of each run
    mcflirt = MapNode(
        fsl.MCFLIRT(cost="normcorr",
                    interpolation="spline",
                    save_mats=True,
                    save_rms=True,
                    save_plots=True), ["in_file", "ref_file"], "mcflirt")

    # Generate a report on the motion correction
    mcreport = MapNode(RealignmentReport(),
                       ["target_file", "realign_params", "displace_params"],
                       "mcreport")

    # Define the outputs
    outputnode = Node(
        IdentityInterface(
            ["timeseries", "example_func", "report", "motion_file"]),
        "outputs")

    # Define and connect the sub workflow
    realignment = Workflow(name)

    realignment.connect([
        (inputnode, extractref, [("timeseries", "in_file")]),
        (inputnode, mcflirt, [("timeseries", "in_file")]),
        (extractref, mcflirt, [("out_file", "ref_file")]),
        (extractref, mcreport, [("out_file", "target_file")]),
        (mcflirt, mcreport, [("par_file", "realign_params"),
                             ("rms_files", "displace_params")]),
        (mcflirt, outputnode, [("out_file", "timeseries")]),
        (extractref, outputnode, [("out_file", "example_func")]),
        (mcreport, outputnode, [("realign_report", "report"),
                                ("motion_file", "motion_file")]),
    ])

    return realignment
Beispiel #22
0
def load_and_mc(infile, workdir):
    """
    Perform motion correction on a dataset and load the result in pymvpa
    """
    # perform motion correction using mcflirt implemented by nipype.
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')

    infilename = infile.split('/')[-1]
    mcfile = os.path.join(workdir, infilename.replace('.nii.gz', '_mc.nii.gz'))

    mcflt = fsl.MCFLIRT(in_file=infile, out_file=mcfile)
    mcflt.run()

    # load the preprocessed nifti as pymvpa data set
    dataset = fmri_dataset(mcfile)
    tr = float(dataset.sa['time_coords'][1] - dataset.sa['time_coords'][0])
    nvolumes = len(dataset.samples)

    return dataset, tr, nvolumes
Beispiel #23
0
    def _run_interface(self, runtime):
        if len(self.inputs.in_files) == 1:
            self._results['out_file'] = self.inputs.in_files[0]
            self._results['out_avg'] = self.inputs.in_files[0]
            # TODO: generate identity out_mats and zero-filled out_movpar

            return runtime

        magmrg = fsl.Merge(dimension='t', in_files=self.inputs.in_files)
        mcflirt = fsl.MCFLIRT(cost='normcorr', save_mats=True, save_plots=True,
                              ref_vol=0, in_file=magmrg.run().outputs.merged_file)
        mcres = mcflirt.run()
        self._results['out_mats'] = mcres.outputs.mat_file
        self._results['out_movpar'] = mcres.outputs.par_file
        self._results['out_file'] = mcres.outputs.out_file

        mean = fsl.MeanImage(dimension='T', in_file=mcres.outputs.out_file)
        self._results['out_avg'] = mean.run().outputs.out_file
        return runtime
Beispiel #24
0
def hmc_mcflirt(settings, name='fMRI_HMC_mcflirt'):
    """
    An :abbr:`HMC (head motion correction)` for functional scans
    using FSL MCFLIRT

    .. workflow::

      from mriqc.workflows.functional import hmc_mcflirt
      wf = hmc_mcflirt({'biggest_file_size_gb': 1})

    """

    workflow = pe.Workflow(name=name)

    inputnode = pe.Node(niu.IdentityInterface(
        fields=['in_file', 'fd_radius', 'start_idx', 'stop_idx']),
                        name='inputnode')

    outputnode = pe.Node(niu.IdentityInterface(fields=['out_file', 'out_fd']),
                         name='outputnode')

    gen_ref = pe.Node(nwr.EstimateReferenceImage(mc_method="AFNI"),
                      name="gen_ref")

    mcflirt = pe.Node(fsl.MCFLIRT(save_plots=True, interpolation='sinc'),
                      name='MCFLIRT')
    mcflirt.interface.estimated_memory_gb = settings[
        "biggest_file_size_gb"] * 2.5
    fdnode = pe.Node(nac.FramewiseDisplacement(normalize=False,
                                               parameter_source="FSL"),
                     name='ComputeFD')

    workflow.connect([
        (inputnode, gen_ref, [('in_file', 'in_file')]),
        (gen_ref, mcflirt, [('ref_image', 'ref_file')]),
        (inputnode, mcflirt, [('in_file', 'in_file')]),
        (inputnode, fdnode, [('fd_radius', 'radius')]),
        (mcflirt, fdnode, [('par_file', 'in_file')]),
        (mcflirt, outputnode, [('out_file', 'out_file')]),
        (fdnode, outputnode, [('out_file', 'out_fd')]),
    ])

    return workflow
Beispiel #25
0
def _multiple_pe_hmc(in_files, in_movpar, in_ref=None):
    """
    This function interprets that we are dealing with a
    multiple PE (phase encoding) input if it finds several
    files in in_files.

    If we have several images with various PE directions,
    it will compute the HMC parameters between them using
    an embedded workflow.

    It just forwards the two inputs otherwise.
    """
    import os
    from nipype.interfaces import fsl
    from nipype.interfaces import ants

    if len(in_files) == 1:
        out_file = in_files[0]
        out_movpar = in_movpar
    else:
        if in_ref is None:
            in_ref = 0

        # Head motion correction
        fslmerge = fsl.Merge(dimension='t', in_files=in_files)
        hmc = fsl.MCFLIRT(ref_vol=in_ref, save_mats=True, save_plots=True)
        hmc.inputs.in_file = fslmerge.run().outputs.merged_file
        hmc_res = hmc.run()
        out_file = hmc_res.outputs.out_file
        out_movpar = hmc_res.outputs.par_file

    mean = fsl.MeanImage(
        dimension='T', in_file=out_file)
    inu = ants.N4BiasFieldCorrection(
        dimension=3, input_image=mean.run().outputs.out_file)
    inu_res = inu.run()
    out_ref = inu_res.outputs.output_image
    bet = fsl.BET(
        frac=0.6, mask=True, in_file=out_ref)
    out_mask = bet.run().outputs.mask_file

    return (out_file, out_ref, out_mask, out_movpar)
Beispiel #26
0
def create_between_run_align_workflow(name='between_run_align'):

    between_run_align = pe.Workflow(name=name)

    inputs = pe.Node(
        interface=util.IdentityInterface(fields=['in_files', 'ref_vol']),
        name='inputs')

    select_ref_vol = pe.Node(interface=util.Select(), name='select_ref_vol')
    #select_ref_vol.inputs.index = [ref_vol]

    extract_ref_vol = pe.Node(interface=nmutil.ExtractVolume(),
                              name='extract_ref_vol')

    #extract_ref_vol = pe.Node(interface=fsl.ExtractROI(), name='extract_ref_vol')
    #extract_ref_vol.inputs.t_min = 0
    #extract_ref_vol.inputs.t_size = 1

    motion_correction = pe.MapNode(interface=fsl.MCFLIRT(),
                                   name='motion_correction',
                                   iterfield=['in_file'])

    outputs = pe.Node(interface=util.IdentityInterface(fields=['out_files']),
                      name='outputs')

    between_run_align.connect(inputs, 'in_files', select_ref_vol, 'inlist')
    between_run_align.connect(inputs, ('ref_vol', to_list), select_ref_vol,
                              'index')
    between_run_align.connect(select_ref_vol, 'out', extract_ref_vol,
                              'in_file')
    between_run_align.connect(inputs, ('ref_vol', to_int), extract_ref_vol,
                              'index')
    between_run_align.connect(inputs, 'in_files', motion_correction, 'in_file')
    between_run_align.connect(extract_ref_vol, 'out_file', motion_correction,
                              'ref_file')
    between_run_align.connect(motion_correction, 'out_file', outputs,
                              'out_files')

    return between_run_align
Beispiel #27
0
def simulate_run(infile, workdir, lfnl=3, hfnl=.5):
    """
    Simple simulation of 4D fmri data. Takes a given functional image,
    performs motion correction, computes the mean and adds autocorrelated
    noise to it.

    Parameters
    ----------
    infile:     str
        Path to the 4D functional image in .nifti format
    outfile:    str
        Path and name of the simulated image
    lfnl:       float
        Low frequency noise level. Default = 3 Hz
    hfnl:       float
        High frequency noise level. Default = None.
    """

    # perform motion correction using mcflirt implemented by nipype.
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')
    infilename = infile.split('/')[-1]
    mcfile = os.path.join(workdir, infilename.replace('.nii.gz', '_mc.nii.gz'))
    mcflt = fsl.MCFLIRT(in_file=infile,
                        out_file=mcfile)
    mcflt.run()

    # load the preprocessed nifti as pymvpa data set
    ds = fmri_dataset(mcfile)

    # get TR from sample attributes
    tr = float(ds.sa['time_coords'][1] - ds.sa['time_coords'][0])

    # convert to sampling rate in Hz
    sr = 1.0 / tr
    cutoff = sr / 4

    # produce simulated 4D fmri data
    shambold = autocorrelated_noise(ds, sr, cutoff, lfnl=lfnl, hfnl=hfnl)
    return shambold
Beispiel #28
0
def hmc_mcflirt(name='fMRI_HMC_mcflirt'):
    """
    An :abbr:`HMC (head motion correction)` for functional scans
    using FSL MCFLIRT
    """

    workflow = pe.Workflow(name=name)
    inputnode = pe.Node(niu.IdentityInterface(
        fields=['in_file', 'fd_radius', 'start_idx', 'stop_idx']),
                        name='inputnode')
    outputnode = pe.Node(
        niu.IdentityInterface(fields=['out_file', 'out_movpar']),
        name='outputnode')

    mcflirt = pe.Node(fsl.MCFLIRT(mean_vol=True,
                                  save_plots=True,
                                  save_rms=True,
                                  save_mats=True),
                      name="MCFLIRT")

    workflow.connect([(inputnode, mcflirt, [('in_file', 'in_file')]),
                      (mcflirt, outputnode, [('out_file', 'out_file'),
                                             ('par_file', 'out_movpar')])])
    return workflow
Beispiel #29
0
    def mcflirt(self,folder,in_path):
        """
        This function for motion correction.
        It is dependent on the class name: func.
        folder : read the string, new folder's name.
        in_path : read the list, element: string, directory address of data.

        returns a list, element: string, directory address of new data.
        For complete details, see the fsl.MCFLIRT() documentation.
        <https://nipype.readthedocs.io/en/latest/interfaces.html>
        """ 
        print('#################_Data_motion_correction_started_###########')
        preprocessing = time.time()

        # Check and if not make the directory
        if not os.path.isdir(folder):
            func.newfolder(folder)

        # Proceed the motion correction and save the data
        output_list = []        
        for i in range(len(in_path)):
            print(in_path[i],"motion correction started")
            file = in_path[i].split('/')
            output = folder+'/'+file[1]
            output_list.append(output)
            
            mcflt = fsl.MCFLIRT()
            mcflt.inputs.in_file = in_path[i]
            mcflt.inputs.cost = 'mutualinfo'
            mcflt.inputs.out_file = output
            mcflt.cmdline
            mcflt.run()
            print(output,"motion correction completed")
        print("computation_time :","%.2fs" %(time.time() - preprocessing))
        print('#################_Data_motion_correction_completed_#########')
        return output_list
Beispiel #30
0
def init_bold_hmc_wf(mem_gb, omp_nthreads, name='bold_hmc_wf'):
    """
    This workflow estimates the motion parameters to perform
    :abbr:`HMC (head motion correction)` over the input
    :abbr:`BOLD (blood-oxygen-level dependent)` image.

    .. workflow::
        :graph2use: orig
        :simple_form: yes

        from fmriprep.workflows.bold import init_bold_hmc_wf
        wf = init_bold_hmc_wf(
            mem_gb=3,
            omp_nthreads=1)

    **Parameters**

        mem_gb : float
            Size of BOLD file in GB
        omp_nthreads : int
            Maximum number of threads an individual process may use
        name : str
            Name of workflow (default: ``bold_hmc_wf``)

    **Inputs**

        bold_file
            BOLD series NIfTI file
        raw_ref_image
            Reference image to which BOLD series is motion corrected

    **Outputs**

        xforms
            ITKTransform file aligning each volume to ``ref_image``
        movpar_file
            MCFLIRT motion parameters, normalized to SPM format (X, Y, Z, Rx, Ry, Rz)

    """
    workflow = pe.Workflow(name=name)
    inputnode = pe.Node(
        niu.IdentityInterface(fields=['bold_file', 'raw_ref_image']),
        name='inputnode')
    outputnode = pe.Node(
        niu.IdentityInterface(fields=['xforms', 'movpar_file']),
        name='outputnode')

    # Head motion correction (hmc)
    mcflirt = pe.Node(fsl.MCFLIRT(save_mats=True, save_plots=True),
                      name='mcflirt',
                      mem_gb=mem_gb * 3)

    fsl2itk = pe.Node(MCFLIRT2ITK(),
                      name='fsl2itk',
                      mem_gb=0.05,
                      n_procs=omp_nthreads)

    normalize_motion = pe.Node(NormalizeMotionParams(format='FSL'),
                               name="normalize_motion",
                               mem_gb=DEFAULT_MEMORY_MIN_GB)

    workflow.connect([
        (inputnode, mcflirt, [('raw_ref_image', 'ref_file'),
                              ('bold_file', 'in_file')]),
        (inputnode, fsl2itk, [('raw_ref_image', 'in_source'),
                              ('raw_ref_image', 'in_reference')]),
        (mcflirt, fsl2itk, [('mat_file', 'in_files')]),
        (mcflirt, normalize_motion, [('par_file', 'in_file')]),
        (fsl2itk, outputnode, [('out_file', 'xforms')]),
        (normalize_motion, outputnode, [('out_file', 'movpar_file')]),
    ])

    return workflow