def test_JistIntensityMp2rageMasking_outputs():
    output_map = dict(outMasked=dict(),
    outMasked2=dict(),
    outSignal=dict(),
    outSignal2=dict(),
    )
    outputs = JistIntensityMp2rageMasking.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value
Exemplo n.º 2
0
def create_mp2rage_pipeline(name='mp2rage'):

    # workflow
    mp2rage = Workflow('mp2rage')

    # inputnode
    inputnode = Node(util.IdentityInterface(fields=['inv2', 'uni', 't1map']),
                     name='inputnode')

    # outputnode
    outputnode = Node(
        util.IdentityInterface(fields=[
            'uni_masked',
            'background_mask',
            'uni_stripped',
            #'skullstrip_mask',
            #'uni_reoriented'
        ]),
        name='outputnode')

    # remove background noise
    background = Node(JistIntensityMp2rageMasking(outMasked=True,
                                                  outMasked2=True,
                                                  outSignal2=True),
                      name='background')

    # skullstrip
    strip = Node(MedicAlgorithmSPECTRE2010(outStripped=True,
                                           outMask=True,
                                           outOriginal=True,
                                           inOutput='true',
                                           inFind='true',
                                           inMMC=4),
                 name='strip')

    # connections
    mp2rage.connect([
        (inputnode, background, [('inv2', 'inSecond'),
                                 ('t1map', 'inQuantitative'),
                                 ('uni', 'inT1weighted')]),
        (background, strip, [('outMasked2', 'inInput')]),
        (background, outputnode, [('outMasked2', 'uni_masked'),
                                  ('outSignal2', 'background_mask')]),
        (
            strip,
            outputnode,
            [
                ('outStripped', 'uni_stripped'),
                #('outMask', 'skullstrip_mask'),
                #('outOriginal','uni_reoriented')
            ])
    ])

    return mp2rage
Exemplo n.º 3
0
def test_JistIntensityMp2rageMasking_outputs():
    output_map = dict(
        outMasked=dict(),
        outMasked2=dict(),
        outSignal=dict(),
        outSignal2=dict(),
    )
    outputs = JistIntensityMp2rageMasking.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value
def test_JistIntensityMp2rageMasking_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    inBackground=dict(argstr='--inBackground %s',
    ),
    inMasking=dict(argstr='--inMasking %s',
    ),
    inQuantitative=dict(argstr='--inQuantitative %s',
    ),
    inSecond=dict(argstr='--inSecond %s',
    ),
    inSkip=dict(argstr='--inSkip %s',
    ),
    inT1weighted=dict(argstr='--inT1weighted %s',
    ),
    null=dict(argstr='--null %s',
    ),
    outMasked=dict(argstr='--outMasked %s',
    hash_files=False,
    ),
    outMasked2=dict(argstr='--outMasked2 %s',
    hash_files=False,
    ),
    outSignal=dict(argstr='--outSignal %s',
    hash_files=False,
    ),
    outSignal2=dict(argstr='--outSignal2 %s',
    hash_files=False,
    ),
    terminal_output=dict(mandatory=True,
    nohash=True,
    ),
    xDefaultMem=dict(argstr='-xDefaultMem %d',
    ),
    xMaxProcess=dict(argstr='-xMaxProcess %d',
    usedefault=True,
    ),
    xPrefExt=dict(argstr='--xPrefExt %s',
    ),
    )
    inputs = JistIntensityMp2rageMasking.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value
Exemplo n.º 5
0
def test_JistIntensityMp2rageMasking_inputs():
    input_map = dict(
        args=dict(argstr='%s', ),
        environ=dict(
            nohash=True,
            usedefault=True,
        ),
        ignore_exception=dict(
            nohash=True,
            usedefault=True,
        ),
        inBackground=dict(argstr='--inBackground %s', ),
        inMasking=dict(argstr='--inMasking %s', ),
        inQuantitative=dict(argstr='--inQuantitative %s', ),
        inSecond=dict(argstr='--inSecond %s', ),
        inSkip=dict(argstr='--inSkip %s', ),
        inT1weighted=dict(argstr='--inT1weighted %s', ),
        null=dict(argstr='--null %s', ),
        outMasked=dict(
            argstr='--outMasked %s',
            hash_files=False,
        ),
        outMasked2=dict(
            argstr='--outMasked2 %s',
            hash_files=False,
        ),
        outSignal=dict(
            argstr='--outSignal %s',
            hash_files=False,
        ),
        outSignal2=dict(
            argstr='--outSignal2 %s',
            hash_files=False,
        ),
        terminal_output=dict(
            mandatory=True,
            nohash=True,
        ),
        xDefaultMem=dict(argstr='-xDefaultMem %d', ),
        xMaxProcess=dict(
            argstr='-xMaxProcess %d',
            usedefault=True,
        ),
        xPrefExt=dict(argstr='--xPrefExt %s', ),
    )
    inputs = JistIntensityMp2rageMasking.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value
def convert_scanner_data(population, afs_dir, data_dumpdir):

    count = 0
    for subject in population:
        count += 1
        print '========================================================================================'
        print '%s- Dicom Conversion and Anatomical Preprocessing for subject %s_%s' % (
            count, subject, afs_dir[-2])
        print '========================================================================================'

        for folder in os.listdir(afs_dir):
            if folder.startswith('p'):

                '===================================================================================================='
                '                                        DICOM to NIFTI                                              '
                '===================================================================================================='

                #set dicom dir
                if os.path.isdir(
                        os.path.join(afs_dir, folder, subject, 'DICOM')):
                    dicom_dir = os.path.join(afs_dir, folder, subject, 'DICOM')

                    if os.path.isdir(os.path.join(data_dumpdir, subject)):
                        pass
                    else:
                        os.makedirs(os.path.join(data_dumpdir, subject))
                    subject_dir = os.path.join(data_dumpdir, subject)

                    # create output out dir
                    try:
                        os.makedirs(os.path.join(subject_dir, 'NIFTI'))
                    except OSError:
                        nifti_dir = str(os.path.join(subject_dir, 'NIFTI'))
                    nifti_dir = str(os.path.join(subject_dir, 'NIFTI'))

                    # convert dicoms to niftis
                    # ensure conversion hasnt been completed before
                    if os.path.isfile(
                            os.path.join(nifti_dir, 'MP2RAGE_UNI.nii')):
                        print 'Dicom Conversion already completed...... moving on'
                    else:
                        print 'Converting DICOM to NIFTI'
                        convert_cmd = [
                            'isisconv', '-in',
                            '%s' % dicom_dir, '-out',
                            '%s/%s_S{sequenceNumber}_{sequenceDescription}_{echoTime}.nii'
                            % (nifti_dir, subject), '-rf', 'dcm', '-wdialect',
                            'fsl'
                        ]
                        print subprocess.list2cmdline(convert_cmd)
                        subprocess.call(convert_cmd)

                        #rename outputs

                        for file in os.listdir(nifti_dir):
                            if 'mp2rage_p3_602B_INV1_2.98' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(
                                        os.path.join(nifti_dir,
                                                     'MP2RAGE_INV1.nii')))
                            elif 'mp2rage_p3_602B_INV2_2.98' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(
                                        os.path.join(nifti_dir,
                                                     'MP2RAGE_INV2.nii')))
                            elif 'mp2rage_p3_602B_DIV_Images_2.98' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(
                                        os.path.join(nifti_dir,
                                                     'MP2RAGE_DIV.nii')))
                            elif 'mp2rage_p3_602B_T1_Images_2.98' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(
                                        os.path.join(nifti_dir,
                                                     'MP2RAGE_T1MAPS.nii')))
                            elif 'mp2rage_p3_602B_UNI_Images_2.98' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(
                                        os.path.join(nifti_dir,
                                                     'MP2RAGE_UNI.nii')))
                            elif 'resting' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(os.path.join(nifti_dir, 'REST.nii')))
                            elif 'mbep2d_se_52' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(os.path.join(nifti_dir,
                                                     'REST_SE.nii')))
                            elif 'se_invpol_52' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(
                                        os.path.join(nifti_dir,
                                                     'REST_SE_INVPOL.nii')))
                            elif 'bvec' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(
                                        os.path.join(nifti_dir,
                                                     'DWI_BVEC.bvec')))
                            elif 'AP_unwarp_diff' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(os.path.join(nifti_dir, 'DWI_AP.nii')))
                            elif 'PA_unwarp_diff' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(os.path.join(nifti_dir, 'DWI_PA.nii')))
                            elif 'mbep2d_diff_80' in file:
                                os.rename(
                                    str(os.path.join(nifti_dir, file)),
                                    str(os.path.join(nifti_dir, 'DWI.nii')))

                            # remove irrelevent files to conserve space
                            irrelvent_lst = [
                                'AAH', 'AX', 'ax', 'Cor', 'cor', 'COR', 'hip',
                                'Hip', 'slab', 'Modus', 'acpc', 'DUMMY',
                                'dummy', 'short', 'SLAB'
                            ]
                            try:
                                for string in irrelvent_lst:
                                    if string in file:
                                        os.remove(
                                            str(os.path.join(nifti_dir, file)))
                            except OSError:
                                print 'cant delete file %s' % str(
                                    os.path.join(nifti_dir, file))

                    '===================================================================================================='
                    '                                  Denoising MPRAGE Anatomical                                       '
                    '===================================================================================================='

                    if os.path.isfile(
                            os.path.join(nifti_dir, 'MP2RAGE_BRAIN.nii')):
                        print 'MP2RAGE already deskulled............... moving on'
                    else:
                        print 'Deskulling  MP2RAGE'

                        try:
                            mp2rage_uni = locate('MP2RAGE_UNI.nii', nifti_dir)
                            mp2rage_inv2 = locate('MP2RAGE_INV2.nii',
                                                  nifti_dir)
                            mp2rage_t1maps = locate('MP2RAGE_T1MAPS.nii',
                                                    nifti_dir)
                        except OSError:
                            continue

                        try:
                            os.makedirs(
                                os.path.join(nifti_dir, 'MIPAV_OUTPUTS'))
                        except OSError:
                            mipav_dir = str(
                                os.path.join(nifti_dir, 'MIPAV_OUTPUTS'))
                        mipav_dir = str(
                            os.path.join(nifti_dir, 'MIPAV_OUTPUTS'))

                        os.chdir(mipav_dir)

                        t1_threshold = fsl.Threshold()
                        t1_threshold.inputs.in_file = mp2rage_t1maps
                        t1_threshold.inputs.thresh = 1
                        t1_threshold.inputs.args = '-uthr 4000'
                        t1_threshold.run()

                        mp2rage_t1maps_thr = locate(
                            'MP2RAGE_T1MAPS_thresh.nii.gz', mipav_dir)

                        anat_denoise = JistIntensityMp2rageMasking(
                            outMasked=True,
                            outMasked2=True,
                            outSignal2=True,
                            inSkip='true')
                        anat_denoise.inputs.inQuantitative = mp2rage_t1maps_thr
                        anat_denoise.inputs.inT1weighted = mp2rage_uni
                        anat_denoise.inputs.inSecond = mp2rage_inv2
                        anat_denoise.run()

                        uni_denoised = locate('outMasked2.nii', mipav_dir)

                        '===================================================================================================='
                        '                                          Deskulling                                                '
                        '===================================================================================================='

                        anat_deskull = MedicAlgorithmSPECTRE2010(
                            inAtlas=str(
                                '/afs/cbs.mpg.de/software/cbstools/3.0/jist-cruise/Atlas/spectre/oasis-3-v2.txt'
                            ),
                            #inInitial    = 5,
                            #inInitial2   = 0.35 ,
                            #inMinimum    = 0.1,
                            #inSmoothing  = 0.02,
                            #inBackground = 0.001,
                            outOriginal=True,
                            #inOutput     = 'true',
                            outStripped=True,
                            outMask=True,
                            inFind='true',
                            xMaxProcess=0,
                            inMMC=2,
                            inMMC2=2)
                        anat_deskull.inputs.inInput = uni_denoised
                        anat_deskull.run()

                        shutil.move(
                            str(os.path.join(mipav_dir, 'outStripped.nii')),
                            str(os.path.join(nifti_dir, 'MP2RAGE_BRAIN.nii')))

                    if os.path.isfile(
                            os.path.join(nifti_dir, 'MP2RAGE_BRAIN.nii')):
                        brain = os.path.join(nifti_dir, 'MP2RAGE_BRAIN.nii')
                        print 'Path =  %s' % brain

    print '========================================================================================'
Exemplo n.º 7
0
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
========================================
sMRI: USing CBS Tools for skullstripping
========================================

This simple workflow uses SPECTRE2010 algorithm to skullstrip an MP2RAGE anatomical scan.
"""

import nipype.pipeline.engine as pe
from nipype.interfaces.mipav.developer import JistIntensityMp2rageMasking, MedicAlgorithmSPECTRE2010

wf = pe.Workflow("skullstripping")

mask = pe.Node(JistIntensityMp2rageMasking(), name="masking")
mask.inputs.inSecond = "/Users/filo/7t_trt/niftis/sub001/session_1/MP2RAGE_INV2.nii.gz"
mask.inputs.inQuantitative = "/Users/filo/7t_trt/niftis/sub001/session_1/MP2RAGE_UNI.nii.gz"
mask.inputs.inT1weighted = "/Users/filo/7t_trt/niftis/sub001/session_1/MP2RAGE_T1.nii.gz"
mask.inputs.outMasked = True
mask.inputs.outMasked2 = True
mask.inputs.outSignal = True
mask.inputs.outSignal2 = True

skullstrip = pe.Node(MedicAlgorithmSPECTRE2010(), name="skullstrip")
skullstrip.inputs.outStripped = True
skullstrip.inputs.xDefaultMem = 6000

wf.connect(mask, 'outMasked', skullstrip, 'inInput')
wf.run()
Exemplo n.º 8
0
def create_mp2rage_pipeline(name='mp2rage'):
    
    # workflow
    mp2rage = Workflow('mp2rage')
    
    # inputnode 
    inputnode=Node(util.IdentityInterface(fields=['inv2',
                                                  'uni',
                                                  't1map']),
               name='inputnode')
               
    # outputnode                                     
    outputnode=Node(util.IdentityInterface(fields=['uni_masked',
                                                   'background_mask',
                                                   'uni_stripped',
                                                   'skullstrip_mask',
                                                   
                                                   ]),
                name='outputnode')
    
    
    #get filenames from list
    def return_list_element(x):
        x_file=x[0]
        return x_file
    
    get_uni= Node(util.Function(input_names=["x"],
                              output_names=["x_file"],
                              function = return_list_element), name="get_uni")  
    get_t1= Node(util.Function(input_names=["x"],
                              output_names=["x_file"],
                              function = return_list_element), name="get_t1") 
    get_inv2= Node(util.Function(input_names=["x"],
                              output_names=["x_file"],
                              function = return_list_element), name="get_inv2") 
    # remove background noise
    background = Node(JistIntensityMp2rageMasking(outMasked=True,
                                            outMasked2=True,
                                            outSignal2=True), 
                      name='background')
    
    # skullstrip
#    strip = Node(MedicAlgorithmSPECTRE2010(outStripped=True,
#                                           outMask=True,
#                                           outOriginal=True,
#                                           inOutput='true',
#                                           inFind='true',
#                                           inMMC=4
#                                           ), 
#                 name='strip')
        
    strip = Node(JistBrainMp2rageSkullStripping(outBrain=True, outMasked2=True),name='strip')

    
    # connections
    mp2rage.connect([(inputnode, get_uni, [('uni','x')]),
                     (inputnode, get_t1, [('t1map','x')]),
                     (inputnode, get_inv2, [('inv2','x')]),
                     (get_inv2, background, [('x_file', 'inSecond')]),
                     (get_t1, background, [('x_file', 'inQuantitative')]),
                     (get_uni, background, [('x_file','inT1weighted')]),                     
                     (background, strip, [('outMasked2','inT1weighted')]),
                     (get_inv2, strip, [('x_file', 'inSecond')]),
                     (background, outputnode, [('outMasked2','uni_masked'),
                                               ('outSignal2','background_mask')]),
                     (strip, outputnode, [('outMasked2','uni_stripped'),
                                         ('outBrain', 'skullstrip_mask')
                                         
                                         ])
                     ])
    
    
    return mp2rage
def create_structural(subject, working_dir, data_dir, freesurfer_dir, out_dir):
    '''
    Workflow to run brackground masking and then freesurfer recon-all
    on "lowres" MP2RAGE data
    '''

    # main workflow
    struct_preproc = Workflow(name='mp2rage_preproc')
    struct_preproc.base_dir = working_dir
    struct_preproc.config['execution'][
        'crashdump_dir'] = struct_preproc.base_dir + "/crash_files"

    # select files
    templates = {
        'inv2': 'raw/mp2rage/inv2.nii.gz',
        't1map': 'raw/mp2rage/t1map.nii.gz',
        'uni': 'raw/mp2rage/uni.nii.gz'
    }
    selectfiles = Node(nio.SelectFiles(templates, base_directory=data_dir),
                       name="selectfiles")

    # mp2rage background masking
    background = Node(JistIntensityMp2rageMasking(outMasked=True,
                                                  outMasked2=True,
                                                  outSignal2=True),
                      name='background')

    # workflow to run freesurfer reconall

    # function to replace / in subject id string with a _
    def sub_id(sub_id):
        return sub_id.replace('/', '_')

    recon_all = Node(fs.ReconAll(args='-nuiterations 7 -no-isrunning'),
                     name="recon_all")
    recon_all.plugin_args = {'submit_specs': 'request_memory = 9000'}
    recon_all.inputs.subjects_dir = freesurfer_dir
    recon_all.inputs.subject_id = sub_id(subject)

    #sink to store files
    sink = Node(nio.DataSink(base_directory=out_dir,
                             parameterization=False,
                             substitutions=[('outStripped', 'uni_stripped'),
                                            ('outMasked2', 'uni_masked'),
                                            ('outSignal2', 'background_mask'),
                                            ('outOriginal', 'uni_reoriented'),
                                            ('outMask', 'skullstrip_mask'),
                                            ('transform_Warped',
                                             'T1_brain2std')]),
                name='sink')

    # connections
    struct_preproc.connect([
        (selectfiles, background, [('inv2', 'inSecond'),
                                   ('t1map', 'inQuantitative'),
                                   ('uni', 'inT1weighted')]),
        (background, recon_all, [('outMasked2', 'T1files')]),
        (background, sink, [('outMasked2', 'preprocessed.mp2rage.@uni_masked'),
                            ('outSignal2',
                             'preprocessed.mp2rage.@background_mask')]),
    ])

    #struct_preproc.write_graph(dotfilename='struct_preproc.dot', graph2use='colored', format='pdf', simple_form=True)
    return struct_preproc