def main(sourcedata, derivatives, tmp_dir, subject, session=None):

    brainmask_fn = os.path.join(derivatives, 'freesurfer',
                                'sub-{}'.format(subject), 'mri',
                                'brainmask.mgz')

    if not os.path.exists(brainmask_fn):
        raise Exception(
            'Brainmask {} does not exits. Did you run Freesurfer?'.format(
                brainmask_fn))

    brainmask = image.load_img(brainmask_fn)

    manual_outside = get_derivative(derivatives,
                                    type='manual_segmentation',
                                    modality='anat',
                                    subject=subject,
                                    suffix='mask',
                                    description='outside',
                                    space='average',
                                    session=session,
                                    check_exists=False)

    manual_outside = image.resample_to_img(manual_outside,
                                           brainmask,
                                           interpolation='nearest')

    manual_inside = get_derivative(derivatives,
                                   type='manual_segmentation',
                                   modality='anat',
                                   subject=subject,
                                   suffix='mask',
                                   description='gm',
                                   space='average',
                                   session=session,
                                   check_exists=False)

    manual_inside = image.resample_to_img(manual_inside,
                                          brainmask,
                                          interpolation='nearest')

    new_brainmask = image.math_img(
        'brainmask * (np.ones_like(brainmask) - manual_outside)'
        '+ (manual_inside - (brainmask > 0)) ',
        brainmask=brainmask,
        manual_inside=manual_inside,
        manual_outside=manual_outside)
    print(new_brainmask.shape)

    new_brainmask = nb.freesurfer.MGHImage(new_brainmask.get_data(),
                                           brainmask.affine, brainmask.header)

    if not (brainmask.get_data() == new_brainmask.get_data()).all():
        print('Brain mask has been altered')
        new_brainmask.to_filename(brainmask_fn)
        print('writing to {}'.format(brainmask_fn))
    else:
        print('Brain mask has NOT been altered')
def main(sourcedata,
         derivatives,
         tmp_dir,
         subject,
         num_threads=8,
         session=None):
    
    if session is None:
        session = '.*'

    derivatives_layout = BIDSLayout(os.path.join(derivatives, 'averaged_mp2rages'))

    inv2 = get_bids_file(derivatives_layout, 
                         subject,
                         suffix='INV2')

    t1w = get_bids_file(derivatives_layout, 
                         subject,
                         suffix='T1w')

    t1map = get_bids_file(derivatives_layout, 
                         subject,
                         suffix='T1map')


    manual_outside = get_derivative(derivatives, type='manual_segmentation',
                                    modality='anat', subject=subject,
                                    suffix='mask', description='outside',
                                    space='average', session=session,
                                    check_exists=False)

    manual_inside = get_derivative(derivatives, type='manual_segmentation',
                                    modality='anat', subject=subject,
                                    suffix='mask', description='gm',
                                    space='average', session=session,
                                    check_exists=False)



    wf_name = 'mask_wf_{}'.format(subject)
    mask_wf = init_masking_wf(name=wf_name, num_threads=num_threads)
    mask_wf.base_dir = '/workflow_folders'

    mask_wf.inputs.inputnode.inv2 = inv2
    mask_wf.inputs.inputnode.t1w = t1w
    mask_wf.inputs.inputnode.t1map = t1map
    mask_wf.inputs.inputnode.manual_inside = manual_inside
    mask_wf.inputs.inputnode.manual_outside = manual_outside

    mask_wf.run()
Ejemplo n.º 3
0
def build_model(image, param1, param2, cycle4, cycle8, facet):
    """
    build ilp model for piecewise linear
    """
    print("Building Cplex model...")
    # initialize model
    model = cplex.Cplex()
    # set sense
    model.objective.set_sense(model.objective.sense.minimize)
    # get discrete second derivative
    derivative = utils.get_derivative(image)

    # build graph
    graph = utils.to_graph(image)

    # build objective function
    vars = get_varibles(image)
    model.variables.add(names=vars)
    colnames, obj, types = get_obj(derivative, param2)
    model.variables.add(obj=obj, types=types, names=colnames)

    # add constraints
    rows, senses, rhs = get_constraints(image,
                                        derivative,
                                        param1,
                                        cycle4=cycle4,
                                        cycle8=cycle8)
    model.linear_constraints.add(lin_expr=rows, senses=senses, rhs=rhs)

    # parallel
    model.parameters.parallel.set(-1)
    model.parameters.threads.set(32)

    # register callback
    #model.register_callback(cutremoveCallback)
    model.register_callback(multicutCallback)
    # associate additional data
    multicutCallback._graph = graph.copy()
    multicutCallback._names = model.variables.get_names()
    multicutCallback._facet = facet
    #cutremoveCallback._names = model.variables.get_names()

    return model
def main(sourcedata, derivatives, subject):

    manual_outside_mask = get_derivative(derivatives,
                                         'manual_segmentation',
                                         'anat',
                                         subject,
                                         'mask',
                                         description='outside',
                                         session='anat',
                                         check_exists=True,
                                         space='average')
    manual_inside_mask = get_derivative(derivatives,
                                        'manual_segmentation',
                                        'anat',
                                        subject,
                                        'mask',
                                        description='gm',
                                        session='anat',
                                        check_exists=True,
                                        space='average')

    manual_wm_mask = get_derivative(derivatives,
                                    'manual_segmentation',
                                    'anat',
                                    subject,
                                    'mask',
                                    description='wm',
                                    session='anat',
                                    check_exists=False,
                                    space='average')

    freesurfer_brainmask_auto = op.join(
        derivatives, 'freesurfer', 'sub-{subject}', 'mri',
        'brainmask.auto.mgz').format(**locals())

    freesurfer_brainmask = op.join(derivatives, 'freesurfer', 'sub-{subject}',
                                   'mri', 'brainmask.mgz').format(**locals())

    freesurfer_t1w = op.join(derivatives, 'freesurfer', 'sub-{subject}', 'mri',
                             'T1.mgz').format(**locals())

    manual_outside_mask = image.resample_to_img(manual_outside_mask,
                                                freesurfer_brainmask_auto,
                                                interpolation='nearest')

    manual_outside_mask = nb.freesurfer.MGHImage(
        manual_outside_mask.get_data().astype(np.float32),
        affine=manual_outside_mask.affine)

    manual_inside_mask = image.resample_to_img(manual_inside_mask,
                                               freesurfer_brainmask_auto,
                                               interpolation='nearest')

    manual_inside_mask = nb.freesurfer.MGHImage(
        manual_inside_mask.get_data().astype(np.float32),
        affine=manual_inside_mask.affine)

    if manual_wm_mask:
        manual_wm_mask = image.resample_to_img(manual_wm_mask,
                                               freesurfer_brainmask_auto,
                                               interpolation='nearest')

        manual_wm_mask = nb.freesurfer.MGHImage(
            manual_wm_mask.get_data().astype(np.float32),
            affine=manual_wm_mask.affine)

        manual_inside_mask = image.math_img(
            '(manual_inside_mask + manual_wm_mask) > 0',
            manual_inside_mask=manual_inside_mask,
            manual_wm_mask=manual_wm_mask)

        freesurfer_wm = op.join(derivatives, 'freesurfer', 'sub-{subject}',
                                'mri', 'wm.mgz').format(**locals())

        freesurfer_wm_new = image.math_img(
            'freesurfer_wm * (1-manual_inside_mask) '
            '* (1 - manual_outside_mask)'
            '+ manual_wm_mask * 255',
            manual_inside_mask=manual_inside_mask,
            manual_wm_mask=manual_wm_mask,
            manual_outside_mask=manual_outside_mask,
            freesurfer_wm=freesurfer_wm)

        # Get rid of any weird small components
        freesurfer_wm_new_ = nb.Nifti1Image(freesurfer_wm_new.get_data(),
                                            freesurfer_wm_new.affine)
        largest_component = image.largest_connected_component_img(
            freesurfer_wm_new_)
        largest_component = nb.MGHImage(largest_component.get_data(),
                                        freesurfer_wm_new.affine,
                                        freesurfer_wm_new.header)

        freesurfer_wm_new = image.math_img('freesurfer_wm * largest_component',
                                           freesurfer_wm=freesurfer_wm_new,
                                           largest_component=largest_component)

        freesurfer_wm_new.to_filename(freesurfer_wm)

    new_brainmask = image.math_img(
        '(((brain_mask > 0) + inside - outside ) > 0) * t1w',
        brain_mask=freesurfer_brainmask_auto,
        outside=manual_outside_mask,
        t1w=freesurfer_t1w,
        inside=manual_inside_mask)

    new_brainmask.to_filename(freesurfer_brainmask)

    new_brainmask.to_filename(
        op.join(derivatives, 'freesurfer', 'sub-{subject}', 'mri',
                'brain.finalsurfs.manedit.mgz').format(**locals()))
Ejemplo n.º 5
0
def main(derivatives,
         subject,
         session,
         task,
         acquisition,
         run,
         workflow_folder='/tmp/workflow_folders'):

    os.environ['SUBJECTS_DIR'] = os.path.join(derivatives, 'freesurfer')

    preproc_bold = get_derivative(derivatives,
                                  'spynoza',
                                  'func',
                                  subject=subject,
                                  session=session,
                                  suffix='preproc',
                                  acquisition=acquisition,
                                  run=run,
                                  task=task)

    registration = get_derivative(derivatives,
                                  'manual_registrations',
                                  'func',
                                  subject=subject,
                                  session=session,
                                  description='spynoza2t1w',
                                  suffix='transform',
                                  extension='lta',
                                  check_exists=False)

    wf = pe.Workflow(name='sample_fs', base_dir=workflow_folder)

    inputnode = pe.Node(niu.IdentityInterface(
        fields=['preproc_bold', 'registration'
                'subject']),
                        name='inputnode')
    inputnode.inputs.preproc_bold = preproc_bold
    inputnode.inputs.subject = 'sub-{}'.format(subject)
    inputnode.inputs.registration = registration

    sampler = pe.Node(fs.SampleToSurface(sampling_method='average',
                                         sampling_range=(0, 1, 0.2),
                                         sampling_units='frac',
                                         interp_method='trilinear',
                                         cortex_mask=True,
                                         subjects_dir=os.path.join(
                                             derivatives, 'freesurfer'),
                                         override_reg_subj=True,
                                         out_type='gii'),
                      iterables=('hemi', ['lh', 'rh']),
                      name='sampler')

    wf.connect(inputnode, 'preproc_bold', sampler, 'source_file')
    if registration is not None:
        wf.connect(inputnode, 'registration', sampler, 'reg_file')
    else:
        sampler.inputs.reg_header = True
    wf.connect(inputnode, 'subject', sampler, 'subject_id')

    merger = pe.JoinNode(niu.Merge(1, ravel_inputs=True),
                         name='merger',
                         joinsource='sampler',
                         joinfield=['in1'])
    wf.connect(sampler, 'out_file', merger, 'in1')

    ds = pe.MapNode(DerivativesDataSink(
        base_directory=derivatives,
        out_path_base='sampled_giis',
    ),
                    iterfield=['in_file', 'suffix'],
                    name='datasink')

    ds.inputs.suffix = ['bold.lh', 'bold.rh']

    wf.connect(merger, 'out', ds, 'in_file')
    wf.connect(inputnode, 'preproc_bold', ds, 'source_file')

    wf.run()
Ejemplo n.º 6
0
def main(sourcedata,
         derivatives,
         tmp_dir,
         subject=None,
         session=None,
         run=None):

    print(subject, session, run)

    layout = BIDSLayout(sourcedata)
    derivatives_layout = BIDSLayout('/derivatives/spynoza', validate=False)

    cortex_l = get_derivative(derivatives,
                              'nighres',
                              'anat',
                              subject,
                              'dseg',
                              session='anat',
                              space='average',
                              description='cortex',
                              hemi='left')

    cortex_r = get_derivative(derivatives,
                              'nighres',
                              'anat',
                              subject,
                              'dseg',
                              session='anat',
                              space='average',
                              description='cortex',
                              hemi='left')

    mask = derivatives_layout.get(subject=subject,
                                  session=session,
                                  suffix='mask',
                                  return_type='file')
    mask = sorted(mask)
    assert (len(mask) == 1)
    mask = mask[0]

    bold = derivatives_layout.get(subject=subject,
                                  session=session,
                                  suffix='preproc',
                                  return_type='file')
    bold = sorted(bold)
    print('BOLD: {}'.format(bold))
    print('MASK: {}'.format(mask))

    inputnode = pe.Node(
        niu.IdentityInterface(fields=['cortex_l', 'cortex_r', 'bold', 'mask']),
        name='inputnode')

    inputnode.inputs.cortex_l = cortex_l
    inputnode.inputs.cortex_r = cortex_r
    inputnode.inputs.bold = bold
    inputnode.inputs.mask = mask

    get_masks = pe.MapNode(niu.Function(
        function=get_brain_regions_cruise,
        input_names=['cortex_l', 'cortex_r', 'type'],
        output_names=['out']),
                           iterfield=['type'],
                           name='get_masks')
    get_masks.inputs.type = ['csf', 'wm']

    wf = pe.Workflow(name='get_confounds_{}_{}'.format(subject, session),
                     base_dir='/workflow_folders')
    wf.connect(inputnode, 'cortex_l', get_masks, 'cortex_l')
    wf.connect(inputnode, 'cortex_r', get_masks, 'cortex_r')

    resampler = pe.MapNode(niu.Function(
        function=resample_img,
        input_names=['input_image', 'ref_image', 'interpolation'],
        output_names=['resampled_image'],
    ),
                           iterfield=['input_image'],
                           name='resampler')

    wf.connect(inputnode, ('bold', pickfirst), resampler, 'ref_image')
    wf.connect(get_masks, 'out', resampler, 'input_image')

    compcorr = pe.MapNode(ACompCor(merge_method='union'),
                          iterfield=['realigned_file'],
                          name='acompcorr')

    wf.connect(resampler, 'resampled_image', compcorr, 'mask_files')
    wf.connect(inputnode, 'bold', compcorr, 'realigned_file')

    dvars = pe.MapNode(ComputeDVARS(), iterfield=['in_file'], name='dvars')
    wf.connect(inputnode, 'mask', dvars, 'in_mask')
    wf.connect(inputnode, 'bold', dvars, 'in_file')

    add_header = pe.MapNode(AddTSVHeader(columns=["dvars"]),
                            iterfield=['in_file'],
                            name="add_header_dvars")
    wf.connect(dvars, 'out_std', add_header, 'in_file')

    concat = pe.MapNode(GatherConfounds(),
                        iterfield=['acompcor', 'dvars'],
                        name="concat")
    wf.connect(add_header, 'out_file', concat, 'dvars')
    wf.connect(compcorr, 'components_file', concat, 'acompcor')

    ds_confounds = pe.MapNode(DerivativesDataSink(out_path_base='spynoza',
                                                  suffix='confounds_compcor',
                                                  base_directory=derivatives),
                              iterfield=['in_file', 'source_file'],
                              name='ds_reg_report')

    wf.connect(inputnode, 'bold', ds_confounds, 'source_file')
    wf.connect(concat, 'confounds_file', ds_confounds, 'in_file')

    wf.run(plugin='MultiProc', plugin_args={'n_procs': 10})
Ejemplo n.º 7
0
def main(derivatives, subject, session, workflow_folder, n_procs=8):

    fn = get_derivative(derivatives,
                        'tsnr',
                        'func',
                        subject=subject,
                        session=session,
                        run='*',
                        acquisition='*',
                        task='*',
                        suffix='invtsnr')

    os.environ['SUBJECTS_DIR'] = op.join(derivatives, 'freesurfer')

    wf = pe.Workflow(name='sample_fs_invtsnt_{}_{}'.format(subject, session),
                     base_dir=workflow_folder)

    input_node = pe.Node(niu.IdentityInterface(fields=['source_file']),
                         name='input_node')
    input_node.inputs.source_file = fn

    config_node = pe.Node(
        niu.IdentityInterface(fields=['depth', 'hemisphere']),
        name='config_node')
    config_node.iterables = [('depth', np.arange(1, 7)),
                             ('hemisphere', ['lh', 'rh'])]

    def get_surf_name(depth, n_surfs=8):
        return 'equi{}.pial'.format(str(float(depth) / (n_surfs - 1)))

    sampler = pe.MapNode(fs.SampleToSurface(
        subjects_dir=os.path.join(derivatives, 'freesurfer'),
        override_reg_subj=True,
        reg_header=True,
        subject_id='sub-{}'.format(subject),
        interp_method='trilinear',
        projection_stem='',
        out_type='gii'),
                         iterfield=['source_file'],
                         name='sampler')

    wf.connect(input_node, 'source_file', sampler, 'source_file')
    wf.connect(config_node, ('depth', get_surf_name), sampler, 'surface')
    wf.connect(config_node, 'hemisphere', sampler, 'hemi')

    def get_desc(depth, n_surfs=8):
        return 'depth.{:.03f}'.format(float(depth) / (n_surfs - 1))

    def get_extra_values(hemi):
        return ['hemi-{}'.format(hemi)]

    ds = pe.MapNode(DerivativesDataSink(
        base_directory=derivatives,
        out_path_base='tsnr',
    ),
                    iterfield=['in_file', 'source_file'],
                    name='datasink')

    wf.connect(input_node, 'source_file', ds, 'source_file')
    wf.connect(sampler, 'out_file', ds, 'in_file')
    wf.connect(config_node, ('depth', get_desc), ds, 'desc')
    wf.connect(config_node, ('hemisphere', get_extra_values), ds,
               'extra_values')

    wf.run(plugin='MultiProc', plugin_args={'n_procs': n_procs})
Ejemplo n.º 8
0
def main(sourcedata, derivatives, tmp_dir, subject=None):

    layout = BIDSLayout(sourcedata)

    inv2 = get_derivative(derivatives,
                          'averaged_mp2rages',
                          'anat',
                          subject,
                          'INV2',
                          session='anat',
                          space='average')
    t1w = get_derivative(derivatives,
                         'averaged_mp2rages',
                         'anat',
                         subject,
                         'T1w',
                         session='anat',
                         space='average')
    t1map = get_derivative(derivatives,
                           'averaged_mp2rages',
                           'anat',
                           subject,
                           'T1map',
                           session='anat',
                           space='average')

    manual_outside_mask = get_derivative(derivatives,
                                         'manual_segmentation',
                                         'anat',
                                         subject,
                                         'mask',
                                         description='outside',
                                         session='anat',
                                         check_exists=False,
                                         space='average')
    manual_gm_mask = get_derivative(derivatives,
                                    'manual_segmentation',
                                    'anat',
                                    subject,
                                    'mask',
                                    description='gm',
                                    session='anat',
                                    check_exists=True,
                                    space='average')
    manual_wm_mask = get_derivative(derivatives,
                                    'manual_segmentation',
                                    'anat',
                                    subject,
                                    'mask',
                                    description='wm',
                                    session='anat',
                                    check_exists=False,
                                    space='average')

    fmriprep_wm = get_derivative(derivatives,
                                 'fmriprep',
                                 'anat',
                                 subject,
                                 'probseg',
                                 label='WM',
                                 old_fmriprep=False)
    fmriprep_gm = get_derivative(derivatives,
                                 'fmriprep',
                                 'anat',
                                 subject,
                                 'probseg',
                                 label='GM',
                                 old_fmriprep=False)

    freesurfer_seg = get_derivative(derivatives,
                                    'fmriprep',
                                    'anat',
                                    subject,
                                    'dseg',
                                    description='aseg',
                                    old_fmriprep=False)

    name = 'nighres_{}'.format(subject)

    wf = init_from_fmriprep_to_nighres_wf(name)
    wf.base_dir = tmp_dir

    wf.inputs.inputnode.inv2 = inv2
    wf.inputs.inputnode.t1w = t1w
    wf.inputs.inputnode.t1map = t1map
    wf.inputs.inputnode.manual_mask_outside = manual_outside_mask
    wf.inputs.inputnode.manual_mask_gm = manual_gm_mask
    wf.inputs.inputnode.manual_mask_wm = manual_wm_mask
    wf.inputs.inputnode.fmriprep_wm = fmriprep_wm
    wf.inputs.inputnode.fmriprep_gm = fmriprep_gm
    wf.inputs.inputnode.aseg = freesurfer_seg

    wf.run(plugin='MultiProc', plugin_args={'n_procs': 10})
Ejemplo n.º 9
0
def main(sourcedata,
         derivatives,
         tmp_dir,
         subject=None,
         acquisition=None,
         session=None,
         run=None):

    if run is []:
        run = '[0-9]+'

    if subject in ['04', '01']:
        dof = 9
    else:
        dof = 6

    layout = BIDSLayout(sourcedata)
    derivatives_layout = BIDSLayout(derivatives)

    dtissue_left = get_derivative(derivatives,
                                  'nighres',
                                  'anat',
                                  subject,
                                  'dseg',
                                  hemi='left',
                                  space='average',
                                  description='cortex',
                                  session='anat')
    dtissue_right = get_derivative(derivatives,
                                   'nighres',
                                   'anat',
                                   subject,
                                   'dseg',
                                   hemi='right',
                                   space='average',
                                   description='cortex',
                                   session='anat')

    dura = get_dura_mask(derivatives, subject, 'average', 'anat')

    get_wm_wf = get_wm_seg_from_nighres(dtissue_left, dtissue_right)

    bold = []

    bold = layout.get(subject=subject,
                      session=session,
                      run=run,
                      acquisition=acquisition,
                      suffix='bold',
                      return_type='file')

    print(bold)

    epi = []
    for b in bold:
        fmaps = layout.get_fieldmap(b, return_list=True)
        for fmap in fmaps:
            if ('type' not in fmap) or (fmap['type'] == 'epi'):
                break
        epi.append(fmap['epi'])
        print('Using {} as epi_op for {}'.format(fmap['epi'], b))

    print(epi)

    t1w = get_derivative(derivatives,
                         'masked_mp2rages',
                         'anat',
                         subject,
                         'T1w',
                         session='anat',
                         space='average',
                         description='masked',
                         extension='nii.gz')

    print(t1w, os.path.exists(t1w))

    init_matrix = get_derivative(derivatives,
                                 'manual_transformations',
                                 'func',
                                 subject,
                                 'transform',
                                 session=session,
                                 space='average',
                                 extension='mat')

    os.environ['SUBJECTS_DIR'] = op.join(derivatives, 'freesurfer')

    wf = init_hires_unwarping_wf(
        name="unwarp_hires_{}_{}_{}".format(subject, session, acquisition),
        method='topup',
        bids_layout=layout,
        single_warpfield=False,
        register_to='last',
        init_transform=init_matrix,
        linear_registration_parameters='linear_hires.json',
        nonlinear_registration_parameters='nonlinear_precise.json',
        bold=bold,
        epi_op=epi,
        t1w_epi=None,
        t1w=t1w,
        dura_mask=dura,
        wm_seg=True,
        inv2_epi=None,
        dof=dof,
        crop_bolds=True,
        topup_package='afni',
        epi_to_t1_package='fsl',
        highpass_filter=True,
        within_epi_reg=True,
        freesurfer_subject_id='sub-{}'.format(subject),
        polish=True,
        num_threads_ants=4)

    wf.connect(get_wm_wf, 'outputspec.wm_seg', wf.get_node('inputspec'),
               'wm_seg')
    wf.base_dir = tmp_dir

    wf.run(plugin='MultiProc', plugin_args={'n_procs': 8})