예제 #1
0
def setup_flirt(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = str(tmpdir)
    _, infile = tempfile.mkstemp(suffix=ext, dir=tmp_dir)
    _, reffile = tempfile.mkstemp(suffix=ext, dir=tmp_dir)

    return (tmp_dir, infile, reffile)
예제 #2
0
def create_files_in_directory(request):
    func_prev_type = set_output_type(request.param)

    testdir = os.path.realpath(mkdtemp())
    origdir = os.getcwd()
    os.chdir(testdir)

    filelist = ['a.nii', 'b.nii']
    for f in filelist:
        hdr = nb.Nifti1Header()
        shape = (3, 3, 3, 4)
        hdr.set_data_shape(shape)
        img = np.random.random(shape)
        nb.save(nb.Nifti1Image(img, np.eye(4), hdr),
                os.path.join(testdir, f))

    out_ext = Info.output_type_to_ext(Info.output_type())

    def fin():
        if os.path.exists(testdir):
            rmtree(testdir)
        set_output_type(func_prev_type)
        os.chdir(origdir)

    request.addfinalizer(fin)
    return (filelist, testdir, out_ext)
예제 #3
0
def setup_infile():
    global tmp_infile, tmp_dir
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = tempfile.mkdtemp()
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    file(tmp_infile, 'w')
    return tmp_infile, tmp_dir
예제 #4
0
def setup_infile(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = str(tmpdir)
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    open(tmp_infile, 'w')

    return (tmp_infile, tmp_dir)
예제 #5
0
def setup_infile():
    global tmp_infile, tmp_dir
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = tempfile.mkdtemp()
    tmp_infile = os.path.join(tmp_dir, "foo" + ext)
    open(tmp_infile, "w")
    return tmp_infile, tmp_dir
예제 #6
0
def setup_flirt(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = str(tmpdir)
    _, infile = tempfile.mkstemp(suffix=ext, dir=tmp_dir)
    _, reffile = tempfile.mkstemp(suffix=ext, dir=tmp_dir)

    return (tmp_dir, infile, reffile)
예제 #7
0
def setup_flirt(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    infile = tmpdir.join("infile" + ext)
    infile.open("w")
    reffile = tmpdir.join("reffile" + ext)
    reffile.open("w")
    return (tmpdir, infile.strpath, reffile.strpath)
예제 #8
0
def setup_infile(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = str(tmpdir)
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    open(tmp_infile, 'w')

    return (tmp_infile, tmp_dir)
예제 #9
0
def setup_flirt(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    infile = tmpdir.join("infile"+ext)
    infile.open("w")
    reffile = tmpdir.join("reffile"+ext)
    reffile.open("w")
    return (tmpdir, infile.strpath, reffile.strpath)
예제 #10
0
def setup_infile():
    global tmp_infile, tmp_dir
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = tempfile.mkdtemp()
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    open(tmp_infile, 'w')
    return tmp_infile, tmp_dir
예제 #11
0
def setup_infile():
    global tmp_infile, tmp_dir, cwd
    cwd = os.getcwd()
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = tempfile.mkdtemp()
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    file(tmp_infile, 'w')
    os.chdir(tmp_dir)
    return tmp_infile, tmp_dir
예제 #12
0
def setup_infile():
    global tmp_infile, tmp_dir, cwd
    cwd = os.getcwd()
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = tempfile.mkdtemp()
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    open(tmp_infile, 'w')
    os.chdir(tmp_dir)
    return tmp_infile, tmp_dir
예제 #13
0
def setup_infile(request):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = tempfile.mkdtemp()
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    open(tmp_infile, 'w')

    def fin():
        shutil.rmtree(tmp_dir)

    request.addfinalizer(fin)
    return (tmp_infile, tmp_dir)
예제 #14
0
def setup_flirt(request):
    ext = Info.output_type_to_ext(Info.output_type())
    tmpdir = tempfile.mkdtemp()
    _, infile = tempfile.mkstemp(suffix=ext, dir=tmpdir)
    _, reffile = tempfile.mkstemp(suffix=ext, dir=tmpdir)

    def teardown_flirt():
        shutil.rmtree(tmpdir)

    request.addfinalizer(teardown_flirt)
    return (tmpdir, infile, reffile)
예제 #15
0
def setup_flirt(request):
    ext = Info.output_type_to_ext(Info.output_type())
    tmpdir = tempfile.mkdtemp()
    _, infile = tempfile.mkstemp(suffix=ext, dir=tmpdir)
    _, reffile = tempfile.mkstemp(suffix=ext, dir=tmpdir)

    def teardown_flirt():
        shutil.rmtree(tmpdir)

    request.addfinalizer(teardown_flirt)
    return (tmpdir, infile, reffile)
예제 #16
0
def setup_infile(request):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_dir = tempfile.mkdtemp()
    tmp_infile = os.path.join(tmp_dir, 'foo' + ext)
    open(tmp_infile, 'w')

    def fin():
        shutil.rmtree(tmp_dir)

    request.addfinalizer(fin)
    return (tmp_infile, tmp_dir)
예제 #17
0
def create_files_in_directory_plus_output_type(request, tmpdir):
    func_prev_type = set_output_type(request.param)
    origdir = tmpdir.chdir()
    filelist = ['a.nii', 'b.nii']
    nifti_image_files(tmpdir.strpath, filelist, shape=(3,3,3,4))

    out_ext = Info.output_type_to_ext(Info.output_type())

    def fin():
        set_output_type(func_prev_type)
        origdir.chdir()

    request.addfinalizer(fin)
    return (filelist, tmpdir.strpath, out_ext)
예제 #18
0
def create_files_in_directory_plus_output_type(request, tmpdir):
    func_prev_type = set_output_type(request.param)
    origdir = tmpdir.chdir()
    filelist = ['a.nii', 'b.nii']
    nifti_image_files(tmpdir.strpath, filelist, shape=(3, 3, 3, 4))

    out_ext = Info.output_type_to_ext(Info.output_type())

    def fin():
        set_output_type(func_prev_type)
        origdir.chdir()

    request.addfinalizer(fin)
    return (filelist, tmpdir.strpath, out_ext)
예제 #19
0
파일: test_maths.py 프로젝트: amoliu/nipype
def create_files_in_directory():
    testdir = os.path.realpath(mkdtemp())
    origdir = os.getcwd()
    os.chdir(testdir)

    filelist = ['a.nii', 'b.nii']
    for f in filelist:
        hdr = nb.Nifti1Header()
        shape = (3, 3, 3, 4)
        hdr.set_data_shape(shape)
        img = np.random.random(shape)
        nb.save(nb.Nifti1Image(img, np.eye(4), hdr), os.path.join(testdir, f))

    out_ext = Info.output_type_to_ext(Info.output_type())
    return filelist, testdir, origdir, out_ext
예제 #20
0
def run_feat(bold_file, bold_folder, brainmask_file, feat_gen):
    from nipype.interfaces.fsl import ImageStats, FEAT, Info
    # from bm_functions import gen_default_feat_config
    from numpy import shape
    from textwrap import dedent

    fslFilename = bold_folder + 'feat.fsf'

    # Get the number of voxels in the 4D file
    statComp = ImageStats()
    statComp.inputs.in_file = bold_file
    statComp.inputs.op_string = '-v'

    numVox = int(statComp.run().outputs.out_stat[0])

    # Get the number of raw volumes
    statComp.inputs.split_4d = True

    numVol = shape(statComp.run().outputs.out_stat)[0]

    # Generate the file
    standard_T1_brain = Info.standard_image('MNI152_T1_2mm_brain')
    theString = feat_gen(bold_folder, bold_file, brainmask_file,
                         standard_T1_brain, numVox, numVol)
    with open(fslFilename, 'w') as out_file:
        out_file.write(dedent(theString))
    out_file.close()

    # Run feat using the previously manipulated config
    runFeat = FEAT(fsf_file=fslFilename)
    # Run and pass back the foldername
    return runFeat.run().outputs.feat_dir
예제 #21
0
파일: rs.py 프로젝트: NBCLab/niconn
def rs_secondlevel(copes, varcopes, dofs, output_dir, work_dir):

    from nipype.workflows.fmri.fsl.estimate import create_fixed_effects_flow
    from nipype.interfaces.fsl import Info

    level2workflow = pe.Workflow(name="level2workflow")
    level2workflow.base_dir = work_dir

    fixedfx = create_fixed_effects_flow()
    fixedfx.inputs.inputspec.copes = copes
    fixedfx.inputs.inputspec.varcopes = varcopes
    fixedfx.inputs.inputspec.dof_files = dofs
    fixedfx.inputs.l2model.num_copes = len(dofs)
    fixedfx.inputs.flameo.mask_file = Info.standard_image(
        'MNI152_T1_2mm_brain_mask.nii.gz')

    datasink = pe.Node(nio.DataSink(), name='sinker')
    datasink.inputs.base_directory = work_dir

    level2workflow.connect([(fixedfx, datasink,
                             [('outputspec.copes', 'copes'),
                              ('outputspec.varcopes', 'varcopes'),
                              ('outputspec.zstats', 'zstats'),
                              ('gendofvolume.dof_volume', 'dofs')])])

    level2workflow.run()

    #copy data to directory
    shutil.rmtree(op.join(work_dir, 'level2workflow'))
    files_to_copy = glob(op.join(work_dir, '*', '_flameo0', '*'))
    for tmp_fn in files_to_copy:
        shutil.copy(tmp_fn, output_dir)
    shutil.copy(op.join(work_dir, 'dofs', 'dof_file.nii.gz'), output_dir)
    shutil.rmtree(work_dir)
예제 #22
0
def run_feat(bold_file, bold_folder, brainmask_file, feat_gen):
    from nipype.interfaces.fsl import ImageStats, FEAT, Info
    # from bm_functions import gen_default_feat_config
    from numpy import shape
    from textwrap import dedent

    fslFilename = bold_folder + 'feat.fsf'

    # Get the number of voxels in the 4D file
    statComp = ImageStats()
    statComp.inputs.in_file = bold_file
    statComp.inputs.op_string = '-v'

    numVox = int(statComp.run().outputs.out_stat[0])

    # Get the number of raw volumes
    statComp.inputs.split_4d = True

    numVol = shape(statComp.run().outputs.out_stat)[0]

    # Generate the file
    standard_T1_brain = Info.standard_image('MNI152_T1_2mm_brain')
    theString = feat_gen(bold_folder, bold_file, brainmask_file, standard_T1_brain, numVox, numVol)
    with open(fslFilename,'w') as out_file:
        out_file.write(dedent(theString))
    out_file.close()   

    # Run feat using the previously manipulated config
    runFeat = FEAT(fsf_file = fslFilename)
    # Run and pass back the foldername
    return runFeat.run().outputs.feat_dir
예제 #23
0
파일: test_maths.py 프로젝트: amoliu/nipype
def create_files_in_directory():
    testdir = os.path.realpath(mkdtemp())
    origdir = os.getcwd()
    os.chdir(testdir)

    filelist = ['a.nii', 'b.nii']
    for f in filelist:
        hdr = nb.Nifti1Header()
        shape = (3, 3, 3, 4)
        hdr.set_data_shape(shape)
        img = np.random.random(shape)
        nb.save(nb.Nifti1Image(img, np.eye(4), hdr),
                os.path.join(testdir, f))

    out_ext = Info.output_type_to_ext(Info.output_type())
    return filelist, testdir, origdir, out_ext
예제 #24
0
파일: fixtures.py 프로젝트: shoshber/nipype
def set_output_type(fsl_output_type):
    prev_output_type = os.environ.get('FSLOUTPUTTYPE', None)

    if fsl_output_type is not None:
        os.environ['FSLOUTPUTTYPE'] = fsl_output_type
    elif 'FSLOUTPUTTYPE' in os.environ:
        del os.environ['FSLOUTPUTTYPE']

    FSLCommand.set_default_output_type(Info.output_type())
    return prev_output_type
예제 #25
0
def set_output_type(fsl_output_type):
    prev_output_type = os.environ.get('FSLOUTPUTTYPE', None)

    if fsl_output_type is not None:
        os.environ['FSLOUTPUTTYPE'] = fsl_output_type
    elif 'FSLOUTPUTTYPE' in os.environ:
        del os.environ['FSLOUTPUTTYPE']

    FSLCommand.set_default_output_type(Info.output_type())
    return prev_output_type
예제 #26
0
def test_tbss_skeleton(create_files_in_directory):
    skeletor = fsl.TractSkeleton()

    files, newdir = create_files_in_directory

    # Test the underlying command
    assert skeletor.cmd == "tbss_skeleton"

    # It shouldn't run yet
    with pytest.raises(ValueError):
        skeletor.run()

    # Test the most basic way to use it
    skeletor.inputs.in_file = files[0]

    # First by implicit argument
    skeletor.inputs.skeleton_file = True
    assert skeletor.cmdline == "tbss_skeleton -i a.nii -o %s" % os.path.join(
        newdir, "a_skeleton.nii")

    # Now with a specific name
    skeletor.inputs.skeleton_file = "old_boney.nii"
    assert skeletor.cmdline == "tbss_skeleton -i a.nii -o old_boney.nii"

    # Now test the more complicated usage
    bones = fsl.TractSkeleton(in_file="a.nii", project_data=True)

    # This should error
    with pytest.raises(ValueError):
        bones.run()

    # But we can set what we need
    bones.inputs.threshold = 0.2
    bones.inputs.distance_map = "b.nii"
    bones.inputs.data_file = "b.nii"  # Even though that's silly

    # Now we get a command line
    assert bones.cmdline == "tbss_skeleton -i a.nii -p 0.200 b.nii %s b.nii %s" % (
        Info.standard_image("LowerCingulum_1mm.nii.gz"),
        os.path.join(newdir, "b_skeletonised.nii"),
    )

    # Can we specify a mask?
    bones.inputs.use_cingulum_mask = Undefined
    bones.inputs.search_mask_file = "a.nii"
    assert (bones.cmdline ==
            "tbss_skeleton -i a.nii -p 0.200 b.nii a.nii b.nii %s" %
            os.path.join(newdir, "b_skeletonised.nii"))
예제 #27
0
def test_tbss_skeleton():
    skeletor = fsl.TractSkeleton()

    files, newdir, olddir = create_files_in_directory()

    # Test the underlying command
    yield assert_equal, skeletor.cmd, "tbss_skeleton"

    # It shouldn't run yet
    yield assert_raises, ValueError, skeletor.run

    # Test the most basic way to use it
    skeletor.inputs.in_file = files[0]

    # First by implicit argument
    skeletor.inputs.skeleton_file = True
    yield assert_equal, skeletor.cmdline, \
    "tbss_skeleton -i a.nii -o %s"%os.path.join(newdir, "a_skeleton.nii")

    # Now with a specific name
    skeletor.inputs.skeleton_file = "old_boney.nii"
    yield assert_equal, skeletor.cmdline, "tbss_skeleton -i a.nii -o old_boney.nii"

    # Now test the more complicated usage
    bones = fsl.TractSkeleton(in_file="a.nii", project_data=True)

    # This should error
    yield assert_raises, ValueError, bones.run

    # But we can set what we need
    bones.inputs.threshold = 0.2
    bones.inputs.distance_map = "b.nii"
    bones.inputs.data_file = "b.nii" # Even though that's silly

    # Now we get a command line
    yield assert_equal, bones.cmdline, \
    "tbss_skeleton -i a.nii -p 0.200 b.nii %s b.nii %s"%(Info.standard_image("LowerCingulum_1mm.nii.gz"),
                                                         os.path.join(newdir, "b_skeletonised.nii"))

    # Can we specify a mask?
    bones.inputs.use_cingulum_mask = Undefined
    bones.inputs.search_mask_file = "a.nii"
    yield assert_equal, bones.cmdline, \
    "tbss_skeleton -i a.nii -p 0.200 b.nii a.nii b.nii %s"%os.path.join(newdir, "b_skeletonised.nii")

    # Looks good; clean up
    clean_directory(newdir, olddir)
예제 #28
0
def test_registration_workflow(use_FS, use_AFNI_ss):

    analysis_info = {
        'do_fnirt': False,
        'use_FS': use_FS,
        'do_FAST': False,
        'use_AFNI_ss': use_AFNI_ss
    }

    wf = create_registration_workflow(analysis_info=analysis_info)
    wf.inputs.inputspec.EPI_space_file = op.join(
        test_data_path, 'func', 'sub-0020_task-harriri_meanbold.nii.gz')
    wf.inputs.inputspec.output_directory = '/tmp/spynoza'
    wf.inputs.inputspec.T1_file = op.join(test_data_path, 'anat',
                                          'sub-0020_T1w.nii.gz')
    wf.inputs.inputspec.sub_id = 'sub-0020'
    wf.inputs.inputspec.standard_file = Info.standard_image(
        'MNI152_T1_2mm_brain.nii.gz')
    wf.inputs.inputspec.freesurfer_subject_ID = 'sub-0020'
    wf.inputs.inputspec.freesurfer_subject_dir = op.join(
        op.dirname(test_data_path), 'fs')
    wf.base_dir = '/tmp/spynoza/workingdir'

    # This is to speed up the analysis
    if not analysis_info['use_FS']:
        wf = set_parameters_in_nodes(wf,
                                     flirt_e2t={
                                         'interp': 'trilinear',
                                         'cost_func': 'corratio'
                                     },
                                     flirt_t2s={'interp': 'trilinear'})

    wf.run()

    reg_files = [
        'example_func.nii.gz', 'example_func2highres.mat',
        'example_func2standard.mat', 'highres.nii.gz',
        'highres2example_func.mat', 'highres2standard.mat', 'standard.nii.gz',
        'standard2example_func.mat', 'standard2highres.mat'
    ]

    datasink = wf.inputs.inputspec.output_directory = '/tmp/spynoza'
    for f in reg_files:
        f_path = op.join(datasink, 'sub-0020', 'reg', f)
        assert (op.isfile(f_path))
예제 #29
0
def RENDERPIPE():
    #--- 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

    #--- 2)  Determine template location and get inputs
    template = Info.standard_image('MNI152_T1_2mm_brain.nii.gz')
    in_file = raw_input('Please drag in the stats image')
    in_matrix_file = raw_input(
        'Please drag in the combined registration matrix\n')
    transforms = raw_input(
        'Please drag in the ANTs normalisation composite transform\n')
    thresh = float(raw_input('Please enter the threshold \n'))

    #--- 3)  Make input node
    inputnode = pe.Node(interface=util.IdentityInterface(fields=['thresh']),
                        name='inputnode')
    inputnode.inputs.thresh = thresh

    #--- 4)  Node for registering to MNI
    registerF2S = pe.Node(interface=fsl.ApplyXFM(), name='RENDEREDREG')
    registerF2S.inputs.reference = template
    registerF2S.inputs.in_file = in_file.strip('\'"')
    registerF2S.inputs.in_matrix_file = in_matrix_file.strip('\'"')

    NIFTIDIR = os.path.split(registerF2S.inputs.in_file)[0]

    #--- 5)  Node for ANTs warping to MNI
    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='RENDEREDNORM')
    apply2mean.inputs.transforms = transforms.strip('\'"')

    #--- 6)  Outputnode for warped volume
    outputnode = pe.Node(interface=util.IdentityInterface(fields=['warped']),
                         name='outputnode')

    #--- 7)  Function for plotting over MNI
    def plot(in_file, threshold):
        from nilearn import image
        from nilearn import plotting
        import matplotlib
        niftifiledim = len(image.load_img(in_file).shape)
        display = plotting.plot_stat_map(stat_map_img=in_file,
                                         black_bg=bool(1),
                                         display_mode='z',
                                         cut_coords=10,
                                         threshold=float(threshold))
        matplotlib.pyplot.show()
        return niftifiledim

    plotter = pe.MapNode(Function(input_names=['in_file', 'threshold'],
                                  output_names='display',
                                  function=plot),
                         iterfield=['in_file'],
                         name='PLOTTER')

    #--- 8)  Define workflow
    workflow = pe.Workflow(name='RENDERPIPE')
    workflow.base_dir = NIFTIDIR

    #--- 9)  Connect nodes
    workflow.connect(registerF2S, 'out_file', apply2mean, 'input_image')
    workflow.connect(apply2mean, 'output_image', outputnode, 'warped')
    workflow.connect(outputnode, 'warped', plotter, 'in_file')
    workflow.connect(inputnode, 'thresh', plotter, 'threshold')

    #--- 10)  Run workflow
    workflow.write_graph(graph2use='exec')
    workflow.run()
예제 #30
0
def fsl_name(obj, fname):
    """Create valid fsl name, including file extension for output type.
    """
    ext = Info.output_type_to_ext(obj.inputs.output_type)
    return fname + ext
FSCommand.set_default_subjects_dir(fs_dir)


###
# Specify variables
experiment_dir = '~/nipype_tutorial'          # location of experiment folder
input_dir_1st = 'output_fMRI_example_1st'     # name of 1st-level output folder
output_dir = 'output_fMRI_example_norm_ants'  # name of norm output folder
working_dir = 'workingdir_fMRI_example_norm_ants'  # name of norm working directory
subject_list = ['sub001', 'sub002', 'sub003',
                'sub004', 'sub005', 'sub006',
                'sub007', 'sub008', 'sub009',
                'sub010']                     # list of subject identifiers

# location of template file
template = Info.standard_image('MNI152_T1_1mm_brain.nii.gz')


###
# Specify Normalization Nodes

# Registration - computes registration between subject's structural and MNI template.
antsreg = Node(Registration(args='--float',
                            collapse_output_transforms=True,
                            fixed_image=template,
                            initial_moving_transform_com=True,
                            num_threads=1,
                            output_inverse_warped_image=True,
                            output_warped_image=True,
                            sigma_units=['vox']*3,
                            transforms=['Rigid', 'Affine', 'SyN'],
예제 #32
0
def fsl_name(obj, fname):
    """Create valid fsl name, including file extension for output type.
    """
    ext = Info.output_type_to_ext(obj.inputs.output_type)
    return fname + ext
"""Droped from pipeline. Replaced by ApplyTransforms"""
from nipype.interfaces.ants import ComposeMultiTransform
from nipype.interfaces.fsl import Info

compose_transf = ComposeMultiTransform()
compose_transf.inputs.dimension = 3
compose_transf.inputs.reference_image = Info.standard_image('MNI152_T1_1mm.nii.gz')

compose_transf.inputs.transforms = ['transform1InverseWarp.nii.gz', 'transform1Warp.nii.gz']

compose_transf.output_image = 'singletransform.nii.gz'
`
예제 #34
0
from nipype.pipeline.engine import Workflow, Node, MapNode
from nipype.interfaces.fsl import Info

# FreeSurfer - Specify the location of the freesurfer folder
fs_dir = '/data/adamt/Apps/fs6beta'
FSCommand.set_default_subjects_dir(fs_dir)

# Specify variables
experiment_dir = '/data/Hippo_hr/cpb/'          # location of experiment folder
input_dir_1st = 'output_ANTS_test_1st_lvl'     # name of 1st-level output folder
output_dir = 'output_ANTS_test_norm'  # name of norm output folder
working_dir = '/home/zhoud4/Hippo_hr/cpb/ants1/lhipp3_batch/'  # name of norm working directory
subject_list = ['d701', 'd702', 'd703']                     # list of subject identifiers

# location of template file
template = Info.standard_image('.nii.gz')

# Registration (good) - computes registration between subject's structural and MNI template.
antsreg = Node(Registration(args='--float',
                            collapse_output_transforms=True,
                            fixed_image=template,
                            initial_moving_transform_com=True,
                            num_threads=1,
                            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-06],
예제 #35
0
def setup_infile(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_infile = tmpdir.join('foo' + ext)
    tmp_infile.open("w")
    return (tmp_infile.strpath, tmpdir.strpath)
예제 #36
0
파일: nodes.py 프로젝트: NILAB-UvA/nitools
def custom_level1design_feat(func_file,
                             highres_file=None,
                             session_info=None,
                             output_dirname='firstlevel',
                             contrasts='single-trial',
                             smoothing=0,
                             temp_deriv=False,
                             registration='full',
                             highpass=100,
                             slicetiming=None,
                             motion_correction=None,
                             bet=True,
                             prewhitening=True,
                             motion_regression=None,
                             thresholding='uncorrected',
                             p_val=0.05,
                             z_val=2.3,
                             mask=None,
                             hrf='doublegamma',
                             open_feat_html=False):
    """ Custom implementation of a FSL create-level1-design function.
    This function (which can be wrapped in a custom Nipype Function node) creates an FSL design.fsf
    file. This function is similar to the Nipype Level1Design node (interfaces.fsl.model) but allows
    for way more options to be set.
    Parameters
    ----------
    func_file : str
        Path to functional file (4D) with timeseries data
    highres_file : str
        Path to file corresponding to high-resolution anatomical scan (should already be skull-stripped!).
        Only necessary if doing functional-highres-standard registration (i.e. registration = 'full');
        otherwise, set to None.
    session_info : Nipype Bunch-object
        Bunch-object (dict-like) with information about stimulus-related and nuisance regressors.
    output_dirname : str
        Name of output directory (.feat will be appended to it).
    contrasts : str, tuple, or list
        (List of) tuple(s) with defined contrasts. Should be formatted using the Nipype syntax:
        `(name_of_contrast, 'T', [cond_name_1, cond_name_2], [weight_1, weight_2])` for a t-contrast,
        or `(name_of_f_test, 'F', [contrast_1, contrast_2])` for F-tests.
    smoothing : float or int
        Smoothing kernel in FWHM (mm)
    temp_deriv : bool
        Whether to include temporal derivates of real EVs.
    registration : str
        Registration-scheme to apply. Currently supports three types: 'full', which registers
        the functional file to the high-res anatomical (using FLIRT BBR) and subsequent linear-
        non-linear registration to the MNI152 (2mm) standard brain (using FNIRT); another option
        is 'fmriprep', which only calculates a 3-parameter (translation only) transformation because
        output from the fmriprep-preprocessing-pipeline is already registered to MNI but is still in
        native dimensions (i.e. EPI-space). Last option is 'none', which doesn't do any registration.
    highpass : int
        Length (in seconds) of FSL highpass filter to apply.
    slicetiming : str
        Whether to apply slice-time correction; options are 'up' (ascending), 'down' (descending),
        or 'no' (no slicetiming correction).
    motion_correction : bool
        Whether to apply motion-correction (MCFLIRT).
    bet : bool
        Whether to BET (skullstrip) the functional file.
    prewhitening : bool
        Whether to do prewhitening.
    motion_regression : str
        Whether to do motion-regression. Options: 'no' (no motion regression), 'yes' (standard 6 parameters motion
        regression), 'ext' (extended 24 parameter motion regression).
    thresholding : str
        What type of thresholding to apply. Options: 'none', 'uncorrected', 'voxel', 'cluster'.
    p_val : float
        What p-value to use in thresholding.
    z_val : float
        What minimum z-value to use in cluster-correction
    mask : str
        File to use in pre-thresholding masking. Setting to None means no masking.
    hrf : str
        What HRF-model to use. Default is 'doublegamma', but other options are: 'gamma',
        'gammabasisfunctions', 'gaussian'.
    open_feat_html : bool
        Whether to automatically open HTML-progress report.
    Returns
    -------
    design_file : str
        The path to the created design.fsf file
    confound_txt_file : str
        Path to the created confounds.txt file
    ev_files : list
        List with paths to EV-text-files.
    """
    import os.path as op
    import nibabel as nib
    from nipype.interfaces.fsl import Info
    import numpy as np
    import spynoza

    if isinstance(session_info, list):

        if len(session_info) == 1:
            session_info = session_info[0]

    if registration == 'full' and highres_file is None:
        raise ValueError(
            "If you want to do a full registration, you need to specify a highres file!"
        )

    if motion_correction in (0, False,
                             'yes') and motion_regression in ('yes', True, 1,
                                                              'ext', 2):
        raise ValueError(
            "If you want to do motion-regression, make sure to turn on motion-correction!"
        )

    if hrf == 'gammabasisfunctions' and temp_deriv:
        print(
            "Cannot add temporal deriv when hrf = gammabasisfunctions; setting temp-deriv to False"
        )
        temp_deriv = False

    n_orig_evs = len(session_info.conditions)
    if contrasts == 'single-trial':

        cons = []
        for i in range(n_orig_evs):
            con_values = np.zeros(len(session_info.conditions))
            con_values[i] = 1
            this_con = (session_info.conditions[i], 'T',
                        session_info.conditions, con_values)
            cons.append(this_con)
        f_con = ('f_all', 'F', cons)
        cons.append(f_con)
        contrasts = cons
    elif isinstance(contrasts, list):  # assume nipype style contrasts
        for i, con in enumerate(contrasts):
            weights = np.zeros(n_orig_evs)
            this_i = 0
            for ii, ev in enumerate(session_info.conditions):
                for iii, this_entry in enumerate(con[2]):
                    if ev == this_entry:
                        weights[ii] = con[3][iii]
            contrasts[i] = (con[0], con[1], con[2], weights.tolist())

    t_contrasts = [con for con in contrasts if con[1] == 'T']
    f_contrasts = [con for con in contrasts if con[1] == 'F']
    n_con = len(t_contrasts)
    n_ftest = len(f_contrasts)
    n_real_evs = n_orig_evs

    if temp_deriv:
        n_real_evs *= 2
    elif hrf == 'gammabasisfunctions':
        n_real_evs *= 3  # ToDo: allow more than 3 basis funcs

    if temp_deriv:
        con_mode_old = 'real'
        con_mode = 'real'
    else:
        con_mode_old = 'orig'
        con_mode = 'orig'

    arg_dict = dict(
        temp_deriv={
            True: 1,
            1: 1,
            False: 0,
            0: 0
        },
        slicetiming={
            'no': 0,
            0: 0,
            None: 0,
            'up': 1,
            1: 1,
            'down': 2,
            2: 2
        },
        motion_correction={
            True: 1,
            1: 1,
            False: 0,
            0: 0,
            None: 0
        },
        bet={
            True: 1,
            1: 1,
            False: 0,
            0: 0,
            None: 0
        },
        motion_regression={
            'no': 0,
            False: 0,
            None: 0,
            'yes': 1,
            True: 1,
            1: 1,
            'ext': 2,
            2: 2
        },
        thresholding={
            'none': 0,
            None: 0,
            'no': 0,
            0: 0,
            'uncorrected': 1,
            'Uncorrected': 1,
            1: 1,
            'voxel': 2,
            'Voxel': 2,
            2: 2,
            'cluster': 3,
            'Cluster': 3,
            3: 3
        },
        prewhitening={
            True: 1,
            1: 1,
            False: 0,
            None: 0,
            0: 0
        },
        hrf={
            'doublegamma': 3,
            'none': 0,
            None: 0,
            'gaussian': 1,
            'gamma': 2,
            'gammabasisfunctions': 4
        },  #,
        #'sinebasisfunctions': 5,
        #'firbasisfunctions': 6},
        open_feat_html={
            True: 1,
            1: 1,
            False: 0,
            0: 0,
            None: 0
        })

    reg_dict = {
        'full': {
            'reghighres_yn': 1,
            'reghighres_dof': 'BBR',
            'regstandard_yn': 1,
            'regstandard': Info.standard_image('MNI152_T1_2mm_brain.nii.gz'),
            'regstandard_dof': 12,
            'regstandard_nonlinear_yn': 1
        },
        'none': {
            'reghighres_yn': 0,
            'regstandard_yn': 0
        },
        'fmriprep': {
            'reghighres_yn': 0,
            'regstandard_yn': 1,
            'regstandard_dof': 3,
            'regstandard_nonlinear_yn': 0
        }
    }

    data_dir = op.join(op.dirname(spynoza.__file__), 'data')
    fsf_template = op.join(data_dir, 'fsf_templates',
                           'firstlevel_template.fsf')

    with open(fsf_template, 'r') as f:
        fsf_template = f.readlines()
        fsf_template = [
            txt.replace('\n', '') for txt in fsf_template if txt != '\n'
        ]
        fsf_template = [txt for txt in fsf_template
                        if txt[0] != '#']  # remove commnts

    hdr = nib.load(func_file).header

    args = {
        'outputdir': "\"%s\"" % output_dirname,
        'tr': hdr['pixdim'][4],
        'npts': hdr['dim'][4],
        'smooth': smoothing,
        'deriv_yn': arg_dict['temp_deriv'][temp_deriv],
        'temphp_yn': 1 if highpass else 0,
        'paradigm_hp': highpass,
        'st': arg_dict['slicetiming'][slicetiming],
        'mc': arg_dict['motion_correction'][motion_correction],
        'bet_yn': arg_dict['bet'][bet],
        'prewhiten_yn': arg_dict['prewhitening'][prewhitening],
        'motionevs': arg_dict['motion_regression'][motion_regression],
        'threshmask': mask if mask is not None else "",
        'thresh': arg_dict['thresholding'][thresholding],
        'prob_thresh': p_val,
        'z_thresh': z_val,
        'evs_orig': n_orig_evs,
        'evs_real': n_real_evs,
        'ncon_orig': n_con,
        'ncon_real': n_con,
        'nftests_orig': n_ftest,
        'nftests_real': n_ftest,
        'con_mode_old': con_mode_old,
        'con_mode': con_mode,
        'featwatcher_yn': arg_dict['open_feat_html'][open_feat_html],
        'confoundevs': 1
    }

    args.update(reg_dict[registration])

    fsf_out = []

    # 4D AVW data or FEAT directory (1)
    fsf_out.append("set feat_files(1) \"%s\"" % func_file)

    confound_txt_file = op.join(op.abspath('confounds.txt'))
    if hasattr(session_info, 'regressors'):
        confounds = np.array(session_info.regressors).T
        np.savetxt(confound_txt_file,
                   confounds,
                   fmt=str('%.5f'),
                   delimiter='\t')
        fsf_out.append('set confoundev_files(1) \"%s\"' % confound_txt_file)
    else:
        open(confound_txt_file, 'a').close()  # for compatibility issues
        fsf_out.append('set confoundev_files(1) \"\"')

    if highres_file is not None:

        fsf_template.append("set highres_files(1) \"%s\"" % highres_file)

    for line in fsf_template:

        if any(key in line for key in args.keys()):
            parts = [str(txt) for txt in line.split(' ') if txt]
            for key, value in args.items():
                if 'set fmri(%s)' % key in line:
                    parts[-1] = str(value)
                    break
            fsf_out.append(" ".join(parts))
        else:
            fsf_out.append(line)

    ev_files = []
    for i in range(n_orig_evs):

        fname = op.join(op.abspath(session_info.conditions[i] + '.txt'))
        info = np.vstack((session_info.onsets[i], session_info.durations[i],
                          session_info.amplitudes[i])).T
        ev_files.append(fname)
        np.savetxt(fname, info, fmt=str('%.3f'), delimiter='\t')

        fsf_out.append('set fmri(evtitle%i) \"%s\"' %
                       ((i + 1), session_info.conditions[i]))
        fsf_out.append('set fmri(shape%i) 3' % (i + 1))
        fsf_out.append('set fmri(convolve%i) %i' %
                       ((i + 1), arg_dict['hrf'][hrf]))
        fsf_out.append('set fmri(convolve_phase%i) 0' % (i + 1))

        # Only relevant if hrf = 'gamma'
        fsf_out.append('set fmri(gammasigma%i) 3' % (i + 1))
        fsf_out.append('set fmri(gammadelay%i) 6' % (i + 1))

        # Only relevant if hrf = 'gammabasisfunctions'
        fsf_out.append('set fmri(basisfnum%i) 3' % (i + 1))
        fsf_out.append('set fmri(basisfwidth%i) 15' % (i + 1))
        fsf_out.append('set fmri(basisorth%i) 0' % (i + 1))

        fsf_out.append('set fmri(tempfilt_yn%i) %i' %
                       ((i + 1), args['temphp_yn']))
        fsf_out.append('set fmri(deriv_yn%i) %i' % ((i + 1), args['deriv_yn']))
        fsf_out.append('set fmri(custom%i) %s' % ((i + 1), fname))

        for x in range(n_orig_evs + 1):
            fsf_out.append('set fmri(ortho%i.%i) 0' % ((i + 1), x))

    if contrasts and contrasts is not None:

        for i, contrast in enumerate(t_contrasts):
            cname, ctype, ccond, cweights = contrast

            fsf_out.append('set fmri(conpic_real.%i) 1' % (i + 1))
            fsf_out.append('set fmri(conname_real.%i) \"%s\"' %
                           ((i + 1), cname))
            fsf_out.append('set fmri(conpic_orig.%i) 1' % (i + 1))
            fsf_out.append('set fmri(conname_orig.%i) \"%s\"' %
                           ((i + 1), cname))

            for ii, weight in enumerate(cweights):
                fsf_out.append('set fmri(con_orig%i.%i) %.1f' %
                               (i + 1, ii + 1, float(weight)))

            ratio_orig_real = int(n_real_evs / n_orig_evs)
            real_weights = [[w] + [0] * (ratio_orig_real - 1)
                            for w in cweights]
            real_weights = [
                item for sublist in real_weights for item in sublist
            ]
            for ii, weight in enumerate(real_weights):
                fsf_out.append('set fmri(con_real%i.%i) %.1f' %
                               (i + 1, ii + 1, float(weight)))

        for i, contrast in enumerate(f_contrasts):

            for ii, tcon in enumerate(t_contrasts):
                to_set = 1 if tcon in contrast[2] else 0
                fsf_out.append('set fmri(ftest_orig%i.%i) %i' %
                               (i + 1, ii + 1, to_set))
                fsf_out.append('set fmri(ftest_real%i.%i) %i' %
                               (i + 1, ii + 1, to_set))

    design_file = op.join(op.abspath('design.fsf'))
    with open(design_file, 'w') as fsfout:
        print("Writing fsf to %s" % design_file)
        fsfout.write("\n".join(fsf_out))

    return design_file, confound_txt_file, ev_files
예제 #37
0
import os
from pathlib import Path
from datetime import datetime as dt
import pytest
from templateflow.api import get as get_template
from nipype.interfaces.fsl import Info as FSLInfo
from nipype.interfaces.freesurfer import Info as FreeSurferInfo

filepath = os.path.dirname(os.path.realpath(__file__))
datadir = os.path.realpath(os.path.join(filepath, 'data'))

test_data_env = os.getenv('TEST_DATA_HOME',
                          str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'ds003_downsampled'

has_fsl = FSLInfo.version() is not None
has_freesurfer = FreeSurferInfo.version() is not None


def _run_interface_mock(objekt, runtime):
    runtime.returncode = 0
    runtime.endTime = dt.isoformat(dt.utcnow())

    objekt._out_report = os.path.abspath(objekt.inputs.out_report)
    objekt._post_run_hook(runtime)
    objekt._generate_report()
    return runtime


@pytest.fixture
def reference():
예제 #38
0
def setup_infile(tmpdir):
    ext = Info.output_type_to_ext(Info.output_type())
    tmp_infile = tmpdir.join('foo' + ext)
    tmp_infile.open("w")
    return (tmp_infile.strpath, tmpdir.strpath)
예제 #39
0
fs_dir = '~/nipype_tutorial/freesurfer'
FSCommand.set_default_subjects_dir(fs_dir)

###
# Specify variables
experiment_dir = '~/nipype_tutorial'  # location of experiment folder
input_dir_1st = 'output_fMRI_example_1st'  # name of 1st-level output folder
output_dir = 'output_fMRI_example_norm_ants'  # name of norm output folder
working_dir = 'workingdir_fMRI_example_norm_ants'  # name of norm working directory
subject_list = [
    'sub001', 'sub002', 'sub003', 'sub004', 'sub005', 'sub006', 'sub007',
    'sub008', 'sub009', 'sub010'
]  # list of subject identifiers

# location of template file
template = Info.standard_image('MNI152_T1_1mm_brain.nii.gz')

###
# Specify Normalization Nodes

# Registration - computes registration between subject's structural and MNI template.
antsreg = Node(Registration(args='--float',
                            collapse_output_transforms=True,
                            fixed_image=template,
                            initial_moving_transform_com=True,
                            num_threads=1,
                            output_inverse_warped_image=True,
                            output_warped_image=True,
                            sigma_units=['vox'] * 3,
                            transforms=['Rigid', 'Affine', 'SyN'],
                            terminal_output='file',
예제 #40
0
파일: rs.py 프로젝트: NBCLab/niconn
def rs_grouplevel(copes, varcopes, dofs, output_dir, work_dir):

    from nipype.interfaces.fsl.model import MultipleRegressDesign
    from nipype.interfaces.utility import Function
    from nipype.interfaces.fsl.model import FLAMEO
    from nipype.interfaces.fsl.model import SmoothEstimate
    from connectivity.interfaces import Cluster
    from nipype.interfaces.fsl.utils import Merge
    from nipype.interfaces.fsl import Info
    from connectivity.interfaces import PtoZ

    grplevelworkflow = pe.Workflow(name="grplevelworkflow")
    grplevelworkflow.base_dir = work_dir

    merger = Merge()
    merger.inputs.dimension = 't'
    merger.inputs.in_files = copes
    merger.inputs.merged_file = op.join(work_dir, 'cope.nii.gz')
    merger.run()

    merger.inputs.in_files = varcopes
    merger.inputs.merged_file = op.join(work_dir, 'varcope.nii.gz')
    merger.run()

    merger.inputs.in_files = dofs
    merger.inputs.merged_file = op.join(work_dir, 'dof.nii.gz')
    merger.run()

    model = pe.Node(interface=MultipleRegressDesign(), name='model')
    model.inputs.contrasts = [['mean', 'T', ['roi'], [1]]]
    model.inputs.regressors = dict(roi=np.ones(len(copes)).tolist())

    flameo = pe.Node(interface=FLAMEO(), name='flameo')
    flameo.inputs.cope_file = op.join(work_dir, 'cope.nii.gz')
    flameo.inputs.var_cope_file = op.join(work_dir, 'varcope.nii.gz')
    flameo.inputs.dof_var_cope_file = op.join(work_dir, 'dof.nii.gz')
    flameo.inputs.run_mode = 'flame1'
    flameo.inputs.mask_file = Info.standard_image(
        'MNI152_T1_2mm_brain_mask.nii.gz')

    grplevelworkflow.connect(model, 'design_con', flameo, 't_con_file')
    grplevelworkflow.connect(model, 'design_grp', flameo, 'cov_split_file')
    grplevelworkflow.connect(model, 'design_mat', flameo, 'design_file')

    smoothest = pe.Node(SmoothEstimate(), name='smooth_estimate')
    grplevelworkflow.connect(flameo, 'zstats', smoothest, 'residual_fit_file')
    smoothest.inputs.mask_file = Info.standard_image(
        'MNI152_T1_2mm_brain_mask.nii.gz')
    smoothest.inputs.dof = len(dofs) - 1

    cluster = pe.Node(Cluster(), name='cluster')
    ptoz = pe.Node(PtoZ(), name='ptoz')
    ptoz.inputs.pvalue = 0.001
    calculate_resels = pe.Node(Function(input_names=["volume", "resels"],
                                        output_names=["resels"],
                                        function=calcres),
                               name="calcres")
    grplevelworkflow.connect(smoothest, 'resels', cluster, 'resels')
    grplevelworkflow.connect(smoothest, 'resels', calculate_resels, 'resels')
    grplevelworkflow.connect(smoothest, 'volume', calculate_resels, 'volume')
    grplevelworkflow.connect(calculate_resels, 'resels', ptoz, 'resels')
    grplevelworkflow.connect(ptoz, 'zstat', cluster, 'threshold')
    cluster.inputs.connectivity = 26
    cluster.inputs.out_threshold_file = True
    cluster.inputs.out_index_file = True
    cluster.inputs.out_localmax_txt_file = True
    cluster.inputs.voxthresh = True

    grplevelworkflow.connect(flameo, 'zstats', cluster, 'in_file')

    datasink = pe.Node(nio.DataSink(), name='sinker')
    datasink.inputs.base_directory = work_dir

    grplevelworkflow.connect(flameo, 'zstats', datasink, 'z')
    grplevelworkflow.connect(cluster, 'threshold_file', datasink, 'z_thresh')

    grplevelworkflow.run()

    shutil.rmtree(op.join(work_dir, 'grplevelworkflow'))
    #copy data to directory
    shutil.copyfile(op.join(work_dir, 'z', 'zstat1.nii.gz'),
                    op.join(output_dir, 'z.nii.gz'))
    shutil.copyfile(op.join(work_dir, 'z_thresh', 'zstat1_threshold.nii.gz'),
                    op.join(output_dir, 'z_level-voxel_corr-FWE.nii.gz'))

    shutil.rmtree(work_dir)
예제 #41
0
def custom_level1design_feat(func_file, highres_file=None, session_info=None, output_dirname='firstlevel',
                             contrasts='single-trial', smoothing=0, temp_deriv=False, registration='full', highpass=100,
                             slicetiming=None, motion_correction=None, bet=True, prewhitening=True, motion_regression=None,
                             thresholding='uncorrected', p_val=0.05, z_val=2.3, mask=None, hrf='doublegamma',
                             open_feat_html=False):
    """ Custom implementation of a FSL create-level1-design function.
    This function (which can be wrapped in a custom Nipype Function node) creates an FSL design.fsf
    file. This function is similar to the Nipype Level1Design node (interfaces.fsl.model) but allows
    for way more options to be set.
    Parameters
    ----------
    func_file : str
        Path to functional file (4D) with timeseries data
    highres_file : str
        Path to file corresponding to high-resolution anatomical scan (should already be skull-stripped!).
        Only necessary if doing functional-highres-standard registration (i.e. registration = 'full');
        otherwise, set to None.
    session_info : Nipype Bunch-object
        Bunch-object (dict-like) with information about stimulus-related and nuisance regressors.
    output_dirname : str
        Name of output directory (.feat will be appended to it).
    contrasts : str, tuple, or list
        (List of) tuple(s) with defined contrasts. Should be formatted using the Nipype syntax:
        `(name_of_contrast, 'T', [cond_name_1, cond_name_2], [weight_1, weight_2])` for a t-contrast,
        or `(name_of_f_test, 'F', [contrast_1, contrast_2])` for F-tests.
    smoothing : float or int
        Smoothing kernel in FWHM (mm)
    temp_deriv : bool
        Whether to include temporal derivates of real EVs.
    registration : str
        Registration-scheme to apply. Currently supports three types: 'full', which registers
        the functional file to the high-res anatomical (using FLIRT BBR) and subsequent linear-
        non-linear registration to the MNI152 (2mm) standard brain (using FNIRT); another option
        is 'fmriprep', which only calculates a 3-parameter (translation only) transformation because
        output from the fmriprep-preprocessing-pipeline is already registered to MNI but is still in
        native dimensions (i.e. EPI-space). Last option is 'none', which doesn't do any registration.
    highpass : int
        Length (in seconds) of FSL highpass filter to apply.
    slicetiming : str
        Whether to apply slice-time correction; options are 'up' (ascending), 'down' (descending),
        or 'no' (no slicetiming correction).
    motion_correction : bool
        Whether to apply motion-correction (MCFLIRT).
    bet : bool
        Whether to BET (skullstrip) the functional file.
    prewhitening : bool
        Whether to do prewhitening.
    motion_regression : str
        Whether to do motion-regression. Options: 'no' (no motion regression), 'yes' (standard 6 parameters motion
        regression), 'ext' (extended 24 parameter motion regression).
    thresholding : str
        What type of thresholding to apply. Options: 'none', 'uncorrected', 'voxel', 'cluster'.
    p_val : float
        What p-value to use in thresholding.
    z_val : float
        What minimum z-value to use in cluster-correction
    mask : str
        File to use in pre-thresholding masking. Setting to None means no masking.
    hrf : str
        What HRF-model to use. Default is 'doublegamma', but other options are: 'gamma',
        'gammabasisfunctions', 'gaussian'.
    open_feat_html : bool
        Whether to automatically open HTML-progress report.
    Returns
    -------
    design_file : str
        The path to the created design.fsf file
    confound_txt_file : str
        Path to the created confounds.txt file
    ev_files : list
        List with paths to EV-text-files.
    """
    import os.path as op
    import nibabel as nib
    from nipype.interfaces.fsl import Info
    import numpy as np
    import spynoza

    if isinstance(session_info, list):

        if len(session_info) == 1:
            session_info = session_info[0]

    if registration == 'full' and highres_file is None:
        raise ValueError("If you want to do a full registration, you need to specify a highres file!")

    if motion_correction in (0, False, 'yes') and motion_regression in ('yes', True, 1, 'ext', 2):
        raise ValueError("If you want to do motion-regression, make sure to turn on motion-correction!")

    if hrf == 'gammabasisfunctions' and temp_deriv:
        print("Cannot add temporal deriv when hrf = gammabasisfunctions; setting temp-deriv to False")
        temp_deriv = False

    n_orig_evs = len(session_info.conditions)
    if contrasts == 'single-trial':

        cons = []
        for i in range(n_orig_evs):
            con_values = np.zeros(len(session_info.conditions))
            con_values[i] = 1
            this_con = (session_info.conditions[i], 'T', session_info.conditions, con_values)
            cons.append(this_con)
        f_con = ('f_all', 'F', cons)
        cons.append(f_con)
        contrasts = cons
    elif isinstance(contrasts, list):  # assume nipype style contrasts
        for i, con in enumerate(contrasts):
            weights = np.zeros(n_orig_evs)
            this_i = 0
            for ii, ev in enumerate(session_info.conditions):
                for iii, this_entry in enumerate(con[2]):
                    if ev == this_entry:
                        weights[ii] = con[3][iii]
            contrasts[i] = (con[0], con[1], con[2], weights.tolist())

    t_contrasts = [con for con in contrasts if con[1] == 'T']
    f_contrasts = [con for con in contrasts if con[1] == 'F']
    n_con = len(t_contrasts)
    n_ftest = len(f_contrasts)
    n_real_evs = n_orig_evs

    if temp_deriv:
        n_real_evs *= 2
    elif hrf == 'gammabasisfunctions':
        n_real_evs *= 3  # ToDo: allow more than 3 basis funcs

    if temp_deriv:
        con_mode_old = 'real'
        con_mode = 'real'
    else:
        con_mode_old = 'orig'
        con_mode = 'orig'

    arg_dict = dict(temp_deriv={True: 1, 1: 1, False: 0, 0: 0},

                    slicetiming={'no': 0, 0: 0, None: 0,
                                 'up': 1, 1: 1,
                                 'down': 2, 2: 2},

                    motion_correction={True: 1, 1: 1, False: 0, 0: 0, None: 0},

                    bet={True: 1, 1: 1, False: 0, 0: 0, None: 0},

                    motion_regression={'no': 0, False: 0, None: 0,
                                       'yes': 1, True: 1, 1: 1,
                                       'ext': 2, 2: 2},

                    thresholding={'none': 0, None: 0, 'no': 0, 0: 0,
                                  'uncorrected': 1, 'Uncorrected': 1, 1: 1,
                                  'voxel': 2, 'Voxel': 2, 2: 2,
                                  'cluster': 3, 'Cluster': 3, 3: 3},

                    prewhitening={True: 1, 1: 1, False: 0, None: 0, 0: 0},

                    hrf={'doublegamma': 3,
                         'none': 0, None: 0,
                         'gaussian': 1,
                         'gamma': 2,
                         'gammabasisfunctions': 4}, #,
                         #'sinebasisfunctions': 5,
                         #'firbasisfunctions': 6},

                    open_feat_html={True: 1, 1: 1,
                                    False: 0, 0: 0, None: 0}
                    )

    reg_dict = {'full': {'reghighres_yn': 1,
                         'reghighres_dof': 'BBR',
                         'regstandard_yn': 1,
                         'regstandard': Info.standard_image('MNI152_T1_2mm_brain.nii.gz'),
                         'regstandard_dof': 12,
                         'regstandard_nonlinear_yn': 1},

                'none': {'reghighres_yn': 0,
                         'regstandard_yn': 0},

                'fmriprep': {'reghighres_yn': 0,
                             'regstandard_yn': 1,
                             'regstandard_dof': 3,
                             'regstandard_nonlinear_yn': 0}
                }

    data_dir = op.join(op.dirname(spynoza.__file__), 'data')
    fsf_template = op.join(data_dir, 'fsf_templates', 'firstlevel_template.fsf')

    with open(fsf_template, 'r') as f:
        fsf_template = f.readlines()
        fsf_template = [txt.replace('\n', '') for txt in fsf_template if txt != '\n']
        fsf_template = [txt for txt in fsf_template if txt[0] != '#']  # remove commnts

    hdr = nib.load(func_file).header

    args = {'outputdir': "\"%s\"" % output_dirname,
            'tr': hdr['pixdim'][4],
            'npts': hdr['dim'][4],
            'smooth': smoothing,
            'deriv_yn': arg_dict['temp_deriv'][temp_deriv],
            'temphp_yn': 1 if highpass else 0,
            'paradigm_hp': highpass,
            'st': arg_dict['slicetiming'][slicetiming],
            'mc': arg_dict['motion_correction'][motion_correction],
            'bet_yn': arg_dict['bet'][bet],
            'prewhiten_yn': arg_dict['prewhitening'][prewhitening],
            'motionevs': arg_dict['motion_regression'][motion_regression],
            'threshmask': mask if mask is not None else "",
            'thresh': arg_dict['thresholding'][thresholding],
            'prob_thresh': p_val,
            'z_thresh': z_val,
            'evs_orig': n_orig_evs,
            'evs_real': n_real_evs,
            'ncon_orig': n_con,
            'ncon_real': n_con,
            'nftests_orig': n_ftest,
            'nftests_real': n_ftest,
            'con_mode_old': con_mode_old,
            'con_mode': con_mode,
            'featwatcher_yn': arg_dict['open_feat_html'][open_feat_html],
            'confoundevs': 1}

    args.update(reg_dict[registration])

    fsf_out = []

    # 4D AVW data or FEAT directory (1)
    fsf_out.append("set feat_files(1) \"%s\"" % func_file)

    confound_txt_file = op.join(op.abspath('confounds.txt'))
    if hasattr(session_info, 'regressors'):
        confounds = np.array(session_info.regressors).T
        np.savetxt(confound_txt_file, confounds, fmt=str('%.5f'), delimiter='\t')
        fsf_out.append('set confoundev_files(1) \"%s\"' % confound_txt_file)
    else:
        open(confound_txt_file, 'a').close()  # for compatibility issues
        fsf_out.append('set confoundev_files(1) \"\"')

    if highres_file is not None:

        fsf_template.append("set highres_files(1) \"%s\"" % highres_file)

    for line in fsf_template:

        if any(key in line for key in args.keys()):
            parts = [str(txt) for txt in line.split(' ') if txt]
            for key, value in args.items():
                if 'set fmri(%s)' % key in line:
                    parts[-1] = str(value)
                    break
            fsf_out.append(" ".join(parts))
        else:
            fsf_out.append(line)

    ev_files = []
    for i in range(n_orig_evs):

        fname = op.join(op.abspath(session_info.conditions[i] + '.txt'))
        info = np.vstack((session_info.onsets[i],
                          session_info.durations[i],
                          session_info.amplitudes[i])).T
        ev_files.append(fname)
        np.savetxt(fname, info, fmt=str('%.3f'), delimiter='\t')

        fsf_out.append('set fmri(evtitle%i) \"%s\"' % ((i + 1), session_info.conditions[i]))
        fsf_out.append('set fmri(shape%i) 3' % (i + 1))
        fsf_out.append('set fmri(convolve%i) %i' % ((i + 1), arg_dict['hrf'][hrf]))
        fsf_out.append('set fmri(convolve_phase%i) 0' % (i + 1))

        # Only relevant if hrf = 'gamma'
        fsf_out.append('set fmri(gammasigma%i) 3' % (i + 1))
        fsf_out.append('set fmri(gammadelay%i) 6' % (i + 1))

        # Only relevant if hrf = 'gammabasisfunctions'
        fsf_out.append('set fmri(basisfnum%i) 3' % (i + 1))
        fsf_out.append('set fmri(basisfwidth%i) 15' % (i + 1))
        fsf_out.append('set fmri(basisorth%i) 0' % (i + 1))

        fsf_out.append('set fmri(tempfilt_yn%i) %i' % ((i + 1), args['temphp_yn']))
        fsf_out.append('set fmri(deriv_yn%i) %i' % ((i + 1), args['deriv_yn']))
        fsf_out.append('set fmri(custom%i) %s' % ((i + 1), fname))

        for x in range(n_orig_evs + 1):
            fsf_out.append('set fmri(ortho%i.%i) 0' % ((i + 1), x))

    if contrasts and contrasts is not None:

        for i, contrast in enumerate(t_contrasts):
            cname, ctype, ccond, cweights = contrast

            fsf_out.append('set fmri(conpic_real.%i) 1' % (i + 1))
            fsf_out.append('set fmri(conname_real.%i) \"%s\"' % ((i + 1),
                                                                  cname))
            fsf_out.append('set fmri(conpic_orig.%i) 1' % (i + 1))
            fsf_out.append('set fmri(conname_orig.%i) \"%s\"' % ((i + 1),
                                                                 cname))

            for ii, weight in enumerate(cweights):
                fsf_out.append('set fmri(con_orig%i.%i) %.1f' % (i  + 1, ii + 1, float(weight)))

            ratio_orig_real = int(n_real_evs / n_orig_evs)
            real_weights = [[w] + [0] * (ratio_orig_real - 1) for w in cweights]
            real_weights = [item for sublist in real_weights for item in sublist]
            for ii, weight in enumerate(real_weights):
                fsf_out.append('set fmri(con_real%i.%i) %.1f' % (i  + 1, ii + 1, float(weight)))

        for i, contrast in enumerate(f_contrasts):

            for ii, tcon in enumerate(t_contrasts):
                to_set = 1 if tcon in contrast[2] else 0
                fsf_out.append('set fmri(ftest_orig%i.%i) %i' % (i + 1, ii + 1, to_set))
                fsf_out.append('set fmri(ftest_real%i.%i) %i' % (i + 1, ii + 1, to_set))

    design_file = op.join(op.abspath('design.fsf'))
    with open(design_file, 'w') as fsfout:
         print("Writing fsf to %s" % design_file)
         fsfout.write("\n".join(fsf_out))

    return design_file, confound_txt_file, ev_files
예제 #42
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)
예제 #43
0
from nipype.interfaces.fsl import Info

Info.standard_image()
template_path = Info.standard_image('MNI152_T1_1mm_brain.nii.gz')